Sync copyright fixes from downstream Emacs
[org-mode/org-tableheadings.git] / lisp / org.el
blob9b76ede1b6054c72b6c07d5c15c58bccc9355d16
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 mew: Support for links to messages in Mew" org-mew)
182 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
183 (const :tag "C registry: A registry for Org links" org-registry)
184 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
185 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
186 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
187 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
188 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
191 (defgroup org-startup nil
192 "Options concerning startup of Org-mode."
193 :tag "Org Startup"
194 :group 'org)
196 (defcustom org-startup-folded t
197 "Non-nil means, entering Org-mode will switch to OVERVIEW.
198 This can also be configured on a per-file basis by adding one of
199 the following lines anywhere in the buffer:
201 #+STARTUP: fold
202 #+STARTUP: nofold
203 #+STARTUP: content"
204 :group 'org-startup
205 :type '(choice
206 (const :tag "nofold: show all" nil)
207 (const :tag "fold: overview" t)
208 (const :tag "content: all headlines" content)))
210 (defcustom org-startup-truncated t
211 "Non-nil means, entering Org-mode will set `truncate-lines'.
212 This is useful since some lines containing links can be very long and
213 uninteresting. Also tables look terrible when wrapped."
214 :group 'org-startup
215 :type 'boolean)
217 (defcustom org-startup-align-all-tables nil
218 "Non-nil means, align all tables when visiting a file.
219 This is useful when the column width in tables is forced with <N> cookies
220 in table fields. Such tables will look correct only after the first re-align.
221 This can also be configured on a per-file basis by adding one of
222 the following lines anywhere in the buffer:
223 #+STARTUP: align
224 #+STARTUP: noalign"
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-insert-mode-line-in-empty-file nil
229 "Non-nil means insert the first line setting Org-mode in empty files.
230 When the function `org-mode' is called interactively in an empty file, this
231 normally means that the file name does not automatically trigger Org-mode.
232 To ensure that the file will always be in Org-mode in the future, a
233 line enforcing Org-mode will be inserted into the buffer, if this option
234 has been set."
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-replace-disputed-keys nil
239 "Non-nil means use alternative key bindings for some keys.
240 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
241 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
242 If you want to use Org-mode together with one of these other modes,
243 or more generally if you would like to move some Org-mode commands to
244 other keys, set this variable and configure the keys with the variable
245 `org-disputed-keys'.
247 This option is only relevant at load-time of Org-mode, and must be set
248 *before* org.el is loaded. Changing it requires a restart of Emacs to
249 become effective."
250 :group 'org-startup
251 :type 'boolean)
253 (if (fboundp 'defvaralias)
254 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
256 (defcustom org-disputed-keys
257 '(([(shift up)] . [(meta p)])
258 ([(shift down)] . [(meta n)])
259 ([(shift left)] . [(meta -)])
260 ([(shift right)] . [(meta +)])
261 ([(control shift right)] . [(meta shift +)])
262 ([(control shift left)] . [(meta shift -)]))
263 "Keys for which Org-mode and other modes compete.
264 This is an alist, cars are the default keys, second element specifies
265 the alternative to use when `org-replace-disputed-keys' is t.
267 Keys can be specified in any syntax supported by `define-key'.
268 The value of this option takes effect only at Org-mode's startup,
269 therefore you'll have to restart Emacs to apply it after changing."
270 :group 'org-startup
271 :type 'alist)
273 (defun org-key (key)
274 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
275 Or return the original if not disputed."
276 (if org-replace-disputed-keys
277 (let* ((nkey (key-description key))
278 (x (org-find-if (lambda (x)
279 (equal (key-description (car x)) nkey))
280 org-disputed-keys)))
281 (if x (cdr x) key))
282 key))
284 (defun org-find-if (predicate seq)
285 (catch 'exit
286 (while seq
287 (if (funcall predicate (car seq))
288 (throw 'exit (car seq))
289 (pop seq)))))
291 (defun org-defkey (keymap key def)
292 "Define a key, possibly translated, as returned by `org-key'."
293 (define-key keymap (org-key key) def))
295 (defcustom org-ellipsis nil
296 "The ellipsis to use in the Org-mode outline.
297 When nil, just use the standard three dots. When a string, use that instead,
298 When a face, use the standart 3 dots, but with the specified face.
299 The change affects only Org-mode (which will then use its own display table).
300 Changing this requires executing `M-x org-mode' in a buffer to become
301 effective."
302 :group 'org-startup
303 :type '(choice (const :tag "Default" nil)
304 (face :tag "Face" :value org-warning)
305 (string :tag "String" :value "...#")))
307 (defvar org-display-table nil
308 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
310 (defgroup org-keywords nil
311 "Keywords in Org-mode."
312 :tag "Org Keywords"
313 :group 'org)
315 (defcustom org-deadline-string "DEADLINE:"
316 "String to mark deadline entries.
317 A deadline is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-deadline].
320 Changes become only effective after restarting Emacs."
321 :group 'org-keywords
322 :type 'string)
324 (defcustom org-scheduled-string "SCHEDULED:"
325 "String to mark scheduled TODO entries.
326 A schedule is this string, followed by a time stamp. Should be a word,
327 terminated by a colon. You can insert a schedule keyword and
328 a timestamp with \\[org-schedule].
329 Changes become only effective after restarting Emacs."
330 :group 'org-keywords
331 :type 'string)
333 (defcustom org-closed-string "CLOSED:"
334 "String used as the prefix for timestamps logging closing a TODO entry."
335 :group 'org-keywords
336 :type 'string)
338 (defcustom org-clock-string "CLOCK:"
339 "String used as prefix for timestamps clocking work hours on an item."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-comment-string "COMMENT"
344 "Entries starting with this keyword will never be exported.
345 An entry can be toggled between COMMENT and normal with
346 \\[org-toggle-comment].
347 Changes become only effective after restarting Emacs."
348 :group 'org-keywords
349 :type 'string)
351 (defcustom org-quote-string "QUOTE"
352 "Entries starting with this keyword will be exported in fixed-width font.
353 Quoting applies only to the text in the entry following the headline, and does
354 not extend beyond the next headline, even if that is lower level.
355 An entry can be toggled between QUOTE and normal with
356 \\[org-toggle-fixed-width-section]."
357 :group 'org-keywords
358 :type 'string)
360 (defconst org-repeat-re
361 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
362 "Regular expression for specifying repeated events.
363 After a match, group 1 contains the repeat expression.")
365 (defgroup org-structure nil
366 "Options concerning the general structure of Org-mode files."
367 :tag "Org Structure"
368 :group 'org)
370 (defgroup org-reveal-location nil
371 "Options about how to make context of a location visible."
372 :tag "Org Reveal Location"
373 :group 'org-structure)
375 (defconst org-context-choice
376 '(choice
377 (const :tag "Always" t)
378 (const :tag "Never" nil)
379 (repeat :greedy t :tag "Individual contexts"
380 (cons
381 (choice :tag "Context"
382 (const agenda)
383 (const org-goto)
384 (const occur-tree)
385 (const tags-tree)
386 (const link-search)
387 (const mark-goto)
388 (const bookmark-jump)
389 (const isearch)
390 (const default))
391 (boolean))))
392 "Contexts for the reveal options.")
394 (defcustom org-show-hierarchy-above '((default . t))
395 "Non-nil means, show full hierarchy when revealing a location.
396 Org-mode often shows locations in an org-mode file which might have
397 been invisible before. When this is set, the hierarchy of headings
398 above the exposed location is shown.
399 Turning this off for example for sparse trees makes them very compact.
400 Instead of t, this can also be an alist specifying this option for different
401 contexts. Valid contexts are
402 agenda when exposing an entry from the agenda
403 org-goto when using the command `org-goto' on key C-c C-j
404 occur-tree when using the command `org-occur' on key C-c /
405 tags-tree when constructing a sparse tree based on tags matches
406 link-search when exposing search matches associated with a link
407 mark-goto when exposing the jump goal of a mark
408 bookmark-jump when exposing a bookmark location
409 isearch when exiting from an incremental search
410 default default for all contexts not set explicitly"
411 :group 'org-reveal-location
412 :type org-context-choice)
414 (defcustom org-show-following-heading '((default . nil))
415 "Non-nil means, show following heading when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the heading following the
418 match is shown.
419 Turning this off for example for sparse trees makes them very compact,
420 but makes it harder to edit the location of the match. In such a case,
421 use the command \\[org-reveal] to show more context.
422 Instead of t, this can also be an alist specifying this option for different
423 contexts. See `org-show-hierarchy-above' for valid contexts."
424 :group 'org-reveal-location
425 :type org-context-choice)
427 (defcustom org-show-siblings '((default . nil) (isearch t))
428 "Non-nil means, show all sibling heading when revealing a location.
429 Org-mode often shows locations in an org-mode file which might have
430 been invisible before. When this is set, the sibling of the current entry
431 heading are all made visible. If `org-show-hierarchy-above' is t,
432 the same happens on each level of the hierarchy above the current entry.
434 By default this is on for the isearch context, off for all other contexts.
435 Turning this off for example for sparse trees makes them very compact,
436 but makes it harder to edit the location of the match. In such a case,
437 use the command \\[org-reveal] to show more context.
438 Instead of t, this can also be an alist specifying this option for different
439 contexts. See `org-show-hierarchy-above' for valid contexts."
440 :group 'org-reveal-location
441 :type org-context-choice)
443 (defcustom org-show-entry-below '((default . nil))
444 "Non-nil means, show the entry below a headline when revealing a location.
445 Org-mode often shows locations in an org-mode file which might have
446 been invisible before. When this is set, the text below the headline that is
447 exposed is also shown.
449 By default this is off for all contexts.
450 Instead of t, this can also be an alist specifying this option for different
451 contexts. See `org-show-hierarchy-above' for valid contexts."
452 :group 'org-reveal-location
453 :type org-context-choice)
455 (defcustom org-indirect-buffer-display 'other-window
456 "How should indirect tree buffers be displayed?
457 This applies to indirect buffers created with the commands
458 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
459 Valid values are:
460 current-window Display in the current window
461 other-window Just display in another window.
462 dedicated-frame Create one new frame, and re-use it each time.
463 new-frame Make a new frame each time. Note that in this case
464 previously-made indirect buffers are kept, and you need to
465 kill these buffers yourself."
466 :group 'org-structure
467 :group 'org-agenda-windows
468 :type '(choice
469 (const :tag "In current window" current-window)
470 (const :tag "In current frame, other window" other-window)
471 (const :tag "Each time a new frame" new-frame)
472 (const :tag "One dedicated frame" dedicated-frame)))
474 (defgroup org-cycle nil
475 "Options concerning visibility cycling in Org-mode."
476 :tag "Org Cycle"
477 :group 'org-structure)
479 (defcustom org-drawers '("PROPERTIES" "CLOCK")
480 "Names of drawers. Drawers are not opened by cycling on the headline above.
481 Drawers only open with a TAB on the drawer line itself. A drawer looks like
482 this:
483 :DRAWERNAME:
484 .....
485 :END:
486 The drawer \"PROPERTIES\" is special for capturing properties through
487 the property API.
489 Drawers can be defined on the per-file basis with a line like:
491 #+DRAWERS: HIDDEN STATE PROPERTIES"
492 :group 'org-structure
493 :type '(repeat (string :tag "Drawer Name")))
495 (defcustom org-cycle-global-at-bob nil
496 "Cycle globally if cursor is at beginning of buffer and not at a headline.
497 This makes it possible to do global cycling without having to use S-TAB or
498 C-u TAB. For this special case to work, the first line of the buffer
499 must not be a headline - it may be empty ot some other text. When used in
500 this way, `org-cycle-hook' is disables temporarily, to make sure the
501 cursor stays at the beginning of the buffer.
502 When this option is nil, don't do anything special at the beginning
503 of the buffer."
504 :group 'org-cycle
505 :type 'boolean)
507 (defcustom org-cycle-emulate-tab t
508 "Where should `org-cycle' emulate TAB.
509 nil Never
510 white Only in completely white lines
511 whitestart Only at the beginning of lines, before the first non-white char
512 t Everywhere except in headlines
513 exc-hl-bol Everywhere except at the start of a headline
514 If TAB is used in a place where it does not emulate TAB, the current subtree
515 visibility is cycled."
516 :group 'org-cycle
517 :type '(choice (const :tag "Never" nil)
518 (const :tag "Only in completely white lines" white)
519 (const :tag "Before first char in a line" whitestart)
520 (const :tag "Everywhere except in headlines" t)
521 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
524 (defcustom org-cycle-separator-lines 2
525 "Number of empty lines needed to keep an empty line between collapsed trees.
526 If you leave an empty line between the end of a subtree and the following
527 headline, this empty line is hidden when the subtree is folded.
528 Org-mode will leave (exactly) one empty line visible if the number of
529 empty lines is equal or larger to the number given in this variable.
530 So the default 2 means, at least 2 empty lines after the end of a subtree
531 are needed to produce free space between a collapsed subtree and the
532 following headline.
534 Special case: when 0, never leave empty lines in collapsed view."
535 :group 'org-cycle
536 :type 'integer)
538 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
539 org-cycle-hide-drawers
540 org-cycle-show-empty-lines
541 org-optimize-window-after-visibility-change)
542 "Hook that is run after `org-cycle' has changed the buffer visibility.
543 The function(s) in this hook must accept a single argument which indicates
544 the new state that was set by the most recent `org-cycle' command. The
545 argument is a symbol. After a global state change, it can have the values
546 `overview', `content', or `all'. After a local state change, it can have
547 the values `folded', `children', or `subtree'."
548 :group 'org-cycle
549 :type 'hook)
551 (defgroup org-edit-structure nil
552 "Options concerning structure editing in Org-mode."
553 :tag "Org Edit Structure"
554 :group 'org-structure)
556 (defcustom org-odd-levels-only nil
557 "Non-nil means, skip even levels and only use odd levels for the outline.
558 This has the effect that two stars are being added/taken away in
559 promotion/demotion commands. It also influences how levels are
560 handled by the exporters.
561 Changing it requires restart of `font-lock-mode' to become effective
562 for fontification also in regions already fontified.
563 You may also set this on a per-file basis by adding one of the following
564 lines to the buffer:
566 #+STARTUP: odd
567 #+STARTUP: oddeven"
568 :group 'org-edit-structure
569 :group 'org-font-lock
570 :type 'boolean)
572 (defcustom org-adapt-indentation t
573 "Non-nil means, adapt indentation when promoting and demoting.
574 When this is set and the *entire* text in an entry is indented, the
575 indentation is increased by one space in a demotion command, and
576 decreased by one in a promotion command. If any line in the entry
577 body starts at column 0, indentation is not changed at all."
578 :group 'org-edit-structure
579 :type 'boolean)
581 (defcustom org-special-ctrl-a/e nil
582 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
583 When t, `C-a' will bring back the cursor to the beginning of the
584 headline text, i.e. after the stars and after a possible TODO keyword.
585 In an item, this will be the position after the bullet.
586 When the cursor is already at that position, another `C-a' will bring
587 it to the beginning of the line.
588 `C-e' will jump to the end of the headline, ignoring the presence of tags
589 in the headline. A second `C-e' will then jump to the true end of the
590 line, after any tags.
591 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
592 and only a directly following, identical keypress will bring the cursor
593 to the special positions."
594 :group 'org-edit-structure
595 :type '(choice
596 (const :tag "off" nil)
597 (const :tag "after bullet first" t)
598 (const :tag "border first" reversed)))
600 (if (fboundp 'defvaralias)
601 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
603 (defcustom org-special-ctrl-k nil
604 "Non-nil means `C-k' will behave specially in headlines.
605 When nil, `C-k' will call the default `kill-line' command.
606 When t, the following will happen while the cursor is in the headline:
608 - When the cursor is at the beginning of a headline, kill the entire
609 line and possible the folded subtree below the line.
610 - When in the middle of the headline text, kill the headline up to the tags.
611 - When after the headline text, kill the tags."
612 :group 'org-edit-structure
613 :type 'boolean)
615 (defcustom org-M-RET-may-split-line '((default . t))
616 "Non-nil means, M-RET will split the line at the cursor position.
617 When nil, it will go to the end of the line before making a
618 new line.
619 You may also set this option in a different way for different
620 contexts. Valid contexts are:
622 headline when creating a new headline
623 item when creating a new item
624 table in a table field
625 default the value to be used for all contexts not explicitly
626 customized"
627 :group 'org-structure
628 :group 'org-table
629 :type '(choice
630 (const :tag "Always" t)
631 (const :tag "Never" nil)
632 (repeat :greedy t :tag "Individual contexts"
633 (cons
634 (choice :tag "Context"
635 (const headline)
636 (const item)
637 (const table)
638 (const default))
639 (boolean)))))
642 (defcustom org-blank-before-new-entry '((heading . nil)
643 (plain-list-item . nil))
644 "Should `org-insert-heading' leave a blank line before new heading/item?
645 The value is an alist, with `heading' and `plain-list-item' as car,
646 and a boolean flag as cdr."
647 :group 'org-edit-structure
648 :type '(list
649 (cons (const heading) (boolean))
650 (cons (const plain-list-item) (boolean))))
652 (defcustom org-insert-heading-hook nil
653 "Hook being run after inserting a new heading."
654 :group 'org-edit-structure
655 :type 'hook)
657 (defcustom org-enable-fixed-width-editor t
658 "Non-nil means, lines starting with \":\" are treated as fixed-width.
659 This currently only means, they are never auto-wrapped.
660 When nil, such lines will be treated like ordinary lines.
661 See also the QUOTE keyword."
662 :group 'org-edit-structure
663 :type 'boolean)
665 (defcustom org-goto-auto-isearch t
666 "Non-nil means, typing characters in org-goto starts incremental search."
667 :group 'org-edit-structure
668 :type 'boolean)
670 (defgroup org-sparse-trees nil
671 "Options concerning sparse trees in Org-mode."
672 :tag "Org Sparse Trees"
673 :group 'org-structure)
675 (defcustom org-highlight-sparse-tree-matches t
676 "Non-nil means, highlight all matches that define a sparse tree.
677 The highlights will automatically disappear the next time the buffer is
678 changed by an edit command."
679 :group 'org-sparse-trees
680 :type 'boolean)
682 (defcustom org-remove-highlights-with-change t
683 "Non-nil means, any change to the buffer will remove temporary highlights.
684 Such highlights are created by `org-occur' and `org-clock-display'.
685 When nil, `C-c C-c needs to be used to get rid of the highlights.
686 The highlights created by `org-preview-latex-fragment' always need
687 `C-c C-c' to be removed."
688 :group 'org-sparse-trees
689 :group 'org-time
690 :type 'boolean)
693 (defcustom org-occur-hook '(org-first-headline-recenter)
694 "Hook that is run after `org-occur' has constructed a sparse tree.
695 This can be used to recenter the window to show as much of the structure
696 as possible."
697 :group 'org-sparse-trees
698 :type 'hook)
700 (defgroup org-plain-lists nil
701 "Options concerning plain lists in Org-mode."
702 :tag "Org Plain lists"
703 :group 'org-structure)
705 (defcustom org-cycle-include-plain-lists nil
706 "Non-nil means, include plain lists into visibility cycling.
707 This means that during cycling, plain list items will *temporarily* be
708 interpreted as outline headlines with a level given by 1000+i where i is the
709 indentation of the bullet. In all other operations, plain list items are
710 not seen as headlines. For example, you cannot assign a TODO keyword to
711 such an item."
712 :group 'org-plain-lists
713 :type 'boolean)
715 (defcustom org-plain-list-ordered-item-terminator t
716 "The character that makes a line with leading number an ordered list item.
717 Valid values are ?. and ?\). To get both terminators, use t. While
718 ?. may look nicer, it creates the danger that a line with leading
719 number may be incorrectly interpreted as an item. ?\) therefore is
720 the safe choice."
721 :group 'org-plain-lists
722 :type '(choice (const :tag "dot like in \"2.\"" ?.)
723 (const :tag "paren like in \"2)\"" ?\))
724 (const :tab "both" t)))
726 (defcustom org-empty-line-terminates-plain-lists nil
727 "Non-nil means, an empty line ends all plain list levels.
728 When nil, empty lines are part of the preceeding item."
729 :group 'org-plain-lists
730 :type 'boolean)
732 (defcustom org-auto-renumber-ordered-lists t
733 "Non-nil means, automatically renumber ordered plain lists.
734 Renumbering happens when the sequence have been changed with
735 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
736 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
737 :group 'org-plain-lists
738 :type 'boolean)
740 (defcustom org-provide-checkbox-statistics t
741 "Non-nil means, update checkbox statistics after insert and toggle.
742 When this is set, checkbox statistics is updated each time you either insert
743 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
744 with \\[org-ctrl-c-ctrl-c\\]."
745 :group 'org-plain-lists
746 :type 'boolean)
749 (defgroup org-imenu-and-speedbar nil
750 "Options concerning imenu and speedbar in Org-mode."
751 :tag "Org Imenu and Speedbar"
752 :group 'org-structure)
754 (defcustom org-imenu-depth 2
755 "The maximum level for Imenu access to Org-mode headlines.
756 This also applied for speedbar access."
757 :group 'org-imenu-and-speedbar
758 :type 'number)
760 (defgroup org-table nil
761 "Options concerning tables in Org-mode."
762 :tag "Org Table"
763 :group 'org)
765 (defcustom org-enable-table-editor 'optimized
766 "Non-nil means, lines starting with \"|\" are handled by the table editor.
767 When nil, such lines will be treated like ordinary lines.
769 When equal to the symbol `optimized', the table editor will be optimized to
770 do the following:
771 - Automatic overwrite mode in front of whitespace in table fields.
772 This makes the structure of the table stay in tact as long as the edited
773 field does not exceed the column width.
774 - Minimize the number of realigns. Normally, the table is aligned each time
775 TAB or RET are pressed to move to another field. With optimization this
776 happens only if changes to a field might have changed the column width.
777 Optimization requires replacing the functions `self-insert-command',
778 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
779 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
780 very good at guessing when a re-align will be necessary, but you can always
781 force one with \\[org-ctrl-c-ctrl-c].
783 If you would like to use the optimized version in Org-mode, but the
784 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
786 This variable can be used to turn on and off the table editor during a session,
787 but in order to toggle optimization, a restart is required.
789 See also the variable `org-table-auto-blank-field'."
790 :group 'org-table
791 :type '(choice
792 (const :tag "off" nil)
793 (const :tag "on" t)
794 (const :tag "on, optimized" optimized)))
796 (defcustom org-table-tab-recognizes-table.el t
797 "Non-nil means, TAB will automatically notice a table.el table.
798 When it sees such a table, it moves point into it and - if necessary -
799 calls `table-recognize-table'."
800 :group 'org-table-editing
801 :type 'boolean)
803 (defgroup org-link nil
804 "Options concerning links in Org-mode."
805 :tag "Org Link"
806 :group 'org)
808 (defvar org-link-abbrev-alist-local nil
809 "Buffer-local version of `org-link-abbrev-alist', which see.
810 The value of this is taken from the #+LINK lines.")
811 (make-variable-buffer-local 'org-link-abbrev-alist-local)
813 (defcustom org-link-abbrev-alist nil
814 "Alist of link abbreviations.
815 The car of each element is a string, to be replaced at the start of a link.
816 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
817 links in Org-mode buffers can have an optional tag after a double colon, e.g.
819 [[linkkey:tag][description]]
821 If REPLACE is a string, the tag will simply be appended to create the link.
822 If the string contains \"%s\", the tag will be inserted there.
824 REPLACE may also be a function that will be called with the tag as the
825 only argument to create the link, which should be returned as a string.
827 See the manual for examples."
828 :group 'org-link
829 :type 'alist)
831 (defcustom org-descriptive-links t
832 "Non-nil means, hide link part and only show description of bracket links.
833 Bracket links are like [[link][descritpion]]. This variable sets the initial
834 state in new org-mode buffers. The setting can then be toggled on a
835 per-buffer basis from the Org->Hyperlinks menu."
836 :group 'org-link
837 :type 'boolean)
839 (defcustom org-link-file-path-type 'adaptive
840 "How the path name in file links should be stored.
841 Valid values are:
843 relative Relative to the current directory, i.e. the directory of the file
844 into which the link is being inserted.
845 absolute Absolute path, if possible with ~ for home directory.
846 noabbrev Absolute path, no abbreviation of home directory.
847 adaptive Use relative path for files in the current directory and sub-
848 directories of it. For other files, use an absolute path."
849 :group 'org-link
850 :type '(choice
851 (const relative)
852 (const absolute)
853 (const noabbrev)
854 (const adaptive)))
856 (defcustom org-activate-links '(bracket angle plain radio tag date)
857 "Types of links that should be activated in Org-mode files.
858 This is a list of symbols, each leading to the activation of a certain link
859 type. In principle, it does not hurt to turn on most link types - there may
860 be a small gain when turning off unused link types. The types are:
862 bracket The recommended [[link][description]] or [[link]] links with hiding.
863 angular Links in angular brackes that may contain whitespace like
864 <bbdb:Carsten Dominik>.
865 plain Plain links in normal text, no whitespace, like http://google.com.
866 radio Text that is matched by a radio target, see manual for details.
867 tag Tag settings in a headline (link to tag search).
868 date Time stamps (link to calendar).
870 Changing this variable requires a restart of Emacs to become effective."
871 :group 'org-link
872 :type '(set (const :tag "Double bracket links (new style)" bracket)
873 (const :tag "Angular bracket links (old style)" angular)
874 (const :tag "Plain text links" plain)
875 (const :tag "Radio target matches" radio)
876 (const :tag "Tags" tag)
877 (const :tag "Timestamps" date)))
879 (defcustom org-make-link-description-function nil
880 "Function to use to generate link descriptions from links. If
881 nil the link location will be used. This function must take two
882 parameters; the first is the link and the second the description
883 org-insert-link has generated, and should return the description
884 to use."
885 :group 'org-link
886 :type 'function)
888 (defgroup org-link-store nil
889 "Options concerning storing links in Org-mode."
890 :tag "Org Store Link"
891 :group 'org-link)
893 (defcustom org-email-link-description-format "Email %c: %.30s"
894 "Format of the description part of a link to an email or usenet message.
895 The following %-excapes will be replaced by corresponding information:
897 %F full \"From\" field
898 %f name, taken from \"From\" field, address if no name
899 %T full \"To\" field
900 %t first name in \"To\" field, address if no name
901 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
902 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
903 %s subject
904 %m message-id.
906 You may use normal field width specification between the % and the letter.
907 This is for example useful to limit the length of the subject.
909 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
910 :group 'org-link-store
911 :type 'string)
913 (defcustom org-from-is-user-regexp
914 (let (r1 r2)
915 (when (and user-mail-address (not (string= user-mail-address "")))
916 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
917 (when (and user-full-name (not (string= user-full-name "")))
918 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
919 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
920 "Regexp mached against the \"From:\" header of an email or usenet message.
921 It should match if the message is from the user him/herself."
922 :group 'org-link-store
923 :type 'regexp)
925 (defcustom org-context-in-file-links t
926 "Non-nil means, file links from `org-store-link' contain context.
927 A search string will be added to the file name with :: as separator and
928 used to find the context when the link is activated by the command
929 `org-open-at-point'.
930 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
931 negates this setting for the duration of the command."
932 :group 'org-link-store
933 :type 'boolean)
935 (defcustom org-keep-stored-link-after-insertion nil
936 "Non-nil means, keep link in list for entire session.
938 The command `org-store-link' adds a link pointing to the current
939 location to an internal list. These links accumulate during a session.
940 The command `org-insert-link' can be used to insert links into any
941 Org-mode file (offering completion for all stored links). When this
942 option is nil, every link which has been inserted once using \\[org-insert-link]
943 will be removed from the list, to make completing the unused links
944 more efficient."
945 :group 'org-link-store
946 :type 'boolean)
948 (defgroup org-link-follow nil
949 "Options concerning following links in Org-mode."
950 :tag "Org Follow Link"
951 :group 'org-link)
953 (defcustom org-follow-link-hook nil
954 "Hook that is run after a link has been followed."
955 :group 'org-link-follow
956 :type 'hook)
958 (defcustom org-tab-follows-link nil
959 "Non-nil means, on links TAB will follow the link.
960 Needs to be set before org.el is loaded."
961 :group 'org-link-follow
962 :type 'boolean)
964 (defcustom org-return-follows-link nil
965 "Non-nil means, on links RET will follow the link.
966 Needs to be set before org.el is loaded."
967 :group 'org-link-follow
968 :type 'boolean)
970 (defcustom org-mouse-1-follows-link
971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
972 "Non-nil means, mouse-1 on a link will follow the link.
973 A longer mouse click will still set point. Does not work on XEmacs.
974 Needs to be set before org.el is loaded."
975 :group 'org-link-follow
976 :type 'boolean)
978 (defcustom org-mark-ring-length 4
979 "Number of different positions to be recorded in the ring
980 Changing this requires a restart of Emacs to work correctly."
981 :group 'org-link-follow
982 :type 'interger)
984 (defcustom org-link-frame-setup
985 '((vm . vm-visit-folder-other-frame)
986 (gnus . gnus-other-frame)
987 (file . find-file-other-window))
988 "Setup the frame configuration for following links.
989 When following a link with Emacs, it may often be useful to display
990 this link in another window or frame. This variable can be used to
991 set this up for the different types of links.
992 For VM, use any of
993 `vm-visit-folder'
994 `vm-visit-folder-other-frame'
995 For Gnus, use any of
996 `gnus'
997 `gnus-other-frame'
998 For FILE, use any of
999 `find-file'
1000 `find-file-other-window'
1001 `find-file-other-frame'
1002 For the calendar, use the variable `calendar-setup'.
1003 For BBDB, it is currently only possible to display the matches in
1004 another window."
1005 :group 'org-link-follow
1006 :type '(list
1007 (cons (const vm)
1008 (choice
1009 (const vm-visit-folder)
1010 (const vm-visit-folder-other-window)
1011 (const vm-visit-folder-other-frame)))
1012 (cons (const gnus)
1013 (choice
1014 (const gnus)
1015 (const gnus-other-frame)))
1016 (cons (const file)
1017 (choice
1018 (const find-file)
1019 (const find-file-other-window)
1020 (const find-file-other-frame)))))
1022 (defcustom org-display-internal-link-with-indirect-buffer nil
1023 "Non-nil means, use indirect buffer to display infile links.
1024 Activating internal links (from one location in a file to another location
1025 in the same file) normally just jumps to the location. When the link is
1026 activated with a C-u prefix (or with mouse-3), the link is displayed in
1027 another window. When this option is set, the other window actually displays
1028 an indirect buffer clone of the current buffer, to avoid any visibility
1029 changes to the current buffer."
1030 :group 'org-link-follow
1031 :type 'boolean)
1033 (defcustom org-open-non-existing-files nil
1034 "Non-nil means, `org-open-file' will open non-existing files.
1035 When nil, an error will be generated."
1036 :group 'org-link-follow
1037 :type 'boolean)
1039 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1040 "Function and arguments to call for following mailto links.
1041 This is a list with the first element being a lisp function, and the
1042 remaining elements being arguments to the function. In string arguments,
1043 %a will be replaced by the address, and %s will be replaced by the subject
1044 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1045 :group 'org-link-follow
1046 :type '(choice
1047 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1048 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1049 (const :tag "message-mail" (message-mail "%a" "%s"))
1050 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1052 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1053 "Non-nil means, ask for confirmation before executing shell links.
1054 Shell links can be dangerous: just think about a link
1056 [[shell:rm -rf ~/*][Google Search]]
1058 This link would show up in your Org-mode document as \"Google Search\",
1059 but really it would remove your entire home directory.
1060 Therefore we advise against setting this variable to nil.
1061 Just change it to `y-or-n-p' of you want to confirm with a
1062 single keystroke rather than having to type \"yes\"."
1063 :group 'org-link-follow
1064 :type '(choice
1065 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1066 (const :tag "with y-or-n (faster)" y-or-n-p)
1067 (const :tag "no confirmation (dangerous)" nil)))
1069 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1070 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1071 Elisp links can be dangerous: just think about a link
1073 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1075 This link would show up in your Org-mode document as \"Google Search\",
1076 but really it would remove your entire home directory.
1077 Therefore we advise against setting this variable to nil.
1078 Just change it to `y-or-n-p' of you want to confirm with a
1079 single keystroke rather than having to type \"yes\"."
1080 :group 'org-link-follow
1081 :type '(choice
1082 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1083 (const :tag "with y-or-n (faster)" y-or-n-p)
1084 (const :tag "no confirmation (dangerous)" nil)))
1086 (defconst org-file-apps-defaults-gnu
1087 '((remote . emacs)
1088 (t . mailcap))
1089 "Default file applications on a UNIX or GNU/Linux system.
1090 See `org-file-apps'.")
1092 (defconst org-file-apps-defaults-macosx
1093 '((remote . emacs)
1094 (t . "open %s")
1095 ("ps" . "gv %s")
1096 ("ps.gz" . "gv %s")
1097 ("eps" . "gv %s")
1098 ("eps.gz" . "gv %s")
1099 ("dvi" . "xdvi %s")
1100 ("fig" . "xfig %s"))
1101 "Default file applications on a MacOS X system.
1102 The system \"open\" is known as a default, but we use X11 applications
1103 for some files for which the OS does not have a good default.
1104 See `org-file-apps'.")
1106 (defconst org-file-apps-defaults-windowsnt
1107 (list
1108 '(remote . emacs)
1109 (cons t
1110 (list (if (featurep 'xemacs)
1111 'mswindows-shell-execute
1112 'w32-shell-execute)
1113 "open" 'file)))
1114 "Default file applications on a Windows NT system.
1115 The system \"open\" is used for most files.
1116 See `org-file-apps'.")
1118 (defcustom org-file-apps
1120 ("txt" . emacs)
1121 ("tex" . emacs)
1122 ("ltx" . emacs)
1123 ("org" . emacs)
1124 ("el" . emacs)
1125 ("bib" . emacs)
1127 "External applications for opening `file:path' items in a document.
1128 Org-mode uses system defaults for different file types, but
1129 you can use this variable to set the application for a given file
1130 extension. The entries in this list are cons cells where the car identifies
1131 files and the cdr the corresponding command. Possible values for the
1132 file identifier are
1133 \"ext\" A string identifying an extension
1134 `directory' Matches a directory
1135 `remote' Matches a remote file, accessible through tramp or efs.
1136 Remote files most likely should be visited through Emacs
1137 because external applications cannot handle such paths.
1138 t Default for all remaining files
1140 Possible values for the command are:
1141 `emacs' The file will be visited by the current Emacs process.
1142 `default' Use the default application for this file type.
1143 string A command to be executed by a shell; %s will be replaced
1144 by the path to the file.
1145 sexp A Lisp form which will be evaluated. The file path will
1146 be available in the Lisp variable `file'.
1147 For more examples, see the system specific constants
1148 `org-file-apps-defaults-macosx'
1149 `org-file-apps-defaults-windowsnt'
1150 `org-file-apps-defaults-gnu'."
1151 :group 'org-link-follow
1152 :type '(repeat
1153 (cons (choice :value ""
1154 (string :tag "Extension")
1155 (const :tag "Default for unrecognized files" t)
1156 (const :tag "Remote file" remote)
1157 (const :tag "Links to a directory" directory))
1158 (choice :value ""
1159 (const :tag "Visit with Emacs" emacs)
1160 (const :tag "Use system default" default)
1161 (string :tag "Command")
1162 (sexp :tag "Lisp form")))))
1164 (defgroup org-refile nil
1165 "Options concerning refiling entries in Org-mode."
1166 :tag "Org Remember"
1167 :group 'org)
1169 (defcustom org-directory "~/org"
1170 "Directory with org files.
1171 This directory will be used as default to prompt for org files.
1172 Used by the hooks for remember.el."
1173 :group 'org-refile
1174 :group 'org-remember
1175 :type 'directory)
1177 (defcustom org-default-notes-file "~/.notes"
1178 "Default target for storing notes.
1179 Used by the hooks for remember.el. This can be a string, or nil to mean
1180 the value of `remember-data-file'.
1181 You can set this on a per-template basis with the variable
1182 `org-remember-templates'."
1183 :group 'org-refile
1184 :group 'org-remember
1185 :type '(choice
1186 (const :tag "Default from remember-data-file" nil)
1187 file))
1189 (defcustom org-goto-interface 'outline
1190 "The default interface to be used for `org-goto'.
1191 Allowed vaues are:
1192 outline The interface shows an outline of the relevant file
1193 and the correct heading is found by moving through
1194 the outline or by searching with incremental search.
1195 outline-path-completion Headlines in the current buffer are offered via
1196 completion."
1197 :group 'org-refile
1198 :type '(choice
1199 (const :tag "Outline" outline)
1200 (const :tag "Outline-path-completion" outline-path-completion)))
1202 (defcustom org-reverse-note-order nil
1203 "Non-nil means, store new notes at the beginning of a file or entry.
1204 When nil, new notes will be filed to the end of a file or entry.
1205 This can also be a list with cons cells of regular expressions that
1206 are matched against file names, and values."
1207 :group 'org-remember
1208 :type '(choice
1209 (const :tag "Reverse always" t)
1210 (const :tag "Reverse never" nil)
1211 (repeat :tag "By file name regexp"
1212 (cons regexp boolean))))
1214 (defcustom org-refile-targets nil
1215 "Targets for refiling entries with \\[org-refile].
1216 This is list of cons cells. Each cell contains:
1217 - a specification of the files to be considered, either a list of files,
1218 or a symbol whose function or variable value will be used to retrieve
1219 a file name or a list of file names. Nil means, refile to a different
1220 heading in the current buffer.
1221 - A specification of how to find candidate refile targets. This may be
1222 any of
1223 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1224 This tag has to be present in all target headlines, inheritance will
1225 not be considered.
1226 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1227 todo keyword.
1228 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1229 headlines that are refiling targets.
1230 - a cons cell (:level . N). Any headline of level N is considered a target.
1231 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1232 :group 'org-remember
1233 :type '(repeat
1234 (cons
1235 (choice :value org-agenda-files
1236 (const :tag "All agenda files" org-agenda-files)
1237 (const :tag "Current buffer" nil)
1238 (function) (variable) (file))
1239 (choice :tag "Identify target headline by"
1240 (cons :tag "Specific tag" (const :tag) (string))
1241 (cons :tag "TODO keyword" (const :todo) (string))
1242 (cons :tag "Regular expression" (const :regexp) (regexp))
1243 (cons :tag "Level number" (const :level) (integer))
1244 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1246 (defcustom org-refile-use-outline-path nil
1247 "Non-nil means, provide refile targets as paths.
1248 So a level 3 headline will be available as level1/level2/level3.
1249 When the value is `file', also include the file name (without directory)
1250 into the path. When `full-file-path', include the full file path."
1251 :group 'org-remember
1252 :type '(choice
1253 (const :tag "Not" nil)
1254 (const :tag "Yes" t)
1255 (const :tag "Start with file name" file)
1256 (const :tag "Start with full file path" full-file-path)))
1258 (defgroup org-todo nil
1259 "Options concerning TODO items in Org-mode."
1260 :tag "Org TODO"
1261 :group 'org)
1263 (defgroup org-progress nil
1264 "Options concerning Progress logging in Org-mode."
1265 :tag "Org Progress"
1266 :group 'org-time)
1268 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1269 "List of TODO entry keyword sequences and their interpretation.
1270 \\<org-mode-map>This is a list of sequences.
1272 Each sequence starts with a symbol, either `sequence' or `type',
1273 indicating if the keywords should be interpreted as a sequence of
1274 action steps, or as different types of TODO items. The first
1275 keywords are states requiring action - these states will select a headline
1276 for inclusion into the global TODO list Org-mode produces. If one of
1277 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1278 signify that no further action is necessary. If \"|\" is not found,
1279 the last keyword is treated as the only DONE state of the sequence.
1281 The command \\[org-todo] cycles an entry through these states, and one
1282 additional state where no keyword is present. For details about this
1283 cycling, see the manual.
1285 TODO keywords and interpretation can also be set on a per-file basis with
1286 the special #+SEQ_TODO and #+TYP_TODO lines.
1288 Each keyword can optionally specify a character for fast state selection
1289 \(in combination with the variable `org-use-fast-todo-selection')
1290 and specifiers for state change logging, using the same syntax
1291 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1292 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1293 indicates to record a time stamp each time this state is selected.
1295 Each keyword may also specify if a timestamp or a note should be
1296 recorded when entering or leaving the state, by adding additional
1297 characters in the parenthesis after the keyword. This looks like this:
1298 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1299 record only the time of the state change. With X and Y being either
1300 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1301 Y when leaving the state if and only if the *target* state does not
1302 define X. You may omit any of the fast-selection key or X or /Y,
1303 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1305 For backward compatibility, this variable may also be just a list
1306 of keywords - in this case the interptetation (sequence or type) will be
1307 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1308 :group 'org-todo
1309 :group 'org-keywords
1310 :type '(choice
1311 (repeat :tag "Old syntax, just keywords"
1312 (string :tag "Keyword"))
1313 (repeat :tag "New syntax"
1314 (cons
1315 (choice
1316 :tag "Interpretation"
1317 (const :tag "Sequence (cycling hits every state)" sequence)
1318 (const :tag "Type (cycling directly to DONE)" type))
1319 (repeat
1320 (string :tag "Keyword"))))))
1322 (defvar org-todo-keywords-1 nil
1323 "All TODO and DONE keywords active in a buffer.")
1324 (make-variable-buffer-local 'org-todo-keywords-1)
1325 (defvar org-todo-keywords-for-agenda nil)
1326 (defvar org-done-keywords-for-agenda nil)
1327 (defvar org-agenda-contributing-files nil)
1328 (defvar org-not-done-keywords nil)
1329 (make-variable-buffer-local 'org-not-done-keywords)
1330 (defvar org-done-keywords nil)
1331 (make-variable-buffer-local 'org-done-keywords)
1332 (defvar org-todo-heads nil)
1333 (make-variable-buffer-local 'org-todo-heads)
1334 (defvar org-todo-sets nil)
1335 (make-variable-buffer-local 'org-todo-sets)
1336 (defvar org-todo-log-states nil)
1337 (make-variable-buffer-local 'org-todo-log-states)
1338 (defvar org-todo-kwd-alist nil)
1339 (make-variable-buffer-local 'org-todo-kwd-alist)
1340 (defvar org-todo-key-alist nil)
1341 (make-variable-buffer-local 'org-todo-key-alist)
1342 (defvar org-todo-key-trigger nil)
1343 (make-variable-buffer-local 'org-todo-key-trigger)
1345 (defcustom org-todo-interpretation 'sequence
1346 "Controls how TODO keywords are interpreted.
1347 This variable is in principle obsolete and is only used for
1348 backward compatibility, if the interpretation of todo keywords is
1349 not given already in `org-todo-keywords'. See that variable for
1350 more information."
1351 :group 'org-todo
1352 :group 'org-keywords
1353 :type '(choice (const sequence)
1354 (const type)))
1356 (defcustom org-use-fast-todo-selection 'prefix
1357 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1358 This variable describes if and under what circumstances the cycling
1359 mechanism for TODO keywords will be replaced by a single-key, direct
1360 selection scheme.
1362 When nil, fast selection is never used.
1364 When the symbol `prefix', it will be used when `org-todo' is called with
1365 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1366 in an agenda buffer.
1368 When t, fast selection is used by default. In this case, the prefix
1369 argument forces cycling instead.
1371 In all cases, the special interface is only used if access keys have actually
1372 been assigned by the user, i.e. if keywords in the configuration are followed
1373 by a letter in parenthesis, like TODO(t)."
1374 :group 'org-todo
1375 :type '(choice
1376 (const :tag "Never" nil)
1377 (const :tag "By default" t)
1378 (const :tag "Only with C-u C-c C-t" prefix)))
1380 (defcustom org-after-todo-state-change-hook nil
1381 "Hook which is run after the state of a TODO item was changed.
1382 The new state (a string with a TODO keyword, or nil) is available in the
1383 Lisp variable `state'."
1384 :group 'org-todo
1385 :type 'hook)
1387 (defcustom org-log-done nil
1388 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1389 When equal to the list (done), also prompt for a closing note.
1390 This can also be configured on a per-file basis by adding one of
1391 the following lines anywhere in the buffer:
1393 #+STARTUP: logdone
1394 #+STARTUP: lognotedone
1395 #+STARTUP: nologdone"
1396 :group 'org-todo
1397 :group 'org-progress
1398 :type '(choice
1399 (const :tag "No logging" nil)
1400 (const :tag "Record CLOSED timestamp" time)
1401 (const :tag "Record CLOSED timestamp with closing note." note)))
1403 ;; Normalize old uses of org-log-done.
1404 (cond
1405 ((eq org-log-done t) (setq org-log-done 'time))
1406 ((and (listp org-log-done) (memq 'done org-log-done))
1407 (setq org-log-done 'note)))
1409 (defcustom org-log-note-clock-out nil
1410 "Non-nil means, recored a note when clocking out of an item.
1411 This can also be configured on a per-file basis by adding one of
1412 the following lines anywhere in the buffer:
1414 #+STARTUP: lognoteclock-out
1415 #+STARTUP: nolognoteclock-out"
1416 :group 'org-todo
1417 :group 'org-progress
1418 :type 'boolean)
1420 (defcustom org-log-done-with-time t
1421 "Non-nil means, the CLOSED time stamp will contain date and time.
1422 When nil, only the date will be recorded."
1423 :group 'org-progress
1424 :type 'boolean)
1426 (defcustom org-log-note-headings
1427 '((done . "CLOSING NOTE %t")
1428 (state . "State %-12s %t")
1429 (note . "Note taken on %t")
1430 (clock-out . ""))
1431 "Headings for notes added to entries.
1432 The value is an alist, with the car being a symbol indicating the note
1433 context, and the cdr is the heading to be used. The heading may also be the
1434 empty string.
1435 %t in the heading will be replaced by a time stamp.
1436 %s will be replaced by the new TODO state, in double quotes.
1437 %u will be replaced by the user name.
1438 %U will be replaced by the full user name."
1439 :group 'org-todo
1440 :group 'org-progress
1441 :type '(list :greedy t
1442 (cons (const :tag "Heading when closing an item" done) string)
1443 (cons (const :tag
1444 "Heading when changing todo state (todo sequence only)"
1445 state) string)
1446 (cons (const :tag "Heading when just taking a note" note) string)
1447 (cons (const :tag "Heading when clocking out" clock-out) string)))
1449 (unless (assq 'note org-log-note-headings)
1450 (push '(note . "%t") org-log-note-headings))
1452 (defcustom org-log-states-order-reversed t
1453 "Non-nil means, the latest state change note will be directly after heading.
1454 When nil, the notes will be orderer according to time."
1455 :group 'org-todo
1456 :group 'org-progress
1457 :type 'boolean)
1459 (defcustom org-log-repeat 'time
1460 "Non-nil means, record moving through the DONE state when triggering repeat.
1461 An auto-repeating tasks is immediately switched back to TODO when marked
1462 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1463 the TODO keyword definition, or recording a closing note by setting
1464 `org-log-done', there will be no record of the task moving through DONE.
1465 This variable forces taking a note anyway. Possible values are:
1467 nil Don't force a record
1468 time Record a time stamp
1469 note Record a note
1471 This option can also be set with on a per-file-basis with
1473 #+STARTUP: logrepeat
1474 #+STARTUP: lognoterepeat
1475 #+STARTUP: nologrepeat
1477 You can have local logging settings for a subtree by setting the LOGGING
1478 property to one or more of these keywords."
1479 :group 'org-todo
1480 :group 'org-progress
1481 :type '(choice
1482 (const :tag "Don't force a record" nil)
1483 (const :tag "Force recording the DONE state" time)
1484 (const :tag "Force recording a note with the DONE state" note)))
1487 (defgroup org-priorities nil
1488 "Priorities in Org-mode."
1489 :tag "Org Priorities"
1490 :group 'org-todo)
1492 (defcustom org-highest-priority ?A
1493 "The highest priority of TODO items. A character like ?A, ?B etc.
1494 Must have a smaller ASCII number than `org-lowest-priority'."
1495 :group 'org-priorities
1496 :type 'character)
1498 (defcustom org-lowest-priority ?C
1499 "The lowest priority of TODO items. A character like ?A, ?B etc.
1500 Must have a larger ASCII number than `org-highest-priority'."
1501 :group 'org-priorities
1502 :type 'character)
1504 (defcustom org-default-priority ?B
1505 "The default priority of TODO items.
1506 This is the priority an item get if no explicit priority is given."
1507 :group 'org-priorities
1508 :type 'character)
1510 (defcustom org-priority-start-cycle-with-default t
1511 "Non-nil means, start with default priority when starting to cycle.
1512 When this is nil, the first step in the cycle will be (depending on the
1513 command used) one higher or lower that the default priority."
1514 :group 'org-priorities
1515 :type 'boolean)
1517 (defgroup org-time nil
1518 "Options concerning time stamps and deadlines in Org-mode."
1519 :tag "Org Time"
1520 :group 'org)
1522 (defcustom org-insert-labeled-timestamps-at-point nil
1523 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1524 When nil, these labeled time stamps are forces into the second line of an
1525 entry, just after the headline. When scheduling from the global TODO list,
1526 the time stamp will always be forced into the second line."
1527 :group 'org-time
1528 :type 'boolean)
1530 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1531 "Formats for `format-time-string' which are used for time stamps.
1532 It is not recommended to change this constant.")
1534 (defcustom org-time-stamp-rounding-minutes '(0 5)
1535 "Number of minutes to round time stamps to.
1536 These are two values, the first applies when first creating a time stamp.
1537 The second applies when changing it with the commands `S-up' and `S-down'.
1538 When changing the time stamp, this means that it will change in steps
1539 of N minutes, as given by the second value.
1541 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1542 numbers should be factors of 60, so for example 5, 10, 15.
1544 When this is larger than 1, you can still force an exact time-stamp by using
1545 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1546 and by using a prefix arg to `S-up/down' to specify the exact number
1547 of minutes to shift."
1548 :group 'org-time
1549 :get '(lambda (var) ; Make sure all entries have 5 elements
1550 (if (integerp (default-value var))
1551 (list (default-value var) 5)
1552 (default-value var)))
1553 :type '(list
1554 (integer :tag "when inserting times")
1555 (integer :tag "when modifying times")))
1557 ;; Normalize old customizations of this variable.
1558 (when (integerp org-time-stamp-rounding-minutes)
1559 (setq org-time-stamp-rounding-minutes
1560 (list org-time-stamp-rounding-minutes
1561 org-time-stamp-rounding-minutes)))
1563 (defcustom org-display-custom-times nil
1564 "Non-nil means, overlay custom formats over all time stamps.
1565 The formats are defined through the variable `org-time-stamp-custom-formats'.
1566 To turn this on on a per-file basis, insert anywhere in the file:
1567 #+STARTUP: customtime"
1568 :group 'org-time
1569 :set 'set-default
1570 :type 'sexp)
1571 (make-variable-buffer-local 'org-display-custom-times)
1573 (defcustom org-time-stamp-custom-formats
1574 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1575 "Custom formats for time stamps. See `format-time-string' for the syntax.
1576 These are overlayed over the default ISO format if the variable
1577 `org-display-custom-times' is set. Time like %H:%M should be at the
1578 end of the second format."
1579 :group 'org-time
1580 :type 'sexp)
1582 (defun org-time-stamp-format (&optional long inactive)
1583 "Get the right format for a time string."
1584 (let ((f (if long (cdr org-time-stamp-formats)
1585 (car org-time-stamp-formats))))
1586 (if inactive
1587 (concat "[" (substring f 1 -1) "]")
1588 f)))
1590 (defcustom org-deadline-warning-days 14
1591 "No. of days before expiration during which a deadline becomes active.
1592 This variable governs the display in sparse trees and in the agenda.
1593 When 0 or negative, it means use this number (the absolute value of it)
1594 even if a deadline has a different individual lead time specified."
1595 :group 'org-time
1596 :group 'org-agenda-daily/weekly
1597 :type 'number)
1599 (defcustom org-read-date-prefer-future t
1600 "Non-nil means, assume future for incomplete date input from user.
1601 This affects the following situations:
1602 1. The user gives a day, but no month.
1603 For example, if today is the 15th, and you enter \"3\", Org-mode will
1604 read this as the third of *next* month. However, if you enter \"17\",
1605 it will be considered as *this* month.
1606 2. The user gives a month but not a year.
1607 For example, if it is april and you enter \"feb 2\", this will be read
1608 as feb 2, *next* year. \"May 5\", however, will be this year.
1610 Currently this does not work for ISO week specifications.
1612 When this option is nil, the current month and year will always be used
1613 as defaults."
1614 :group 'org-time
1615 :type 'boolean)
1617 (defcustom org-read-date-display-live t
1618 "Non-nil means, display current interpretation of date prompt live.
1619 This display will be in an overlay, in the minibuffer."
1620 :group 'org-time
1621 :type 'boolean)
1623 (defcustom org-read-date-popup-calendar t
1624 "Non-nil means, pop up a calendar when prompting for a date.
1625 In the calendar, the date can be selected with mouse-1. However, the
1626 minibuffer will also be active, and you can simply enter the date as well.
1627 When nil, only the minibuffer will be available."
1628 :group 'org-time
1629 :type 'boolean)
1630 (if (fboundp 'defvaralias)
1631 (defvaralias 'org-popup-calendar-for-date-prompt
1632 'org-read-date-popup-calendar))
1634 (defcustom org-extend-today-until 0
1635 "The hour when your day really ends.
1636 This has influence for the following applications:
1637 - When switching the agenda to \"today\". It it is still earlier than
1638 the time given here, the day recognized as TODAY is actually yesterday.
1639 - When a date is read from the user and it is still before the time given
1640 here, the current date and time will be assumed to be yesterday, 23:59.
1642 FIXME:
1643 IMPORTANT: This is still a very experimental feature, it may disappear
1644 again or it may be extended to mean more things."
1645 :group 'org-time
1646 :type 'number)
1648 (defcustom org-edit-timestamp-down-means-later nil
1649 "Non-nil means, S-down will increase the time in a time stamp.
1650 When nil, S-up will increase."
1651 :group 'org-time
1652 :type 'boolean)
1654 (defcustom org-calendar-follow-timestamp-change t
1655 "Non-nil means, make the calendar window follow timestamp changes.
1656 When a timestamp is modified and the calendar window is visible, it will be
1657 moved to the new date."
1658 :group 'org-time
1659 :type 'boolean)
1661 (defgroup org-tags nil
1662 "Options concerning tags in Org-mode."
1663 :tag "Org Tags"
1664 :group 'org)
1666 (defcustom org-tag-alist nil
1667 "List of tags allowed in Org-mode files.
1668 When this list is nil, Org-mode will base TAG input on what is already in the
1669 buffer.
1670 The value of this variable is an alist, the car of each entry must be a
1671 keyword as a string, the cdr may be a character that is used to select
1672 that tag through the fast-tag-selection interface.
1673 See the manual for details."
1674 :group 'org-tags
1675 :type '(repeat
1676 (choice
1677 (cons (string :tag "Tag name")
1678 (character :tag "Access char"))
1679 (const :tag "Start radio group" (:startgroup))
1680 (const :tag "End radio group" (:endgroup)))))
1682 (defcustom org-use-fast-tag-selection 'auto
1683 "Non-nil means, use fast tag selection scheme.
1684 This is a special interface to select and deselect tags with single keys.
1685 When nil, fast selection is never used.
1686 When the symbol `auto', fast selection is used if and only if selection
1687 characters for tags have been configured, either through the variable
1688 `org-tag-alist' or through a #+TAGS line in the buffer.
1689 When t, fast selection is always used and selection keys are assigned
1690 automatically if necessary."
1691 :group 'org-tags
1692 :type '(choice
1693 (const :tag "Always" t)
1694 (const :tag "Never" nil)
1695 (const :tag "When selection characters are configured" 'auto)))
1697 (defcustom org-fast-tag-selection-single-key nil
1698 "Non-nil means, fast tag selection exits after first change.
1699 When nil, you have to press RET to exit it.
1700 During fast tag selection, you can toggle this flag with `C-c'.
1701 This variable can also have the value `expert'. In this case, the window
1702 displaying the tags menu is not even shown, until you press C-c again."
1703 :group 'org-tags
1704 :type '(choice
1705 (const :tag "No" nil)
1706 (const :tag "Yes" t)
1707 (const :tag "Expert" expert)))
1709 (defvar org-fast-tag-selection-include-todo nil
1710 "Non-nil means, fast tags selection interface will also offer TODO states.
1711 This is an undocumented feature, you should not rely on it.")
1713 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1714 "The column to which tags should be indented in a headline.
1715 If this number is positive, it specifies the column. If it is negative,
1716 it means that the tags should be flushright to that column. For example,
1717 -80 works well for a normal 80 character screen."
1718 :group 'org-tags
1719 :type 'integer)
1721 (defcustom org-auto-align-tags t
1722 "Non-nil means, realign tags after pro/demotion of TODO state change.
1723 These operations change the length of a headline and therefore shift
1724 the tags around. With this options turned on, after each such operation
1725 the tags are again aligned to `org-tags-column'."
1726 :group 'org-tags
1727 :type 'boolean)
1729 (defcustom org-use-tag-inheritance t
1730 "Non-nil means, tags in levels apply also for sublevels.
1731 When nil, only the tags directly given in a specific line apply there.
1732 If you turn off this option, you very likely want to turn on the
1733 companion option `org-tags-match-list-sublevels'.
1735 This may also be a list of tags that should be inherited, or a regexp that
1736 matches tags that should be inherited."
1737 :group 'org-tags
1738 :type '(choice
1739 (const :tag "Not" nil)
1740 (const :tag "Always" t)
1741 (repeat :tag "Specific tags" (string :tag "Tag"))
1742 (regexp :tag "Tags matched by regexp")))
1744 (defun org-tag-inherit-p (tag)
1745 "Check if TAG is one that should be inherited."
1746 (cond
1747 ((eq org-use-tag-inheritance t) t)
1748 ((not org-use-tag-inheritance) nil)
1749 ((stringp org-use-tag-inheritance)
1750 (string-match org-use-tag-inheritance tag))
1751 ((listp org-use-tag-inheritance)
1752 (member tag org-use-tag-inheritance))
1753 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1755 (defcustom org-tags-match-list-sublevels nil
1756 "Non-nil means list also sublevels of headlines matching tag search.
1757 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1758 the sublevels of a headline matching a tag search often also match
1759 the same search. Listing all of them can create very long lists.
1760 Setting this variable to nil causes subtrees of a match to be skipped.
1761 This option is off by default, because inheritance in on. If you turn
1762 inheritance off, you very likely want to turn this option on.
1764 As a special case, if the tag search is restricted to TODO items, the
1765 value of this variable is ignored and sublevels are always checked, to
1766 make sure all corresponding TODO items find their way into the list."
1767 :group 'org-tags
1768 :type 'boolean)
1770 (defvar org-tags-history nil
1771 "History of minibuffer reads for tags.")
1772 (defvar org-last-tags-completion-table nil
1773 "The last used completion table for tags.")
1774 (defvar org-after-tags-change-hook nil
1775 "Hook that is run after the tags in a line have changed.")
1777 (defgroup org-properties nil
1778 "Options concerning properties in Org-mode."
1779 :tag "Org Properties"
1780 :group 'org)
1782 (defcustom org-property-format "%-10s %s"
1783 "How property key/value pairs should be formatted by `indent-line'.
1784 When `indent-line' hits a property definition, it will format the line
1785 according to this format, mainly to make sure that the values are
1786 lined-up with respect to each other."
1787 :group 'org-properties
1788 :type 'string)
1790 (defcustom org-use-property-inheritance nil
1791 "Non-nil means, properties apply also for sublevels.
1793 This setting is chiefly used during property searches. Turning it on can
1794 cause significant overhead when doing a search, which is why it is not
1795 on by default.
1797 When nil, only the properties directly given in the current entry count.
1798 When t, every property is inherited. The value may also be a list of
1799 properties that should have inheritance, or a regular expression matching
1800 properties that should be inherited.
1802 However, note that some special properties use inheritance under special
1803 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1804 and the properties ending in \"_ALL\" when they are used as descriptor
1805 for valid values of a property.
1807 Note for programmers:
1808 When querying an entry with `org-entry-get', you can control if inheritance
1809 should be used. By default, `org-entry-get' looks only at the local
1810 properties. You can request inheritance by setting the inherit argument
1811 to t (to force inheritance) or to `selective' (to respect the setting
1812 in this variable)."
1813 :group 'org-properties
1814 :type '(choice
1815 (const :tag "Not" nil)
1816 (const :tag "Always" t)
1817 (repeat :tag "Specific properties" (string :tag "Property"))
1818 (regexp :tag "Properties matched by regexp")))
1820 (defun org-property-inherit-p (property)
1821 "Check if PROPERTY is one that should be inherited."
1822 (cond
1823 ((eq org-use-property-inheritance t) t)
1824 ((not org-use-property-inheritance) nil)
1825 ((stringp org-use-property-inheritance)
1826 (string-match org-use-property-inheritance property))
1827 ((listp org-use-property-inheritance)
1828 (member property org-use-property-inheritance))
1829 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1831 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1832 "The default column format, if no other format has been defined.
1833 This variable can be set on the per-file basis by inserting a line
1835 #+COLUMNS: %25ITEM ....."
1836 :group 'org-properties
1837 :type 'string)
1839 (defcustom org-effort-property "Effort"
1840 "The property that is being used to keep track of effort estimates.
1841 Effort estimates given in this property need to have the format H:MM."
1842 :group 'org-properties
1843 :group 'org-progress
1844 :type '(string :tag "Property"))
1846 (defcustom org-global-properties nil
1847 "List of property/value pairs that can be inherited by any entry.
1848 You can set buffer-local values for this by adding lines like
1850 #+PROPERTY: NAME VALUE"
1851 :group 'org-properties
1852 :type '(repeat
1853 (cons (string :tag "Property")
1854 (string :tag "Value"))))
1856 (defvar org-local-properties nil
1857 "List of property/value pairs that can be inherited by any entry.
1858 Valid for the current buffer.
1859 This variable is populated from #+PROPERTY lines.")
1861 (defgroup org-agenda nil
1862 "Options concerning agenda views in Org-mode."
1863 :tag "Org Agenda"
1864 :group 'org)
1866 (defvar org-category nil
1867 "Variable used by org files to set a category for agenda display.
1868 Such files should use a file variable to set it, for example
1870 # -*- mode: org; org-category: \"ELisp\"
1872 or contain a special line
1874 #+CATEGORY: ELisp
1876 If the file does not specify a category, then file's base name
1877 is used instead.")
1878 (make-variable-buffer-local 'org-category)
1880 (defcustom org-agenda-files nil
1881 "The files to be used for agenda display.
1882 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1883 \\[org-remove-file]. You can also use customize to edit the list.
1885 If an entry is a directory, all files in that directory that are matched by
1886 `org-agenda-file-regexp' will be part of the file list.
1888 If the value of the variable is not a list but a single file name, then
1889 the list of agenda files is actually stored and maintained in that file, one
1890 agenda file per line."
1891 :group 'org-agenda
1892 :type '(choice
1893 (repeat :tag "List of files and directories" file)
1894 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1896 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1897 "Regular expression to match files for `org-agenda-files'.
1898 If any element in the list in that variable contains a directory instead
1899 of a normal file, all files in that directory that are matched by this
1900 regular expression will be included."
1901 :group 'org-agenda
1902 :type 'regexp)
1904 (defcustom org-agenda-text-search-extra-files nil
1905 "List of extra files to be searched by text search commands.
1906 These files will be search in addition to the agenda files by the
1907 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1908 Note that these files will only be searched for text search commands,
1909 not for the other agenda views like todo lists, tag searches or the weekly
1910 agenda. This variable is intended to list notes and possibly archive files
1911 that should also be searched by these two commands.
1912 In fact, if the first element in the list is the symbol `agenda-archives',
1913 than all archive files of all agenda files will be added to the search
1914 scope."
1915 :group 'org-agenda
1916 :type '(set :greedy t
1917 (const :tag "Agenda Archives" agenda-archives)
1918 (repeat :inline t (file))))
1920 (if (fboundp 'defvaralias)
1921 (defvaralias 'org-agenda-multi-occur-extra-files
1922 'org-agenda-text-search-extra-files))
1924 (defcustom org-agenda-skip-unavailable-files nil
1925 "t means to just skip non-reachable files in `org-agenda-files'.
1926 Nil means to remove them, after a query, from the list."
1927 :group 'org-agenda
1928 :type 'boolean)
1930 (defcustom org-calendar-to-agenda-key [?c]
1931 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1932 The command `org-calendar-goto-agenda' will be bound to this key. The
1933 default is the character `c' because then `c' can be used to switch back and
1934 forth between agenda and calendar."
1935 :group 'org-agenda
1936 :type 'sexp)
1938 (eval-after-load "calendar"
1939 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1940 'org-calendar-goto-agenda))
1942 (defgroup org-latex nil
1943 "Options for embedding LaTeX code into Org-mode."
1944 :tag "Org LaTeX"
1945 :group 'org)
1947 (defcustom org-format-latex-options
1948 '(:foreground default :background default :scale 1.0
1949 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1950 :matchers ("begin" "$" "$$" "\\(" "\\["))
1951 "Options for creating images from LaTeX fragments.
1952 This is a property list with the following properties:
1953 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1954 `default' means use the forground of the default face.
1955 :background the background color, or \"Transparent\".
1956 `default' means use the background of the default face.
1957 :scale a scaling factor for the size of the images
1958 :html-foreground, :html-background, :html-scale
1959 The same numbers for HTML export.
1960 :matchers a list indicating which matchers should be used to
1961 find LaTeX fragments. Valid members of this list are:
1962 \"begin\" find environments
1963 \"$\" find math expressions surrounded by $...$
1964 \"$$\" find math expressions surrounded by $$....$$
1965 \"\\(\" find math expressions surrounded by \\(...\\)
1966 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1967 :group 'org-latex
1968 :type 'plist)
1970 (defcustom org-format-latex-header "\\documentclass{article}
1971 \\usepackage{fullpage} % do not remove
1972 \\usepackage{amssymb}
1973 \\usepackage[usenames]{color}
1974 \\usepackage{amsmath}
1975 \\usepackage{latexsym}
1976 \\usepackage[mathscr]{eucal}
1977 \\pagestyle{empty} % do not remove"
1978 "The document header used for processing LaTeX fragments."
1979 :group 'org-latex
1980 :type 'string)
1983 (defgroup org-font-lock nil
1984 "Font-lock settings for highlighting in Org-mode."
1985 :tag "Org Font Lock"
1986 :group 'org)
1988 (defcustom org-level-color-stars-only nil
1989 "Non-nil means fontify only the stars in each headline.
1990 When nil, the entire headline is fontified.
1991 Changing it requires restart of `font-lock-mode' to become effective
1992 also in regions already fontified."
1993 :group 'org-font-lock
1994 :type 'boolean)
1996 (defcustom org-hide-leading-stars nil
1997 "Non-nil means, hide the first N-1 stars in a headline.
1998 This works by using the face `org-hide' for these stars. This
1999 face is white for a light background, and black for a dark
2000 background. You may have to customize the face `org-hide' to
2001 make this work.
2002 Changing it requires restart of `font-lock-mode' to become effective
2003 also in regions already fontified.
2004 You may also set this on a per-file basis by adding one of the following
2005 lines to the buffer:
2007 #+STARTUP: hidestars
2008 #+STARTUP: showstars"
2009 :group 'org-font-lock
2010 :type 'boolean)
2012 (defcustom org-fontify-done-headline nil
2013 "Non-nil means, change the face of a headline if it is marked DONE.
2014 Normally, only the TODO/DONE keyword indicates the state of a headline.
2015 When this is non-nil, the headline after the keyword is set to the
2016 `org-headline-done' as an additional indication."
2017 :group 'org-font-lock
2018 :type 'boolean)
2020 (defcustom org-fontify-emphasized-text t
2021 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2022 Changing this variable requires a restart of Emacs to take effect."
2023 :group 'org-font-lock
2024 :type 'boolean)
2026 (defcustom org-highlight-latex-fragments-and-specials nil
2027 "Non-nil means, fontify what is treated specially by the exporters."
2028 :group 'org-font-lock
2029 :type 'boolean)
2031 (defcustom org-hide-emphasis-markers nil
2032 "Non-nil mean font-lock should hide the emphasis marker characters."
2033 :group 'org-font-lock
2034 :type 'boolean)
2036 (defvar org-emph-re nil
2037 "Regular expression for matching emphasis.")
2038 (defvar org-verbatim-re nil
2039 "Regular expression for matching verbatim text.")
2040 (defvar org-emphasis-regexp-components) ; defined just below
2041 (defvar org-emphasis-alist) ; defined just below
2042 (defun org-set-emph-re (var val)
2043 "Set variable and compute the emphasis regular expression."
2044 (set var val)
2045 (when (and (boundp 'org-emphasis-alist)
2046 (boundp 'org-emphasis-regexp-components)
2047 org-emphasis-alist org-emphasis-regexp-components)
2048 (let* ((e org-emphasis-regexp-components)
2049 (pre (car e))
2050 (post (nth 1 e))
2051 (border (nth 2 e))
2052 (body (nth 3 e))
2053 (nl (nth 4 e))
2054 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2055 (body1 (concat body "*?"))
2056 (markers (mapconcat 'car org-emphasis-alist ""))
2057 (vmarkers (mapconcat
2058 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2059 org-emphasis-alist "")))
2060 ;; make sure special characters appear at the right position in the class
2061 (if (string-match "\\^" markers)
2062 (setq markers (concat (replace-match "" t t markers) "^")))
2063 (if (string-match "-" markers)
2064 (setq markers (concat (replace-match "" t t markers) "-")))
2065 (if (string-match "\\^" vmarkers)
2066 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2067 (if (string-match "-" vmarkers)
2068 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2069 (if (> nl 0)
2070 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2071 (int-to-string nl) "\\}")))
2072 ;; Make the regexp
2073 (setq org-emph-re
2074 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2075 "\\("
2076 "\\([" markers "]\\)"
2077 "\\("
2078 "[^" border "]\\|"
2079 "[^" border (if (and nil stacked) markers) "]"
2080 body1
2081 "[^" border (if (and nil stacked) markers) "]"
2082 "\\)"
2083 "\\3\\)"
2084 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2085 (setq org-verbatim-re
2086 (concat "\\([" pre "]\\|^\\)"
2087 "\\("
2088 "\\([" vmarkers "]\\)"
2089 "\\("
2090 "[^" border "]\\|"
2091 "[^" border "]"
2092 body1
2093 "[^" border "]"
2094 "\\)"
2095 "\\3\\)"
2096 "\\([" post "]\\|$\\)")))))
2098 (defcustom org-emphasis-regexp-components
2099 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2100 "Components used to build the regular expression for emphasis.
2101 This is a list with 6 entries. Terminology: In an emphasis string
2102 like \" *strong word* \", we call the initial space PREMATCH, the final
2103 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2104 and \"trong wor\" is the body. The different components in this variable
2105 specify what is allowed/forbidden in each part:
2107 pre Chars allowed as prematch. Beginning of line will be allowed too.
2108 post Chars allowed as postmatch. End of line will be allowed too.
2109 border The chars *forbidden* as border characters.
2110 body-regexp A regexp like \".\" to match a body character. Don't use
2111 non-shy groups here, and don't allow newline here.
2112 newline The maximum number of newlines allowed in an emphasis exp.
2114 Use customize to modify this, or restart Emacs after changing it."
2115 :group 'org-font-lock
2116 :set 'org-set-emph-re
2117 :type '(list
2118 (sexp :tag "Allowed chars in pre ")
2119 (sexp :tag "Allowed chars in post ")
2120 (sexp :tag "Forbidden chars in border ")
2121 (sexp :tag "Regexp for body ")
2122 (integer :tag "number of newlines allowed")
2123 (option (boolean :tag "Stacking (DISABLED) "))))
2125 (defcustom org-emphasis-alist
2126 `(("*" bold "<b>" "</b>")
2127 ("/" italic "<i>" "</i>")
2128 ("_" underline "<u>" "</u>")
2129 ("=" org-code "<code>" "</code>" verbatim)
2130 ("~" org-verbatim "" "" verbatim)
2131 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2132 "<del>" "</del>")
2134 "Special syntax for emphasized text.
2135 Text starting and ending with a special character will be emphasized, for
2136 example *bold*, _underlined_ and /italic/. This variable sets the marker
2137 characters, the face to be used by font-lock for highlighting in Org-mode
2138 Emacs buffers, and the HTML tags to be used for this.
2139 Use customize to modify this, or restart Emacs after changing it."
2140 :group 'org-font-lock
2141 :set 'org-set-emph-re
2142 :type '(repeat
2143 (list
2144 (string :tag "Marker character")
2145 (choice
2146 (face :tag "Font-lock-face")
2147 (plist :tag "Face property list"))
2148 (string :tag "HTML start tag")
2149 (string :tag "HTML end tag")
2150 (option (const verbatim)))))
2152 ;;; Miscellaneous options
2154 (defgroup org-completion nil
2155 "Completion in Org-mode."
2156 :tag "Org Completion"
2157 :group 'org)
2159 (defcustom org-completion-fallback-command 'hippie-expand
2160 "The expansion command called by \\[org-complete] in normal context.
2161 Normal means, no org-mode-specific context."
2162 :group 'org-completion
2163 :type 'function)
2165 ;;; Functions and variables from ther packages
2166 ;; Declared here to avoid compiler warnings
2168 ;; XEmacs only
2169 (defvar outline-mode-menu-heading)
2170 (defvar outline-mode-menu-show)
2171 (defvar outline-mode-menu-hide)
2172 (defvar zmacs-regions) ; XEmacs regions
2174 ;; Emacs only
2175 (defvar mark-active)
2177 ;; Various packages
2178 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2179 (declare-function calendar-forward-day "cal-move" (arg))
2180 (declare-function calendar-goto-date "cal-move" (date))
2181 (declare-function calendar-goto-today "cal-move" ())
2182 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2183 (defvar calc-embedded-close-formula)
2184 (defvar calc-embedded-open-formula)
2185 (declare-function cdlatex-tab "ext:cdlatex" ())
2186 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2187 (defvar font-lock-unfontify-region-function)
2188 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2189 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2190 (defvar iswitchb-temp-buflist)
2191 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2192 (declare-function org-agenda-skip "org-agenda" ())
2193 (declare-function org-format-agenda-item "org-agenda"
2194 (extra txt &optional category tags dotime noprefix remove-re))
2195 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2196 (declare-function org-agenda-change-all-lines "org-agenda"
2197 (newhead hdmarker &optional fixface))
2198 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2199 (declare-function org-agenda-maybe-redo "org-agenda" ())
2200 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2201 (beg end))
2202 (declare-function parse-time-string "parse-time" (string))
2203 (declare-function remember "remember" (&optional initial))
2204 (declare-function remember-buffer-desc "remember" ())
2205 (declare-function remember-finalize "remember" ())
2206 (defvar remember-save-after-remembering)
2207 (defvar remember-data-file)
2208 (defvar remember-register)
2209 (defvar remember-buffer)
2210 (defvar remember-handler-functions)
2211 (defvar remember-annotation-functions)
2212 (defvar texmathp-why)
2213 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2214 (declare-function table--at-cell-p "table" (position &optional object at-column))
2216 (defvar w3m-current-url)
2217 (defvar w3m-current-title)
2219 (defvar org-latex-regexps)
2221 ;;; Autoload and prepare some org modules
2223 ;; Some table stuff that needs to be defined here, because it is used
2224 ;; by the functions setting up org-mode or checking for table context.
2226 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2227 "Detects an org-type or table-type table.")
2228 (defconst org-table-line-regexp "^[ \t]*|"
2229 "Detects an org-type table line.")
2230 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2231 "Detects an org-type table line.")
2232 (defconst org-table-hline-regexp "^[ \t]*|-"
2233 "Detects an org-type table hline.")
2234 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2235 "Detects a table-type table hline.")
2236 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2237 "Searching from within a table (any type) this finds the first line
2238 outside the table.")
2240 ;; Autoload the functions in org-table.el that are needed by functions here.
2242 (eval-and-compile
2243 (org-autoload "org-table"
2244 '(org-table-align org-table-begin org-table-blank-field
2245 org-table-convert org-table-convert-region org-table-copy-down
2246 org-table-copy-region org-table-create
2247 org-table-create-or-convert-from-region
2248 org-table-create-with-table.el org-table-current-dline
2249 org-table-cut-region org-table-delete-column org-table-edit-field
2250 org-table-edit-formulas org-table-end org-table-eval-formula
2251 org-table-export org-table-field-info
2252 org-table-get-stored-formulas org-table-goto-column
2253 org-table-hline-and-move org-table-import org-table-insert-column
2254 org-table-insert-hline org-table-insert-row org-table-iterate
2255 org-table-justify-field-maybe org-table-kill-row
2256 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2257 org-table-move-column org-table-move-column-left
2258 org-table-move-column-right org-table-move-row
2259 org-table-move-row-down org-table-move-row-up
2260 org-table-next-field org-table-next-row org-table-paste-rectangle
2261 org-table-previous-field org-table-recalculate
2262 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2263 org-table-toggle-coordinate-overlays
2264 org-table-toggle-formula-debugger org-table-wrap-region
2265 orgtbl-mode turn-on-orgtbl)))
2267 (defun org-at-table-p (&optional table-type)
2268 "Return t if the cursor is inside an org-type table.
2269 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2270 (if org-enable-table-editor
2271 (save-excursion
2272 (beginning-of-line 1)
2273 (looking-at (if table-type org-table-any-line-regexp
2274 org-table-line-regexp)))
2275 nil))
2276 (defsubst org-table-p () (org-at-table-p))
2278 (defun org-at-table.el-p ()
2279 "Return t if and only if we are at a table.el table."
2280 (and (org-at-table-p 'any)
2281 (save-excursion
2282 (goto-char (org-table-begin 'any))
2283 (looking-at org-table1-hline-regexp))))
2284 (defun org-table-recognize-table.el ()
2285 "If there is a table.el table nearby, recognize it and move into it."
2286 (if org-table-tab-recognizes-table.el
2287 (if (org-at-table.el-p)
2288 (progn
2289 (beginning-of-line 1)
2290 (if (looking-at org-table-dataline-regexp)
2292 (if (looking-at org-table1-hline-regexp)
2293 (progn
2294 (beginning-of-line 2)
2295 (if (looking-at org-table-any-border-regexp)
2296 (beginning-of-line -1)))))
2297 (if (re-search-forward "|" (org-table-end t) t)
2298 (progn
2299 (require 'table)
2300 (if (table--at-cell-p (point))
2302 (message "recognizing table.el table...")
2303 (table-recognize-table)
2304 (message "recognizing table.el table...done")))
2305 (error "This should not happen..."))
2307 nil)
2308 nil))
2310 (defun org-at-table-hline-p ()
2311 "Return t if the cursor is inside a hline in a table."
2312 (if org-enable-table-editor
2313 (save-excursion
2314 (beginning-of-line 1)
2315 (looking-at org-table-hline-regexp))
2316 nil))
2318 (defvar org-table-clean-did-remove-column nil)
2320 (defun org-table-map-tables (function)
2321 "Apply FUNCTION to the start of all tables in the buffer."
2322 (save-excursion
2323 (save-restriction
2324 (widen)
2325 (goto-char (point-min))
2326 (while (re-search-forward org-table-any-line-regexp nil t)
2327 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2328 (beginning-of-line 1)
2329 (if (looking-at org-table-line-regexp)
2330 (save-excursion (funcall function)))
2331 (re-search-forward org-table-any-border-regexp nil 1))))
2332 (message "Mapping tables: done"))
2334 ;; Declare and autoload functions from org-exp.el
2336 (declare-function org-default-export-plist "org-exp")
2337 (declare-function org-infile-export-plist "org-exp")
2338 (declare-function org-get-current-options "org-exp")
2339 (eval-and-compile
2340 (org-autoload "org-exp"
2341 '(org-export org-export-as-ascii org-export-visible
2342 org-insert-export-options-template org-export-as-html-and-open
2343 org-export-as-html-batch org-export-as-html-to-buffer
2344 org-replace-region-by-html org-export-region-as-html
2345 org-export-as-html org-export-icalendar-this-file
2346 org-export-icalendar-all-agenda-files
2347 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2349 ;; Declare and autoload functions from org-exp.el
2351 (eval-and-compile
2352 (org-autoload "org-exp"
2353 '(org-agenda org-agenda-list org-search-view
2354 org-todo-list org-tags-view org-agenda-list-stuck-projects
2355 org-diary org-agenda-to-appt)))
2357 ;; Autoload org-remember
2359 (eval-and-compile
2360 (org-autoload "org-remember"
2361 '(org-remember-insinuate org-remember-annotation
2362 org-remember-apply-template org-remember org-remember-handler)))
2364 ;; Autoload org-clock.el
2367 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2368 (beg end))
2369 (defvar org-clock-marker (make-marker)
2370 "Marker recording the last clock-in.")
2372 (eval-and-compile
2373 (org-autoload
2374 "org-clock"
2375 '(org-clock-in org-clock-out org-clock-cancel
2376 org-clock-goto org-clock-sum org-clock-display
2377 org-remove-clock-overlays org-clock-report
2378 org-clocktable-shift org-dblock-write:clocktable
2379 org-get-clocktable)))
2381 (defun org-clock-update-time-maybe ()
2382 "If this is a CLOCK line, update it and return t.
2383 Otherwise, return nil."
2384 (interactive)
2385 (save-excursion
2386 (beginning-of-line 1)
2387 (skip-chars-forward " \t")
2388 (when (looking-at org-clock-string)
2389 (let ((re (concat "[ \t]*" org-clock-string
2390 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2391 "\\([ \t]*=>.*\\)?"))
2392 ts te h m s)
2393 (if (not (looking-at re))
2395 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2396 (end-of-line 1)
2397 (setq ts (match-string 1)
2398 te (match-string 2))
2399 (setq s (- (time-to-seconds
2400 (apply 'encode-time (org-parse-time-string te)))
2401 (time-to-seconds
2402 (apply 'encode-time (org-parse-time-string ts))))
2403 h (floor (/ s 3600))
2404 s (- s (* 3600 h))
2405 m (floor (/ s 60))
2406 s (- s (* 60 s)))
2407 (insert " => " (format "%2d:%02d" h m))
2408 t)))))
2410 (defun org-check-running-clock ()
2411 "Check if the current buffer contains the running clock.
2412 If yes, offer to stop it and to save the buffer with the changes."
2413 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2414 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2415 (buffer-name))))
2416 (org-clock-out)
2417 (when (y-or-n-p "Save changed buffer?")
2418 (save-buffer))))
2420 (defun org-clocktable-try-shift (dir n)
2421 "Check if this line starts a clock table, if yes, shift the time block."
2422 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2423 (org-clocktable-shift dir n)))
2425 ;; Autoload archiving code
2426 ;; The stuff that is needed for cycling and tags has to be defined here.
2428 (defgroup org-archive nil
2429 "Options concerning archiving in Org-mode."
2430 :tag "Org Archive"
2431 :group 'org-structure)
2433 (defcustom org-archive-location "%s_archive::"
2434 "The location where subtrees should be archived.
2436 Otherwise, the value of this variable is a string, consisting of two
2437 parts, separated by a double-colon.
2439 The first part is a file name - when omitted, archiving happens in the same
2440 file. %s will be replaced by the current file name (without directory part).
2441 Archiving to a different file is useful to keep archived entries from
2442 contributing to the Org-mode Agenda.
2444 The part after the double colon is a headline. The archived entries will be
2445 filed under that headline. When omitted, the subtrees are simply filed away
2446 at the end of the file, as top-level entries.
2448 Here are a few examples:
2449 \"%s_archive::\"
2450 If the current file is Projects.org, archive in file
2451 Projects.org_archive, as top-level trees. This is the default.
2453 \"::* Archived Tasks\"
2454 Archive in the current file, under the top-level headline
2455 \"* Archived Tasks\".
2457 \"~/org/archive.org::\"
2458 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2460 \"basement::** Finished Tasks\"
2461 Archive in file ./basement (relative path), as level 3 trees
2462 below the level 2 heading \"** Finished Tasks\".
2464 You may set this option on a per-file basis by adding to the buffer a
2465 line like
2467 #+ARCHIVE: basement::** Finished Tasks
2469 You may also define it locally for a subtree by setting an ARCHIVE property
2470 in the entry. If such a property is found in an entry, or anywhere up
2471 the hierarchy, it will be used."
2472 :group 'org-archive
2473 :type 'string)
2475 (defcustom org-archive-tag "ARCHIVE"
2476 "The tag that marks a subtree as archived.
2477 An archived subtree does not open during visibility cycling, and does
2478 not contribute to the agenda listings.
2479 After changing this, font-lock must be restarted in the relevant buffers to
2480 get the proper fontification."
2481 :group 'org-archive
2482 :group 'org-keywords
2483 :type 'string)
2485 (defcustom org-agenda-skip-archived-trees t
2486 "Non-nil means, the agenda will skip any items located in archived trees.
2487 An archived tree is a tree marked with the tag ARCHIVE."
2488 :group 'org-archive
2489 :group 'org-agenda-skip
2490 :type 'boolean)
2492 (defcustom org-cycle-open-archived-trees nil
2493 "Non-nil means, `org-cycle' will open archived trees.
2494 An archived tree is a tree marked with the tag ARCHIVE.
2495 When nil, archived trees will stay folded. You can still open them with
2496 normal outline commands like `show-all', but not with the cycling commands."
2497 :group 'org-archive
2498 :group 'org-cycle
2499 :type 'boolean)
2501 (defcustom org-sparse-tree-open-archived-trees nil
2502 "Non-nil means sparse tree construction shows matches in archived trees.
2503 When nil, matches in these trees are highlighted, but the trees are kept in
2504 collapsed state."
2505 :group 'org-archive
2506 :group 'org-sparse-trees
2507 :type 'boolean)
2509 (defun org-cycle-hide-archived-subtrees (state)
2510 "Re-hide all archived subtrees after a visibility state change."
2511 (when (and (not org-cycle-open-archived-trees)
2512 (not (memq state '(overview folded))))
2513 (save-excursion
2514 (let* ((globalp (memq state '(contents all)))
2515 (beg (if globalp (point-min) (point)))
2516 (end (if globalp (point-max) (org-end-of-subtree t))))
2517 (org-hide-archived-subtrees beg end)
2518 (goto-char beg)
2519 (if (looking-at (concat ".*:" org-archive-tag ":"))
2520 (message "%s" (substitute-command-keys
2521 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2523 (defun org-force-cycle-archived ()
2524 "Cycle subtree even if it is archived."
2525 (interactive)
2526 (setq this-command 'org-cycle)
2527 (let ((org-cycle-open-archived-trees t))
2528 (call-interactively 'org-cycle)))
2530 (defun org-hide-archived-subtrees (beg end)
2531 "Re-hide all archived subtrees after a visibility state change."
2532 (save-excursion
2533 (let* ((re (concat ":" org-archive-tag ":")))
2534 (goto-char beg)
2535 (while (re-search-forward re end t)
2536 (and (org-on-heading-p) (hide-subtree))
2537 (org-end-of-subtree t)))))
2539 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2541 (eval-and-compile
2542 (org-autoload "org-archive"
2543 '(org-add-archive-files org-archive-subtree
2544 org-archive-to-archive-sibling org-toggle-archive-tag)))
2546 ;; Autoload Column View Code
2548 (declare-function org-columns-number-to-string "org-colview")
2549 (declare-function org-columns-get-format-and-top-level "org-colview")
2550 (declare-function org-columns-compute "org-colview")
2552 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2553 '(org-columns-number-to-string org-columns-get-format-and-top-level
2554 org-columns-compute org-agenda-columns org-columns-remove-overlays
2555 org-columns org-insert-columns-dblock))
2557 ;;; Variables for pre-computed regular expressions, all buffer local
2559 (defvar org-drawer-regexp nil
2560 "Matches first line of a hidden block.")
2561 (make-variable-buffer-local 'org-drawer-regexp)
2562 (defvar org-todo-regexp nil
2563 "Matches any of the TODO state keywords.")
2564 (make-variable-buffer-local 'org-todo-regexp)
2565 (defvar org-not-done-regexp nil
2566 "Matches any of the TODO state keywords except the last one.")
2567 (make-variable-buffer-local 'org-not-done-regexp)
2568 (defvar org-todo-line-regexp nil
2569 "Matches a headline and puts TODO state into group 2 if present.")
2570 (make-variable-buffer-local 'org-todo-line-regexp)
2571 (defvar org-complex-heading-regexp nil
2572 "Matches a headline and puts everything into groups:
2573 group 1: the stars
2574 group 2: The todo keyword, maybe
2575 group 3: Priority cookie
2576 group 4: True headline
2577 group 5: Tags")
2578 (make-variable-buffer-local 'org-complex-heading-regexp)
2579 (defvar org-todo-line-tags-regexp nil
2580 "Matches a headline and puts TODO state into group 2 if present.
2581 Also put tags into group 4 if tags are present.")
2582 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2583 (defvar org-nl-done-regexp nil
2584 "Matches newline followed by a headline with the DONE keyword.")
2585 (make-variable-buffer-local 'org-nl-done-regexp)
2586 (defvar org-looking-at-done-regexp nil
2587 "Matches the DONE keyword a point.")
2588 (make-variable-buffer-local 'org-looking-at-done-regexp)
2589 (defvar org-ds-keyword-length 12
2590 "Maximum length of the Deadline and SCHEDULED keywords.")
2591 (make-variable-buffer-local 'org-ds-keyword-length)
2592 (defvar org-deadline-regexp nil
2593 "Matches the DEADLINE keyword.")
2594 (make-variable-buffer-local 'org-deadline-regexp)
2595 (defvar org-deadline-time-regexp nil
2596 "Matches the DEADLINE keyword together with a time stamp.")
2597 (make-variable-buffer-local 'org-deadline-time-regexp)
2598 (defvar org-deadline-line-regexp nil
2599 "Matches the DEADLINE keyword and the rest of the line.")
2600 (make-variable-buffer-local 'org-deadline-line-regexp)
2601 (defvar org-scheduled-regexp nil
2602 "Matches the SCHEDULED keyword.")
2603 (make-variable-buffer-local 'org-scheduled-regexp)
2604 (defvar org-scheduled-time-regexp nil
2605 "Matches the SCHEDULED keyword together with a time stamp.")
2606 (make-variable-buffer-local 'org-scheduled-time-regexp)
2607 (defvar org-closed-time-regexp nil
2608 "Matches the CLOSED keyword together with a time stamp.")
2609 (make-variable-buffer-local 'org-closed-time-regexp)
2611 (defvar org-keyword-time-regexp nil
2612 "Matches any of the 4 keywords, together with the time stamp.")
2613 (make-variable-buffer-local 'org-keyword-time-regexp)
2614 (defvar org-keyword-time-not-clock-regexp nil
2615 "Matches any of the 3 keywords, together with the time stamp.")
2616 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2617 (defvar org-maybe-keyword-time-regexp nil
2618 "Matches a timestamp, possibly preceeded by a keyword.")
2619 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2620 (defvar org-planning-or-clock-line-re nil
2621 "Matches a line with planning or clock info.")
2622 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2624 (defconst org-plain-time-of-day-regexp
2625 (concat
2626 "\\(\\<[012]?[0-9]"
2627 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2628 "\\(--?"
2629 "\\(\\<[012]?[0-9]"
2630 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2631 "\\)?")
2632 "Regular expression to match a plain time or time range.
2633 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2634 groups carry important information:
2635 0 the full match
2636 1 the first time, range or not
2637 8 the second time, if it is a range.")
2639 (defconst org-plain-time-extension-regexp
2640 (concat
2641 "\\(\\<[012]?[0-9]"
2642 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2643 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2644 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2645 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2646 groups carry important information:
2647 0 the full match
2648 7 hours of duration
2649 9 minutes of duration")
2651 (defconst org-stamp-time-of-day-regexp
2652 (concat
2653 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2654 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2655 "\\(--?"
2656 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2657 "Regular expression to match a timestamp time or time range.
2658 After a match, the following groups carry important information:
2659 0 the full match
2660 1 date plus weekday, for backreferencing to make sure both times on same day
2661 2 the first time, range or not
2662 4 the second time, if it is a range.")
2664 (defconst org-startup-options
2665 '(("fold" org-startup-folded t)
2666 ("overview" org-startup-folded t)
2667 ("nofold" org-startup-folded nil)
2668 ("showall" org-startup-folded nil)
2669 ("content" org-startup-folded content)
2670 ("hidestars" org-hide-leading-stars t)
2671 ("showstars" org-hide-leading-stars nil)
2672 ("odd" org-odd-levels-only t)
2673 ("oddeven" org-odd-levels-only nil)
2674 ("align" org-startup-align-all-tables t)
2675 ("noalign" org-startup-align-all-tables nil)
2676 ("customtime" org-display-custom-times t)
2677 ("logdone" org-log-done time)
2678 ("lognotedone" org-log-done note)
2679 ("nologdone" org-log-done nil)
2680 ("lognoteclock-out" org-log-note-clock-out t)
2681 ("nolognoteclock-out" org-log-note-clock-out nil)
2682 ("logrepeat" org-log-repeat state)
2683 ("lognoterepeat" org-log-repeat note)
2684 ("nologrepeat" org-log-repeat nil)
2685 ("constcgs" constants-unit-system cgs)
2686 ("constSI" constants-unit-system SI))
2687 "Variable associated with STARTUP options for org-mode.
2688 Each element is a list of three items: The startup options as written
2689 in the #+STARTUP line, the corresponding variable, and the value to
2690 set this variable to if the option is found. An optional forth element PUSH
2691 means to push this value onto the list in the variable.")
2693 (defun org-set-regexps-and-options ()
2694 "Precompute regular expressions for current buffer."
2695 (when (org-mode-p)
2696 (org-set-local 'org-todo-kwd-alist nil)
2697 (org-set-local 'org-todo-key-alist nil)
2698 (org-set-local 'org-todo-key-trigger nil)
2699 (org-set-local 'org-todo-keywords-1 nil)
2700 (org-set-local 'org-done-keywords nil)
2701 (org-set-local 'org-todo-heads nil)
2702 (org-set-local 'org-todo-sets nil)
2703 (org-set-local 'org-todo-log-states nil)
2704 (let ((re (org-make-options-regexp
2705 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2706 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2707 "CONSTANTS" "PROPERTY" "DRAWERS")))
2708 (splitre "[ \t]+")
2709 kwds kws0 kwsa key log value cat arch tags const links hw dws
2710 tail sep kws1 prio props drawers)
2711 (save-excursion
2712 (save-restriction
2713 (widen)
2714 (goto-char (point-min))
2715 (while (re-search-forward re nil t)
2716 (setq key (match-string 1) value (org-match-string-no-properties 2))
2717 (cond
2718 ((equal key "CATEGORY")
2719 (if (string-match "[ \t]+$" value)
2720 (setq value (replace-match "" t t value)))
2721 (setq cat value))
2722 ((member key '("SEQ_TODO" "TODO"))
2723 (push (cons 'sequence (org-split-string value splitre)) kwds))
2724 ((equal key "TYP_TODO")
2725 (push (cons 'type (org-split-string value splitre)) kwds))
2726 ((equal key "TAGS")
2727 (setq tags (append tags (org-split-string value splitre))))
2728 ((equal key "COLUMNS")
2729 (org-set-local 'org-columns-default-format value))
2730 ((equal key "LINK")
2731 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2732 (push (cons (match-string 1 value)
2733 (org-trim (match-string 2 value)))
2734 links)))
2735 ((equal key "PRIORITIES")
2736 (setq prio (org-split-string value " +")))
2737 ((equal key "PROPERTY")
2738 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2739 (push (cons (match-string 1 value) (match-string 2 value))
2740 props)))
2741 ((equal key "DRAWERS")
2742 (setq drawers (org-split-string value splitre)))
2743 ((equal key "CONSTANTS")
2744 (setq const (append const (org-split-string value splitre))))
2745 ((equal key "STARTUP")
2746 (let ((opts (org-split-string value splitre))
2747 l var val)
2748 (while (setq l (pop opts))
2749 (when (setq l (assoc l org-startup-options))
2750 (setq var (nth 1 l) val (nth 2 l))
2751 (if (not (nth 3 l))
2752 (set (make-local-variable var) val)
2753 (if (not (listp (symbol-value var)))
2754 (set (make-local-variable var) nil))
2755 (set (make-local-variable var) (symbol-value var))
2756 (add-to-list var val))))))
2757 ((equal key "ARCHIVE")
2758 (string-match " *$" value)
2759 (setq arch (replace-match "" t t value))
2760 (remove-text-properties 0 (length arch)
2761 '(face t fontified t) arch)))
2763 (when cat
2764 (org-set-local 'org-category (intern cat))
2765 (push (cons "CATEGORY" cat) props))
2766 (when prio
2767 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2768 (setq prio (mapcar 'string-to-char prio))
2769 (org-set-local 'org-highest-priority (nth 0 prio))
2770 (org-set-local 'org-lowest-priority (nth 1 prio))
2771 (org-set-local 'org-default-priority (nth 2 prio)))
2772 (and props (org-set-local 'org-local-properties (nreverse props)))
2773 (and drawers (org-set-local 'org-drawers drawers))
2774 (and arch (org-set-local 'org-archive-location arch))
2775 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2776 ;; Process the TODO keywords
2777 (unless kwds
2778 ;; Use the global values as if they had been given locally.
2779 (setq kwds (default-value 'org-todo-keywords))
2780 (if (stringp (car kwds))
2781 (setq kwds (list (cons org-todo-interpretation
2782 (default-value 'org-todo-keywords)))))
2783 (setq kwds (reverse kwds)))
2784 (setq kwds (nreverse kwds))
2785 (let (inter kws kw)
2786 (while (setq kws (pop kwds))
2787 (setq inter (pop kws) sep (member "|" kws)
2788 kws0 (delete "|" (copy-sequence kws))
2789 kwsa nil
2790 kws1 (mapcar
2791 (lambda (x)
2792 ;; 1 2
2793 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2794 (progn
2795 (setq kw (match-string 1 x)
2796 key (and (match-end 2) (match-string 2 x))
2797 log (org-extract-log-state-settings x))
2798 (push (cons kw (and key (string-to-char key))) kwsa)
2799 (and log (push log org-todo-log-states))
2801 (error "Invalid TODO keyword %s" x)))
2802 kws0)
2803 kwsa (if kwsa (append '((:startgroup))
2804 (nreverse kwsa)
2805 '((:endgroup))))
2806 hw (car kws1)
2807 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2808 tail (list inter hw (car dws) (org-last dws)))
2809 (add-to-list 'org-todo-heads hw 'append)
2810 (push kws1 org-todo-sets)
2811 (setq org-done-keywords (append org-done-keywords dws nil))
2812 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2813 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2814 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2815 (setq org-todo-sets (nreverse org-todo-sets)
2816 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2817 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2818 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2819 ;; Process the constants
2820 (when const
2821 (let (e cst)
2822 (while (setq e (pop const))
2823 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2824 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2825 (setq org-table-formula-constants-local cst)))
2827 ;; Process the tags.
2828 (when tags
2829 (let (e tgs)
2830 (while (setq e (pop tags))
2831 (cond
2832 ((equal e "{") (push '(:startgroup) tgs))
2833 ((equal e "}") (push '(:endgroup) tgs))
2834 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2835 (push (cons (match-string 1 e)
2836 (string-to-char (match-string 2 e)))
2837 tgs))
2838 (t (push (list e) tgs))))
2839 (org-set-local 'org-tag-alist nil)
2840 (while (setq e (pop tgs))
2841 (or (and (stringp (car e))
2842 (assoc (car e) org-tag-alist))
2843 (push e org-tag-alist))))))
2845 ;; Compute the regular expressions and other local variables
2846 (if (not org-done-keywords)
2847 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2848 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2849 (length org-scheduled-string)
2850 (length org-clock-string)
2851 (length org-closed-string)))
2852 org-drawer-regexp
2853 (concat "^[ \t]*:\\("
2854 (mapconcat 'regexp-quote org-drawers "\\|")
2855 "\\):[ \t]*$")
2856 org-not-done-keywords
2857 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2858 org-todo-regexp
2859 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2860 "\\|") "\\)\\>")
2861 org-not-done-regexp
2862 (concat "\\<\\("
2863 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2864 "\\)\\>")
2865 org-todo-line-regexp
2866 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2867 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2868 "\\)\\>\\)?[ \t]*\\(.*\\)")
2869 org-complex-heading-regexp
2870 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2871 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2872 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2873 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2874 org-nl-done-regexp
2875 (concat "\n\\*+[ \t]+"
2876 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2877 "\\)" "\\>")
2878 org-todo-line-tags-regexp
2879 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2880 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2881 (org-re
2882 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2883 org-looking-at-done-regexp
2884 (concat "^" "\\(?:"
2885 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2886 "\\>")
2887 org-deadline-regexp (concat "\\<" org-deadline-string)
2888 org-deadline-time-regexp
2889 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2890 org-deadline-line-regexp
2891 (concat "\\<\\(" org-deadline-string "\\).*")
2892 org-scheduled-regexp
2893 (concat "\\<" org-scheduled-string)
2894 org-scheduled-time-regexp
2895 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2896 org-closed-time-regexp
2897 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2898 org-keyword-time-regexp
2899 (concat "\\<\\(" org-scheduled-string
2900 "\\|" org-deadline-string
2901 "\\|" org-closed-string
2902 "\\|" org-clock-string "\\)"
2903 " *[[<]\\([^]>]+\\)[]>]")
2904 org-keyword-time-not-clock-regexp
2905 (concat "\\<\\(" org-scheduled-string
2906 "\\|" org-deadline-string
2907 "\\|" org-closed-string
2908 "\\)"
2909 " *[[<]\\([^]>]+\\)[]>]")
2910 org-maybe-keyword-time-regexp
2911 (concat "\\(\\<\\(" org-scheduled-string
2912 "\\|" org-deadline-string
2913 "\\|" org-closed-string
2914 "\\|" org-clock-string "\\)\\)?"
2915 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2916 org-planning-or-clock-line-re
2917 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2918 "\\|" org-deadline-string
2919 "\\|" org-closed-string "\\|" org-clock-string
2920 "\\)\\>\\)")
2922 (org-compute-latex-and-specials-regexp)
2923 (org-set-font-lock-defaults)))
2925 (defun org-extract-log-state-settings (x)
2926 "Extract the log state setting from a TODO keyword string.
2927 This will extract info from a string like \"WAIT(w@/!)\"."
2928 (let (kw key log1 log2)
2929 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2930 (setq kw (match-string 1 x)
2931 key (and (match-end 2) (match-string 2 x))
2932 log1 (and (match-end 3) (match-string 3 x))
2933 log2 (and (match-end 4) (match-string 4 x)))
2934 (and (or log1 log2)
2935 (list kw
2936 (and log1 (if (equal log1 "!") 'time 'note))
2937 (and log2 (if (equal log2 "!") 'time 'note)))))))
2939 (defun org-remove-keyword-keys (list)
2940 "Remove a pair of parenthesis at the end of each string in LIST."
2941 (mapcar (lambda (x)
2942 (if (string-match "(.*)$" x)
2943 (substring x 0 (match-beginning 0))
2945 list))
2947 ;; FIXME: this could be done much better, using second characters etc.
2948 (defun org-assign-fast-keys (alist)
2949 "Assign fast keys to a keyword-key alist.
2950 Respect keys that are already there."
2951 (let (new e k c c1 c2 (char ?a))
2952 (while (setq e (pop alist))
2953 (cond
2954 ((equal e '(:startgroup)) (push e new))
2955 ((equal e '(:endgroup)) (push e new))
2957 (setq k (car e) c2 nil)
2958 (if (cdr e)
2959 (setq c (cdr e))
2960 ;; automatically assign a character.
2961 (setq c1 (string-to-char
2962 (downcase (substring
2963 k (if (= (string-to-char k) ?@) 1 0)))))
2964 (if (or (rassoc c1 new) (rassoc c1 alist))
2965 (while (or (rassoc char new) (rassoc char alist))
2966 (setq char (1+ char)))
2967 (setq c2 c1))
2968 (setq c (or c2 char)))
2969 (push (cons k c) new))))
2970 (nreverse new)))
2972 ;;; Some variables used in various places
2974 (defvar org-window-configuration nil
2975 "Used in various places to store a window configuration.")
2976 (defvar org-finish-function nil
2977 "Function to be called when `C-c C-c' is used.
2978 This is for getting out of special buffers like remember.")
2981 ;; FIXME: Occasionally check by commenting these, to make sure
2982 ;; no other functions uses these, forgetting to let-bind them.
2983 (defvar entry)
2984 (defvar state)
2985 (defvar last-state)
2986 (defvar date)
2987 (defvar description)
2989 ;; Defined somewhere in this file, but used before definition.
2990 (defvar org-html-entities)
2991 (defvar org-struct-menu)
2992 (defvar org-org-menu)
2993 (defvar org-tbl-menu)
2994 (defvar org-agenda-keymap)
2996 ;;;; Define the Org-mode
2998 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2999 (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."))
3002 ;; We use a before-change function to check if a table might need
3003 ;; an update.
3004 (defvar org-table-may-need-update t
3005 "Indicates that a table might need an update.
3006 This variable is set by `org-before-change-function'.
3007 `org-table-align' sets it back to nil.")
3008 (defun org-before-change-function (beg end)
3009 "Every change indicates that a table might need an update."
3010 (setq org-table-may-need-update t))
3011 (defvar org-mode-map)
3012 (defvar org-mode-hook nil)
3013 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3014 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3015 (defvar org-table-buffer-is-an nil)
3016 (defconst org-outline-regexp "\\*+ ")
3018 ;;;###autoload
3019 (define-derived-mode org-mode outline-mode "Org"
3020 "Outline-based notes management and organizer, alias
3021 \"Carsten's outline-mode for keeping track of everything.\"
3023 Org-mode develops organizational tasks around a NOTES file which
3024 contains information about projects as plain text. Org-mode is
3025 implemented on top of outline-mode, which is ideal to keep the content
3026 of large files well structured. It supports ToDo items, deadlines and
3027 time stamps, which magically appear in the diary listing of the Emacs
3028 calendar. Tables are easily created with a built-in table editor.
3029 Plain text URL-like links connect to websites, emails (VM), Usenet
3030 messages (Gnus), BBDB entries, and any files related to the project.
3031 For printing and sharing of notes, an Org-mode file (or a part of it)
3032 can be exported as a structured ASCII or HTML file.
3034 The following commands are available:
3036 \\{org-mode-map}"
3038 ;; Get rid of Outline menus, they are not needed
3039 ;; Need to do this here because define-derived-mode sets up
3040 ;; the keymap so late. Still, it is a waste to call this each time
3041 ;; we switch another buffer into org-mode.
3042 (if (featurep 'xemacs)
3043 (when (boundp 'outline-mode-menu-heading)
3044 ;; Assume this is Greg's port, it used easymenu
3045 (easy-menu-remove outline-mode-menu-heading)
3046 (easy-menu-remove outline-mode-menu-show)
3047 (easy-menu-remove outline-mode-menu-hide))
3048 (define-key org-mode-map [menu-bar headings] 'undefined)
3049 (define-key org-mode-map [menu-bar hide] 'undefined)
3050 (define-key org-mode-map [menu-bar show] 'undefined))
3052 (org-load-modules-maybe)
3053 (easy-menu-add org-org-menu)
3054 (easy-menu-add org-tbl-menu)
3055 (org-install-agenda-files-menu)
3056 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3057 (org-add-to-invisibility-spec '(org-cwidth))
3058 (when (featurep 'xemacs)
3059 (org-set-local 'line-move-ignore-invisible t))
3060 (org-set-local 'outline-regexp org-outline-regexp)
3061 (org-set-local 'outline-level 'org-outline-level)
3062 (when (and org-ellipsis
3063 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3064 (fboundp 'make-glyph-code))
3065 (unless org-display-table
3066 (setq org-display-table (make-display-table)))
3067 (set-display-table-slot
3068 org-display-table 4
3069 (vconcat (mapcar
3070 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3071 org-ellipsis)))
3072 (if (stringp org-ellipsis) org-ellipsis "..."))))
3073 (setq buffer-display-table org-display-table))
3074 (org-set-regexps-and-options)
3075 ;; Calc embedded
3076 (org-set-local 'calc-embedded-open-mode "# ")
3077 (modify-syntax-entry ?# "<")
3078 (modify-syntax-entry ?@ "w")
3079 (if org-startup-truncated (setq truncate-lines t))
3080 (org-set-local 'font-lock-unfontify-region-function
3081 'org-unfontify-region)
3082 ;; Activate before-change-function
3083 (org-set-local 'org-table-may-need-update t)
3084 (org-add-hook 'before-change-functions 'org-before-change-function nil
3085 'local)
3086 ;; Check for running clock before killing a buffer
3087 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3088 ;; Paragraphs and auto-filling
3089 (org-set-autofill-regexps)
3090 (setq indent-line-function 'org-indent-line-function)
3091 (org-update-radio-target-regexp)
3093 ;; Comment characters
3094 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3095 (org-set-local 'comment-padding " ")
3097 ;; Align options lines
3098 (org-set-local
3099 'align-mode-rules-list
3100 '((org-in-buffer-settings
3101 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3102 (modes . '(org-mode)))))
3104 ;; Imenu
3105 (org-set-local 'imenu-create-index-function
3106 'org-imenu-get-tree)
3108 ;; Make isearch reveal context
3109 (if (or (featurep 'xemacs)
3110 (not (boundp 'outline-isearch-open-invisible-function)))
3111 ;; Emacs 21 and XEmacs make use of the hook
3112 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3113 ;; Emacs 22 deals with this through a special variable
3114 (org-set-local 'outline-isearch-open-invisible-function
3115 (lambda (&rest ignore) (org-show-context 'isearch))))
3117 ;; If empty file that did not turn on org-mode automatically, make it to.
3118 (if (and org-insert-mode-line-in-empty-file
3119 (interactive-p)
3120 (= (point-min) (point-max)))
3121 (insert "# -*- mode: org -*-\n\n"))
3123 (unless org-inhibit-startup
3124 (when org-startup-align-all-tables
3125 (let ((bmp (buffer-modified-p)))
3126 (org-table-map-tables 'org-table-align)
3127 (set-buffer-modified-p bmp)))
3128 (org-cycle-hide-drawers 'all)
3129 (cond
3130 ((eq org-startup-folded t)
3131 (org-cycle '(4)))
3132 ((eq org-startup-folded 'content)
3133 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3134 (org-cycle '(4)) (org-cycle '(4)))))))
3136 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3138 (defun org-current-time ()
3139 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3140 (if (> (car org-time-stamp-rounding-minutes) 1)
3141 (let ((r (car org-time-stamp-rounding-minutes))
3142 (time (decode-time)))
3143 (apply 'encode-time
3144 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3145 (nthcdr 2 time))))
3146 (current-time)))
3148 ;;;; Font-Lock stuff, including the activators
3150 (defvar org-mouse-map (make-sparse-keymap))
3151 (org-defkey org-mouse-map
3152 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3153 (org-defkey org-mouse-map
3154 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3155 (when org-mouse-1-follows-link
3156 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3157 (when org-tab-follows-link
3158 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3159 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3160 (when org-return-follows-link
3161 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3162 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3164 (require 'font-lock)
3166 (defconst org-non-link-chars "]\t\n\r<>")
3167 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3168 "shell" "elisp"))
3169 (defvar org-link-types-re nil
3170 "Matches a link that has a url-like prefix like \"http:\"")
3171 (defvar org-link-re-with-space nil
3172 "Matches a link with spaces, optional angular brackets around it.")
3173 (defvar org-link-re-with-space2 nil
3174 "Matches a link with spaces, optional angular brackets around it.")
3175 (defvar org-angle-link-re nil
3176 "Matches link with angular brackets, spaces are allowed.")
3177 (defvar org-plain-link-re nil
3178 "Matches plain link, without spaces.")
3179 (defvar org-bracket-link-regexp nil
3180 "Matches a link in double brackets.")
3181 (defvar org-bracket-link-analytic-regexp nil
3182 "Regular expression used to analyze links.
3183 Here is what the match groups contain after a match:
3184 1: http:
3185 2: http
3186 3: path
3187 4: [desc]
3188 5: desc")
3189 (defvar org-any-link-re nil
3190 "Regular expression matching any link.")
3192 (defun org-make-link-regexps ()
3193 "Update the link regular expressions.
3194 This should be called after the variable `org-link-types' has changed."
3195 (setq org-link-types-re
3196 (concat
3197 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3198 org-link-re-with-space
3199 (concat
3200 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3201 "\\([^" org-non-link-chars " ]"
3202 "[^" org-non-link-chars "]*"
3203 "[^" org-non-link-chars " ]\\)>?")
3204 org-link-re-with-space2
3205 (concat
3206 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3207 "\\([^" org-non-link-chars " ]"
3208 "[^]\t\n\r]*"
3209 "[^" org-non-link-chars " ]\\)>?")
3210 org-angle-link-re
3211 (concat
3212 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3213 "\\([^" org-non-link-chars " ]"
3214 "[^" org-non-link-chars "]*"
3215 "\\)>")
3216 org-plain-link-re
3217 (concat
3218 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3219 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3220 org-bracket-link-regexp
3221 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3222 org-bracket-link-analytic-regexp
3223 (concat
3224 "\\[\\["
3225 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3226 "\\([^]]+\\)"
3227 "\\]"
3228 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3229 "\\]")
3230 org-any-link-re
3231 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3232 org-angle-link-re "\\)\\|\\("
3233 org-plain-link-re "\\)")))
3235 (org-make-link-regexps)
3237 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3238 "Regular expression for fast time stamp matching.")
3239 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3240 "Regular expression for fast time stamp matching.")
3241 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3242 "Regular expression matching time strings for analysis.
3243 This one does not require the space after the date, so it can be used
3244 on a string that terminates immediately after the date.")
3245 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3246 "Regular expression matching time strings for analysis.")
3247 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3248 "Regular expression matching time stamps, with groups.")
3249 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3250 "Regular expression matching time stamps (also [..]), with groups.")
3251 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3252 "Regular expression matching a time stamp range.")
3253 (defconst org-tr-regexp-both
3254 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3255 "Regular expression matching a time stamp range.")
3256 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3257 org-ts-regexp "\\)?")
3258 "Regular expression matching a time stamp or time stamp range.")
3259 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3260 org-ts-regexp-both "\\)?")
3261 "Regular expression matching a time stamp or time stamp range.
3262 The time stamps may be either active or inactive.")
3264 (defvar org-emph-face nil)
3266 (defun org-do-emphasis-faces (limit)
3267 "Run through the buffer and add overlays to links."
3268 (let (rtn)
3269 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3270 (if (not (= (char-after (match-beginning 3))
3271 (char-after (match-beginning 4))))
3272 (progn
3273 (setq rtn t)
3274 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3275 'face
3276 (nth 1 (assoc (match-string 3)
3277 org-emphasis-alist)))
3278 (add-text-properties (match-beginning 2) (match-end 2)
3279 '(font-lock-multiline t))
3280 (when org-hide-emphasis-markers
3281 (add-text-properties (match-end 4) (match-beginning 5)
3282 '(invisible org-link))
3283 (add-text-properties (match-beginning 3) (match-end 3)
3284 '(invisible org-link)))))
3285 (backward-char 1))
3286 rtn))
3288 (defun org-emphasize (&optional char)
3289 "Insert or change an emphasis, i.e. a font like bold or italic.
3290 If there is an active region, change that region to a new emphasis.
3291 If there is no region, just insert the marker characters and position
3292 the cursor between them.
3293 CHAR should be either the marker character, or the first character of the
3294 HTML tag associated with that emphasis. If CHAR is a space, the means
3295 to remove the emphasis of the selected region.
3296 If char is not given (for example in an interactive call) it
3297 will be prompted for."
3298 (interactive)
3299 (let ((eal org-emphasis-alist) e det
3300 (erc org-emphasis-regexp-components)
3301 (prompt "")
3302 (string "") beg end move tag c s)
3303 (if (org-region-active-p)
3304 (setq beg (region-beginning) end (region-end)
3305 string (buffer-substring beg end))
3306 (setq move t))
3308 (while (setq e (pop eal))
3309 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3310 c (aref tag 0))
3311 (push (cons c (string-to-char (car e))) det)
3312 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3313 (substring tag 1)))))
3314 (unless char
3315 (message "%s" (concat "Emphasis marker or tag:" prompt))
3316 (setq char (read-char-exclusive)))
3317 (setq char (or (cdr (assoc char det)) char))
3318 (if (equal char ?\ )
3319 (setq s "" move nil)
3320 (unless (assoc (char-to-string char) org-emphasis-alist)
3321 (error "No such emphasis marker: \"%c\"" char))
3322 (setq s (char-to-string char)))
3323 (while (and (> (length string) 1)
3324 (equal (substring string 0 1) (substring string -1))
3325 (assoc (substring string 0 1) org-emphasis-alist))
3326 (setq string (substring string 1 -1)))
3327 (setq string (concat s string s))
3328 (if beg (delete-region beg end))
3329 (unless (or (bolp)
3330 (string-match (concat "[" (nth 0 erc) "\n]")
3331 (char-to-string (char-before (point)))))
3332 (insert " "))
3333 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3334 (char-to-string (char-after (point))))
3335 (insert " ") (backward-char 1))
3336 (insert string)
3337 (and move (backward-char 1))))
3339 (defconst org-nonsticky-props
3340 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3343 (defun org-activate-plain-links (limit)
3344 "Run through the buffer and add overlays to links."
3345 (catch 'exit
3346 (let (f)
3347 (while (re-search-forward org-plain-link-re limit t)
3348 (setq f (get-text-property (match-beginning 0) 'face))
3349 (if (or (eq f 'org-tag)
3350 (and (listp f) (memq 'org-tag f)))
3352 (add-text-properties (match-beginning 0) (match-end 0)
3353 (list 'mouse-face 'highlight
3354 'rear-nonsticky org-nonsticky-props
3355 'keymap org-mouse-map
3357 (throw 'exit t))))))
3359 (defun org-activate-code (limit)
3360 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3361 (unless (get-text-property (match-beginning 1) 'face)
3362 (remove-text-properties (match-beginning 0) (match-end 0)
3363 '(display t invisible t intangible t))
3364 t)))
3366 (defun org-activate-angle-links (limit)
3367 "Run through the buffer and add overlays to links."
3368 (if (re-search-forward org-angle-link-re limit t)
3369 (progn
3370 (add-text-properties (match-beginning 0) (match-end 0)
3371 (list 'mouse-face 'highlight
3372 'rear-nonsticky org-nonsticky-props
3373 'keymap org-mouse-map
3375 t)))
3377 (defun org-activate-bracket-links (limit)
3378 "Run through the buffer and add overlays to bracketed links."
3379 (if (re-search-forward org-bracket-link-regexp limit t)
3380 (let* ((help (concat "LINK: "
3381 (org-match-string-no-properties 1)))
3382 ;; FIXME: above we should remove the escapes.
3383 ;; but that requires another match, protecting match data,
3384 ;; a lot of overhead for font-lock.
3385 (ip (org-maybe-intangible
3386 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3387 'keymap org-mouse-map 'mouse-face 'highlight
3388 'font-lock-multiline t 'help-echo help)))
3389 (vp (list 'rear-nonsticky org-nonsticky-props
3390 'keymap org-mouse-map 'mouse-face 'highlight
3391 ' font-lock-multiline t 'help-echo help)))
3392 ;; We need to remove the invisible property here. Table narrowing
3393 ;; may have made some of this invisible.
3394 (remove-text-properties (match-beginning 0) (match-end 0)
3395 '(invisible nil))
3396 (if (match-end 3)
3397 (progn
3398 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3399 (add-text-properties (match-beginning 3) (match-end 3) vp)
3400 (add-text-properties (match-end 3) (match-end 0) ip))
3401 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3402 (add-text-properties (match-beginning 1) (match-end 1) vp)
3403 (add-text-properties (match-end 1) (match-end 0) ip))
3404 t)))
3406 (defun org-activate-dates (limit)
3407 "Run through the buffer and add overlays to dates."
3408 (if (re-search-forward org-tsr-regexp-both limit t)
3409 (progn
3410 (add-text-properties (match-beginning 0) (match-end 0)
3411 (list 'mouse-face 'highlight
3412 'rear-nonsticky org-nonsticky-props
3413 'keymap org-mouse-map))
3414 (when org-display-custom-times
3415 (if (match-end 3)
3416 (org-display-custom-time (match-beginning 3) (match-end 3)))
3417 (org-display-custom-time (match-beginning 1) (match-end 1)))
3418 t)))
3420 (defvar org-target-link-regexp nil
3421 "Regular expression matching radio targets in plain text.")
3422 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3423 "Regular expression matching a link target.")
3424 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3425 "Regular expression matching a radio target.")
3426 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3427 "Regular expression matching any target.")
3429 (defun org-activate-target-links (limit)
3430 "Run through the buffer and add overlays to target matches."
3431 (when org-target-link-regexp
3432 (let ((case-fold-search t))
3433 (if (re-search-forward org-target-link-regexp limit t)
3434 (progn
3435 (add-text-properties (match-beginning 0) (match-end 0)
3436 (list 'mouse-face 'highlight
3437 'rear-nonsticky org-nonsticky-props
3438 'keymap org-mouse-map
3439 'help-echo "Radio target link"
3440 'org-linked-text t))
3441 t)))))
3443 (defun org-update-radio-target-regexp ()
3444 "Find all radio targets in this file and update the regular expression."
3445 (interactive)
3446 (when (memq 'radio org-activate-links)
3447 (setq org-target-link-regexp
3448 (org-make-target-link-regexp (org-all-targets 'radio)))
3449 (org-restart-font-lock)))
3451 (defun org-hide-wide-columns (limit)
3452 (let (s e)
3453 (setq s (text-property-any (point) (or limit (point-max))
3454 'org-cwidth t))
3455 (when s
3456 (setq e (next-single-property-change s 'org-cwidth))
3457 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3458 (goto-char e)
3459 t)))
3461 (defvar org-latex-and-specials-regexp nil
3462 "Regular expression for highlighting export special stuff.")
3463 (defvar org-match-substring-regexp)
3464 (defvar org-match-substring-with-braces-regexp)
3465 (defvar org-export-html-special-string-regexps)
3467 (defun org-compute-latex-and-specials-regexp ()
3468 "Compute regular expression for stuff treated specially by exporters."
3469 (if (not org-highlight-latex-fragments-and-specials)
3470 (org-set-local 'org-latex-and-specials-regexp nil)
3471 (require 'org-exp)
3472 (let*
3473 ((matchers (plist-get org-format-latex-options :matchers))
3474 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3475 org-latex-regexps)))
3476 (options (org-combine-plists (org-default-export-plist)
3477 (org-infile-export-plist)))
3478 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3479 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3480 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3481 (org-export-html-expand (plist-get options :expand-quoted-html))
3482 (org-export-with-special-strings (plist-get options :special-strings))
3483 (re-sub
3484 (cond
3485 ((equal org-export-with-sub-superscripts '{})
3486 (list org-match-substring-with-braces-regexp))
3487 (org-export-with-sub-superscripts
3488 (list org-match-substring-regexp))
3489 (t nil)))
3490 (re-latex
3491 (if org-export-with-LaTeX-fragments
3492 (mapcar (lambda (x) (nth 1 x)) latexs)))
3493 (re-macros
3494 (if org-export-with-TeX-macros
3495 (list (concat "\\\\"
3496 (regexp-opt
3497 (append (mapcar 'car org-html-entities)
3498 (if (boundp 'org-latex-entities)
3499 org-latex-entities nil))
3500 'words))) ; FIXME
3502 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3503 (re-special (if org-export-with-special-strings
3504 (mapcar (lambda (x) (car x))
3505 org-export-html-special-string-regexps)))
3506 (re-rest
3507 (delq nil
3508 (list
3509 (if org-export-html-expand "@<[^>\n]+>")
3510 ))))
3511 (org-set-local
3512 'org-latex-and-specials-regexp
3513 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3514 re-rest) "\\|")))))
3516 (defun org-do-latex-and-special-faces (limit)
3517 "Run through the buffer and add overlays to links."
3518 (when org-latex-and-specials-regexp
3519 (let (rtn d)
3520 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3521 limit t))
3522 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3523 'face))
3524 '(org-code org-verbatim underline)))
3525 (progn
3526 (setq rtn t
3527 d (cond ((member (char-after (1+ (match-beginning 0)))
3528 '(?_ ?^)) 1)
3529 (t 0)))
3530 (font-lock-prepend-text-property
3531 (+ d (match-beginning 0)) (match-end 0)
3532 'face 'org-latex-and-export-specials)
3533 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3534 '(font-lock-multiline t)))))
3535 rtn)))
3537 (defun org-restart-font-lock ()
3538 "Restart font-lock-mode, to force refontification."
3539 (when (and (boundp 'font-lock-mode) font-lock-mode)
3540 (font-lock-mode -1)
3541 (font-lock-mode 1)))
3543 (defun org-all-targets (&optional radio)
3544 "Return a list of all targets in this file.
3545 With optional argument RADIO, only find radio targets."
3546 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3547 rtn)
3548 (save-excursion
3549 (goto-char (point-min))
3550 (while (re-search-forward re nil t)
3551 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3552 rtn)))
3554 (defun org-make-target-link-regexp (targets)
3555 "Make regular expression matching all strings in TARGETS.
3556 The regular expression finds the targets also if there is a line break
3557 between words."
3558 (and targets
3559 (concat
3560 "\\<\\("
3561 (mapconcat
3562 (lambda (x)
3563 (while (string-match " +" x)
3564 (setq x (replace-match "\\s-+" t t x)))
3566 targets
3567 "\\|")
3568 "\\)\\>")))
3570 (defun org-activate-tags (limit)
3571 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3572 (progn
3573 (add-text-properties (match-beginning 1) (match-end 1)
3574 (list 'mouse-face 'highlight
3575 'rear-nonsticky org-nonsticky-props
3576 'keymap org-mouse-map))
3577 t)))
3579 (defun org-outline-level ()
3580 (save-excursion
3581 (looking-at outline-regexp)
3582 (if (match-beginning 1)
3583 (+ (org-get-string-indentation (match-string 1)) 1000)
3584 (1- (- (match-end 0) (match-beginning 0))))))
3586 (defvar org-font-lock-keywords nil)
3588 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3589 "Regular expression matching a property line.")
3591 (defvar org-font-lock-hook nil
3592 "Functions to be called for special font loch stuff.")
3594 (defun org-font-lock-hook (limit)
3595 (run-hook-with-args 'org-font-lock-hook limit))
3597 (defun org-set-font-lock-defaults ()
3598 (let* ((em org-fontify-emphasized-text)
3599 (lk org-activate-links)
3600 (org-font-lock-extra-keywords
3601 (list
3602 ;; Call the hook
3603 '(org-font-lock-hook)
3604 ;; Headlines
3605 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3606 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3607 ;; Table lines
3608 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3609 (1 'org-table t))
3610 ;; Table internals
3611 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3612 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3613 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3614 ;; Drawers
3615 (list org-drawer-regexp '(0 'org-special-keyword t))
3616 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3617 ;; Properties
3618 (list org-property-re
3619 '(1 'org-special-keyword t)
3620 '(3 'org-property-value t))
3621 (if org-format-transports-properties-p
3622 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3623 ;; Links
3624 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3625 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3626 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3627 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3628 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3629 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3630 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3631 '(org-hide-wide-columns (0 nil append))
3632 ;; TODO lines
3633 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3634 '(1 (org-get-todo-face 1) t))
3635 ;; DONE
3636 (if org-fontify-done-headline
3637 (list (concat "^[*]+ +\\<\\("
3638 (mapconcat 'regexp-quote org-done-keywords "\\|")
3639 "\\)\\(.*\\)")
3640 '(2 'org-headline-done t))
3641 nil)
3642 ;; Priorities
3643 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3644 ;; Special keywords
3645 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3646 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3647 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3648 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3649 ;; Emphasis
3650 (if em
3651 (if (featurep 'xemacs)
3652 '(org-do-emphasis-faces (0 nil append))
3653 '(org-do-emphasis-faces)))
3654 ;; Checkboxes
3655 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3656 2 'bold prepend)
3657 (if org-provide-checkbox-statistics
3658 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3659 (0 (org-get-checkbox-statistics-face) t)))
3660 ;; Description list items
3661 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3662 2 'bold prepend)
3663 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3664 '(1 'org-archived prepend))
3665 ;; Specials
3666 '(org-do-latex-and-special-faces)
3667 ;; Code
3668 '(org-activate-code (1 'org-code t))
3669 ;; COMMENT
3670 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3671 "\\|" org-quote-string "\\)\\>")
3672 '(1 'org-special-keyword t))
3673 '("^#.*" (0 'font-lock-comment-face t))
3675 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3676 ;; Now set the full font-lock-keywords
3677 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3678 (org-set-local 'font-lock-defaults
3679 '(org-font-lock-keywords t nil nil backward-paragraph))
3680 (kill-local-variable 'font-lock-keywords) nil))
3682 (defvar org-m nil)
3683 (defvar org-l nil)
3684 (defvar org-f nil)
3685 (defun org-get-level-face (n)
3686 "Get the right face for match N in font-lock matching of healdines."
3687 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3688 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3689 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3690 (cond
3691 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3692 ((eq n 2) org-f)
3693 (t (if org-level-color-stars-only nil org-f))))
3695 (defun org-get-todo-face (kwd)
3696 "Get the right face for a TODO keyword KWD.
3697 If KWD is a number, get the corresponding match group."
3698 (if (numberp kwd) (setq kwd (match-string kwd)))
3699 (or (cdr (assoc kwd org-todo-keyword-faces))
3700 (and (member kwd org-done-keywords) 'org-done)
3701 'org-todo))
3703 (defun org-unfontify-region (beg end &optional maybe_loudly)
3704 "Remove fontification and activation overlays from links."
3705 (font-lock-default-unfontify-region beg end)
3706 (let* ((buffer-undo-list t)
3707 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3708 (inhibit-modification-hooks t)
3709 deactivate-mark buffer-file-name buffer-file-truename)
3710 (remove-text-properties beg end
3711 '(mouse-face t keymap t org-linked-text t
3712 invisible t intangible t))))
3714 ;;;; Visibility cycling, including org-goto and indirect buffer
3716 ;;; Cycling
3718 (defvar org-cycle-global-status nil)
3719 (make-variable-buffer-local 'org-cycle-global-status)
3720 (defvar org-cycle-subtree-status nil)
3721 (make-variable-buffer-local 'org-cycle-subtree-status)
3723 ;;;###autoload
3724 (defun org-cycle (&optional arg)
3725 "Visibility cycling for Org-mode.
3727 - When this function is called with a prefix argument, rotate the entire
3728 buffer through 3 states (global cycling)
3729 1. OVERVIEW: Show only top-level headlines.
3730 2. CONTENTS: Show all headlines of all levels, but no body text.
3731 3. SHOW ALL: Show everything.
3733 - When point is at the beginning of a headline, rotate the subtree started
3734 by this line through 3 different states (local cycling)
3735 1. FOLDED: Only the main headline is shown.
3736 2. CHILDREN: The main headline and the direct children are shown.
3737 From this state, you can move to one of the children
3738 and zoom in further.
3739 3. SUBTREE: Show the entire subtree, including body text.
3741 - When there is a numeric prefix, go up to a heading with level ARG, do
3742 a `show-subtree' and return to the previous cursor position. If ARG
3743 is negative, go up that many levels.
3745 - When point is not at the beginning of a headline, execute
3746 `indent-relative', like TAB normally does. See the option
3747 `org-cycle-emulate-tab' for details.
3749 - Special case: if point is at the beginning of the buffer and there is
3750 no headline in line 1, this function will act as if called with prefix arg.
3751 But only if also the variable `org-cycle-global-at-bob' is t."
3752 (interactive "P")
3753 (org-load-modules-maybe)
3754 (let* ((outline-regexp
3755 (if (and (org-mode-p) org-cycle-include-plain-lists)
3756 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3757 outline-regexp))
3758 (bob-special (and org-cycle-global-at-bob (bobp)
3759 (not (looking-at outline-regexp))))
3760 (org-cycle-hook
3761 (if bob-special
3762 (delq 'org-optimize-window-after-visibility-change
3763 (copy-sequence org-cycle-hook))
3764 org-cycle-hook))
3765 (pos (point)))
3767 (if (or bob-special (equal arg '(4)))
3768 ;; special case: use global cycling
3769 (setq arg t))
3771 (cond
3773 ((org-at-table-p 'any)
3774 ;; Enter the table or move to the next field in the table
3775 (or (org-table-recognize-table.el)
3776 (progn
3777 (if arg (org-table-edit-field t)
3778 (org-table-justify-field-maybe)
3779 (call-interactively 'org-table-next-field)))))
3781 ((eq arg t) ;; Global cycling
3783 (cond
3784 ((and (eq last-command this-command)
3785 (eq org-cycle-global-status 'overview))
3786 ;; We just created the overview - now do table of contents
3787 ;; This can be slow in very large buffers, so indicate action
3788 (message "CONTENTS...")
3789 (org-content)
3790 (message "CONTENTS...done")
3791 (setq org-cycle-global-status 'contents)
3792 (run-hook-with-args 'org-cycle-hook 'contents))
3794 ((and (eq last-command this-command)
3795 (eq org-cycle-global-status 'contents))
3796 ;; We just showed the table of contents - now show everything
3797 (show-all)
3798 (message "SHOW ALL")
3799 (setq org-cycle-global-status 'all)
3800 (run-hook-with-args 'org-cycle-hook 'all))
3803 ;; Default action: go to overview
3804 (org-overview)
3805 (message "OVERVIEW")
3806 (setq org-cycle-global-status 'overview)
3807 (run-hook-with-args 'org-cycle-hook 'overview))))
3809 ((and org-drawers org-drawer-regexp
3810 (save-excursion
3811 (beginning-of-line 1)
3812 (looking-at org-drawer-regexp)))
3813 ;; Toggle block visibility
3814 (org-flag-drawer
3815 (not (get-char-property (match-end 0) 'invisible))))
3817 ((integerp arg)
3818 ;; Show-subtree, ARG levels up from here.
3819 (save-excursion
3820 (org-back-to-heading)
3821 (outline-up-heading (if (< arg 0) (- arg)
3822 (- (funcall outline-level) arg)))
3823 (org-show-subtree)))
3825 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3826 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3827 ;; At a heading: rotate between three different views
3828 (org-back-to-heading)
3829 (let ((goal-column 0) eoh eol eos)
3830 ;; First, some boundaries
3831 (save-excursion
3832 (org-back-to-heading)
3833 (save-excursion
3834 (beginning-of-line 2)
3835 (while (and (not (eobp)) ;; this is like `next-line'
3836 (get-char-property (1- (point)) 'invisible))
3837 (beginning-of-line 2)) (setq eol (point)))
3838 (outline-end-of-heading) (setq eoh (point))
3839 (org-end-of-subtree t)
3840 (unless (eobp)
3841 (skip-chars-forward " \t\n")
3842 (beginning-of-line 1) ; in case this is an item
3844 (setq eos (1- (point))))
3845 ;; Find out what to do next and set `this-command'
3846 (cond
3847 ((= eos eoh)
3848 ;; Nothing is hidden behind this heading
3849 (message "EMPTY ENTRY")
3850 (setq org-cycle-subtree-status nil)
3851 (save-excursion
3852 (goto-char eos)
3853 (outline-next-heading)
3854 (if (org-invisible-p) (org-flag-heading nil))))
3855 ((or (>= eol eos)
3856 (not (string-match "\\S-" (buffer-substring eol eos))))
3857 ;; Entire subtree is hidden in one line: open it
3858 (org-show-entry)
3859 (show-children)
3860 (message "CHILDREN")
3861 (save-excursion
3862 (goto-char eos)
3863 (outline-next-heading)
3864 (if (org-invisible-p) (org-flag-heading nil)))
3865 (setq org-cycle-subtree-status 'children)
3866 (run-hook-with-args 'org-cycle-hook 'children))
3867 ((and (eq last-command this-command)
3868 (eq org-cycle-subtree-status 'children))
3869 ;; We just showed the children, now show everything.
3870 (org-show-subtree)
3871 (message "SUBTREE")
3872 (setq org-cycle-subtree-status 'subtree)
3873 (run-hook-with-args 'org-cycle-hook 'subtree))
3875 ;; Default action: hide the subtree.
3876 (hide-subtree)
3877 (message "FOLDED")
3878 (setq org-cycle-subtree-status 'folded)
3879 (run-hook-with-args 'org-cycle-hook 'folded)))))
3881 ;; TAB emulation
3882 (buffer-read-only (org-back-to-heading))
3884 ((org-try-cdlatex-tab))
3886 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3887 (or (not (bolp))
3888 (not (looking-at outline-regexp))))
3889 (call-interactively (global-key-binding "\t")))
3891 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3892 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3893 (or (and (eq org-cycle-emulate-tab 'white)
3894 (= (match-end 0) (point-at-eol)))
3895 (and (eq org-cycle-emulate-tab 'whitestart)
3896 (>= (match-end 0) pos))))
3898 (eq org-cycle-emulate-tab t))
3899 (call-interactively (global-key-binding "\t")))
3901 (t (save-excursion
3902 (org-back-to-heading)
3903 (org-cycle))))))
3905 ;;;###autoload
3906 (defun org-global-cycle (&optional arg)
3907 "Cycle the global visibility. For details see `org-cycle'."
3908 (interactive "P")
3909 (let ((org-cycle-include-plain-lists
3910 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3911 (if (integerp arg)
3912 (progn
3913 (show-all)
3914 (hide-sublevels arg)
3915 (setq org-cycle-global-status 'contents))
3916 (org-cycle '(4)))))
3918 (defun org-overview ()
3919 "Switch to overview mode, shoing only top-level headlines.
3920 Really, this shows all headlines with level equal or greater than the level
3921 of the first headline in the buffer. This is important, because if the
3922 first headline is not level one, then (hide-sublevels 1) gives confusing
3923 results."
3924 (interactive)
3925 (let ((level (save-excursion
3926 (goto-char (point-min))
3927 (if (re-search-forward (concat "^" outline-regexp) nil t)
3928 (progn
3929 (goto-char (match-beginning 0))
3930 (funcall outline-level))))))
3931 (and level (hide-sublevels level))))
3933 (defun org-content (&optional arg)
3934 "Show all headlines in the buffer, like a table of contents.
3935 With numerical argument N, show content up to level N."
3936 (interactive "P")
3937 (save-excursion
3938 ;; Visit all headings and show their offspring
3939 (and (integerp arg) (org-overview))
3940 (goto-char (point-max))
3941 (catch 'exit
3942 (while (and (progn (condition-case nil
3943 (outline-previous-visible-heading 1)
3944 (error (goto-char (point-min))))
3946 (looking-at outline-regexp))
3947 (if (integerp arg)
3948 (show-children (1- arg))
3949 (show-branches))
3950 (if (bobp) (throw 'exit nil))))))
3953 (defun org-optimize-window-after-visibility-change (state)
3954 "Adjust the window after a change in outline visibility.
3955 This function is the default value of the hook `org-cycle-hook'."
3956 (when (get-buffer-window (current-buffer))
3957 (cond
3958 ; ((eq state 'overview) (org-first-headline-recenter 1))
3959 ; ((eq state 'overview) (org-beginning-of-line))
3960 ((eq state 'content) nil)
3961 ((eq state 'all) nil)
3962 ((eq state 'folded) nil)
3963 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3964 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3966 (defun org-compact-display-after-subtree-move ()
3967 (let (beg end)
3968 (save-excursion
3969 (if (org-up-heading-safe)
3970 (progn
3971 (hide-subtree)
3972 (show-entry)
3973 (show-children)
3974 (org-cycle-show-empty-lines 'children)
3975 (org-cycle-hide-drawers 'children))
3976 (org-overview)))))
3978 (defun org-cycle-show-empty-lines (state)
3979 "Show empty lines above all visible headlines.
3980 The region to be covered depends on STATE when called through
3981 `org-cycle-hook'. Lisp program can use t for STATE to get the
3982 entire buffer covered. Note that an empty line is only shown if there
3983 are at least `org-cycle-separator-lines' empty lines before the headeline."
3984 (when (> org-cycle-separator-lines 0)
3985 (save-excursion
3986 (let* ((n org-cycle-separator-lines)
3987 (re (cond
3988 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3989 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3990 (t (let ((ns (number-to-string (- n 2))))
3991 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3992 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3993 beg end)
3994 (cond
3995 ((memq state '(overview contents t))
3996 (setq beg (point-min) end (point-max)))
3997 ((memq state '(children folded))
3998 (setq beg (point) end (progn (org-end-of-subtree t t)
3999 (beginning-of-line 2)
4000 (point)))))
4001 (when beg
4002 (goto-char beg)
4003 (while (re-search-forward re end t)
4004 (if (not (get-char-property (match-end 1) 'invisible))
4005 (outline-flag-region
4006 (match-beginning 1) (match-end 1) nil)))))))
4007 ;; Never hide empty lines at the end of the file.
4008 (save-excursion
4009 (goto-char (point-max))
4010 (outline-previous-heading)
4011 (outline-end-of-heading)
4012 (if (and (looking-at "[ \t\n]+")
4013 (= (match-end 0) (point-max)))
4014 (outline-flag-region (point) (match-end 0) nil))))
4016 (defun org-cycle-hide-drawers (state)
4017 "Re-hide all drawers after a visibility state change."
4018 (when (and (org-mode-p)
4019 (not (memq state '(overview folded))))
4020 (save-excursion
4021 (let* ((globalp (memq state '(contents all)))
4022 (beg (if globalp (point-min) (point)))
4023 (end (if globalp (point-max) (org-end-of-subtree t))))
4024 (goto-char beg)
4025 (while (re-search-forward org-drawer-regexp end t)
4026 (org-flag-drawer t))))))
4028 (defun org-flag-drawer (flag)
4029 (save-excursion
4030 (beginning-of-line 1)
4031 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4032 (let ((b (match-end 0))
4033 (outline-regexp org-outline-regexp))
4034 (if (re-search-forward
4035 "^[ \t]*:END:"
4036 (save-excursion (outline-next-heading) (point)) t)
4037 (outline-flag-region b (point-at-eol) flag)
4038 (error ":END: line missing"))))))
4040 (defun org-subtree-end-visible-p ()
4041 "Is the end of the current subtree visible?"
4042 (pos-visible-in-window-p
4043 (save-excursion (org-end-of-subtree t) (point))))
4045 (defun org-first-headline-recenter (&optional N)
4046 "Move cursor to the first headline and recenter the headline.
4047 Optional argument N means, put the headline into the Nth line of the window."
4048 (goto-char (point-min))
4049 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4050 (beginning-of-line)
4051 (recenter (prefix-numeric-value N))))
4053 ;;; Org-goto
4055 (defvar org-goto-window-configuration nil)
4056 (defvar org-goto-marker nil)
4057 (defvar org-goto-map
4058 (let ((map (make-sparse-keymap)))
4059 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4060 (while (setq cmd (pop cmds))
4061 (substitute-key-definition cmd cmd map global-map)))
4062 (suppress-keymap map)
4063 (org-defkey map "\C-m" 'org-goto-ret)
4064 (org-defkey map [(return)] 'org-goto-ret)
4065 (org-defkey map [(left)] 'org-goto-left)
4066 (org-defkey map [(right)] 'org-goto-right)
4067 (org-defkey map [(control ?g)] 'org-goto-quit)
4068 (org-defkey map "\C-i" 'org-cycle)
4069 (org-defkey map [(tab)] 'org-cycle)
4070 (org-defkey map [(down)] 'outline-next-visible-heading)
4071 (org-defkey map [(up)] 'outline-previous-visible-heading)
4072 (if org-goto-auto-isearch
4073 (if (fboundp 'define-key-after)
4074 (define-key-after map [t] 'org-goto-local-auto-isearch)
4075 nil)
4076 (org-defkey map "q" 'org-goto-quit)
4077 (org-defkey map "n" 'outline-next-visible-heading)
4078 (org-defkey map "p" 'outline-previous-visible-heading)
4079 (org-defkey map "f" 'outline-forward-same-level)
4080 (org-defkey map "b" 'outline-backward-same-level)
4081 (org-defkey map "u" 'outline-up-heading))
4082 (org-defkey map "/" 'org-occur)
4083 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4084 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4085 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4086 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4087 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4088 map))
4090 (defconst org-goto-help
4091 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4092 RET=jump to location [Q]uit and return to previous location
4093 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4095 (defvar org-goto-start-pos) ; dynamically scoped parameter
4097 (defun org-goto (&optional alternative-interface)
4098 "Look up a different location in the current file, keeping current visibility.
4100 When you want look-up or go to a different location in a document, the
4101 fastest way is often to fold the entire buffer and then dive into the tree.
4102 This method has the disadvantage, that the previous location will be folded,
4103 which may not be what you want.
4105 This command works around this by showing a copy of the current buffer
4106 in an indirect buffer, in overview mode. You can dive into the tree in
4107 that copy, use org-occur and incremental search to find a location.
4108 When pressing RET or `Q', the command returns to the original buffer in
4109 which the visibility is still unchanged. After RET is will also jump to
4110 the location selected in the indirect buffer and expose the
4111 the headline hierarchy above."
4112 (interactive "P")
4113 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4114 (org-refile-use-outline-path t)
4115 (interface
4116 (if (not alternative-interface)
4117 org-goto-interface
4118 (if (eq org-goto-interface 'outline)
4119 'outline-path-completion
4120 'outline)))
4121 (org-goto-start-pos (point))
4122 (selected-point
4123 (if (eq interface 'outline)
4124 (car (org-get-location (current-buffer) org-goto-help))
4125 (nth 3 (org-refile-get-location "Goto: ")))))
4126 (if selected-point
4127 (progn
4128 (org-mark-ring-push org-goto-start-pos)
4129 (goto-char selected-point)
4130 (if (or (org-invisible-p) (org-invisible-p2))
4131 (org-show-context 'org-goto)))
4132 (message "Quit"))))
4134 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4135 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4136 (defvar org-goto-local-auto-isearch-map) ; defined below
4138 (defun org-get-location (buf help)
4139 "Let the user select a location in the Org-mode buffer BUF.
4140 This function uses a recursive edit. It returns the selected position
4141 or nil."
4142 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4143 (isearch-hide-immediately nil)
4144 (isearch-search-fun-function
4145 (lambda () 'org-goto-local-search-forward-headings))
4146 (org-goto-selected-point org-goto-exit-command))
4147 (save-excursion
4148 (save-window-excursion
4149 (delete-other-windows)
4150 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4151 (switch-to-buffer
4152 (condition-case nil
4153 (make-indirect-buffer (current-buffer) "*org-goto*")
4154 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4155 (with-output-to-temp-buffer "*Help*"
4156 (princ help))
4157 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4158 (setq buffer-read-only nil)
4159 (let ((org-startup-truncated t)
4160 (org-startup-folded nil)
4161 (org-startup-align-all-tables nil))
4162 (org-mode)
4163 (org-overview))
4164 (setq buffer-read-only t)
4165 (if (and (boundp 'org-goto-start-pos)
4166 (integer-or-marker-p org-goto-start-pos))
4167 (let ((org-show-hierarchy-above t)
4168 (org-show-siblings t)
4169 (org-show-following-heading t))
4170 (goto-char org-goto-start-pos)
4171 (and (org-invisible-p) (org-show-context)))
4172 (goto-char (point-min)))
4173 (org-beginning-of-line)
4174 (message "Select location and press RET")
4175 (use-local-map org-goto-map)
4176 (recursive-edit)
4178 (kill-buffer "*org-goto*")
4179 (cons org-goto-selected-point org-goto-exit-command)))
4181 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4182 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4183 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4184 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4186 (defun org-goto-local-search-forward-headings (string bound noerror)
4187 "Search and make sure that anu matches are in headlines."
4188 (catch 'return
4189 (while (search-forward string bound noerror)
4190 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4191 (and (member :headline context)
4192 (not (member :tags context))))
4193 (throw 'return (point))))))
4195 (defun org-goto-local-auto-isearch ()
4196 "Start isearch."
4197 (interactive)
4198 (goto-char (point-min))
4199 (let ((keys (this-command-keys)))
4200 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4201 (isearch-mode t)
4202 (isearch-process-search-char (string-to-char keys)))))
4204 (defun org-goto-ret (&optional arg)
4205 "Finish `org-goto' by going to the new location."
4206 (interactive "P")
4207 (setq org-goto-selected-point (point)
4208 org-goto-exit-command 'return)
4209 (throw 'exit nil))
4211 (defun org-goto-left ()
4212 "Finish `org-goto' by going to the new location."
4213 (interactive)
4214 (if (org-on-heading-p)
4215 (progn
4216 (beginning-of-line 1)
4217 (setq org-goto-selected-point (point)
4218 org-goto-exit-command 'left)
4219 (throw 'exit nil))
4220 (error "Not on a heading")))
4222 (defun org-goto-right ()
4223 "Finish `org-goto' by going to the new location."
4224 (interactive)
4225 (if (org-on-heading-p)
4226 (progn
4227 (setq org-goto-selected-point (point)
4228 org-goto-exit-command 'right)
4229 (throw 'exit nil))
4230 (error "Not on a heading")))
4232 (defun org-goto-quit ()
4233 "Finish `org-goto' without cursor motion."
4234 (interactive)
4235 (setq org-goto-selected-point nil)
4236 (setq org-goto-exit-command 'quit)
4237 (throw 'exit nil))
4239 ;;; Indirect buffer display of subtrees
4241 (defvar org-indirect-dedicated-frame nil
4242 "This is the frame being used for indirect tree display.")
4243 (defvar org-last-indirect-buffer nil)
4245 (defun org-tree-to-indirect-buffer (&optional arg)
4246 "Create indirect buffer and narrow it to current subtree.
4247 With numerical prefix ARG, go up to this level and then take that tree.
4248 If ARG is negative, go up that many levels.
4249 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4250 indirect buffer previously made with this command, to avoid proliferation of
4251 indirect buffers. However, when you call the command with a `C-u' prefix, or
4252 when `org-indirect-buffer-display' is `new-frame', the last buffer
4253 is kept so that you can work with several indirect buffers at the same time.
4254 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4255 requests that a new frame be made for the new buffer, so that the dedicated
4256 frame is not changed."
4257 (interactive "P")
4258 (let ((cbuf (current-buffer))
4259 (cwin (selected-window))
4260 (pos (point))
4261 beg end level heading ibuf)
4262 (save-excursion
4263 (org-back-to-heading t)
4264 (when (numberp arg)
4265 (setq level (org-outline-level))
4266 (if (< arg 0) (setq arg (+ level arg)))
4267 (while (> (setq level (org-outline-level)) arg)
4268 (outline-up-heading 1 t)))
4269 (setq beg (point)
4270 heading (org-get-heading))
4271 (org-end-of-subtree t) (setq end (point)))
4272 (if (and (buffer-live-p org-last-indirect-buffer)
4273 (not (eq org-indirect-buffer-display 'new-frame))
4274 (not arg))
4275 (kill-buffer org-last-indirect-buffer))
4276 (setq ibuf (org-get-indirect-buffer cbuf)
4277 org-last-indirect-buffer ibuf)
4278 (cond
4279 ((or (eq org-indirect-buffer-display 'new-frame)
4280 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4281 (select-frame (make-frame))
4282 (delete-other-windows)
4283 (switch-to-buffer ibuf)
4284 (org-set-frame-title heading))
4285 ((eq org-indirect-buffer-display 'dedicated-frame)
4286 (raise-frame
4287 (select-frame (or (and org-indirect-dedicated-frame
4288 (frame-live-p org-indirect-dedicated-frame)
4289 org-indirect-dedicated-frame)
4290 (setq org-indirect-dedicated-frame (make-frame)))))
4291 (delete-other-windows)
4292 (switch-to-buffer ibuf)
4293 (org-set-frame-title (concat "Indirect: " heading)))
4294 ((eq org-indirect-buffer-display 'current-window)
4295 (switch-to-buffer ibuf))
4296 ((eq org-indirect-buffer-display 'other-window)
4297 (pop-to-buffer ibuf))
4298 (t (error "Invalid value.")))
4299 (if (featurep 'xemacs)
4300 (save-excursion (org-mode) (turn-on-font-lock)))
4301 (narrow-to-region beg end)
4302 (show-all)
4303 (goto-char pos)
4304 (and (window-live-p cwin) (select-window cwin))))
4306 (defun org-get-indirect-buffer (&optional buffer)
4307 (setq buffer (or buffer (current-buffer)))
4308 (let ((n 1) (base (buffer-name buffer)) bname)
4309 (while (buffer-live-p
4310 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4311 (setq n (1+ n)))
4312 (condition-case nil
4313 (make-indirect-buffer buffer bname 'clone)
4314 (error (make-indirect-buffer buffer bname)))))
4316 (defun org-set-frame-title (title)
4317 "Set the title of the current frame to the string TITLE."
4318 ;; FIXME: how to name a single frame in XEmacs???
4319 (unless (featurep 'xemacs)
4320 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4322 ;;;; Structure editing
4324 ;;; Inserting headlines
4326 (defun org-insert-heading (&optional force-heading)
4327 "Insert a new heading or item with same depth at point.
4328 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4329 If point is at the beginning of a headline, insert a sibling before the
4330 current headline. If point is not at the beginning, do not split the line,
4331 but create the new hedline after the current line."
4332 (interactive "P")
4333 (if (= (buffer-size) 0)
4334 (insert "\n* ")
4335 (when (or force-heading (not (org-insert-item)))
4336 (let* ((head (save-excursion
4337 (condition-case nil
4338 (progn
4339 (org-back-to-heading)
4340 (match-string 0))
4341 (error "*"))))
4342 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4343 pos)
4344 (cond
4345 ((and (org-on-heading-p) (bolp)
4346 (or (bobp)
4347 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4348 ;; insert before the current line
4349 (open-line (if blank 2 1)))
4350 ((and (bolp)
4351 (or (bobp)
4352 (save-excursion
4353 (backward-char 1) (not (org-invisible-p)))))
4354 ;; insert right here
4355 nil)
4357 ;; in the middle of the line
4358 (org-show-entry)
4359 (let ((split
4360 (org-get-alist-option org-M-RET-may-split-line 'headline))
4361 tags pos)
4362 (if (org-on-heading-p)
4363 (progn
4364 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4365 (setq tags (and (match-end 2) (match-string 2)))
4366 (and (match-end 1)
4367 (delete-region (match-beginning 1) (match-end 1)))
4368 (setq pos (point-at-bol))
4369 (or split (end-of-line 1))
4370 (delete-horizontal-space)
4371 (newline (if blank 2 1))
4372 (when tags
4373 (save-excursion
4374 (goto-char pos)
4375 (end-of-line 1)
4376 (insert " " tags)
4377 (org-set-tags nil 'align))))
4378 (or split (end-of-line 1))
4379 (newline (if blank 2 1))))))
4380 (insert head) (just-one-space)
4381 (setq pos (point))
4382 (end-of-line 1)
4383 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4384 (run-hooks 'org-insert-heading-hook)))))
4386 (defun org-get-heading (&optional no-tags)
4387 "Return the heading of the current entry, without the stars."
4388 (save-excursion
4389 (org-back-to-heading t)
4390 (if (looking-at
4391 (if no-tags
4392 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4393 "\\*+[ \t]+\\([^\r\n]*\\)"))
4394 (match-string 1) "")))
4396 (defun org-insert-heading-after-current ()
4397 "Insert a new heading with same level as current, after current subtree."
4398 (interactive)
4399 (org-back-to-heading)
4400 (org-insert-heading)
4401 (org-move-subtree-down)
4402 (end-of-line 1))
4404 (defun org-insert-todo-heading (arg)
4405 "Insert a new heading with the same level and TODO state as current heading.
4406 If the heading has no TODO state, or if the state is DONE, use the first
4407 state (TODO by default). Also with prefix arg, force first state."
4408 (interactive "P")
4409 (when (not (org-insert-item 'checkbox))
4410 (org-insert-heading)
4411 (save-excursion
4412 (org-back-to-heading)
4413 (outline-previous-heading)
4414 (looking-at org-todo-line-regexp))
4415 (if (or arg
4416 (not (match-beginning 2))
4417 (member (match-string 2) org-done-keywords))
4418 (insert (car org-todo-keywords-1) " ")
4419 (insert (match-string 2) " "))))
4421 (defun org-insert-subheading (arg)
4422 "Insert a new subheading and demote it.
4423 Works for outline headings and for plain lists alike."
4424 (interactive "P")
4425 (org-insert-heading arg)
4426 (cond
4427 ((org-on-heading-p) (org-do-demote))
4428 ((org-at-item-p) (org-indent-item 1))))
4430 (defun org-insert-todo-subheading (arg)
4431 "Insert a new subheading with TODO keyword or checkbox and demote it.
4432 Works for outline headings and for plain lists alike."
4433 (interactive "P")
4434 (org-insert-todo-heading arg)
4435 (cond
4436 ((org-on-heading-p) (org-do-demote))
4437 ((org-at-item-p) (org-indent-item 1))))
4439 ;;; Promotion and Demotion
4441 (defun org-promote-subtree ()
4442 "Promote the entire subtree.
4443 See also `org-promote'."
4444 (interactive)
4445 (save-excursion
4446 (org-map-tree 'org-promote))
4447 (org-fix-position-after-promote))
4449 (defun org-demote-subtree ()
4450 "Demote the entire subtree. See `org-demote'.
4451 See also `org-promote'."
4452 (interactive)
4453 (save-excursion
4454 (org-map-tree 'org-demote))
4455 (org-fix-position-after-promote))
4458 (defun org-do-promote ()
4459 "Promote the current heading higher up the tree.
4460 If the region is active in `transient-mark-mode', promote all headings
4461 in the region."
4462 (interactive)
4463 (save-excursion
4464 (if (org-region-active-p)
4465 (org-map-region 'org-promote (region-beginning) (region-end))
4466 (org-promote)))
4467 (org-fix-position-after-promote))
4469 (defun org-do-demote ()
4470 "Demote the current heading lower down the tree.
4471 If the region is active in `transient-mark-mode', demote all headings
4472 in the region."
4473 (interactive)
4474 (save-excursion
4475 (if (org-region-active-p)
4476 (org-map-region 'org-demote (region-beginning) (region-end))
4477 (org-demote)))
4478 (org-fix-position-after-promote))
4480 (defun org-fix-position-after-promote ()
4481 "Make sure that after pro/demotion cursor position is right."
4482 (let ((pos (point)))
4483 (when (save-excursion
4484 (beginning-of-line 1)
4485 (looking-at org-todo-line-regexp)
4486 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4487 (cond ((eobp) (insert " "))
4488 ((eolp) (insert " "))
4489 ((equal (char-after) ?\ ) (forward-char 1))))))
4491 (defun org-reduced-level (l)
4492 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4494 (defun org-get-valid-level (level &optional change)
4495 "Rectify a level change under the influence of `org-odd-levels-only'
4496 LEVEL is a current level, CHANGE is by how much the level should be
4497 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4498 even level numbers will become the next higher odd number."
4499 (if org-odd-levels-only
4500 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4501 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4502 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4503 (max 1 (+ level change))))
4505 (if (boundp 'define-obsolete-function-alias)
4506 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4507 (define-obsolete-function-alias 'org-get-legal-level
4508 'org-get-valid-level)
4509 (define-obsolete-function-alias 'org-get-legal-level
4510 'org-get-valid-level "23.1")))
4512 (defun org-promote ()
4513 "Promote the current heading higher up the tree.
4514 If the region is active in `transient-mark-mode', promote all headings
4515 in the region."
4516 (org-back-to-heading t)
4517 (let* ((level (save-match-data (funcall outline-level)))
4518 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4519 (diff (abs (- level (length up-head) -1))))
4520 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4521 (replace-match up-head nil t)
4522 ;; Fixup tag positioning
4523 (and org-auto-align-tags (org-set-tags nil t))
4524 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4526 (defun org-demote ()
4527 "Demote the current heading lower down the tree.
4528 If the region is active in `transient-mark-mode', demote all headings
4529 in the region."
4530 (org-back-to-heading t)
4531 (let* ((level (save-match-data (funcall outline-level)))
4532 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4533 (diff (abs (- level (length down-head) -1))))
4534 (replace-match down-head nil t)
4535 ;; Fixup tag positioning
4536 (and org-auto-align-tags (org-set-tags nil t))
4537 (if org-adapt-indentation (org-fixup-indentation diff))))
4539 (defun org-map-tree (fun)
4540 "Call FUN for every heading underneath the current one."
4541 (org-back-to-heading)
4542 (let ((level (funcall outline-level)))
4543 (save-excursion
4544 (funcall fun)
4545 (while (and (progn
4546 (outline-next-heading)
4547 (> (funcall outline-level) level))
4548 (not (eobp)))
4549 (funcall fun)))))
4551 (defun org-map-region (fun beg end)
4552 "Call FUN for every heading between BEG and END."
4553 (let ((org-ignore-region t))
4554 (save-excursion
4555 (setq end (copy-marker end))
4556 (goto-char beg)
4557 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4558 (< (point) end))
4559 (funcall fun))
4560 (while (and (progn
4561 (outline-next-heading)
4562 (< (point) end))
4563 (not (eobp)))
4564 (funcall fun)))))
4566 (defun org-fixup-indentation (diff)
4567 "Change the indentation in the current entry by DIFF
4568 However, if any line in the current entry has no indentation, or if it
4569 would end up with no indentation after the change, nothing at all is done."
4570 (save-excursion
4571 (let ((end (save-excursion (outline-next-heading)
4572 (point-marker)))
4573 (prohibit (if (> diff 0)
4574 "^\\S-"
4575 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4576 col)
4577 (unless (save-excursion (end-of-line 1)
4578 (re-search-forward prohibit end t))
4579 (while (and (< (point) end)
4580 (re-search-forward "^[ \t]+" end t))
4581 (goto-char (match-end 0))
4582 (setq col (current-column))
4583 (if (< diff 0) (replace-match ""))
4584 (indent-to (+ diff col))))
4585 (move-marker end nil))))
4587 (defun org-convert-to-odd-levels ()
4588 "Convert an org-mode file with all levels allowed to one with odd levels.
4589 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4590 level 5 etc."
4591 (interactive)
4592 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4593 (let ((org-odd-levels-only nil) n)
4594 (save-excursion
4595 (goto-char (point-min))
4596 (while (re-search-forward "^\\*\\*+ " nil t)
4597 (setq n (- (length (match-string 0)) 2))
4598 (while (>= (setq n (1- n)) 0)
4599 (org-demote))
4600 (end-of-line 1))))))
4603 (defun org-convert-to-oddeven-levels ()
4604 "Convert an org-mode file with only odd levels to one with odd and even levels.
4605 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4606 section with an even level, conversion would destroy the structure of the file. An error
4607 is signaled in this case."
4608 (interactive)
4609 (goto-char (point-min))
4610 ;; First check if there are no even levels
4611 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4612 (org-show-context t)
4613 (error "Not all levels are odd in this file. Conversion not possible."))
4614 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4615 (let ((org-odd-levels-only nil) n)
4616 (save-excursion
4617 (goto-char (point-min))
4618 (while (re-search-forward "^\\*\\*+ " nil t)
4619 (setq n (/ (1- (length (match-string 0))) 2))
4620 (while (>= (setq n (1- n)) 0)
4621 (org-promote))
4622 (end-of-line 1))))))
4624 (defun org-tr-level (n)
4625 "Make N odd if required."
4626 (if org-odd-levels-only (1+ (/ n 2)) n))
4628 ;;; Vertical tree motion, cutting and pasting of subtrees
4630 (defun org-move-subtree-up (&optional arg)
4631 "Move the current subtree up past ARG headlines of the same level."
4632 (interactive "p")
4633 (org-move-subtree-down (- (prefix-numeric-value arg))))
4635 (defun org-move-subtree-down (&optional arg)
4636 "Move the current subtree down past ARG headlines of the same level."
4637 (interactive "p")
4638 (setq arg (prefix-numeric-value arg))
4639 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4640 'outline-get-last-sibling))
4641 (ins-point (make-marker))
4642 (cnt (abs arg))
4643 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4644 ;; Select the tree
4645 (org-back-to-heading)
4646 (setq beg0 (point))
4647 (save-excursion
4648 (setq ne-beg (org-back-over-empty-lines))
4649 (setq beg (point)))
4650 (save-match-data
4651 (save-excursion (outline-end-of-heading)
4652 (setq folded (org-invisible-p)))
4653 (outline-end-of-subtree))
4654 (outline-next-heading)
4655 (setq ne-end (org-back-over-empty-lines))
4656 (setq end (point))
4657 (goto-char beg0)
4658 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4659 ;; include less whitespace
4660 (save-excursion
4661 (goto-char beg)
4662 (forward-line (- ne-beg ne-end))
4663 (setq beg (point))))
4664 ;; Find insertion point, with error handling
4665 (while (> cnt 0)
4666 (or (and (funcall movfunc) (looking-at outline-regexp))
4667 (progn (goto-char beg0)
4668 (error "Cannot move past superior level or buffer limit")))
4669 (setq cnt (1- cnt)))
4670 (if (> arg 0)
4671 ;; Moving forward - still need to move over subtree
4672 (progn (org-end-of-subtree t t)
4673 (save-excursion
4674 (org-back-over-empty-lines)
4675 (or (bolp) (newline)))))
4676 (setq ne-ins (org-back-over-empty-lines))
4677 (move-marker ins-point (point))
4678 (setq txt (buffer-substring beg end))
4679 (org-save-markers-in-region beg end)
4680 (delete-region beg end)
4681 (outline-flag-region (1- beg) beg nil)
4682 (outline-flag-region (1- (point)) (point) nil)
4683 (let ((bbb (point)))
4684 (insert-before-markers txt)
4685 (org-reinstall-markers-in-region bbb)
4686 (move-marker ins-point bbb))
4687 (or (bolp) (insert "\n"))
4688 (setq ins-end (point))
4689 (goto-char ins-point)
4690 (org-skip-whitespace)
4691 (when (and (< arg 0)
4692 (org-first-sibling-p)
4693 (> ne-ins ne-beg))
4694 ;; Move whitespace back to beginning
4695 (save-excursion
4696 (goto-char ins-end)
4697 (let ((kill-whole-line t))
4698 (kill-line (- ne-ins ne-beg)) (point)))
4699 (insert (make-string (- ne-ins ne-beg) ?\n)))
4700 (move-marker ins-point nil)
4701 (org-compact-display-after-subtree-move)
4702 (unless folded
4703 (org-show-entry)
4704 (show-children)
4705 (org-cycle-hide-drawers 'children))))
4707 (defvar org-subtree-clip ""
4708 "Clipboard for cut and paste of subtrees.
4709 This is actually only a copy of the kill, because we use the normal kill
4710 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4712 (defvar org-subtree-clip-folded nil
4713 "Was the last copied subtree folded?
4714 This is used to fold the tree back after pasting.")
4716 (defun org-cut-subtree (&optional n)
4717 "Cut the current subtree into the clipboard.
4718 With prefix arg N, cut this many sequential subtrees.
4719 This is a short-hand for marking the subtree and then cutting it."
4720 (interactive "p")
4721 (org-copy-subtree n 'cut))
4723 (defun org-copy-subtree (&optional n cut force-store-markers)
4724 "Cut the current subtree into the clipboard.
4725 With prefix arg N, cut this many sequential subtrees.
4726 This is a short-hand for marking the subtree and then copying it.
4727 If CUT is non-nil, actually cut the subtree.
4728 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4729 of some markers in the region, even if CUT is non-nil. This is
4730 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4731 (interactive "p")
4732 (let (beg end folded (beg0 (point)))
4733 (if (interactive-p)
4734 (org-back-to-heading nil) ; take what looks like a subtree
4735 (org-back-to-heading t)) ; take what is really there
4736 (org-back-over-empty-lines)
4737 (setq beg (point))
4738 (skip-chars-forward " \t\r\n")
4739 (save-match-data
4740 (save-excursion (outline-end-of-heading)
4741 (setq folded (org-invisible-p)))
4742 (condition-case nil
4743 (outline-forward-same-level (1- n))
4744 (error nil))
4745 (org-end-of-subtree t t))
4746 (org-back-over-empty-lines)
4747 (setq end (point))
4748 (goto-char beg0)
4749 (when (> end beg)
4750 (setq org-subtree-clip-folded folded)
4751 (when (or cut force-store-markers)
4752 (org-save-markers-in-region beg end))
4753 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4754 (setq org-subtree-clip (current-kill 0))
4755 (message "%s: Subtree(s) with %d characters"
4756 (if cut "Cut" "Copied")
4757 (length org-subtree-clip)))))
4759 (defun org-paste-subtree (&optional level tree)
4760 "Paste the clipboard as a subtree, with modification of headline level.
4761 The entire subtree is promoted or demoted in order to match a new headline
4762 level. By default, the new level is derived from the visible headings
4763 before and after the insertion point, and taken to be the inferior headline
4764 level of the two. So if the previous visible heading is level 3 and the
4765 next is level 4 (or vice versa), level 4 will be used for insertion.
4766 This makes sure that the subtree remains an independent subtree and does
4767 not swallow low level entries.
4769 You can also force a different level, either by using a numeric prefix
4770 argument, or by inserting the heading marker by hand. For example, if the
4771 cursor is after \"*****\", then the tree will be shifted to level 5.
4773 If you want to insert the tree as is, just use \\[yank].
4775 If optional TREE is given, use this text instead of the kill ring."
4776 (interactive "P")
4777 (unless (org-kill-is-subtree-p tree)
4778 (error "%s"
4779 (substitute-command-keys
4780 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4781 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4782 (^re (concat "^\\(" outline-regexp "\\)"))
4783 (re (concat "\\(" outline-regexp "\\)"))
4784 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4786 (old-level (if (string-match ^re txt)
4787 (- (match-end 0) (match-beginning 0) 1)
4788 -1))
4789 (force-level (cond (level (prefix-numeric-value level))
4790 ((string-match
4791 ^re_ (buffer-substring (point-at-bol) (point)))
4792 (- (match-end 1) (match-beginning 1)))
4793 (t nil)))
4794 (previous-level (save-excursion
4795 (condition-case nil
4796 (progn
4797 (outline-previous-visible-heading 1)
4798 (if (looking-at re)
4799 (- (match-end 0) (match-beginning 0) 1)
4801 (error 1))))
4802 (next-level (save-excursion
4803 (condition-case nil
4804 (progn
4805 (or (looking-at outline-regexp)
4806 (outline-next-visible-heading 1))
4807 (if (looking-at re)
4808 (- (match-end 0) (match-beginning 0) 1)
4810 (error 1))))
4811 (new-level (or force-level (max previous-level next-level)))
4812 (shift (if (or (= old-level -1)
4813 (= new-level -1)
4814 (= old-level new-level))
4816 (- new-level old-level)))
4817 (delta (if (> shift 0) -1 1))
4818 (func (if (> shift 0) 'org-demote 'org-promote))
4819 (org-odd-levels-only nil)
4820 beg end)
4821 ;; Remove the forced level indicator
4822 (if force-level
4823 (delete-region (point-at-bol) (point)))
4824 ;; Paste
4825 (beginning-of-line 1)
4826 (org-back-over-empty-lines)
4827 (setq beg (point))
4828 (insert-before-markers txt)
4829 (unless (string-match "\n\\'" txt) (insert "\n"))
4830 (org-reinstall-markers-in-region beg)
4831 (setq end (point))
4832 (goto-char beg)
4833 (skip-chars-forward " \t\n\r")
4834 (setq beg (point))
4835 ;; Shift if necessary
4836 (unless (= shift 0)
4837 (save-restriction
4838 (narrow-to-region beg end)
4839 (while (not (= shift 0))
4840 (org-map-region func (point-min) (point-max))
4841 (setq shift (+ delta shift)))
4842 (goto-char (point-min))))
4843 (when (interactive-p)
4844 (message "Clipboard pasted as level %d subtree" new-level))
4845 (if (and kill-ring
4846 (eq org-subtree-clip (current-kill 0))
4847 org-subtree-clip-folded)
4848 ;; The tree was folded before it was killed/copied
4849 (hide-subtree))))
4851 (defun org-kill-is-subtree-p (&optional txt)
4852 "Check if the current kill is an outline subtree, or a set of trees.
4853 Returns nil if kill does not start with a headline, or if the first
4854 headline level is not the largest headline level in the tree.
4855 So this will actually accept several entries of equal levels as well,
4856 which is OK for `org-paste-subtree'.
4857 If optional TXT is given, check this string instead of the current kill."
4858 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4859 (start-level (and kill
4860 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4861 org-outline-regexp "\\)")
4862 kill)
4863 (- (match-end 2) (match-beginning 2) 1)))
4864 (re (concat "^" org-outline-regexp))
4865 (start (1+ (match-beginning 2))))
4866 (if (not start-level)
4867 (progn
4868 nil) ;; does not even start with a heading
4869 (catch 'exit
4870 (while (setq start (string-match re kill (1+ start)))
4871 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4872 (throw 'exit nil)))
4873 t))))
4875 (defvar org-markers-to-move nil
4876 "Markers that should be moved with a cut-and-paste operation.
4877 Those markers are stored together with their positions relative to
4878 the start of the region.")
4880 (defun org-save-markers-in-region (beg end)
4881 "Check markers in region.
4882 If these markers are between BEG and END, record their position relative
4883 to BEG, so that after moving the block of text, we can put the markers back
4884 into place.
4885 This function gets called just before an entry or tree gets cut from the
4886 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4887 called immediately, to move the markers with the entries."
4888 (setq org-markers-to-move nil)
4889 (when (featurep 'org-clock)
4890 (org-clock-save-markers-for-cut-and-paste beg end))
4891 (when (featurep 'org-agenda)
4892 (org-agenda-save-markers-for-cut-and-paste beg end)))
4894 (defun org-check-and-save-marker (marker beg end)
4895 "Check if MARKER is between BEG and END.
4896 If yes, remember the marker and the distance to BEG."
4897 (when (and (marker-buffer marker)
4898 (equal (marker-buffer marker) (current-buffer)))
4899 (if (and (>= marker beg) (< marker end))
4900 (push (cons marker (- marker beg)) org-markers-to-move))))
4902 (defun org-reinstall-markers-in-region (beg)
4903 "Move all remembered markers to their position relative to BEG."
4904 (mapc (lambda (x)
4905 (move-marker (car x) (+ beg (cdr x))))
4906 org-markers-to-move)
4907 (setq org-markers-to-move nil))
4909 (defun org-narrow-to-subtree ()
4910 "Narrow buffer to the current subtree."
4911 (interactive)
4912 (save-excursion
4913 (save-match-data
4914 (narrow-to-region
4915 (progn (org-back-to-heading) (point))
4916 (progn (org-end-of-subtree t t) (point))))))
4919 ;;; Outline Sorting
4921 (defun org-sort (with-case)
4922 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4923 Optional argument WITH-CASE means sort case-sensitively."
4924 (interactive "P")
4925 (if (org-at-table-p)
4926 (org-call-with-arg 'org-table-sort-lines with-case)
4927 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4929 (defun org-sort-remove-invisible (s)
4930 (remove-text-properties 0 (length s) org-rm-props s)
4931 (while (string-match org-bracket-link-regexp s)
4932 (setq s (replace-match (if (match-end 2)
4933 (match-string 3 s)
4934 (match-string 1 s)) t t s)))
4937 (defvar org-priority-regexp) ; defined later in the file
4939 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4940 "Sort entries on a certain level of an outline tree.
4941 If there is an active region, the entries in the region are sorted.
4942 Else, if the cursor is before the first entry, sort the top-level items.
4943 Else, the children of the entry at point are sorted.
4945 Sorting can be alphabetically, numerically, and by date/time as given by
4946 the first time stamp in the entry. The command prompts for the sorting
4947 type unless it has been given to the function through the SORTING-TYPE
4948 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4949 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4950 called with point at the beginning of the record. It must return either
4951 a string or a number that should serve as the sorting key for that record.
4953 Comparing entries ignores case by default. However, with an optional argument
4954 WITH-CASE, the sorting considers case as well."
4955 (interactive "P")
4956 (let ((case-func (if with-case 'identity 'downcase))
4957 start beg end stars re re2
4958 txt what tmp plain-list-p)
4959 ;; Find beginning and end of region to sort
4960 (cond
4961 ((org-region-active-p)
4962 ;; we will sort the region
4963 (setq end (region-end)
4964 what "region")
4965 (goto-char (region-beginning))
4966 (if (not (org-on-heading-p)) (outline-next-heading))
4967 (setq start (point)))
4968 ((org-at-item-p)
4969 ;; we will sort this plain list
4970 (org-beginning-of-item-list) (setq start (point))
4971 (org-end-of-item-list) (setq end (point))
4972 (goto-char start)
4973 (setq plain-list-p t
4974 what "plain list"))
4975 ((or (org-on-heading-p)
4976 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4977 ;; we will sort the children of the current headline
4978 (org-back-to-heading)
4979 (setq start (point)
4980 end (progn (org-end-of-subtree t t)
4981 (org-back-over-empty-lines)
4982 (point))
4983 what "children")
4984 (goto-char start)
4985 (show-subtree)
4986 (outline-next-heading))
4988 ;; we will sort the top-level entries in this file
4989 (goto-char (point-min))
4990 (or (org-on-heading-p) (outline-next-heading))
4991 (setq start (point) end (point-max) what "top-level")
4992 (goto-char start)
4993 (show-all)))
4995 (setq beg (point))
4996 (if (>= beg end) (error "Nothing to sort"))
4998 (unless plain-list-p
4999 (looking-at "\\(\\*+\\)")
5000 (setq stars (match-string 1)
5001 re (concat "^" (regexp-quote stars) " +")
5002 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5003 txt (buffer-substring beg end))
5004 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5005 (if (and (not (equal stars "*")) (string-match re2 txt))
5006 (error "Region to sort contains a level above the first entry")))
5008 (unless sorting-type
5009 (message
5010 (if plain-list-p
5011 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5012 "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:")
5013 what)
5014 (setq sorting-type (read-char-exclusive))
5016 (and (= (downcase sorting-type) ?f)
5017 (setq getkey-func
5018 (completing-read "Sort using function: "
5019 obarray 'fboundp t nil nil))
5020 (setq getkey-func (intern getkey-func)))
5022 (and (= (downcase sorting-type) ?r)
5023 (setq property
5024 (completing-read "Property: "
5025 (mapcar 'list (org-buffer-property-keys t))
5026 nil t))))
5028 (message "Sorting entries...")
5030 (save-restriction
5031 (narrow-to-region start end)
5033 (let ((dcst (downcase sorting-type))
5034 (now (current-time)))
5035 (sort-subr
5036 (/= dcst sorting-type)
5037 ;; This function moves to the beginning character of the "record" to
5038 ;; be sorted.
5039 (if plain-list-p
5040 (lambda nil
5041 (if (org-at-item-p) t (goto-char (point-max))))
5042 (lambda nil
5043 (if (re-search-forward re nil t)
5044 (goto-char (match-beginning 0))
5045 (goto-char (point-max)))))
5046 ;; This function moves to the last character of the "record" being
5047 ;; sorted.
5048 (if plain-list-p
5049 'org-end-of-item
5050 (lambda nil
5051 (save-match-data
5052 (condition-case nil
5053 (outline-forward-same-level 1)
5054 (error
5055 (goto-char (point-max)))))))
5057 ;; This function returns the value that gets sorted against.
5058 (if plain-list-p
5059 (lambda nil
5060 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5061 (cond
5062 ((= dcst ?n)
5063 (string-to-number (buffer-substring (match-end 0)
5064 (point-at-eol))))
5065 ((= dcst ?a)
5066 (buffer-substring (match-end 0) (point-at-eol)))
5067 ((= dcst ?t)
5068 (if (re-search-forward org-ts-regexp
5069 (point-at-eol) t)
5070 (org-time-string-to-time (match-string 0))
5071 now))
5072 ((= dcst ?f)
5073 (if getkey-func
5074 (progn
5075 (setq tmp (funcall getkey-func))
5076 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5077 tmp)
5078 (error "Invalid key function `%s'" getkey-func)))
5079 (t (error "Invalid sorting type `%c'" sorting-type)))))
5080 (lambda nil
5081 (cond
5082 ((= dcst ?n)
5083 (if (looking-at outline-regexp)
5084 (string-to-number (buffer-substring (match-end 0)
5085 (point-at-eol)))
5086 nil))
5087 ((= dcst ?a)
5088 (funcall case-func (buffer-substring (point-at-bol)
5089 (point-at-eol))))
5090 ((= dcst ?t)
5091 (if (re-search-forward org-ts-regexp
5092 (save-excursion
5093 (forward-line 2)
5094 (point)) t)
5095 (org-time-string-to-time (match-string 0))
5096 now))
5097 ((= dcst ?p)
5098 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5099 (string-to-char (match-string 2))
5100 org-default-priority))
5101 ((= dcst ?r)
5102 (or (org-entry-get nil property) ""))
5103 ((= dcst ?o)
5104 (if (looking-at org-complex-heading-regexp)
5105 (- 9999 (length (member (match-string 2)
5106 org-todo-keywords-1)))))
5107 ((= dcst ?f)
5108 (if getkey-func
5109 (progn
5110 (setq tmp (funcall getkey-func))
5111 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5112 tmp)
5113 (error "Invalid key function `%s'" getkey-func)))
5114 (t (error "Invalid sorting type `%c'" sorting-type)))))
5116 (cond
5117 ((= dcst ?a) 'string<)
5118 ((= dcst ?t) 'time-less-p)
5119 (t nil)))))
5120 (message "Sorting entries...done")))
5122 (defun org-do-sort (table what &optional with-case sorting-type)
5123 "Sort TABLE of WHAT according to SORTING-TYPE.
5124 The user will be prompted for the SORTING-TYPE if the call to this
5125 function does not specify it. WHAT is only for the prompt, to indicate
5126 what is being sorted. The sorting key will be extracted from
5127 the car of the elements of the table.
5128 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5129 (unless sorting-type
5130 (message
5131 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5132 what)
5133 (setq sorting-type (read-char-exclusive)))
5134 (let ((dcst (downcase sorting-type))
5135 extractfun comparefun)
5136 ;; Define the appropriate functions
5137 (cond
5138 ((= dcst ?n)
5139 (setq extractfun 'string-to-number
5140 comparefun (if (= dcst sorting-type) '< '>)))
5141 ((= dcst ?a)
5142 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5143 (lambda(x) (downcase (org-sort-remove-invisible x))))
5144 comparefun (if (= dcst sorting-type)
5145 'string<
5146 (lambda (a b) (and (not (string< a b))
5147 (not (string= a b)))))))
5148 ((= dcst ?t)
5149 (setq extractfun
5150 (lambda (x)
5151 (if (string-match org-ts-regexp x)
5152 (time-to-seconds
5153 (org-time-string-to-time (match-string 0 x)))
5155 comparefun (if (= dcst sorting-type) '< '>)))
5156 (t (error "Invalid sorting type `%c'" sorting-type)))
5158 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5159 table)
5160 (lambda (a b) (funcall comparefun (car a) (car b))))))
5162 ;;;; Plain list items, including checkboxes
5164 ;;; Plain list items
5166 (defun org-at-item-p ()
5167 "Is point in a line starting a hand-formatted item?"
5168 (let ((llt org-plain-list-ordered-item-terminator))
5169 (save-excursion
5170 (goto-char (point-at-bol))
5171 (looking-at
5172 (cond
5173 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5174 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5175 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5176 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5178 (defun org-in-item-p ()
5179 "It the cursor inside a plain list item.
5180 Does not have to be the first line."
5181 (save-excursion
5182 (condition-case nil
5183 (progn
5184 (org-beginning-of-item)
5185 (org-at-item-p)
5187 (error nil))))
5189 (defun org-insert-item (&optional checkbox)
5190 "Insert a new item at the current level.
5191 Return t when things worked, nil when we are not in an item."
5192 (when (save-excursion
5193 (condition-case nil
5194 (progn
5195 (org-beginning-of-item)
5196 (org-at-item-p)
5197 (if (org-invisible-p) (error "Invisible item"))
5199 (error nil)))
5200 (let* ((bul (match-string 0))
5201 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5202 (match-end 0)))
5203 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5204 pos)
5205 (cond
5206 ((and (org-at-item-p) (<= (point) eow))
5207 ;; before the bullet
5208 (beginning-of-line 1)
5209 (open-line (if blank 2 1)))
5210 ((<= (point) eow)
5211 (beginning-of-line 1))
5213 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5214 (end-of-line 1)
5215 (delete-horizontal-space))
5216 (newline (if blank 2 1))))
5217 (insert bul (if checkbox "[ ]" ""))
5218 (just-one-space)
5219 (setq pos (point))
5220 (end-of-line 1)
5221 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5222 (org-maybe-renumber-ordered-list)
5223 (and checkbox (org-update-checkbox-count-maybe))
5226 ;;; Checkboxes
5228 (defun org-at-item-checkbox-p ()
5229 "Is point at a line starting a plain-list item with a checklet?"
5230 (and (org-at-item-p)
5231 (save-excursion
5232 (goto-char (match-end 0))
5233 (skip-chars-forward " \t")
5234 (looking-at "\\[[- X]\\]"))))
5236 (defun org-toggle-checkbox (&optional arg)
5237 "Toggle the checkbox in the current line."
5238 (interactive "P")
5239 (catch 'exit
5240 (let (beg end status (firstnew 'unknown))
5241 (cond
5242 ((org-region-active-p)
5243 (setq beg (region-beginning) end (region-end)))
5244 ((org-on-heading-p)
5245 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5246 ((org-at-item-checkbox-p)
5247 (let ((pos (point)))
5248 (replace-match
5249 (cond (arg "[-]")
5250 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5251 (t "[ ]"))
5252 t t)
5253 (goto-char pos))
5254 (throw 'exit t))
5255 (t (error "Not at a checkbox or heading, and no active region")))
5256 (save-excursion
5257 (goto-char beg)
5258 (while (< (point) end)
5259 (when (org-at-item-checkbox-p)
5260 (setq status (equal (match-string 0) "[X]"))
5261 (when (eq firstnew 'unknown)
5262 (setq firstnew (not status)))
5263 (replace-match
5264 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5265 (beginning-of-line 2)))))
5266 (org-update-checkbox-count-maybe))
5268 (defun org-update-checkbox-count-maybe ()
5269 "Update checkbox statistics unless turned off by user."
5270 (when org-provide-checkbox-statistics
5271 (org-update-checkbox-count)))
5273 (defun org-update-checkbox-count (&optional all)
5274 "Update the checkbox statistics in the current section.
5275 This will find all statistic cookies like [57%] and [6/12] and update them
5276 with the current numbers. With optional prefix argument ALL, do this for
5277 the whole buffer."
5278 (interactive "P")
5279 (save-excursion
5280 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5281 (beg (condition-case nil
5282 (progn (outline-back-to-heading) (point))
5283 (error (point-min))))
5284 (end (move-marker (make-marker)
5285 (progn (outline-next-heading) (point))))
5286 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5287 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5288 (re-find (concat re "\\|" re-box))
5289 beg-cookie end-cookie is-percent c-on c-off lim
5290 eline curr-ind next-ind continue-from startsearch
5291 (cstat 0)
5293 (when all
5294 (goto-char (point-min))
5295 (outline-next-heading)
5296 (setq beg (point) end (point-max)))
5297 (goto-char end)
5298 ;; find each statistic cookie
5299 (while (re-search-backward re-find beg t)
5300 (setq beg-cookie (match-beginning 1)
5301 end-cookie (match-end 1)
5302 cstat (+ cstat (if end-cookie 1 0))
5303 startsearch (point-at-eol)
5304 continue-from (point-at-bol)
5305 is-percent (match-beginning 2)
5306 lim (cond
5307 ((org-on-heading-p) (outline-next-heading) (point))
5308 ((org-at-item-p) (org-end-of-item) (point))
5309 (t nil))
5310 c-on 0
5311 c-off 0)
5312 (when lim
5313 ;; find first checkbox for this cookie and gather
5314 ;; statistics from all that are at this indentation level
5315 (goto-char startsearch)
5316 (if (re-search-forward re-box lim t)
5317 (progn
5318 (org-beginning-of-item)
5319 (setq curr-ind (org-get-indentation))
5320 (setq next-ind curr-ind)
5321 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5322 (save-excursion (end-of-line) (setq eline (point)))
5323 (if (re-search-forward re-box eline t)
5324 (if (member (match-string 2) '("[ ]" "[-]"))
5325 (setq c-off (1+ c-off))
5326 (setq c-on (1+ c-on))
5329 (org-end-of-item)
5330 (setq next-ind (org-get-indentation))
5332 (goto-char continue-from)
5333 ;; update cookie
5334 (when end-cookie
5335 (delete-region beg-cookie end-cookie)
5336 (goto-char beg-cookie)
5337 (insert
5338 (if is-percent
5339 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5340 (format "[%d/%d]" c-on (+ c-on c-off)))))
5341 ;; update items checkbox if it has one
5342 (when (org-at-item-p)
5343 (org-beginning-of-item)
5344 (when (and (> (+ c-on c-off) 0)
5345 (re-search-forward re-box (point-at-eol) t))
5346 (setq beg-cookie (match-beginning 2)
5347 end-cookie (match-end 2))
5348 (delete-region beg-cookie end-cookie)
5349 (goto-char beg-cookie)
5350 (cond ((= c-off 0) (insert "[X]"))
5351 ((= c-on 0) (insert "[ ]"))
5352 (t (insert "[-]")))
5354 (goto-char continue-from))
5355 (when (interactive-p)
5356 (message "Checkbox satistics updated %s (%d places)"
5357 (if all "in entire file" "in current outline entry") cstat)))))
5359 (defun org-get-checkbox-statistics-face ()
5360 "Select the face for checkbox statistics.
5361 The face will be `org-done' when all relevant boxes are checked. Otherwise
5362 it will be `org-todo'."
5363 (if (match-end 1)
5364 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5365 (if (and (> (match-end 2) (match-beginning 2))
5366 (equal (match-string 2) (match-string 3)))
5367 'org-done
5368 'org-todo)))
5370 (defun org-get-indentation (&optional line)
5371 "Get the indentation of the current line, interpreting tabs.
5372 When LINE is given, assume it represents a line and compute its indentation."
5373 (if line
5374 (if (string-match "^ *" (org-remove-tabs line))
5375 (match-end 0))
5376 (save-excursion
5377 (beginning-of-line 1)
5378 (skip-chars-forward " \t")
5379 (current-column))))
5381 (defun org-remove-tabs (s &optional width)
5382 "Replace tabulators in S with spaces.
5383 Assumes that s is a single line, starting in column 0."
5384 (setq width (or width tab-width))
5385 (while (string-match "\t" s)
5386 (setq s (replace-match
5387 (make-string
5388 (- (* width (/ (+ (match-beginning 0) width) width))
5389 (match-beginning 0)) ?\ )
5390 t t s)))
5393 (defun org-fix-indentation (line ind)
5394 "Fix indentation in LINE.
5395 IND is a cons cell with target and minimum indentation.
5396 If the current indenation in LINE is smaller than the minimum,
5397 leave it alone. If it is larger than ind, set it to the target."
5398 (let* ((l (org-remove-tabs line))
5399 (i (org-get-indentation l))
5400 (i1 (car ind)) (i2 (cdr ind)))
5401 (if (>= i i2) (setq l (substring line i2)))
5402 (if (> i1 0)
5403 (concat (make-string i1 ?\ ) l)
5404 l)))
5406 (defun org-beginning-of-item ()
5407 "Go to the beginning of the current hand-formatted item.
5408 If the cursor is not in an item, throw an error."
5409 (interactive)
5410 (let ((pos (point))
5411 (limit (save-excursion
5412 (condition-case nil
5413 (progn
5414 (org-back-to-heading)
5415 (beginning-of-line 2) (point))
5416 (error (point-min)))))
5417 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5418 ind ind1)
5419 (if (org-at-item-p)
5420 (beginning-of-line 1)
5421 (beginning-of-line 1)
5422 (skip-chars-forward " \t")
5423 (setq ind (current-column))
5424 (if (catch 'exit
5425 (while t
5426 (beginning-of-line 0)
5427 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5429 (if (looking-at "[ \t]*$")
5430 (setq ind1 ind-empty)
5431 (skip-chars-forward " \t")
5432 (setq ind1 (current-column)))
5433 (if (< ind1 ind)
5434 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5436 (goto-char pos)
5437 (error "Not in an item")))))
5439 (defun org-end-of-item ()
5440 "Go to the end of the current hand-formatted item.
5441 If the cursor is not in an item, throw an error."
5442 (interactive)
5443 (let* ((pos (point))
5444 ind1
5445 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5446 (limit (save-excursion (outline-next-heading) (point)))
5447 (ind (save-excursion
5448 (org-beginning-of-item)
5449 (skip-chars-forward " \t")
5450 (current-column)))
5451 (end (catch 'exit
5452 (while t
5453 (beginning-of-line 2)
5454 (if (eobp) (throw 'exit (point)))
5455 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5456 (if (looking-at "[ \t]*$")
5457 (setq ind1 ind-empty)
5458 (skip-chars-forward " \t")
5459 (setq ind1 (current-column)))
5460 (if (<= ind1 ind)
5461 (throw 'exit (point-at-bol)))))))
5462 (if end
5463 (goto-char end)
5464 (goto-char pos)
5465 (error "Not in an item"))))
5467 (defun org-next-item ()
5468 "Move to the beginning of the next item in the current plain list.
5469 Error if not at a plain list, or if this is the last item in the list."
5470 (interactive)
5471 (let (ind ind1 (pos (point)))
5472 (org-beginning-of-item)
5473 (setq ind (org-get-indentation))
5474 (org-end-of-item)
5475 (setq ind1 (org-get-indentation))
5476 (unless (and (org-at-item-p) (= ind ind1))
5477 (goto-char pos)
5478 (error "On last item"))))
5480 (defun org-previous-item ()
5481 "Move to the beginning of the previous item in the current plain list.
5482 Error if not at a plain list, or if this is the first item in the list."
5483 (interactive)
5484 (let (beg ind ind1 (pos (point)))
5485 (org-beginning-of-item)
5486 (setq beg (point))
5487 (setq ind (org-get-indentation))
5488 (goto-char beg)
5489 (catch 'exit
5490 (while t
5491 (beginning-of-line 0)
5492 (if (looking-at "[ \t]*$")
5494 (if (<= (setq ind1 (org-get-indentation)) ind)
5495 (throw 'exit t)))))
5496 (condition-case nil
5497 (if (or (not (org-at-item-p))
5498 (< ind1 (1- ind)))
5499 (error "")
5500 (org-beginning-of-item))
5501 (error (goto-char pos)
5502 (error "On first item")))))
5504 (defun org-first-list-item-p ()
5505 "Is this heading the item in a plain list?"
5506 (unless (org-at-item-p)
5507 (error "Not at a plain list item"))
5508 (org-beginning-of-item)
5509 (= (point) (save-excursion (org-beginning-of-item-list))))
5511 (defun org-move-item-down ()
5512 "Move the plain list item at point down, i.e. swap with following item.
5513 Subitems (items with larger indentation) are considered part of the item,
5514 so this really moves item trees."
5515 (interactive)
5516 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5517 (org-beginning-of-item)
5518 (setq beg0 (point))
5519 (save-excursion
5520 (setq ne-beg (org-back-over-empty-lines))
5521 (setq beg (point)))
5522 (goto-char beg0)
5523 (setq ind (org-get-indentation))
5524 (org-end-of-item)
5525 (setq end0 (point))
5526 (setq ind1 (org-get-indentation))
5527 (setq ne-end (org-back-over-empty-lines))
5528 (setq end (point))
5529 (goto-char beg0)
5530 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5531 ;; include less whitespace
5532 (save-excursion
5533 (goto-char beg)
5534 (forward-line (- ne-beg ne-end))
5535 (setq beg (point))))
5536 (goto-char end0)
5537 (if (and (org-at-item-p) (= ind ind1))
5538 (progn
5539 (org-end-of-item)
5540 (org-back-over-empty-lines)
5541 (setq txt (buffer-substring beg end))
5542 (save-excursion
5543 (delete-region beg end))
5544 (setq pos (point))
5545 (insert txt)
5546 (goto-char pos) (org-skip-whitespace)
5547 (org-maybe-renumber-ordered-list))
5548 (goto-char pos)
5549 (error "Cannot move this item further down"))))
5551 (defun org-move-item-up (arg)
5552 "Move the plain list item at point up, i.e. swap with previous item.
5553 Subitems (items with larger indentation) are considered part of the item,
5554 so this really moves item trees."
5555 (interactive "p")
5556 (let (beg beg0 end ind ind1 (pos (point)) txt
5557 ne-beg ne-ins ins-end)
5558 (org-beginning-of-item)
5559 (setq beg0 (point))
5560 (setq ind (org-get-indentation))
5561 (save-excursion
5562 (setq ne-beg (org-back-over-empty-lines))
5563 (setq beg (point)))
5564 (goto-char beg0)
5565 (org-end-of-item)
5566 (setq end (point))
5567 (goto-char beg0)
5568 (catch 'exit
5569 (while t
5570 (beginning-of-line 0)
5571 (if (looking-at "[ \t]*$")
5572 (if org-empty-line-terminates-plain-lists
5573 (progn
5574 (goto-char pos)
5575 (error "Cannot move this item further up"))
5576 nil)
5577 (if (<= (setq ind1 (org-get-indentation)) ind)
5578 (throw 'exit t)))))
5579 (condition-case nil
5580 (org-beginning-of-item)
5581 (error (goto-char beg)
5582 (error "Cannot move this item further up")))
5583 (setq ind1 (org-get-indentation))
5584 (if (and (org-at-item-p) (= ind ind1))
5585 (progn
5586 (setq ne-ins (org-back-over-empty-lines))
5587 (setq txt (buffer-substring beg end))
5588 (save-excursion
5589 (delete-region beg end))
5590 (setq pos (point))
5591 (insert txt)
5592 (setq ins-end (point))
5593 (goto-char pos) (org-skip-whitespace)
5595 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5596 ;; Move whitespace back to beginning
5597 (save-excursion
5598 (goto-char ins-end)
5599 (let ((kill-whole-line t))
5600 (kill-line (- ne-ins ne-beg)) (point)))
5601 (insert (make-string (- ne-ins ne-beg) ?\n)))
5603 (org-maybe-renumber-ordered-list))
5604 (goto-char pos)
5605 (error "Cannot move this item further up"))))
5607 (defun org-maybe-renumber-ordered-list ()
5608 "Renumber the ordered list at point if setup allows it.
5609 This tests the user option `org-auto-renumber-ordered-lists' before
5610 doing the renumbering."
5611 (interactive)
5612 (when (and org-auto-renumber-ordered-lists
5613 (org-at-item-p))
5614 (if (match-beginning 3)
5615 (org-renumber-ordered-list 1)
5616 (org-fix-bullet-type))))
5618 (defun org-maybe-renumber-ordered-list-safe ()
5619 (condition-case nil
5620 (save-excursion
5621 (org-maybe-renumber-ordered-list))
5622 (error nil)))
5624 (defun org-cycle-list-bullet (&optional which)
5625 "Cycle through the different itemize/enumerate bullets.
5626 This cycle the entire list level through the sequence:
5628 `-' -> `+' -> `*' -> `1.' -> `1)'
5630 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5631 0 meand `-', 1 means `+' etc."
5632 (interactive "P")
5633 (org-preserve-lc
5634 (org-beginning-of-item-list)
5635 (org-at-item-p)
5636 (beginning-of-line 1)
5637 (let ((current (match-string 0))
5638 (prevp (eq which 'previous))
5639 new)
5640 (setq new (cond
5641 ((and (numberp which)
5642 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5643 ((string-match "-" current) (if prevp "1)" "+"))
5644 ((string-match "\\+" current)
5645 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5646 ((string-match "\\*" current) (if prevp "+" "1."))
5647 ((string-match "\\." current) (if prevp "*" "1)"))
5648 ((string-match ")" current) (if prevp "1." "-"))
5649 (t (error "This should not happen"))))
5650 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5651 (org-fix-bullet-type)
5652 (org-maybe-renumber-ordered-list))))
5654 (defun org-get-string-indentation (s)
5655 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5656 (let ((n -1) (i 0) (w tab-width) c)
5657 (catch 'exit
5658 (while (< (setq n (1+ n)) (length s))
5659 (setq c (aref s n))
5660 (cond ((= c ?\ ) (setq i (1+ i)))
5661 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5662 (t (throw 'exit t)))))
5665 (defun org-renumber-ordered-list (arg)
5666 "Renumber an ordered plain list.
5667 Cursor needs to be in the first line of an item, the line that starts
5668 with something like \"1.\" or \"2)\"."
5669 (interactive "p")
5670 (unless (and (org-at-item-p)
5671 (match-beginning 3))
5672 (error "This is not an ordered list"))
5673 (let ((line (org-current-line))
5674 (col (current-column))
5675 (ind (org-get-string-indentation
5676 (buffer-substring (point-at-bol) (match-beginning 3))))
5677 ;; (term (substring (match-string 3) -1))
5678 ind1 (n (1- arg))
5679 fmt)
5680 ;; find where this list begins
5681 (org-beginning-of-item-list)
5682 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5683 (setq fmt (concat "%d" (match-string 1)))
5684 (beginning-of-line 0)
5685 ;; walk forward and replace these numbers
5686 (catch 'exit
5687 (while t
5688 (catch 'next
5689 (beginning-of-line 2)
5690 (if (eobp) (throw 'exit nil))
5691 (if (looking-at "[ \t]*$") (throw 'next nil))
5692 (skip-chars-forward " \t") (setq ind1 (current-column))
5693 (if (> ind1 ind) (throw 'next t))
5694 (if (< ind1 ind) (throw 'exit t))
5695 (if (not (org-at-item-p)) (throw 'exit nil))
5696 (delete-region (match-beginning 2) (match-end 2))
5697 (goto-char (match-beginning 2))
5698 (insert (format fmt (setq n (1+ n)))))))
5699 (goto-line line)
5700 (org-move-to-column col)))
5702 (defun org-fix-bullet-type ()
5703 "Make sure all items in this list have the same bullet as the firsst item."
5704 (interactive)
5705 (unless (org-at-item-p) (error "This is not a list"))
5706 (let ((line (org-current-line))
5707 (col (current-column))
5708 (ind (current-indentation))
5709 ind1 bullet)
5710 ;; find where this list begins
5711 (org-beginning-of-item-list)
5712 (beginning-of-line 1)
5713 ;; find out what the bullet type is
5714 (looking-at "[ \t]*\\(\\S-+\\)")
5715 (setq bullet (match-string 1))
5716 ;; walk forward and replace these numbers
5717 (beginning-of-line 0)
5718 (catch 'exit
5719 (while t
5720 (catch 'next
5721 (beginning-of-line 2)
5722 (if (eobp) (throw 'exit nil))
5723 (if (looking-at "[ \t]*$") (throw 'next nil))
5724 (skip-chars-forward " \t") (setq ind1 (current-column))
5725 (if (> ind1 ind) (throw 'next t))
5726 (if (< ind1 ind) (throw 'exit t))
5727 (if (not (org-at-item-p)) (throw 'exit nil))
5728 (skip-chars-forward " \t")
5729 (looking-at "\\S-+")
5730 (replace-match bullet))))
5731 (goto-line line)
5732 (org-move-to-column col)
5733 (if (string-match "[0-9]" bullet)
5734 (org-renumber-ordered-list 1))))
5736 (defun org-beginning-of-item-list ()
5737 "Go to the beginning of the current item list.
5738 I.e. to the first item in this list."
5739 (interactive)
5740 (org-beginning-of-item)
5741 (let ((pos (point-at-bol))
5742 (ind (org-get-indentation))
5743 ind1)
5744 ;; find where this list begins
5745 (catch 'exit
5746 (while t
5747 (catch 'next
5748 (beginning-of-line 0)
5749 (if (looking-at "[ \t]*$")
5750 (throw (if (bobp) 'exit 'next) t))
5751 (skip-chars-forward " \t") (setq ind1 (current-column))
5752 (if (or (< ind1 ind)
5753 (and (= ind1 ind)
5754 (not (org-at-item-p)))
5755 (bobp))
5756 (throw 'exit t)
5757 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5758 (goto-char pos)))
5761 (defun org-end-of-item-list ()
5762 "Go to the end of the current item list.
5763 I.e. to the text after the last item."
5764 (interactive)
5765 (org-beginning-of-item)
5766 (let ((pos (point-at-bol))
5767 (ind (org-get-indentation))
5768 ind1)
5769 ;; find where this list begins
5770 (catch 'exit
5771 (while t
5772 (catch 'next
5773 (beginning-of-line 2)
5774 (if (looking-at "[ \t]*$")
5775 (throw (if (eobp) 'exit 'next) t))
5776 (skip-chars-forward " \t") (setq ind1 (current-column))
5777 (if (or (< ind1 ind)
5778 (and (= ind1 ind)
5779 (not (org-at-item-p)))
5780 (eobp))
5781 (progn
5782 (setq pos (point-at-bol))
5783 (throw 'exit t))))))
5784 (goto-char pos)))
5787 (defvar org-last-indent-begin-marker (make-marker))
5788 (defvar org-last-indent-end-marker (make-marker))
5790 (defun org-outdent-item (arg)
5791 "Outdent a local list item."
5792 (interactive "p")
5793 (org-indent-item (- arg)))
5795 (defun org-indent-item (arg)
5796 "Indent a local list item."
5797 (interactive "p")
5798 (unless (org-at-item-p)
5799 (error "Not on an item"))
5800 (save-excursion
5801 (let (beg end ind ind1 tmp delta ind-down ind-up)
5802 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5803 (setq beg org-last-indent-begin-marker
5804 end org-last-indent-end-marker)
5805 (org-beginning-of-item)
5806 (setq beg (move-marker org-last-indent-begin-marker (point)))
5807 (org-end-of-item)
5808 (setq end (move-marker org-last-indent-end-marker (point))))
5809 (goto-char beg)
5810 (setq tmp (org-item-indent-positions)
5811 ind (car tmp)
5812 ind-down (nth 2 tmp)
5813 ind-up (nth 1 tmp)
5814 delta (if (> arg 0)
5815 (if ind-down (- ind-down ind) 2)
5816 (if ind-up (- ind-up ind) -2)))
5817 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5818 (while (< (point) end)
5819 (beginning-of-line 1)
5820 (skip-chars-forward " \t") (setq ind1 (current-column))
5821 (delete-region (point-at-bol) (point))
5822 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5823 (beginning-of-line 2))))
5824 (org-fix-bullet-type)
5825 (org-maybe-renumber-ordered-list-safe)
5826 (save-excursion
5827 (beginning-of-line 0)
5828 (condition-case nil (org-beginning-of-item) (error nil))
5829 (org-maybe-renumber-ordered-list-safe)))
5831 (defun org-item-indent-positions ()
5832 "Return indentation for plain list items.
5833 This returns a list with three values: The current indentation, the
5834 parent indentation and the indentation a child should habe.
5835 Assumes cursor in item line."
5836 (let* ((bolpos (point-at-bol))
5837 (ind (org-get-indentation))
5838 ind-down ind-up pos)
5839 (save-excursion
5840 (org-beginning-of-item-list)
5841 (skip-chars-backward "\n\r \t")
5842 (when (org-in-item-p)
5843 (org-beginning-of-item)
5844 (setq ind-up (org-get-indentation))))
5845 (setq pos (point))
5846 (save-excursion
5847 (cond
5848 ((and (condition-case nil (progn (org-previous-item) t)
5849 (error nil))
5850 (or (forward-char 1) t)
5851 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5852 (setq ind-down (org-get-indentation)))
5853 ((and (goto-char pos)
5854 (org-at-item-p))
5855 (goto-char (match-end 0))
5856 (skip-chars-forward " \t")
5857 (setq ind-down (current-column)))))
5858 (list ind ind-up ind-down)))
5860 ;;; The orgstruct minor mode
5862 ;; Define a minor mode which can be used in other modes in order to
5863 ;; integrate the org-mode structure editing commands.
5865 ;; This is really a hack, because the org-mode structure commands use
5866 ;; keys which normally belong to the major mode. Here is how it
5867 ;; works: The minor mode defines all the keys necessary to operate the
5868 ;; structure commands, but wraps the commands into a function which
5869 ;; tests if the cursor is currently at a headline or a plain list
5870 ;; item. If that is the case, the structure command is used,
5871 ;; temporarily setting many Org-mode variables like regular
5872 ;; expressions for filling etc. However, when any of those keys is
5873 ;; used at a different location, function uses `key-binding' to look
5874 ;; up if the key has an associated command in another currently active
5875 ;; keymap (minor modes, major mode, global), and executes that
5876 ;; command. There might be problems if any of the keys is otherwise
5877 ;; used as a prefix key.
5879 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5880 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5881 ;; addresses this by checking explicitly for both bindings.
5883 (defvar orgstruct-mode-map (make-sparse-keymap)
5884 "Keymap for the minor `orgstruct-mode'.")
5886 (defvar org-local-vars nil
5887 "List of local variables, for use by `orgstruct-mode'")
5889 ;;;###autoload
5890 (define-minor-mode orgstruct-mode
5891 "Toggle the minor more `orgstruct-mode'.
5892 This mode is for using Org-mode structure commands in other modes.
5893 The following key behave as if Org-mode was active, if the cursor
5894 is on a headline, or on a plain list item (both in the definition
5895 of Org-mode).
5897 M-up Move entry/item up
5898 M-down Move entry/item down
5899 M-left Promote
5900 M-right Demote
5901 M-S-up Move entry/item up
5902 M-S-down Move entry/item down
5903 M-S-left Promote subtree
5904 M-S-right Demote subtree
5905 M-q Fill paragraph and items like in Org-mode
5906 C-c ^ Sort entries
5907 C-c - Cycle list bullet
5908 TAB Cycle item visibility
5909 M-RET Insert new heading/item
5910 S-M-RET Insert new TODO heading / Chekbox item
5911 C-c C-c Set tags / toggle checkbox"
5912 nil " OrgStruct" nil
5913 (org-load-modules-maybe)
5914 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5916 ;;;###autoload
5917 (defun turn-on-orgstruct ()
5918 "Unconditionally turn on `orgstruct-mode'."
5919 (orgstruct-mode 1))
5921 ;;;###autoload
5922 (defun turn-on-orgstruct++ ()
5923 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5924 In addition to setting orgstruct-mode, this also exports all indentation and
5925 autofilling variables from org-mode into the buffer. Note that turning
5926 off orgstruct-mode will *not* remove these additional settings."
5927 (orgstruct-mode 1)
5928 (let (var val)
5929 (mapc
5930 (lambda (x)
5931 (when (string-match
5932 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5933 (symbol-name (car x)))
5934 (setq var (car x) val (nth 1 x))
5935 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5936 org-local-vars)))
5938 (defun orgstruct-error ()
5939 "Error when there is no default binding for a structure key."
5940 (interactive)
5941 (error "This key has no function outside structure elements"))
5943 (defun orgstruct-setup ()
5944 "Setup orgstruct keymaps."
5945 (let ((nfunc 0)
5946 (bindings
5947 (list
5948 '([(meta up)] org-metaup)
5949 '([(meta down)] org-metadown)
5950 '([(meta left)] org-metaleft)
5951 '([(meta right)] org-metaright)
5952 '([(meta shift up)] org-shiftmetaup)
5953 '([(meta shift down)] org-shiftmetadown)
5954 '([(meta shift left)] org-shiftmetaleft)
5955 '([(meta shift right)] org-shiftmetaright)
5956 '([(shift up)] org-shiftup)
5957 '([(shift down)] org-shiftdown)
5958 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5959 '("\M-q" fill-paragraph)
5960 '("\C-c^" org-sort)
5961 '("\C-c-" org-cycle-list-bullet)))
5962 elt key fun cmd)
5963 (while (setq elt (pop bindings))
5964 (setq nfunc (1+ nfunc))
5965 (setq key (org-key (car elt))
5966 fun (nth 1 elt)
5967 cmd (orgstruct-make-binding fun nfunc key))
5968 (org-defkey orgstruct-mode-map key cmd))
5970 ;; Special treatment needed for TAB and RET
5971 (org-defkey orgstruct-mode-map [(tab)]
5972 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5973 (org-defkey orgstruct-mode-map "\C-i"
5974 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5976 (org-defkey orgstruct-mode-map "\M-\C-m"
5977 (orgstruct-make-binding 'org-insert-heading 105
5978 "\M-\C-m" [(meta return)]))
5979 (org-defkey orgstruct-mode-map [(meta return)]
5980 (orgstruct-make-binding 'org-insert-heading 106
5981 [(meta return)] "\M-\C-m"))
5983 (org-defkey orgstruct-mode-map [(shift meta return)]
5984 (orgstruct-make-binding 'org-insert-todo-heading 107
5985 [(meta return)] "\M-\C-m"))
5987 (unless org-local-vars
5988 (setq org-local-vars (org-get-local-variables)))
5992 (defun orgstruct-make-binding (fun n &rest keys)
5993 "Create a function for binding in the structure minor mode.
5994 FUN is the command to call inside a table. N is used to create a unique
5995 command name. KEYS are keys that should be checked in for a command
5996 to execute outside of tables."
5997 (eval
5998 (list 'defun
5999 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6000 '(arg)
6001 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6002 "Outside of structure, run the binding of `"
6003 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6004 "'.")
6005 '(interactive "p")
6006 (list 'if
6007 '(org-context-p 'headline 'item)
6008 (list 'org-run-like-in-org-mode (list 'quote fun))
6009 (list 'let '(orgstruct-mode)
6010 (list 'call-interactively
6011 (append '(or)
6012 (mapcar (lambda (k)
6013 (list 'key-binding k))
6014 keys)
6015 '('orgstruct-error))))))))
6017 (defun org-context-p (&rest contexts)
6018 "Check if local context is and of CONTEXTS.
6019 Possible values in the list of contexts are `table', `headline', and `item'."
6020 (let ((pos (point)))
6021 (goto-char (point-at-bol))
6022 (prog1 (or (and (memq 'table contexts)
6023 (looking-at "[ \t]*|"))
6024 (and (memq 'headline contexts)
6025 (looking-at "\\*+"))
6026 (and (memq 'item contexts)
6027 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6028 (goto-char pos))))
6030 (defun org-get-local-variables ()
6031 "Return a list of all local variables in an org-mode buffer."
6032 (let (varlist)
6033 (with-current-buffer (get-buffer-create "*Org tmp*")
6034 (erase-buffer)
6035 (org-mode)
6036 (setq varlist (buffer-local-variables)))
6037 (kill-buffer "*Org tmp*")
6038 (delq nil
6039 (mapcar
6040 (lambda (x)
6041 (setq x
6042 (if (symbolp x)
6043 (list x)
6044 (list (car x) (list 'quote (cdr x)))))
6045 (if (string-match
6046 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6047 (symbol-name (car x)))
6048 x nil))
6049 varlist))))
6051 ;;;###autoload
6052 (defun org-run-like-in-org-mode (cmd)
6053 (org-load-modules-maybe)
6054 (unless org-local-vars
6055 (setq org-local-vars (org-get-local-variables)))
6056 (eval (list 'let org-local-vars
6057 (list 'call-interactively (list 'quote cmd)))))
6059 ;;;; Archiving
6061 (defun org-get-category (&optional pos)
6062 "Get the category applying to position POS."
6063 (get-text-property (or pos (point)) 'org-category))
6065 (defun org-refresh-category-properties ()
6066 "Refresh category text properties in the buffer."
6067 (let ((def-cat (cond
6068 ((null org-category)
6069 (if buffer-file-name
6070 (file-name-sans-extension
6071 (file-name-nondirectory buffer-file-name))
6072 "???"))
6073 ((symbolp org-category) (symbol-name org-category))
6074 (t org-category)))
6075 beg end cat pos optionp)
6076 (org-unmodified
6077 (save-excursion
6078 (save-restriction
6079 (widen)
6080 (goto-char (point-min))
6081 (put-text-property (point) (point-max) 'org-category def-cat)
6082 (while (re-search-forward
6083 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6084 (setq pos (match-end 0)
6085 optionp (equal (char-after (match-beginning 0)) ?#)
6086 cat (org-trim (match-string 2)))
6087 (if optionp
6088 (setq beg (point-at-bol) end (point-max))
6089 (org-back-to-heading t)
6090 (setq beg (point) end (org-end-of-subtree t t)))
6091 (put-text-property beg end 'org-category cat)
6092 (goto-char pos)))))))
6095 ;;;; Link Stuff
6097 ;;; Link abbreviations
6099 (defun org-link-expand-abbrev (link)
6100 "Apply replacements as defined in `org-link-abbrev-alist."
6101 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6102 (let* ((key (match-string 1 link))
6103 (as (or (assoc key org-link-abbrev-alist-local)
6104 (assoc key org-link-abbrev-alist)))
6105 (tag (and (match-end 2) (match-string 3 link)))
6106 rpl)
6107 (if (not as)
6108 link
6109 (setq rpl (cdr as))
6110 (cond
6111 ((symbolp rpl) (funcall rpl tag))
6112 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6113 (t (concat rpl tag)))))
6114 link))
6116 ;;; Storing and inserting links
6118 (defvar org-insert-link-history nil
6119 "Minibuffer history for links inserted with `org-insert-link'.")
6121 (defvar org-stored-links nil
6122 "Contains the links stored with `org-store-link'.")
6124 (defvar org-store-link-plist nil
6125 "Plist with info about the most recently link created with `org-store-link'.")
6127 (defvar org-link-protocols nil
6128 "Link protocols added to Org-mode using `org-add-link-type'.")
6130 (defvar org-store-link-functions nil
6131 "List of functions that are called to create and store a link.
6132 Each function will be called in turn until one returns a non-nil
6133 value. Each function should check if it is responsible for creating
6134 this link (for example by looking at the major mode).
6135 If not, it must exit and return nil.
6136 If yes, it should return a non-nil value after a calling
6137 `org-store-link-props' with a list of properties and values.
6138 Special properties are:
6140 :type The link prefix. like \"http\". This must be given.
6141 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6142 This is obligatory as well.
6143 :description Optional default description for the second pair
6144 of brackets in an Org-mode link. The user can still change
6145 this when inserting this link into an Org-mode buffer.
6147 In addition to these, any additional properties can be specified
6148 and then used in remember templates.")
6150 (defun org-add-link-type (type &optional follow export)
6151 "Add TYPE to the list of `org-link-types'.
6152 Re-compute all regular expressions depending on `org-link-types'
6154 FOLLOW and EXPORT are two functions.
6156 FOLLOW should take the link path as the single argument and do whatever
6157 is necessary to follow the link, for example find a file or display
6158 a mail message.
6160 EXPORT should format the link path for export to one of the export formats.
6161 It should be a function accepting three arguments:
6163 path the path of the link, the text after the prefix (like \"http:\")
6164 desc the description of the link, if any, nil if there was no descripton
6165 format the export format, a symbol like `html' or `latex'.
6167 The function may use the FORMAT information to return different values
6168 depending on the format. The return value will be put literally into
6169 the exported file.
6170 Org-mode has a built-in default for exporting links. If you are happy with
6171 this default, there is no need to define an export function for the link
6172 type. For a simple example of an export function, see `org-bbdb.el'."
6173 (add-to-list 'org-link-types type t)
6174 (org-make-link-regexps)
6175 (if (assoc type org-link-protocols)
6176 (setcdr (assoc type org-link-protocols) (list follow export))
6177 (push (list type follow export) org-link-protocols)))
6180 ;;;###autoload
6181 (defun org-store-link (arg)
6182 "\\<org-mode-map>Store an org-link to the current location.
6183 This link is added to `org-stored-links' and can later be inserted
6184 into an org-buffer with \\[org-insert-link].
6186 For some link types, a prefix arg is interpreted:
6187 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6188 For file links, arg negates `org-context-in-file-links'."
6189 (interactive "P")
6190 (org-load-modules-maybe)
6191 (setq org-store-link-plist nil) ; reset
6192 (let (link cpltxt desc description search txt)
6193 (cond
6195 ((run-hook-with-args-until-success 'org-store-link-functions)
6196 (setq link (plist-get org-store-link-plist :link)
6197 desc (or (plist-get org-store-link-plist :description) link)))
6199 ((eq major-mode 'calendar-mode)
6200 (let ((cd (calendar-cursor-to-date)))
6201 (setq link
6202 (format-time-string
6203 (car org-time-stamp-formats)
6204 (apply 'encode-time
6205 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6206 nil nil nil))))
6207 (org-store-link-props :type "calendar" :date cd)))
6209 ((eq major-mode 'w3-mode)
6210 (setq cpltxt (url-view-url t)
6211 link (org-make-link cpltxt))
6212 (org-store-link-props :type "w3" :url (url-view-url t)))
6214 ((eq major-mode 'w3m-mode)
6215 (setq cpltxt (or w3m-current-title w3m-current-url)
6216 link (org-make-link w3m-current-url))
6217 (org-store-link-props :type "w3m" :url (url-view-url t)))
6219 ((setq search (run-hook-with-args-until-success
6220 'org-create-file-search-functions))
6221 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6222 "::" search))
6223 (setq cpltxt (or description link)))
6225 ((eq major-mode 'image-mode)
6226 (setq cpltxt (concat "file:"
6227 (abbreviate-file-name buffer-file-name))
6228 link (org-make-link cpltxt))
6229 (org-store-link-props :type "image" :file buffer-file-name))
6231 ((eq major-mode 'dired-mode)
6232 ;; link to the file in the current line
6233 (setq cpltxt (concat "file:"
6234 (abbreviate-file-name
6235 (expand-file-name
6236 (dired-get-filename nil t))))
6237 link (org-make-link cpltxt)))
6239 ((and buffer-file-name (org-mode-p))
6240 ;; Just link to current headline
6241 (setq cpltxt (concat "file:"
6242 (abbreviate-file-name buffer-file-name)))
6243 ;; Add a context search string
6244 (when (org-xor org-context-in-file-links arg)
6245 ;; Check if we are on a target
6246 (if (org-in-regexp "<<\\(.*?\\)>>")
6247 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6248 (setq txt (cond
6249 ((org-on-heading-p) nil)
6250 ((org-region-active-p)
6251 (buffer-substring (region-beginning) (region-end)))
6252 (t nil)))
6253 (when (or (null txt) (string-match "\\S-" txt))
6254 (setq cpltxt
6255 (concat cpltxt "::"
6256 (condition-case nil
6257 (org-make-org-heading-search-string txt)
6258 (error "")))
6259 desc "NONE"))))
6260 (if (string-match "::\\'" cpltxt)
6261 (setq cpltxt (substring cpltxt 0 -2)))
6262 (setq link (org-make-link cpltxt)))
6264 ((buffer-file-name (buffer-base-buffer))
6265 ;; Just link to this file here.
6266 (setq cpltxt (concat "file:"
6267 (abbreviate-file-name
6268 (buffer-file-name (buffer-base-buffer)))))
6269 ;; Add a context string
6270 (when (org-xor org-context-in-file-links arg)
6271 (setq txt (if (org-region-active-p)
6272 (buffer-substring (region-beginning) (region-end))
6273 (buffer-substring (point-at-bol) (point-at-eol))))
6274 ;; Only use search option if there is some text.
6275 (when (string-match "\\S-" txt)
6276 (setq cpltxt
6277 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6278 desc "NONE")))
6279 (setq link (org-make-link cpltxt)))
6281 ((interactive-p)
6282 (error "Cannot link to a buffer which is not visiting a file"))
6284 (t (setq link nil)))
6286 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6287 (setq link (or link cpltxt)
6288 desc (or desc cpltxt))
6289 (if (equal desc "NONE") (setq desc nil))
6291 (if (and (interactive-p) link)
6292 (progn
6293 (setq org-stored-links
6294 (cons (list link desc) org-stored-links))
6295 (message "Stored: %s" (or desc link)))
6296 (and link (org-make-link-string link desc)))))
6298 (defun org-store-link-props (&rest plist)
6299 "Store link properties, extract names and addresses."
6300 (let (x adr)
6301 (when (setq x (plist-get plist :from))
6302 (setq adr (mail-extract-address-components x))
6303 (plist-put plist :fromname (car adr))
6304 (plist-put plist :fromaddress (nth 1 adr)))
6305 (when (setq x (plist-get plist :to))
6306 (setq adr (mail-extract-address-components x))
6307 (plist-put plist :toname (car adr))
6308 (plist-put plist :toaddress (nth 1 adr))))
6309 (let ((from (plist-get plist :from))
6310 (to (plist-get plist :to)))
6311 (when (and from to org-from-is-user-regexp)
6312 (plist-put plist :fromto
6313 (if (string-match org-from-is-user-regexp from)
6314 (concat "to %t")
6315 (concat "from %f")))))
6316 (setq org-store-link-plist plist))
6318 (defun org-add-link-props (&rest plist)
6319 "Add these properties to the link property list."
6320 (let (key value)
6321 (while plist
6322 (setq key (pop plist) value (pop plist))
6323 (setq org-store-link-plist
6324 (plist-put org-store-link-plist key value)))))
6326 (defun org-email-link-description (&optional fmt)
6327 "Return the description part of an email link.
6328 This takes information from `org-store-link-plist' and formats it
6329 according to FMT (default from `org-email-link-description-format')."
6330 (setq fmt (or fmt org-email-link-description-format))
6331 (let* ((p org-store-link-plist)
6332 (to (plist-get p :toaddress))
6333 (from (plist-get p :fromaddress))
6334 (table
6335 (list
6336 (cons "%c" (plist-get p :fromto))
6337 (cons "%F" (plist-get p :from))
6338 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6339 (cons "%T" (plist-get p :to))
6340 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6341 (cons "%s" (plist-get p :subject))
6342 (cons "%m" (plist-get p :message-id)))))
6343 (when (string-match "%c" fmt)
6344 ;; Check if the user wrote this message
6345 (if (and org-from-is-user-regexp from to
6346 (save-match-data (string-match org-from-is-user-regexp from)))
6347 (setq fmt (replace-match "to %t" t t fmt))
6348 (setq fmt (replace-match "from %f" t t fmt))))
6349 (org-replace-escapes fmt table)))
6351 (defun org-make-org-heading-search-string (&optional string heading)
6352 "Make search string for STRING or current headline."
6353 (interactive)
6354 (let ((s (or string (org-get-heading))))
6355 (unless (and string (not heading))
6356 ;; We are using a headline, clean up garbage in there.
6357 (if (string-match org-todo-regexp s)
6358 (setq s (replace-match "" t t s)))
6359 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6360 (setq s (replace-match "" t t s)))
6361 (setq s (org-trim s))
6362 (if (string-match (concat "^\\(" org-quote-string "\\|"
6363 org-comment-string "\\)") s)
6364 (setq s (replace-match "" t t s)))
6365 (while (string-match org-ts-regexp s)
6366 (setq s (replace-match "" t t s))))
6367 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6368 (setq s (replace-match " " t t s)))
6369 (or string (setq s (concat "*" s))) ; Add * for headlines
6370 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6372 (defun org-make-link (&rest strings)
6373 "Concatenate STRINGS."
6374 (apply 'concat strings))
6376 (defun org-make-link-string (link &optional description)
6377 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6378 (unless (string-match "\\S-" link)
6379 (error "Empty link"))
6380 (when (stringp description)
6381 ;; Remove brackets from the description, they are fatal.
6382 (while (string-match "\\[" description)
6383 (setq description (replace-match "{" t t description)))
6384 (while (string-match "\\]" description)
6385 (setq description (replace-match "}" t t description))))
6386 (when (equal (org-link-escape link) description)
6387 ;; No description needed, it is identical
6388 (setq description nil))
6389 (when (and (not description)
6390 (not (equal link (org-link-escape link))))
6391 (setq description link))
6392 (concat "[[" (org-link-escape link) "]"
6393 (if description (concat "[" description "]") "")
6394 "]"))
6396 (defconst org-link-escape-chars
6397 '((?\ . "%20")
6398 (?\[ . "%5B")
6399 (?\] . "%5D")
6400 (?\340 . "%E0") ; `a
6401 (?\342 . "%E2") ; ^a
6402 (?\347 . "%E7") ; ,c
6403 (?\350 . "%E8") ; `e
6404 (?\351 . "%E9") ; 'e
6405 (?\352 . "%EA") ; ^e
6406 (?\356 . "%EE") ; ^i
6407 (?\364 . "%F4") ; ^o
6408 (?\371 . "%F9") ; `u
6409 (?\373 . "%FB") ; ^u
6410 (?\; . "%3B")
6411 (?? . "%3F")
6412 (?= . "%3D")
6413 (?+ . "%2B")
6415 "Association list of escapes for some characters problematic in links.
6416 This is the list that is used for internal purposes.")
6418 (defconst org-link-escape-chars-browser
6419 '((?\ . "%20")) ; 32 for the SPC char
6420 "Association list of escapes for some characters problematic in links.
6421 This is the list that is used before handing over to the browser.")
6423 (defun org-link-escape (text &optional table)
6424 "Escape charaters in TEXT that are problematic for links."
6425 (setq table (or table org-link-escape-chars))
6426 (when text
6427 (let ((re (mapconcat (lambda (x) (regexp-quote
6428 (char-to-string (car x))))
6429 table "\\|")))
6430 (while (string-match re text)
6431 (setq text
6432 (replace-match
6433 (cdr (assoc (string-to-char (match-string 0 text))
6434 table))
6435 t t text)))
6436 text)))
6438 (defun org-link-unescape (text &optional table)
6439 "Reverse the action of `org-link-escape'."
6440 (setq table (or table org-link-escape-chars))
6441 (when text
6442 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6443 table "\\|")))
6444 (while (string-match re text)
6445 (setq text
6446 (replace-match
6447 (char-to-string (car (rassoc (match-string 0 text) table)))
6448 t t text)))
6449 text)))
6451 (defun org-xor (a b)
6452 "Exclusive or."
6453 (if a (not b) b))
6455 (defun org-get-header (header)
6456 "Find a header field in the current buffer."
6457 (save-excursion
6458 (goto-char (point-min))
6459 (let ((case-fold-search t) s)
6460 (cond
6461 ((eq header 'from)
6462 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6463 (setq s (match-string 1)))
6464 (while (string-match "\"" s)
6465 (setq s (replace-match "" t t s)))
6466 (if (string-match "[<(].*" s)
6467 (setq s (replace-match "" t t s))))
6468 ((eq header 'message-id)
6469 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6470 (setq s (match-string 1))))
6471 ((eq header 'subject)
6472 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6473 (setq s (match-string 1)))))
6474 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6475 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6476 s)))
6479 (defun org-fixup-message-id-for-http (s)
6480 "Replace special characters in a message id, so it can be used in an http query."
6481 (while (string-match "<" s)
6482 (setq s (replace-match "%3C" t t s)))
6483 (while (string-match ">" s)
6484 (setq s (replace-match "%3E" t t s)))
6485 (while (string-match "@" s)
6486 (setq s (replace-match "%40" t t s)))
6489 ;;;###autoload
6490 (defun org-insert-link-global ()
6491 "Insert a link like Org-mode does.
6492 This command can be called in any mode to insert a link in Org-mode syntax."
6493 (interactive)
6494 (org-load-modules-maybe)
6495 (org-run-like-in-org-mode 'org-insert-link))
6497 (defun org-insert-link (&optional complete-file link-location)
6498 "Insert a link. At the prompt, enter the link.
6500 Completion can be used to select a link previously stored with
6501 `org-store-link'. When the empty string is entered (i.e. if you just
6502 press RET at the prompt), the link defaults to the most recently
6503 stored link. As SPC triggers completion in the minibuffer, you need to
6504 use M-SPC or C-q SPC to force the insertion of a space character.
6506 You will also be prompted for a description, and if one is given, it will
6507 be displayed in the buffer instead of the link.
6509 If there is already a link at point, this command will allow you to edit link
6510 and description parts.
6512 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6513 be selected using completion. The path to the file will be relative to the
6514 current directory if the file is in the current directory or a subdirectory.
6515 Otherwise, the link will be the absolute path as completed in the minibuffer
6516 \(i.e. normally ~/path/to/file).
6518 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6519 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6520 of `org-keep-stored-link-after-insertion'.
6522 If `org-make-link-description-function' is non-nil, this function will be
6523 called with the link target, and the result will be the default
6524 link description.
6526 If the LINK-LOCATION parameter is non-nil, this value will be
6527 used as the link location instead of reading one interactively."
6528 (interactive "P")
6529 (let* ((wcf (current-window-configuration))
6530 (region (if (org-region-active-p)
6531 (buffer-substring (region-beginning) (region-end))))
6532 (remove (and region (list (region-beginning) (region-end))))
6533 (desc region)
6534 tmphist ; byte-compile incorrectly complains about this
6535 (link link-location)
6536 entry file)
6537 (cond
6538 (link-location) ; specified by arg, just use it.
6539 ((org-in-regexp org-bracket-link-regexp 1)
6540 ;; We do have a link at point, and we are going to edit it.
6541 (setq remove (list (match-beginning 0) (match-end 0)))
6542 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6543 (setq link (read-string "Link: "
6544 (org-link-unescape
6545 (org-match-string-no-properties 1)))))
6546 ((or (org-in-regexp org-angle-link-re)
6547 (org-in-regexp org-plain-link-re))
6548 ;; Convert to bracket link
6549 (setq remove (list (match-beginning 0) (match-end 0))
6550 link (read-string "Link: "
6551 (org-remove-angle-brackets (match-string 0)))))
6552 ((equal complete-file '(4))
6553 ;; Completing read for file names.
6554 (setq file (read-file-name "File: "))
6555 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6556 (pwd1 (file-name-as-directory (abbreviate-file-name
6557 (expand-file-name ".")))))
6558 (cond
6559 ((equal complete-file '(16))
6560 (setq link (org-make-link
6561 "file:"
6562 (abbreviate-file-name (expand-file-name file)))))
6563 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6564 (setq link (org-make-link "file:" (match-string 1 file))))
6565 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6566 (expand-file-name file))
6567 (setq link (org-make-link
6568 "file:" (match-string 1 (expand-file-name file)))))
6569 (t (setq link (org-make-link "file:" file))))))
6571 ;; Read link, with completion for stored links.
6572 (with-output-to-temp-buffer "*Org Links*"
6573 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6574 (when org-stored-links
6575 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6576 (princ (mapconcat
6577 (lambda (x)
6578 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6579 (reverse org-stored-links) "\n"))))
6580 (let ((cw (selected-window)))
6581 (select-window (get-buffer-window "*Org Links*"))
6582 (shrink-window-if-larger-than-buffer)
6583 (setq truncate-lines t)
6584 (select-window cw))
6585 ;; Fake a link history, containing the stored links.
6586 (setq tmphist (append (mapcar 'car org-stored-links)
6587 org-insert-link-history))
6588 (unwind-protect
6589 (setq link (org-completing-read
6590 "Link: "
6591 (append
6592 (mapcar (lambda (x) (list (concat (car x) ":")))
6593 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6594 (mapcar (lambda (x) (list (concat x ":")))
6595 org-link-types))
6596 nil nil nil
6597 'tmphist
6598 (or (car (car org-stored-links)))))
6599 (set-window-configuration wcf)
6600 (kill-buffer "*Org Links*"))
6601 (setq entry (assoc link org-stored-links))
6602 (or entry (push link org-insert-link-history))
6603 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6604 (not org-keep-stored-link-after-insertion))
6605 (setq org-stored-links (delq (assoc link org-stored-links)
6606 org-stored-links)))
6607 (setq desc (or desc (nth 1 entry)))))
6609 (if (string-match org-plain-link-re link)
6610 ;; URL-like link, normalize the use of angular brackets.
6611 (setq link (org-make-link (org-remove-angle-brackets link))))
6613 ;; Check if we are linking to the current file with a search option
6614 ;; If yes, simplify the link by using only the search option.
6615 (when (and buffer-file-name
6616 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6617 (let* ((path (match-string 1 link))
6618 (case-fold-search nil)
6619 (search (match-string 2 link)))
6620 (save-match-data
6621 (if (equal (file-truename buffer-file-name) (file-truename path))
6622 ;; We are linking to this same file, with a search option
6623 (setq link search)))))
6625 ;; Check if we can/should use a relative path. If yes, simplify the link
6626 (when (string-match "\\<file:\\(.*\\)" link)
6627 (let* ((path (match-string 1 link))
6628 (origpath path)
6629 (case-fold-search nil))
6630 (cond
6631 ((eq org-link-file-path-type 'absolute)
6632 (setq path (abbreviate-file-name (expand-file-name path))))
6633 ((eq org-link-file-path-type 'noabbrev)
6634 (setq path (expand-file-name path)))
6635 ((eq org-link-file-path-type 'relative)
6636 (setq path (file-relative-name path)))
6638 (save-match-data
6639 (if (string-match (concat "^" (regexp-quote
6640 (file-name-as-directory
6641 (expand-file-name "."))))
6642 (expand-file-name path))
6643 ;; We are linking a file with relative path name.
6644 (setq path (substring (expand-file-name path)
6645 (match-end 0)))))))
6646 (setq link (concat "file:" path))
6647 (if (equal desc origpath)
6648 (setq desc path))))
6650 (if org-make-link-description-function
6651 (setq desc (funcall org-make-link-description-function link desc)))
6653 (setq desc (read-string "Description: " desc))
6654 (unless (string-match "\\S-" desc) (setq desc nil))
6655 (if remove (apply 'delete-region remove))
6656 (insert (org-make-link-string link desc))))
6658 (defun org-completing-read (&rest args)
6659 (let ((minibuffer-local-completion-map
6660 (copy-keymap minibuffer-local-completion-map)))
6661 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6662 (apply 'completing-read args)))
6664 ;;; Opening/following a link
6666 (defvar org-link-search-failed nil)
6668 (defun org-next-link ()
6669 "Move forward to the next link.
6670 If the link is in hidden text, expose it."
6671 (interactive)
6672 (when (and org-link-search-failed (eq this-command last-command))
6673 (goto-char (point-min))
6674 (message "Link search wrapped back to beginning of buffer"))
6675 (setq org-link-search-failed nil)
6676 (let* ((pos (point))
6677 (ct (org-context))
6678 (a (assoc :link ct)))
6679 (if a (goto-char (nth 2 a)))
6680 (if (re-search-forward org-any-link-re nil t)
6681 (progn
6682 (goto-char (match-beginning 0))
6683 (if (org-invisible-p) (org-show-context)))
6684 (goto-char pos)
6685 (setq org-link-search-failed t)
6686 (error "No further link found"))))
6688 (defun org-previous-link ()
6689 "Move backward to the previous link.
6690 If the link is in hidden text, expose it."
6691 (interactive)
6692 (when (and org-link-search-failed (eq this-command last-command))
6693 (goto-char (point-max))
6694 (message "Link search wrapped back to end of buffer"))
6695 (setq org-link-search-failed nil)
6696 (let* ((pos (point))
6697 (ct (org-context))
6698 (a (assoc :link ct)))
6699 (if a (goto-char (nth 1 a)))
6700 (if (re-search-backward org-any-link-re nil t)
6701 (progn
6702 (goto-char (match-beginning 0))
6703 (if (org-invisible-p) (org-show-context)))
6704 (goto-char pos)
6705 (setq org-link-search-failed t)
6706 (error "No further link found"))))
6708 (defun org-find-file-at-mouse (ev)
6709 "Open file link or URL at mouse."
6710 (interactive "e")
6711 (mouse-set-point ev)
6712 (org-open-at-point 'in-emacs))
6714 (defun org-open-at-mouse (ev)
6715 "Open file link or URL at mouse."
6716 (interactive "e")
6717 (mouse-set-point ev)
6718 (org-open-at-point))
6720 (defvar org-window-config-before-follow-link nil
6721 "The window configuration before following a link.
6722 This is saved in case the need arises to restore it.")
6724 (defvar org-open-link-marker (make-marker)
6725 "Marker pointing to the location where `org-open-at-point; was called.")
6727 ;;;###autoload
6728 (defun org-open-at-point-global ()
6729 "Follow a link like Org-mode does.
6730 This command can be called in any mode to follow a link that has
6731 Org-mode syntax."
6732 (interactive)
6733 (org-run-like-in-org-mode 'org-open-at-point))
6735 ;;;###autoload
6736 (defun org-open-link-from-string (s &optional arg)
6737 "Open a link in the string S, as if it was in Org-mode."
6738 (interactive "sLink: \nP")
6739 (with-temp-buffer
6740 (let ((org-inhibit-startup t))
6741 (org-mode)
6742 (insert s)
6743 (goto-char (point-min))
6744 (org-open-at-point arg))))
6746 (defun org-open-at-point (&optional in-emacs)
6747 "Open link at or after point.
6748 If there is no link at point, this function will search forward up to
6749 the end of the current subtree.
6750 Normally, files will be opened by an appropriate application. If the
6751 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6752 (interactive "P")
6753 (org-load-modules-maybe)
6754 (move-marker org-open-link-marker (point))
6755 (setq org-window-config-before-follow-link (current-window-configuration))
6756 (org-remove-occur-highlights nil nil t)
6757 (if (org-at-timestamp-p t)
6758 (org-follow-timestamp-link)
6759 (let (type path link line search (pos (point)))
6760 (catch 'match
6761 (save-excursion
6762 (skip-chars-forward "^]\n\r")
6763 (when (org-in-regexp org-bracket-link-regexp)
6764 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6765 (while (string-match " *\n *" link)
6766 (setq link (replace-match " " t t link)))
6767 (setq link (org-link-expand-abbrev link))
6768 (if (string-match org-link-re-with-space2 link)
6769 (setq type (match-string 1 link) path (match-string 2 link))
6770 (setq type "thisfile" path link))
6771 (throw 'match t)))
6773 (when (get-text-property (point) 'org-linked-text)
6774 (setq type "thisfile"
6775 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6776 (1+ (point)) (point))
6777 path (buffer-substring
6778 (previous-single-property-change pos 'org-linked-text)
6779 (next-single-property-change pos 'org-linked-text)))
6780 (throw 'match t))
6782 (save-excursion
6783 (when (or (org-in-regexp org-angle-link-re)
6784 (org-in-regexp org-plain-link-re))
6785 (setq type (match-string 1) path (match-string 2))
6786 (throw 'match t)))
6787 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6788 (setq type "tree-match"
6789 path (match-string 1))
6790 (throw 'match t))
6791 (save-excursion
6792 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6793 (setq type "tags"
6794 path (match-string 1))
6795 (while (string-match ":" path)
6796 (setq path (replace-match "+" t t path)))
6797 (throw 'match t))))
6798 (unless path
6799 (error "No link found"))
6800 ;; Remove any trailing spaces in path
6801 (if (string-match " +\\'" path)
6802 (setq path (replace-match "" t t path)))
6804 (cond
6806 ((assoc type org-link-protocols)
6807 (funcall (nth 1 (assoc type org-link-protocols)) path))
6809 ((equal type "mailto")
6810 (let ((cmd (car org-link-mailto-program))
6811 (args (cdr org-link-mailto-program)) args1
6812 (address path) (subject "") a)
6813 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6814 (setq address (match-string 1 path)
6815 subject (org-link-escape (match-string 2 path))))
6816 (while args
6817 (cond
6818 ((not (stringp (car args))) (push (pop args) args1))
6819 (t (setq a (pop args))
6820 (if (string-match "%a" a)
6821 (setq a (replace-match address t t a)))
6822 (if (string-match "%s" a)
6823 (setq a (replace-match subject t t a)))
6824 (push a args1))))
6825 (apply cmd (nreverse args1))))
6827 ((member type '("http" "https" "ftp" "news"))
6828 (browse-url (concat type ":" (org-link-escape
6829 path org-link-escape-chars-browser))))
6831 ((member type '("message"))
6832 (browse-url (concat type ":" path)))
6834 ((string= type "tags")
6835 (org-tags-view in-emacs path))
6836 ((string= type "thisfile")
6837 (if in-emacs
6838 (switch-to-buffer-other-window
6839 (org-get-buffer-for-internal-link (current-buffer)))
6840 (org-mark-ring-push))
6841 (let ((cmd `(org-link-search
6842 ,path
6843 ,(cond ((equal in-emacs '(4)) 'occur)
6844 ((equal in-emacs '(16)) 'org-occur)
6845 (t nil))
6846 ,pos)))
6847 (condition-case nil (eval cmd)
6848 (error (progn (widen) (eval cmd))))))
6850 ((string= type "tree-match")
6851 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6853 ((string= type "file")
6854 (if (string-match "::\\([0-9]+\\)\\'" path)
6855 (setq line (string-to-number (match-string 1 path))
6856 path (substring path 0 (match-beginning 0)))
6857 (if (string-match "::\\(.+\\)\\'" path)
6858 (setq search (match-string 1 path)
6859 path (substring path 0 (match-beginning 0)))))
6860 (if (string-match "[*?{]" (file-name-nondirectory path))
6861 (dired path)
6862 (org-open-file path in-emacs line search)))
6864 ((string= type "news")
6865 (require 'org-gnus)
6866 (org-gnus-follow-link path))
6868 ((string= type "shell")
6869 (let ((cmd path))
6870 (if (or (not org-confirm-shell-link-function)
6871 (funcall org-confirm-shell-link-function
6872 (format "Execute \"%s\" in shell? "
6873 (org-add-props cmd nil
6874 'face 'org-warning))))
6875 (progn
6876 (message "Executing %s" cmd)
6877 (shell-command cmd))
6878 (error "Abort"))))
6880 ((string= type "elisp")
6881 (let ((cmd path))
6882 (if (or (not org-confirm-elisp-link-function)
6883 (funcall org-confirm-elisp-link-function
6884 (format "Execute \"%s\" as elisp? "
6885 (org-add-props cmd nil
6886 'face 'org-warning))))
6887 (message "%s => %s" cmd (eval (read cmd)))
6888 (error "Abort"))))
6891 (browse-url-at-point)))))
6892 (move-marker org-open-link-marker nil)
6893 (run-hook-with-args 'org-follow-link-hook))
6895 ;;;; Time estimates
6897 (defun org-get-effort (&optional pom)
6898 "Get the effort estimate for the current entry."
6899 (org-entry-get pom org-effort-property))
6901 ;;; File search
6903 (defvar org-create-file-search-functions nil
6904 "List of functions to construct the right search string for a file link.
6905 These functions are called in turn with point at the location to
6906 which the link should point.
6908 A function in the hook should first test if it would like to
6909 handle this file type, for example by checking the major-mode or
6910 the file extension. If it decides not to handle this file, it
6911 should just return nil to give other functions a chance. If it
6912 does handle the file, it must return the search string to be used
6913 when following the link. The search string will be part of the
6914 file link, given after a double colon, and `org-open-at-point'
6915 will automatically search for it. If special measures must be
6916 taken to make the search successful, another function should be
6917 added to the companion hook `org-execute-file-search-functions',
6918 which see.
6920 A function in this hook may also use `setq' to set the variable
6921 `description' to provide a suggestion for the descriptive text to
6922 be used for this link when it gets inserted into an Org-mode
6923 buffer with \\[org-insert-link].")
6925 (defvar org-execute-file-search-functions nil
6926 "List of functions to execute a file search triggered by a link.
6928 Functions added to this hook must accept a single argument, the
6929 search string that was part of the file link, the part after the
6930 double colon. The function must first check if it would like to
6931 handle this search, for example by checking the major-mode or the
6932 file extension. If it decides not to handle this search, it
6933 should just return nil to give other functions a chance. If it
6934 does handle the search, it must return a non-nil value to keep
6935 other functions from trying.
6937 Each function can access the current prefix argument through the
6938 variable `current-prefix-argument'. Note that a single prefix is
6939 used to force opening a link in Emacs, so it may be good to only
6940 use a numeric or double prefix to guide the search function.
6942 In case this is needed, a function in this hook can also restore
6943 the window configuration before `org-open-at-point' was called using:
6945 (set-window-configuration org-window-config-before-follow-link)")
6947 (defun org-link-search (s &optional type avoid-pos)
6948 "Search for a link search option.
6949 If S is surrounded by forward slashes, it is interpreted as a
6950 regular expression. In org-mode files, this will create an `org-occur'
6951 sparse tree. In ordinary files, `occur' will be used to list matches.
6952 If the current buffer is in `dired-mode', grep will be used to search
6953 in all files. If AVOID-POS is given, ignore matches near that position."
6954 (let ((case-fold-search t)
6955 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6956 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6957 (append '(("") (" ") ("\t") ("\n"))
6958 org-emphasis-alist)
6959 "\\|") "\\)"))
6960 (pos (point))
6961 (pre nil) (post nil)
6962 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6963 (cond
6964 ;; First check if there are any special
6965 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6966 ;; Now try the builtin stuff
6967 ((save-excursion
6968 (goto-char (point-min))
6969 (and
6970 (re-search-forward
6971 (concat "<<" (regexp-quote s0) ">>") nil t)
6972 (setq type 'dedicated
6973 pos (match-beginning 0))))
6974 ;; There is an exact target for this
6975 (goto-char pos))
6976 ((string-match "^/\\(.*\\)/$" s)
6977 ;; A regular expression
6978 (cond
6979 ((org-mode-p)
6980 (org-occur (match-string 1 s)))
6981 ;;((eq major-mode 'dired-mode)
6982 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6983 (t (org-do-occur (match-string 1 s)))))
6985 ;; A normal search strings
6986 (when (equal (string-to-char s) ?*)
6987 ;; Anchor on headlines, post may include tags.
6988 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6989 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6990 s (substring s 1)))
6991 (remove-text-properties
6992 0 (length s)
6993 '(face nil mouse-face nil keymap nil fontified nil) s)
6994 ;; Make a series of regular expressions to find a match
6995 (setq words (org-split-string s "[ \n\r\t]+")
6997 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6998 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6999 "\\)" markers)
7000 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7001 re2a (concat "[ \t\r\n]" re2a_)
7002 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7003 re4 (concat "[^a-zA-Z_]" re4_)
7005 re1 (concat pre re2 post)
7006 re3 (concat pre (if pre re4_ re4) post)
7007 re5 (concat pre ".*" re4)
7008 re2 (concat pre re2)
7009 re2a (concat pre (if pre re2a_ re2a))
7010 re4 (concat pre (if pre re4_ re4))
7011 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7012 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7013 re5 "\\)"
7015 (cond
7016 ((eq type 'org-occur) (org-occur reall))
7017 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7018 (t (goto-char (point-min))
7019 (setq type 'fuzzy)
7020 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7021 (org-search-not-self 1 re1 nil t)
7022 (org-search-not-self 1 re2 nil t)
7023 (org-search-not-self 1 re2a nil t)
7024 (org-search-not-self 1 re3 nil t)
7025 (org-search-not-self 1 re4 nil t)
7026 (org-search-not-self 1 re5 nil t)
7028 (goto-char (match-beginning 1))
7029 (goto-char pos)
7030 (error "No match")))))
7032 ;; Normal string-search
7033 (goto-char (point-min))
7034 (if (search-forward s nil t)
7035 (goto-char (match-beginning 0))
7036 (error "No match"))))
7037 (and (org-mode-p) (org-show-context 'link-search))
7038 type))
7040 (defun org-search-not-self (group &rest args)
7041 "Execute `re-search-forward', but only accept matches that do not
7042 enclose the position of `org-open-link-marker'."
7043 (let ((m org-open-link-marker))
7044 (catch 'exit
7045 (while (apply 're-search-forward args)
7046 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7047 (goto-char (match-end group))
7048 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7049 (> (match-beginning 0) (marker-position m))
7050 (< (match-end 0) (marker-position m)))
7051 (save-match-data
7052 (or (not (org-in-regexp
7053 org-bracket-link-analytic-regexp 1))
7054 (not (match-end 4)) ; no description
7055 (and (<= (match-beginning 4) (point))
7056 (>= (match-end 4) (point))))))
7057 (throw 'exit (point))))))))
7059 (defun org-get-buffer-for-internal-link (buffer)
7060 "Return a buffer to be used for displaying the link target of internal links."
7061 (cond
7062 ((not org-display-internal-link-with-indirect-buffer)
7063 buffer)
7064 ((string-match "(Clone)$" (buffer-name buffer))
7065 (message "Buffer is already a clone, not making another one")
7066 ;; we also do not modify visibility in this case
7067 buffer)
7068 (t ; make a new indirect buffer for displaying the link
7069 (let* ((bn (buffer-name buffer))
7070 (ibn (concat bn "(Clone)"))
7071 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7072 (with-current-buffer ib (org-overview))
7073 ib))))
7075 (defun org-do-occur (regexp &optional cleanup)
7076 "Call the Emacs command `occur'.
7077 If CLEANUP is non-nil, remove the printout of the regular expression
7078 in the *Occur* buffer. This is useful if the regex is long and not useful
7079 to read."
7080 (occur regexp)
7081 (when cleanup
7082 (let ((cwin (selected-window)) win beg end)
7083 (when (setq win (get-buffer-window "*Occur*"))
7084 (select-window win))
7085 (goto-char (point-min))
7086 (when (re-search-forward "match[a-z]+" nil t)
7087 (setq beg (match-end 0))
7088 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7089 (setq end (1- (match-beginning 0)))))
7090 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7091 (goto-char (point-min))
7092 (select-window cwin))))
7094 ;;; The mark ring for links jumps
7096 (defvar org-mark-ring nil
7097 "Mark ring for positions before jumps in Org-mode.")
7098 (defvar org-mark-ring-last-goto nil
7099 "Last position in the mark ring used to go back.")
7100 ;; Fill and close the ring
7101 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7102 (loop for i from 1 to org-mark-ring-length do
7103 (push (make-marker) org-mark-ring))
7104 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7105 org-mark-ring)
7107 (defun org-mark-ring-push (&optional pos buffer)
7108 "Put the current position or POS into the mark ring and rotate it."
7109 (interactive)
7110 (setq pos (or pos (point)))
7111 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7112 (move-marker (car org-mark-ring)
7113 (or pos (point))
7114 (or buffer (current-buffer)))
7115 (message "%s"
7116 (substitute-command-keys
7117 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7119 (defun org-mark-ring-goto (&optional n)
7120 "Jump to the previous position in the mark ring.
7121 With prefix arg N, jump back that many stored positions. When
7122 called several times in succession, walk through the entire ring.
7123 Org-mode commands jumping to a different position in the current file,
7124 or to another Org-mode file, automatically push the old position
7125 onto the ring."
7126 (interactive "p")
7127 (let (p m)
7128 (if (eq last-command this-command)
7129 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7130 (setq p org-mark-ring))
7131 (setq org-mark-ring-last-goto p)
7132 (setq m (car p))
7133 (switch-to-buffer (marker-buffer m))
7134 (goto-char m)
7135 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7137 (defun org-remove-angle-brackets (s)
7138 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7139 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7141 (defun org-add-angle-brackets (s)
7142 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7143 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7146 ;;; Following specific links
7148 (defun org-follow-timestamp-link ()
7149 (cond
7150 ((org-at-date-range-p t)
7151 (let ((org-agenda-start-on-weekday)
7152 (t1 (match-string 1))
7153 (t2 (match-string 2)))
7154 (setq t1 (time-to-days (org-time-string-to-time t1))
7155 t2 (time-to-days (org-time-string-to-time t2)))
7156 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7157 ((org-at-timestamp-p t)
7158 (org-agenda-list nil (time-to-days (org-time-string-to-time
7159 (substring (match-string 1) 0 10)))
7161 (t (error "This should not happen"))))
7164 ;;; Following file links
7165 (defvar org-wait nil)
7166 (defun org-open-file (path &optional in-emacs line search)
7167 "Open the file at PATH.
7168 First, this expands any special file name abbreviations. Then the
7169 configuration variable `org-file-apps' is checked if it contains an
7170 entry for this file type, and if yes, the corresponding command is launched.
7171 If no application is found, Emacs simply visits the file.
7172 With optional argument IN-EMACS, Emacs will visit the file.
7173 Optional LINE specifies a line to go to, optional SEARCH a string to
7174 search for. If LINE or SEARCH is given, the file will always be
7175 opened in Emacs.
7176 If the file does not exist, an error is thrown."
7177 (setq in-emacs (or in-emacs line search))
7178 (let* ((file (if (equal path "")
7179 buffer-file-name
7180 (substitute-in-file-name (expand-file-name path))))
7181 (apps (append org-file-apps (org-default-apps)))
7182 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7183 (dirp (if remp nil (file-directory-p file)))
7184 (dfile (downcase file))
7185 (old-buffer (current-buffer))
7186 (old-pos (point))
7187 (old-mode major-mode)
7188 ext cmd)
7189 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7190 (setq ext (match-string 1 dfile))
7191 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7192 (setq ext (match-string 1 dfile))))
7193 (if in-emacs
7194 (setq cmd 'emacs)
7195 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7196 (and dirp (cdr (assoc 'directory apps)))
7197 (cdr (assoc ext apps))
7198 (cdr (assoc t apps)))))
7199 (when (eq cmd 'mailcap)
7200 (require 'mailcap)
7201 (mailcap-parse-mailcaps)
7202 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7203 (command (mailcap-mime-info mime-type)))
7204 (if (stringp command)
7205 (setq cmd command)
7206 (setq cmd 'emacs))))
7207 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7208 (not (file-exists-p file))
7209 (not org-open-non-existing-files))
7210 (error "No such file: %s" file))
7211 (cond
7212 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7213 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7214 (while (string-match "['\"]%s['\"]" cmd)
7215 (setq cmd (replace-match "%s" t t cmd)))
7216 (while (string-match "%s" cmd)
7217 (setq cmd (replace-match
7218 (save-match-data (shell-quote-argument file))
7219 t t cmd)))
7220 (save-window-excursion
7221 (start-process-shell-command cmd nil cmd)
7222 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7224 ((or (stringp cmd)
7225 (eq cmd 'emacs))
7226 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7227 (widen)
7228 (if line (goto-line line)
7229 (if search (org-link-search search))))
7230 ((consp cmd)
7231 (eval cmd))
7232 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7233 (and (org-mode-p) (eq old-mode 'org-mode)
7234 (or (not (equal old-buffer (current-buffer)))
7235 (not (equal old-pos (point))))
7236 (org-mark-ring-push old-pos old-buffer))))
7238 (defun org-default-apps ()
7239 "Return the default applications for this operating system."
7240 (cond
7241 ((eq system-type 'darwin)
7242 org-file-apps-defaults-macosx)
7243 ((eq system-type 'windows-nt)
7244 org-file-apps-defaults-windowsnt)
7245 (t org-file-apps-defaults-gnu)))
7247 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7248 (defun org-file-remote-p (file)
7249 "Test whether FILE specifies a location on a remote system.
7250 Return non-nil if the location is indeed remote.
7252 For example, the filename \"/user@host:/foo\" specifies a location
7253 on the system \"/user@host:\"."
7254 (cond ((fboundp 'file-remote-p)
7255 (file-remote-p file))
7256 ((fboundp 'tramp-handle-file-remote-p)
7257 (tramp-handle-file-remote-p file))
7258 ((and (boundp 'ange-ftp-name-format)
7259 (string-match (car ange-ftp-name-format) file))
7261 (t nil)))
7264 ;;;; Refiling
7266 (defun org-get-org-file ()
7267 "Read a filename, with default directory `org-directory'."
7268 (let ((default (or org-default-notes-file remember-data-file)))
7269 (read-file-name (format "File name [%s]: " default)
7270 (file-name-as-directory org-directory)
7271 default)))
7273 (defun org-notes-order-reversed-p ()
7274 "Check if the current file should receive notes in reversed order."
7275 (cond
7276 ((not org-reverse-note-order) nil)
7277 ((eq t org-reverse-note-order) t)
7278 ((not (listp org-reverse-note-order)) nil)
7279 (t (catch 'exit
7280 (let ((all org-reverse-note-order)
7281 entry)
7282 (while (setq entry (pop all))
7283 (if (string-match (car entry) buffer-file-name)
7284 (throw 'exit (cdr entry))))
7285 nil)))))
7287 (defvar org-refile-target-table nil
7288 "The list of refile targets, created by `org-refile'.")
7290 (defvar org-agenda-new-buffers nil
7291 "Buffers created to visit agenda files.")
7293 (defun org-get-refile-targets (&optional default-buffer)
7294 "Produce a table with refile targets."
7295 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7296 targets txt re files f desc descre)
7297 (with-current-buffer (or default-buffer (current-buffer))
7298 (while (setq entry (pop entries))
7299 (setq files (car entry) desc (cdr entry))
7300 (cond
7301 ((null files) (setq files (list (current-buffer))))
7302 ((eq files 'org-agenda-files)
7303 (setq files (org-agenda-files 'unrestricted)))
7304 ((and (symbolp files) (fboundp files))
7305 (setq files (funcall files)))
7306 ((and (symbolp files) (boundp files))
7307 (setq files (symbol-value files))))
7308 (if (stringp files) (setq files (list files)))
7309 (cond
7310 ((eq (car desc) :tag)
7311 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7312 ((eq (car desc) :todo)
7313 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7314 ((eq (car desc) :regexp)
7315 (setq descre (cdr desc)))
7316 ((eq (car desc) :level)
7317 (setq descre (concat "^\\*\\{" (number-to-string
7318 (if org-odd-levels-only
7319 (1- (* 2 (cdr desc)))
7320 (cdr desc)))
7321 "\\}[ \t]")))
7322 ((eq (car desc) :maxlevel)
7323 (setq descre (concat "^\\*\\{1," (number-to-string
7324 (if org-odd-levels-only
7325 (1- (* 2 (cdr desc)))
7326 (cdr desc)))
7327 "\\}[ \t]")))
7328 (t (error "Bad refiling target description %s" desc)))
7329 (while (setq f (pop files))
7330 (save-excursion
7331 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7332 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7333 (save-excursion
7334 (save-restriction
7335 (widen)
7336 (goto-char (point-min))
7337 (while (re-search-forward descre nil t)
7338 (goto-char (point-at-bol))
7339 (when (looking-at org-complex-heading-regexp)
7340 (setq txt (match-string 4)
7341 re (concat "^" (regexp-quote
7342 (buffer-substring (match-beginning 1)
7343 (match-end 4)))))
7344 (if (match-end 5) (setq re (concat re "[ \t]+"
7345 (regexp-quote
7346 (match-string 5)))))
7347 (setq re (concat re "[ \t]*$"))
7348 (when org-refile-use-outline-path
7349 (setq txt (mapconcat 'identity
7350 (append
7351 (if (eq org-refile-use-outline-path 'file)
7352 (list (file-name-nondirectory
7353 (buffer-file-name (buffer-base-buffer))))
7354 (if (eq org-refile-use-outline-path 'full-file-path)
7355 (list (buffer-file-name (buffer-base-buffer)))))
7356 (org-get-outline-path)
7357 (list txt))
7358 "/")))
7359 (push (list txt f re (point)) targets))
7360 (goto-char (point-at-eol))))))))
7361 (nreverse targets))))
7363 (defun org-get-outline-path ()
7364 "Return the outline path to the current entry, as a list."
7365 (let (rtn)
7366 (save-excursion
7367 (while (org-up-heading-safe)
7368 (when (looking-at org-complex-heading-regexp)
7369 (push (org-match-string-no-properties 4) rtn)))
7370 rtn)))
7372 (defvar org-refile-history nil
7373 "History for refiling operations.")
7375 (defun org-refile (&optional goto default-buffer)
7376 "Move the entry at point to another heading.
7377 The list of target headings is compiled using the information in
7378 `org-refile-targets', which see. This list is created before each use
7379 and will therefore always be up-to-date.
7381 At the target location, the entry is filed as a subitem of the target heading.
7382 Depending on `org-reverse-note-order', the new subitem will either be the
7383 first of the last subitem.
7385 With prefix arg GOTO, the command will only visit the target location,
7386 not actually move anything.
7387 With a double prefix `C-c C-c', go to the location where the last refiling
7388 operation has put the subtree."
7389 (interactive "P")
7390 (let* ((cbuf (current-buffer))
7391 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7392 pos it nbuf file re level reversed)
7393 (if (equal goto '(16))
7394 (org-refile-goto-last-stored)
7395 (when (setq it (org-refile-get-location
7396 (if goto "Goto: " "Refile to: ") default-buffer))
7397 (setq file (nth 1 it)
7398 re (nth 2 it)
7399 pos (nth 3 it))
7400 (setq nbuf (or (find-buffer-visiting file)
7401 (find-file-noselect file)))
7402 (if goto
7403 (progn
7404 (switch-to-buffer nbuf)
7405 (goto-char pos)
7406 (org-show-context 'org-goto))
7407 (org-copy-subtree 1 nil t)
7408 (save-excursion
7409 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7410 (find-file-noselect file))))
7411 (setq reversed (org-notes-order-reversed-p))
7412 (save-excursion
7413 (save-restriction
7414 (widen)
7415 (goto-char pos)
7416 (looking-at outline-regexp)
7417 (setq level (org-get-valid-level (funcall outline-level) 1))
7418 (goto-char
7419 (if reversed
7420 (outline-next-heading)
7421 (or (save-excursion (outline-get-next-sibling))
7422 (org-end-of-subtree t t)
7423 (point-max))))
7424 (bookmark-set "org-refile-last-stored")
7425 (org-paste-subtree level))))
7426 (org-cut-subtree)
7427 (setq org-markers-to-move nil)
7428 (message "Entry refiled to \"%s\"" (car it)))))))
7430 (defun org-refile-goto-last-stored ()
7431 "Go to the location where the last refile was stored."
7432 (interactive)
7433 (bookmark-jump "org-refile-last-stored")
7434 (message "This is the location of the last refile"))
7436 (defun org-refile-get-location (&optional prompt default-buffer)
7437 "Prompt the user for a refile location, using PROMPT."
7438 (let ((org-refile-targets org-refile-targets)
7439 (org-refile-use-outline-path org-refile-use-outline-path))
7440 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7441 (unless org-refile-target-table
7442 (error "No refile targets"))
7443 (let* ((cbuf (current-buffer))
7444 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7445 (fname (and filename (file-truename filename)))
7446 (tbl (mapcar
7447 (lambda (x)
7448 (if (not (equal fname (file-truename (nth 1 x))))
7449 (cons (concat (car x) " (" (file-name-nondirectory
7450 (nth 1 x)) ")")
7451 (cdr x))
7453 org-refile-target-table))
7454 (completion-ignore-case t))
7455 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7456 tbl)))
7458 ;;;; Dynamic blocks
7460 (defun org-find-dblock (name)
7461 "Find the first dynamic block with name NAME in the buffer.
7462 If not found, stay at current position and return nil."
7463 (let (pos)
7464 (save-excursion
7465 (goto-char (point-min))
7466 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7467 nil t)
7468 (match-beginning 0))))
7469 (if pos (goto-char pos))
7470 pos))
7472 (defconst org-dblock-start-re
7473 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7474 "Matches the startline of a dynamic block, with parameters.")
7476 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7477 "Matches the end of a dyhamic block.")
7479 (defun org-create-dblock (plist)
7480 "Create a dynamic block section, with parameters taken from PLIST.
7481 PLIST must containe a :name entry which is used as name of the block."
7482 (unless (bolp) (newline))
7483 (let ((name (plist-get plist :name)))
7484 (insert "#+BEGIN: " name)
7485 (while plist
7486 (if (eq (car plist) :name)
7487 (setq plist (cddr plist))
7488 (insert " " (prin1-to-string (pop plist)))))
7489 (insert "\n\n#+END:\n")
7490 (beginning-of-line -2)))
7492 (defun org-prepare-dblock ()
7493 "Prepare dynamic block for refresh.
7494 This empties the block, puts the cursor at the insert position and returns
7495 the property list including an extra property :name with the block name."
7496 (unless (looking-at org-dblock-start-re)
7497 (error "Not at a dynamic block"))
7498 (let* ((begdel (1+ (match-end 0)))
7499 (name (org-no-properties (match-string 1)))
7500 (params (append (list :name name)
7501 (read (concat "(" (match-string 3) ")")))))
7502 (unless (re-search-forward org-dblock-end-re nil t)
7503 (error "Dynamic block not terminated"))
7504 (setq params
7505 (append params
7506 (list :content (buffer-substring
7507 begdel (match-beginning 0)))))
7508 (delete-region begdel (match-beginning 0))
7509 (goto-char begdel)
7510 (open-line 1)
7511 params))
7513 (defun org-map-dblocks (&optional command)
7514 "Apply COMMAND to all dynamic blocks in the current buffer.
7515 If COMMAND is not given, use `org-update-dblock'."
7516 (let ((cmd (or command 'org-update-dblock))
7517 pos)
7518 (save-excursion
7519 (goto-char (point-min))
7520 (while (re-search-forward org-dblock-start-re nil t)
7521 (goto-char (setq pos (match-beginning 0)))
7522 (condition-case nil
7523 (funcall cmd)
7524 (error (message "Error during update of dynamic block")))
7525 (goto-char pos)
7526 (unless (re-search-forward org-dblock-end-re nil t)
7527 (error "Dynamic block not terminated"))))))
7529 (defun org-dblock-update (&optional arg)
7530 "User command for updating dynamic blocks.
7531 Update the dynamic block at point. With prefix ARG, update all dynamic
7532 blocks in the buffer."
7533 (interactive "P")
7534 (if arg
7535 (org-update-all-dblocks)
7536 (or (looking-at org-dblock-start-re)
7537 (org-beginning-of-dblock))
7538 (org-update-dblock)))
7540 (defun org-update-dblock ()
7541 "Update the dynamic block at point
7542 This means to empty the block, parse for parameters and then call
7543 the correct writing function."
7544 (save-window-excursion
7545 (let* ((pos (point))
7546 (line (org-current-line))
7547 (params (org-prepare-dblock))
7548 (name (plist-get params :name))
7549 (cmd (intern (concat "org-dblock-write:" name))))
7550 (message "Updating dynamic block `%s' at line %d..." name line)
7551 (funcall cmd params)
7552 (message "Updating dynamic block `%s' at line %d...done" name line)
7553 (goto-char pos))))
7555 (defun org-beginning-of-dblock ()
7556 "Find the beginning of the dynamic block at point.
7557 Error if there is no scuh block at point."
7558 (let ((pos (point))
7559 beg)
7560 (end-of-line 1)
7561 (if (and (re-search-backward org-dblock-start-re nil t)
7562 (setq beg (match-beginning 0))
7563 (re-search-forward org-dblock-end-re nil t)
7564 (> (match-end 0) pos))
7565 (goto-char beg)
7566 (goto-char pos)
7567 (error "Not in a dynamic block"))))
7569 (defun org-update-all-dblocks ()
7570 "Update all dynamic blocks in the buffer.
7571 This function can be used in a hook."
7572 (when (org-mode-p)
7573 (org-map-dblocks 'org-update-dblock)))
7576 ;;;; Completion
7578 (defconst org-additional-option-like-keywords
7579 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7580 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7581 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7583 (defun org-complete (&optional arg)
7584 "Perform completion on word at point.
7585 At the beginning of a headline, this completes TODO keywords as given in
7586 `org-todo-keywords'.
7587 If the current word is preceded by a backslash, completes the TeX symbols
7588 that are supported for HTML support.
7589 If the current word is preceded by \"#+\", completes special words for
7590 setting file options.
7591 In the line after \"#+STARTUP:, complete valid keywords.\"
7592 At all other locations, this simply calls the value of
7593 `org-completion-fallback-command'."
7594 (interactive "P")
7595 (org-without-partial-completion
7596 (catch 'exit
7597 (let* ((end (point))
7598 (beg1 (save-excursion
7599 (skip-chars-backward (org-re "[:alnum:]_@"))
7600 (point)))
7601 (beg (save-excursion
7602 (skip-chars-backward "a-zA-Z0-9_:$")
7603 (point)))
7604 (confirm (lambda (x) (stringp (car x))))
7605 (searchhead (equal (char-before beg) ?*))
7606 (tag (and (equal (char-before beg1) ?:)
7607 (equal (char-after (point-at-bol)) ?*)))
7608 (prop (and (equal (char-before beg1) ?:)
7609 (not (equal (char-after (point-at-bol)) ?*))))
7610 (texp (equal (char-before beg) ?\\))
7611 (link (equal (char-before beg) ?\[))
7612 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7613 beg)
7614 "#+"))
7615 (startup (string-match "^#\\+STARTUP:.*"
7616 (buffer-substring (point-at-bol) (point))))
7617 (completion-ignore-case opt)
7618 (type nil)
7619 (tbl nil)
7620 (table (cond
7621 (opt
7622 (setq type :opt)
7623 (require 'org-exp)
7624 (append
7625 (mapcar
7626 (lambda (x)
7627 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7628 (cons (match-string 2 x) (match-string 1 x)))
7629 (org-split-string (org-get-current-options) "\n"))
7630 (mapcar 'list org-additional-option-like-keywords)))
7631 (startup
7632 (setq type :startup)
7633 org-startup-options)
7634 (link (append org-link-abbrev-alist-local
7635 org-link-abbrev-alist))
7636 (texp
7637 (setq type :tex)
7638 org-html-entities)
7639 ((string-match "\\`\\*+[ \t]+\\'"
7640 (buffer-substring (point-at-bol) beg))
7641 (setq type :todo)
7642 (mapcar 'list org-todo-keywords-1))
7643 (searchhead
7644 (setq type :searchhead)
7645 (save-excursion
7646 (goto-char (point-min))
7647 (while (re-search-forward org-todo-line-regexp nil t)
7648 (push (list
7649 (org-make-org-heading-search-string
7650 (match-string 3) t))
7651 tbl)))
7652 tbl)
7653 (tag (setq type :tag beg beg1)
7654 (or org-tag-alist (org-get-buffer-tags)))
7655 (prop (setq type :prop beg beg1)
7656 (mapcar 'list (org-buffer-property-keys nil t t)))
7657 (t (progn
7658 (call-interactively org-completion-fallback-command)
7659 (throw 'exit nil)))))
7660 (pattern (buffer-substring-no-properties beg end))
7661 (completion (try-completion pattern table confirm)))
7662 (cond ((eq completion t)
7663 (if (not (assoc (upcase pattern) table))
7664 (message "Already complete")
7665 (if (and (equal type :opt)
7666 (not (member (car (assoc (upcase pattern) table))
7667 org-additional-option-like-keywords)))
7668 (insert (substring (cdr (assoc (upcase pattern) table))
7669 (length pattern)))
7670 (if (memq type '(:tag :prop)) (insert ":")))))
7671 ((null completion)
7672 (message "Can't find completion for \"%s\"" pattern)
7673 (ding))
7674 ((not (string= pattern completion))
7675 (delete-region beg end)
7676 (if (string-match " +$" completion)
7677 (setq completion (replace-match "" t t completion)))
7678 (insert completion)
7679 (if (get-buffer-window "*Completions*")
7680 (delete-window (get-buffer-window "*Completions*")))
7681 (if (assoc completion table)
7682 (if (eq type :todo) (insert " ")
7683 (if (memq type '(:tag :prop)) (insert ":"))))
7684 (if (and (equal type :opt) (assoc completion table))
7685 (message "%s" (substitute-command-keys
7686 "Press \\[org-complete] again to insert example settings"))))
7688 (message "Making completion list...")
7689 (let ((list (sort (all-completions pattern table confirm)
7690 'string<)))
7691 (with-output-to-temp-buffer "*Completions*"
7692 (condition-case nil
7693 ;; Protection needed for XEmacs and emacs 21
7694 (display-completion-list list pattern)
7695 (error (display-completion-list list)))))
7696 (message "Making completion list...%s" "done")))))))
7698 ;;;; TODO, DEADLINE, Comments
7700 (defun org-toggle-comment ()
7701 "Change the COMMENT state of an entry."
7702 (interactive)
7703 (save-excursion
7704 (org-back-to-heading)
7705 (let (case-fold-search)
7706 (if (looking-at (concat outline-regexp
7707 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7708 (replace-match "" t t nil 1)
7709 (if (looking-at outline-regexp)
7710 (progn
7711 (goto-char (match-end 0))
7712 (insert org-comment-string " ")))))))
7714 (defvar org-last-todo-state-is-todo nil
7715 "This is non-nil when the last TODO state change led to a TODO state.
7716 If the last change removed the TODO tag or switched to DONE, then
7717 this is nil.")
7719 (defvar org-setting-tags nil) ; dynamically skiped
7721 (defun org-parse-local-options (string var)
7722 "Parse STRING for startup setting relevant for variable VAR."
7723 (let ((rtn (symbol-value var))
7724 e opts)
7725 (save-match-data
7726 (if (or (not string) (not (string-match "\\S-" string)))
7728 (setq opts (delq nil (mapcar (lambda (x)
7729 (setq e (assoc x org-startup-options))
7730 (if (eq (nth 1 e) var) e nil))
7731 (org-split-string string "[ \t]+"))))
7732 (if (not opts)
7734 (setq rtn nil)
7735 (while (setq e (pop opts))
7736 (if (not (nth 3 e))
7737 (setq rtn (nth 2 e))
7738 (if (not (listp rtn)) (setq rtn nil))
7739 (push (nth 2 e) rtn)))
7740 rtn)))))
7742 (defvar org-blocker-hook nil
7743 "Hook for functions that are allowed to block a state change.
7745 Each function gets as its single argument a property list, see
7746 `org-trigger-hook' for more information about this list.
7748 If any of the functions in this hook returns nil, the state change
7749 is blocked.")
7751 (defvar org-trigger-hook nil
7752 "Hook for functions that are triggered by a state change.
7754 Each function gets as its single argument a property list with at least
7755 the following elements:
7757 (:type type-of-change :position pos-at-entry-start
7758 :from old-state :to new-state)
7760 Depending on the type, more properties may be present.
7762 This mechanism is currently implemented for:
7764 TODO state changes
7765 ------------------
7766 :type todo-state-change
7767 :from previous state (keyword as a string), or nil
7768 :to new state (keyword as a string), or nil")
7771 (defun org-todo (&optional arg)
7772 "Change the TODO state of an item.
7773 The state of an item is given by a keyword at the start of the heading,
7774 like
7775 *** TODO Write paper
7776 *** DONE Call mom
7778 The different keywords are specified in the variable `org-todo-keywords'.
7779 By default the available states are \"TODO\" and \"DONE\".
7780 So for this example: when the item starts with TODO, it is changed to DONE.
7781 When it starts with DONE, the DONE is removed. And when neither TODO nor
7782 DONE are present, add TODO at the beginning of the heading.
7784 With C-u prefix arg, use completion to determine the new state.
7785 With numeric prefix arg, switch to that state.
7787 For calling through lisp, arg is also interpreted in the following way:
7788 'none -> empty state
7789 \"\"(empty string) -> switch to empty state
7790 'done -> switch to DONE
7791 'nextset -> switch to the next set of keywords
7792 'previousset -> switch to the previous set of keywords
7793 \"WAITING\" -> switch to the specified keyword, but only if it
7794 really is a member of `org-todo-keywords'."
7795 (interactive "P")
7796 (save-excursion
7797 (catch 'exit
7798 (org-back-to-heading)
7799 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7800 (or (looking-at (concat " +" org-todo-regexp " *"))
7801 (looking-at " *"))
7802 (let* ((match-data (match-data))
7803 (startpos (point-at-bol))
7804 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7805 (org-log-done org-log-done)
7806 (org-log-repeat org-log-repeat)
7807 (org-todo-log-states org-todo-log-states)
7808 (this (match-string 1))
7809 (hl-pos (match-beginning 0))
7810 (head (org-get-todo-sequence-head this))
7811 (ass (assoc head org-todo-kwd-alist))
7812 (interpret (nth 1 ass))
7813 (done-word (nth 3 ass))
7814 (final-done-word (nth 4 ass))
7815 (last-state (or this ""))
7816 (completion-ignore-case t)
7817 (member (member this org-todo-keywords-1))
7818 (tail (cdr member))
7819 (state (cond
7820 ((and org-todo-key-trigger
7821 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7822 (and (not arg) org-use-fast-todo-selection
7823 (not (eq org-use-fast-todo-selection 'prefix)))))
7824 ;; Use fast selection
7825 (org-fast-todo-selection))
7826 ((and (equal arg '(4))
7827 (or (not org-use-fast-todo-selection)
7828 (not org-todo-key-trigger)))
7829 ;; Read a state with completion
7830 (completing-read "State: " (mapcar (lambda(x) (list x))
7831 org-todo-keywords-1)
7832 nil t))
7833 ((eq arg 'right)
7834 (if this
7835 (if tail (car tail) nil)
7836 (car org-todo-keywords-1)))
7837 ((eq arg 'left)
7838 (if (equal member org-todo-keywords-1)
7840 (if this
7841 (nth (- (length org-todo-keywords-1) (length tail) 2)
7842 org-todo-keywords-1)
7843 (org-last org-todo-keywords-1))))
7844 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7845 (setq arg nil))) ; hack to fall back to cycling
7846 (arg
7847 ;; user or caller requests a specific state
7848 (cond
7849 ((equal arg "") nil)
7850 ((eq arg 'none) nil)
7851 ((eq arg 'done) (or done-word (car org-done-keywords)))
7852 ((eq arg 'nextset)
7853 (or (car (cdr (member head org-todo-heads)))
7854 (car org-todo-heads)))
7855 ((eq arg 'previousset)
7856 (let ((org-todo-heads (reverse org-todo-heads)))
7857 (or (car (cdr (member head org-todo-heads)))
7858 (car org-todo-heads))))
7859 ((car (member arg org-todo-keywords-1)))
7860 ((nth (1- (prefix-numeric-value arg))
7861 org-todo-keywords-1))))
7862 ((null member) (or head (car org-todo-keywords-1)))
7863 ((equal this final-done-word) nil) ;; -> make empty
7864 ((null tail) nil) ;; -> first entry
7865 ((eq interpret 'sequence)
7866 (car tail))
7867 ((memq interpret '(type priority))
7868 (if (eq this-command last-command)
7869 (car tail)
7870 (if (> (length tail) 0)
7871 (or done-word (car org-done-keywords))
7872 nil)))
7873 (t nil)))
7874 (next (if state (concat " " state " ") " "))
7875 (change-plist (list :type 'todo-state-change :from this :to state
7876 :position startpos))
7877 dolog now-done-p)
7878 (when org-blocker-hook
7879 (unless (save-excursion
7880 (save-match-data
7881 (run-hook-with-args-until-failure
7882 'org-blocker-hook change-plist)))
7883 (if (interactive-p)
7884 (error "TODO state change from %s to %s blocked" this state)
7885 ;; fail silently
7886 (message "TODO state change from %s to %s blocked" this state)
7887 (throw 'exit nil))))
7888 (store-match-data match-data)
7889 (replace-match next t t)
7890 (unless (pos-visible-in-window-p hl-pos)
7891 (message "TODO state changed to %s" (org-trim next)))
7892 (unless head
7893 (setq head (org-get-todo-sequence-head state)
7894 ass (assoc head org-todo-kwd-alist)
7895 interpret (nth 1 ass)
7896 done-word (nth 3 ass)
7897 final-done-word (nth 4 ass)))
7898 (when (memq arg '(nextset previousset))
7899 (message "Keyword-Set %d/%d: %s"
7900 (- (length org-todo-sets) -1
7901 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7902 (length org-todo-sets)
7903 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7904 (setq org-last-todo-state-is-todo
7905 (not (member state org-done-keywords)))
7906 (setq now-done-p (and (member state org-done-keywords)
7907 (not (member this org-done-keywords))))
7908 (and logging (org-local-logging logging))
7909 (when (and (or org-todo-log-states org-log-done)
7910 (not (memq arg '(nextset previousset))))
7911 ;; we need to look at recording a time and note
7912 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7913 (nth 2 (assoc this org-todo-log-states))))
7914 (when (and state
7915 (member state org-not-done-keywords)
7916 (not (member this org-not-done-keywords)))
7917 ;; This is now a todo state and was not one before
7918 ;; If there was a CLOSED time stamp, get rid of it.
7919 (org-add-planning-info nil nil 'closed))
7920 (when (and now-done-p org-log-done)
7921 ;; It is now done, and it was not done before
7922 (org-add-planning-info 'closed (org-current-time))
7923 (if (and (not dolog) (eq 'note org-log-done))
7924 (org-add-log-setup 'done state 'findpos 'note)))
7925 (when (and state dolog)
7926 ;; This is a non-nil state, and we need to log it
7927 (org-add-log-setup 'state state 'findpos dolog)))
7928 ;; Fixup tag positioning
7929 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7930 (run-hooks 'org-after-todo-state-change-hook)
7931 (if (and arg (not (member state org-done-keywords)))
7932 (setq head (org-get-todo-sequence-head state)))
7933 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7934 ;; Do we need to trigger a repeat?
7935 (when now-done-p (org-auto-repeat-maybe state))
7936 ;; Fixup cursor location if close to the keyword
7937 (if (and (outline-on-heading-p)
7938 (not (bolp))
7939 (save-excursion (beginning-of-line 1)
7940 (looking-at org-todo-line-regexp))
7941 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7942 (progn
7943 (goto-char (or (match-end 2) (match-end 1)))
7944 (just-one-space)))
7945 (when org-trigger-hook
7946 (save-excursion
7947 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7949 (defun org-local-logging (value)
7950 "Get logging settings from a property VALUE."
7951 (let* (words w a)
7952 ;; directly set the variables, they are already local.
7953 (setq org-log-done nil
7954 org-log-repeat nil
7955 org-todo-log-states nil)
7956 (setq words (org-split-string value))
7957 (while (setq w (pop words))
7958 (cond
7959 ((setq a (assoc w org-startup-options))
7960 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7961 (set (nth 1 a) (nth 2 a))))
7962 ((setq a (org-extract-log-state-settings w))
7963 (and (member (car a) org-todo-keywords-1)
7964 (push a org-todo-log-states)))))))
7966 (defun org-get-todo-sequence-head (kwd)
7967 "Return the head of the TODO sequence to which KWD belongs.
7968 If KWD is not set, check if there is a text property remembering the
7969 right sequence."
7970 (let (p)
7971 (cond
7972 ((not kwd)
7973 (or (get-text-property (point-at-bol) 'org-todo-head)
7974 (progn
7975 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7976 nil (point-at-eol)))
7977 (get-text-property p 'org-todo-head))))
7978 ((not (member kwd org-todo-keywords-1))
7979 (car org-todo-keywords-1))
7980 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7982 (defun org-fast-todo-selection ()
7983 "Fast TODO keyword selection with single keys.
7984 Returns the new TODO keyword, or nil if no state change should occur."
7985 (let* ((fulltable org-todo-key-alist)
7986 (done-keywords org-done-keywords) ;; needed for the faces.
7987 (maxlen (apply 'max (mapcar
7988 (lambda (x)
7989 (if (stringp (car x)) (string-width (car x)) 0))
7990 fulltable)))
7991 (expert nil)
7992 (fwidth (+ maxlen 3 1 3))
7993 (ncol (/ (- (window-width) 4) fwidth))
7994 tg cnt e c tbl
7995 groups ingroup)
7996 (save-window-excursion
7997 (if expert
7998 (set-buffer (get-buffer-create " *Org todo*"))
7999 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8000 (erase-buffer)
8001 (org-set-local 'org-done-keywords done-keywords)
8002 (setq tbl fulltable cnt 0)
8003 (while (setq e (pop tbl))
8004 (cond
8005 ((equal e '(:startgroup))
8006 (push '() groups) (setq ingroup t)
8007 (when (not (= cnt 0))
8008 (setq cnt 0)
8009 (insert "\n"))
8010 (insert "{ "))
8011 ((equal e '(:endgroup))
8012 (setq ingroup nil cnt 0)
8013 (insert "}\n"))
8015 (setq tg (car e) c (cdr e))
8016 (if ingroup (push tg (car groups)))
8017 (setq tg (org-add-props tg nil 'face
8018 (org-get-todo-face tg)))
8019 (if (and (= cnt 0) (not ingroup)) (insert " "))
8020 (insert "[" c "] " tg (make-string
8021 (- fwidth 4 (length tg)) ?\ ))
8022 (when (= (setq cnt (1+ cnt)) ncol)
8023 (insert "\n")
8024 (if ingroup (insert " "))
8025 (setq cnt 0)))))
8026 (insert "\n")
8027 (goto-char (point-min))
8028 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8029 (fit-window-to-buffer))
8030 (message "[a-z..]:Set [SPC]:clear")
8031 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8032 (cond
8033 ((or (= c ?\C-g)
8034 (and (= c ?q) (not (rassoc c fulltable))))
8035 (setq quit-flag t))
8036 ((= c ?\ ) nil)
8037 ((setq e (rassoc c fulltable) tg (car e))
8039 (t (setq quit-flag t))))))
8041 (defun org-entry-is-todo-p ()
8042 (member (org-get-todo-state) org-not-done-keywords))
8044 (defun org-entry-is-done-p ()
8045 (member (org-get-todo-state) org-done-keywords))
8047 (defun org-get-todo-state ()
8048 (save-excursion
8049 (org-back-to-heading t)
8050 (and (looking-at org-todo-line-regexp)
8051 (match-end 2)
8052 (match-string 2))))
8054 (defun org-at-date-range-p (&optional inactive-ok)
8055 "Is the cursor inside a date range?"
8056 (interactive)
8057 (save-excursion
8058 (catch 'exit
8059 (let ((pos (point)))
8060 (skip-chars-backward "^[<\r\n")
8061 (skip-chars-backward "<[")
8062 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8063 (>= (match-end 0) pos)
8064 (throw 'exit t))
8065 (skip-chars-backward "^<[\r\n")
8066 (skip-chars-backward "<[")
8067 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8068 (>= (match-end 0) pos)
8069 (throw 'exit t)))
8070 nil)))
8072 (defun org-get-repeat ()
8073 "Check if tere is a deadline/schedule with repeater in this entry."
8074 (save-match-data
8075 (save-excursion
8076 (org-back-to-heading t)
8077 (if (re-search-forward
8078 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8079 (match-string 1)))))
8081 (defvar org-last-changed-timestamp)
8082 (defvar org-log-post-message)
8083 (defvar org-log-note-purpose)
8084 (defvar org-log-note-how)
8085 (defun org-auto-repeat-maybe (done-word)
8086 "Check if the current headline contains a repeated deadline/schedule.
8087 If yes, set TODO state back to what it was and change the base date
8088 of repeating deadline/scheduled time stamps to new date.
8089 This function is run automatically after each state change to a DONE state."
8090 ;; last-state is dynamically scoped into this function
8091 (let* ((repeat (org-get-repeat))
8092 (aa (assoc last-state org-todo-kwd-alist))
8093 (interpret (nth 1 aa))
8094 (head (nth 2 aa))
8095 (whata '(("d" . day) ("m" . month) ("y" . year)))
8096 (msg "Entry repeats: ")
8097 (org-log-done nil)
8098 (org-todo-log-states nil)
8099 (nshiftmax 10) (nshift 0)
8100 re type n what ts mb0 time)
8101 (when repeat
8102 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8103 (org-todo (if (eq interpret 'type) last-state head))
8104 (when org-log-repeat
8105 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8106 (memq 'org-add-log-note post-command-hook))
8107 ;; OK, we are already setup for some record
8108 (if (eq org-log-repeat 'note)
8109 ;; make sure we take a note, not only a time stamp
8110 (setq org-log-note-how 'note))
8111 ;; Set up for taking a record
8112 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8113 'findpos org-log-repeat)))
8114 (org-back-to-heading t)
8115 (org-add-planning-info nil nil 'closed)
8116 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8117 org-deadline-time-regexp "\\)\\|\\("
8118 org-ts-regexp "\\)"))
8119 (while (re-search-forward
8120 re (save-excursion (outline-next-heading) (point)) t)
8121 (setq type (if (match-end 1) org-scheduled-string
8122 (if (match-end 3) org-deadline-string "Plain:"))
8123 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8124 mb0 (match-beginning 0))
8125 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8126 (setq n (string-to-number (match-string 2 ts))
8127 what (match-string 3 ts))
8128 (if (equal what "w") (setq n (* n 7) what "d"))
8129 ;; Preparation, see if we need to modify the start date for the change
8130 (when (match-end 1)
8131 (setq time (save-match-data (org-time-string-to-time ts)))
8132 (cond
8133 ((equal (match-string 1 ts) ".")
8134 ;; Shift starting date to today
8135 (org-timestamp-change
8136 (- (time-to-days (current-time)) (time-to-days time))
8137 'day))
8138 ((equal (match-string 1 ts) "+")
8139 (while (or (= nshift 0)
8140 (<= (time-to-days time) (time-to-days (current-time))))
8141 (when (= (incf nshift) nshiftmax)
8142 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8143 (error "Abort")))
8144 (org-timestamp-change n (cdr (assoc what whata)))
8145 (org-at-timestamp-p t)
8146 (setq ts (match-string 1))
8147 (setq time (save-match-data (org-time-string-to-time ts))))
8148 (org-timestamp-change (- n) (cdr (assoc what whata)))
8149 ;; rematch, so that we have everything in place for the real shift
8150 (org-at-timestamp-p t)
8151 (setq ts (match-string 1))
8152 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8153 (org-timestamp-change n (cdr (assoc what whata)))
8154 (setq msg (concat msg type org-last-changed-timestamp " "))))
8155 (setq org-log-post-message msg)
8156 (message "%s" msg))))
8158 (defun org-show-todo-tree (arg)
8159 "Make a compact tree which shows all headlines marked with TODO.
8160 The tree will show the lines where the regexp matches, and all higher
8161 headlines above the match.
8162 With a \\[universal-argument] prefix, also show the DONE entries.
8163 With a numeric prefix N, construct a sparse tree for the Nth element
8164 of `org-todo-keywords-1'."
8165 (interactive "P")
8166 (let ((case-fold-search nil)
8167 (kwd-re
8168 (cond ((null arg) org-not-done-regexp)
8169 ((equal arg '(4))
8170 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8171 (mapcar 'list org-todo-keywords-1))))
8172 (concat "\\("
8173 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8174 "\\)\\>")))
8175 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8176 (regexp-quote (nth (1- (prefix-numeric-value arg))
8177 org-todo-keywords-1)))
8178 (t (error "Invalid prefix argument: %s" arg)))))
8179 (message "%d TODO entries found"
8180 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8182 (defun org-deadline (&optional remove)
8183 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8184 With argument REMOVE, remove any deadline from the item."
8185 (interactive "P")
8186 (if remove
8187 (progn
8188 (org-remove-timestamp-with-keyword org-deadline-string)
8189 (message "Item no longer has a deadline."))
8190 (org-add-planning-info 'deadline nil 'closed)))
8192 (defun org-schedule (&optional remove)
8193 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8194 With argument REMOVE, remove any scheduling date from the item."
8195 (interactive "P")
8196 (if remove
8197 (progn
8198 (org-remove-timestamp-with-keyword org-scheduled-string)
8199 (message "Item is no longer scheduled."))
8200 (org-add-planning-info 'scheduled nil 'closed)))
8202 (defun org-remove-timestamp-with-keyword (keyword)
8203 "Remove all time stamps with KEYWORD in the current entry."
8204 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8205 beg)
8206 (save-excursion
8207 (org-back-to-heading t)
8208 (setq beg (point))
8209 (org-end-of-subtree t t)
8210 (while (re-search-backward re beg t)
8211 (replace-match "")
8212 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8213 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8215 (defun org-add-planning-info (what &optional time &rest remove)
8216 "Insert new timestamp with keyword in the line directly after the headline.
8217 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8218 If non is given, the user is prompted for a date.
8219 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8220 be removed."
8221 (interactive)
8222 (let (org-time-was-given org-end-time-was-given ts
8223 end default-time default-input)
8225 (when (and (not time) (memq what '(scheduled deadline)))
8226 ;; Try to get a default date/time from existing timestamp
8227 (save-excursion
8228 (org-back-to-heading t)
8229 (setq end (save-excursion (outline-next-heading) (point)))
8230 (when (re-search-forward (if (eq what 'scheduled)
8231 org-scheduled-time-regexp
8232 org-deadline-time-regexp)
8233 end t)
8234 (setq ts (match-string 1)
8235 default-time
8236 (apply 'encode-time (org-parse-time-string ts))
8237 default-input (and ts (org-get-compact-tod ts))))))
8238 (when what
8239 ;; If necessary, get the time from the user
8240 (setq time (or time (org-read-date nil 'to-time nil nil
8241 default-time default-input))))
8243 (when (and org-insert-labeled-timestamps-at-point
8244 (member what '(scheduled deadline)))
8245 (insert
8246 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8247 (org-insert-time-stamp time org-time-was-given
8248 nil nil nil (list org-end-time-was-given))
8249 (setq what nil))
8250 (save-excursion
8251 (save-restriction
8252 (let (col list elt ts buffer-invisibility-spec)
8253 (org-back-to-heading t)
8254 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8255 (goto-char (match-end 1))
8256 (setq col (current-column))
8257 (goto-char (match-end 0))
8258 (if (eobp) (insert "\n") (forward-char 1))
8259 (if (and (not (looking-at outline-regexp))
8260 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8261 "[^\r\n]*"))
8262 (not (equal (match-string 1) org-clock-string)))
8263 (narrow-to-region (match-beginning 0) (match-end 0))
8264 (insert-before-markers "\n")
8265 (backward-char 1)
8266 (narrow-to-region (point) (point))
8267 (org-indent-to-column col))
8268 ;; Check if we have to remove something.
8269 (setq list (cons what remove))
8270 (while list
8271 (setq elt (pop list))
8272 (goto-char (point-min))
8273 (when (or (and (eq elt 'scheduled)
8274 (re-search-forward org-scheduled-time-regexp nil t))
8275 (and (eq elt 'deadline)
8276 (re-search-forward org-deadline-time-regexp nil t))
8277 (and (eq elt 'closed)
8278 (re-search-forward org-closed-time-regexp nil t)))
8279 (replace-match "")
8280 (if (looking-at "--+<[^>]+>") (replace-match ""))
8281 (if (looking-at " +") (replace-match ""))))
8282 (goto-char (point-max))
8283 (when what
8284 (insert
8285 (if (not (equal (char-before) ?\ )) " " "")
8286 (cond ((eq what 'scheduled) org-scheduled-string)
8287 ((eq what 'deadline) org-deadline-string)
8288 ((eq what 'closed) org-closed-string))
8289 " ")
8290 (setq ts (org-insert-time-stamp
8291 time
8292 (or org-time-was-given
8293 (and (eq what 'closed) org-log-done-with-time))
8294 (eq what 'closed)
8295 nil nil (list org-end-time-was-given)))
8296 (end-of-line 1))
8297 (goto-char (point-min))
8298 (widen)
8299 (if (and (looking-at "[ \t]+\n")
8300 (equal (char-before) ?\n))
8301 (backward-delete-char 1))
8302 ts)))))
8304 (defvar org-log-note-marker (make-marker))
8305 (defvar org-log-note-purpose nil)
8306 (defvar org-log-note-state nil)
8307 (defvar org-log-note-how nil)
8308 (defvar org-log-note-window-configuration nil)
8309 (defvar org-log-note-return-to (make-marker))
8310 (defvar org-log-post-message nil
8311 "Message to be displayed after a log note has been stored.
8312 The auto-repeater uses this.")
8314 (defun org-add-note ()
8315 "Add a note to the current entry.
8316 This is done in the same way as adding a state change note."
8317 (interactive)
8318 (org-add-log-setup 'note nil t nil))
8320 (defun org-add-log-setup (&optional purpose state findpos how)
8321 "Set up the post command hook to take a note.
8322 If this is about to TODO state change, the new state is expected in STATE.
8323 When FINDPOS is non-nil, find the correct position for the note in
8324 the current entry. If not, assume that it can be inserted at point."
8325 (save-excursion
8326 (when findpos
8327 (org-back-to-heading t)
8328 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8329 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8330 "[^\r\n]*\\)?"))
8331 (goto-char (match-end 0))
8332 (unless org-log-states-order-reversed
8333 (and (= (char-after) ?\n) (forward-char 1))
8334 (org-skip-over-state-notes)
8335 (skip-chars-backward " \t\n\r")))
8336 (move-marker org-log-note-marker (point))
8337 (setq org-log-note-purpose purpose
8338 org-log-note-state state
8339 org-log-note-how how)
8340 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8342 (defun org-skip-over-state-notes ()
8343 "Skip past the list of State notes in an entry."
8344 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8345 (while (looking-at "[ \t]*- State")
8346 (condition-case nil
8347 (org-next-item)
8348 (error (org-end-of-item)))))
8350 (defun org-add-log-note (&optional purpose)
8351 "Pop up a window for taking a note, and add this note later at point."
8352 (remove-hook 'post-command-hook 'org-add-log-note)
8353 (setq org-log-note-window-configuration (current-window-configuration))
8354 (delete-other-windows)
8355 (move-marker org-log-note-return-to (point))
8356 (switch-to-buffer (marker-buffer org-log-note-marker))
8357 (goto-char org-log-note-marker)
8358 (org-switch-to-buffer-other-window "*Org Note*")
8359 (erase-buffer)
8360 (if (memq org-log-note-how '(time state))
8361 (org-store-log-note)
8362 (let ((org-inhibit-startup t)) (org-mode))
8363 (insert (format "# Insert note for %s.
8364 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8365 (cond
8366 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8367 ((eq org-log-note-purpose 'done) "closed todo item")
8368 ((eq org-log-note-purpose 'state)
8369 (format "state change to \"%s\"" org-log-note-state))
8370 ((eq org-log-note-purpose 'note)
8371 "this entry")
8372 (t (error "This should not happen")))))
8373 (org-set-local 'org-finish-function 'org-store-log-note)))
8375 (defvar org-note-abort nil) ; dynamically scoped
8376 (defun org-store-log-note ()
8377 "Finish taking a log note, and insert it to where it belongs."
8378 (let ((txt (buffer-string))
8379 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8380 lines ind)
8381 (kill-buffer (current-buffer))
8382 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8383 (setq txt (replace-match "" t t txt)))
8384 (if (string-match "\\s-+\\'" txt)
8385 (setq txt (replace-match "" t t txt)))
8386 (setq lines (org-split-string txt "\n"))
8387 (when (and note (string-match "\\S-" note))
8388 (setq note
8389 (org-replace-escapes
8390 note
8391 (list (cons "%u" (user-login-name))
8392 (cons "%U" user-full-name)
8393 (cons "%t" (format-time-string
8394 (org-time-stamp-format 'long 'inactive)
8395 (current-time)))
8396 (cons "%s" (if org-log-note-state
8397 (concat "\"" org-log-note-state "\"")
8398 "")))))
8399 (if lines (setq note (concat note " \\\\")))
8400 (push note lines))
8401 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8402 (when lines
8403 (save-excursion
8404 (set-buffer (marker-buffer org-log-note-marker))
8405 (save-excursion
8406 (goto-char org-log-note-marker)
8407 (move-marker org-log-note-marker nil)
8408 (end-of-line 1)
8409 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8410 (indent-relative nil)
8411 (insert "- " (pop lines))
8412 (org-indent-line-function)
8413 (beginning-of-line 1)
8414 (looking-at "[ \t]*")
8415 (setq ind (concat (match-string 0) " "))
8416 (end-of-line 1)
8417 (while lines (insert "\n" ind (pop lines)))))))
8418 (set-window-configuration org-log-note-window-configuration)
8419 (with-current-buffer (marker-buffer org-log-note-return-to)
8420 (goto-char org-log-note-return-to))
8421 (move-marker org-log-note-return-to nil)
8422 (and org-log-post-message (message "%s" org-log-post-message)))
8424 (defun org-sparse-tree (&optional arg)
8425 "Create a sparse tree, prompt for the details.
8426 This command can create sparse trees. You first need to select the type
8427 of match used to create the tree:
8429 t Show entries with a specific TODO keyword.
8430 T Show entries selected by a tags match.
8431 p Enter a property name and its value (both with completion on existing
8432 names/values) and show entries with that property.
8433 r Show entries matching a regular expression
8434 d Show deadlines due within `org-deadline-warning-days'."
8435 (interactive "P")
8436 (let (ans kwd value)
8437 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8438 (setq ans (read-char-exclusive))
8439 (cond
8440 ((equal ans ?d)
8441 (call-interactively 'org-check-deadlines))
8442 ((equal ans ?b)
8443 (call-interactively 'org-check-before-date))
8444 ((equal ans ?t)
8445 (org-show-todo-tree '(4)))
8446 ((equal ans ?T)
8447 (call-interactively 'org-tags-sparse-tree))
8448 ((member ans '(?p ?P))
8449 (setq kwd (completing-read "Property: "
8450 (mapcar 'list (org-buffer-property-keys))))
8451 (setq value (completing-read "Value: "
8452 (mapcar 'list (org-property-values kwd))))
8453 (unless (string-match "\\`{.*}\\'" value)
8454 (setq value (concat "\"" value "\"")))
8455 (org-tags-sparse-tree arg (concat kwd "=" value)))
8456 ((member ans '(?r ?R ?/))
8457 (call-interactively 'org-occur))
8458 (t (error "No such sparse tree command \"%c\"" ans)))))
8460 (defvar org-occur-highlights nil
8461 "List of overlays used for occur matches.")
8462 (make-variable-buffer-local 'org-occur-highlights)
8463 (defvar org-occur-parameters nil
8464 "Parameters of the active org-occur calls.
8465 This is a list, each call to org-occur pushes as cons cell,
8466 containing the regular expression and the callback, onto the list.
8467 The list can contain several entries if `org-occur' has been called
8468 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8469 will only contain one set of parameters. When the highlights are
8470 removed (for example with `C-c C-c', or with the next edit (depending
8471 on `org-remove-highlights-with-change'), this variable is emptied
8472 as well.")
8473 (make-variable-buffer-local 'org-occur-parameters)
8475 (defun org-occur (regexp &optional keep-previous callback)
8476 "Make a compact tree which shows all matches of REGEXP.
8477 The tree will show the lines where the regexp matches, and all higher
8478 headlines above the match. It will also show the heading after the match,
8479 to make sure editing the matching entry is easy.
8480 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8481 call to `org-occur' will be kept, to allow stacking of calls to this
8482 command.
8483 If CALLBACK is non-nil, it is a function which is called to confirm
8484 that the match should indeed be shown."
8485 (interactive "sRegexp: \nP")
8486 (unless keep-previous
8487 (org-remove-occur-highlights nil nil t))
8488 (push (cons regexp callback) org-occur-parameters)
8489 (let ((cnt 0))
8490 (save-excursion
8491 (goto-char (point-min))
8492 (if (or (not keep-previous) ; do not want to keep
8493 (not org-occur-highlights)) ; no previous matches
8494 ;; hide everything
8495 (org-overview))
8496 (while (re-search-forward regexp nil t)
8497 (when (or (not callback)
8498 (save-match-data (funcall callback)))
8499 (setq cnt (1+ cnt))
8500 (when org-highlight-sparse-tree-matches
8501 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8502 (org-show-context 'occur-tree))))
8503 (when org-remove-highlights-with-change
8504 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8505 nil 'local))
8506 (unless org-sparse-tree-open-archived-trees
8507 (org-hide-archived-subtrees (point-min) (point-max)))
8508 (run-hooks 'org-occur-hook)
8509 (if (interactive-p)
8510 (message "%d match(es) for regexp %s" cnt regexp))
8511 cnt))
8513 (defun org-show-context (&optional key)
8514 "Make sure point and context and visible.
8515 How much context is shown depends upon the variables
8516 `org-show-hierarchy-above', `org-show-following-heading'. and
8517 `org-show-siblings'."
8518 (let ((heading-p (org-on-heading-p t))
8519 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8520 (following-p (org-get-alist-option org-show-following-heading key))
8521 (entry-p (org-get-alist-option org-show-entry-below key))
8522 (siblings-p (org-get-alist-option org-show-siblings key)))
8523 (catch 'exit
8524 ;; Show heading or entry text
8525 (if (and heading-p (not entry-p))
8526 (org-flag-heading nil) ; only show the heading
8527 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8528 (org-show-hidden-entry))) ; show entire entry
8529 (when following-p
8530 ;; Show next sibling, or heading below text
8531 (save-excursion
8532 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8533 (org-flag-heading nil))))
8534 (when siblings-p (org-show-siblings))
8535 (when hierarchy-p
8536 ;; show all higher headings, possibly with siblings
8537 (save-excursion
8538 (while (and (condition-case nil
8539 (progn (org-up-heading-all 1) t)
8540 (error nil))
8541 (not (bobp)))
8542 (org-flag-heading nil)
8543 (when siblings-p (org-show-siblings))))))))
8545 (defun org-reveal (&optional siblings)
8546 "Show current entry, hierarchy above it, and the following headline.
8547 This can be used to show a consistent set of context around locations
8548 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8549 not t for the search context.
8551 With optional argument SIBLINGS, on each level of the hierarchy all
8552 siblings are shown. This repairs the tree structure to what it would
8553 look like when opened with hierarchical calls to `org-cycle'."
8554 (interactive "P")
8555 (let ((org-show-hierarchy-above t)
8556 (org-show-following-heading t)
8557 (org-show-siblings (if siblings t org-show-siblings)))
8558 (org-show-context nil)))
8560 (defun org-highlight-new-match (beg end)
8561 "Highlight from BEG to END and mark the highlight is an occur headline."
8562 (let ((ov (org-make-overlay beg end)))
8563 (org-overlay-put ov 'face 'secondary-selection)
8564 (push ov org-occur-highlights)))
8566 (defun org-remove-occur-highlights (&optional beg end noremove)
8567 "Remove the occur highlights from the buffer.
8568 BEG and END are ignored. If NOREMOVE is nil, remove this function
8569 from the `before-change-functions' in the current buffer."
8570 (interactive)
8571 (unless org-inhibit-highlight-removal
8572 (mapc 'org-delete-overlay org-occur-highlights)
8573 (setq org-occur-highlights nil)
8574 (setq org-occur-parameters nil)
8575 (unless noremove
8576 (remove-hook 'before-change-functions
8577 'org-remove-occur-highlights 'local))))
8579 ;;;; Priorities
8581 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8582 "Regular expression matching the priority indicator.")
8584 (defvar org-remove-priority-next-time nil)
8586 (defun org-priority-up ()
8587 "Increase the priority of the current item."
8588 (interactive)
8589 (org-priority 'up))
8591 (defun org-priority-down ()
8592 "Decrease the priority of the current item."
8593 (interactive)
8594 (org-priority 'down))
8596 (defun org-priority (&optional action)
8597 "Change the priority of an item by ARG.
8598 ACTION can be `set', `up', `down', or a character."
8599 (interactive)
8600 (setq action (or action 'set))
8601 (let (current new news have remove)
8602 (save-excursion
8603 (org-back-to-heading)
8604 (if (looking-at org-priority-regexp)
8605 (setq current (string-to-char (match-string 2))
8606 have t)
8607 (setq current org-default-priority))
8608 (cond
8609 ((or (eq action 'set)
8610 (if (featurep 'xemacs) (characterp action) (integerp action)))
8611 (if (not (eq action 'set))
8612 (setq new action)
8613 (message "Priority %c-%c, SPC to remove: "
8614 org-highest-priority org-lowest-priority)
8615 (setq new (read-char-exclusive)))
8616 (if (and (= (upcase org-highest-priority) org-highest-priority)
8617 (= (upcase org-lowest-priority) org-lowest-priority))
8618 (setq new (upcase new)))
8619 (cond ((equal new ?\ ) (setq remove t))
8620 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8621 (error "Priority must be between `%c' and `%c'"
8622 org-highest-priority org-lowest-priority))))
8623 ((eq action 'up)
8624 (if (and (not have) (eq last-command this-command))
8625 (setq new org-lowest-priority)
8626 (setq new (if (and org-priority-start-cycle-with-default (not have))
8627 org-default-priority (1- current)))))
8628 ((eq action 'down)
8629 (if (and (not have) (eq last-command this-command))
8630 (setq new org-highest-priority)
8631 (setq new (if (and org-priority-start-cycle-with-default (not have))
8632 org-default-priority (1+ current)))))
8633 (t (error "Invalid action")))
8634 (if (or (< (upcase new) org-highest-priority)
8635 (> (upcase new) org-lowest-priority))
8636 (setq remove t))
8637 (setq news (format "%c" new))
8638 (if have
8639 (if remove
8640 (replace-match "" t t nil 1)
8641 (replace-match news t t nil 2))
8642 (if remove
8643 (error "No priority cookie found in line")
8644 (looking-at org-todo-line-regexp)
8645 (if (match-end 2)
8646 (progn
8647 (goto-char (match-end 2))
8648 (insert " [#" news "]"))
8649 (goto-char (match-beginning 3))
8650 (insert "[#" news "] ")))))
8651 (org-preserve-lc (org-set-tags nil 'align))
8652 (if remove
8653 (message "Priority removed")
8654 (message "Priority of current item set to %s" news))))
8657 (defun org-get-priority (s)
8658 "Find priority cookie and return priority."
8659 (save-match-data
8660 (if (not (string-match org-priority-regexp s))
8661 (* 1000 (- org-lowest-priority org-default-priority))
8662 (* 1000 (- org-lowest-priority
8663 (string-to-char (match-string 2 s)))))))
8665 ;;;; Tags
8667 (defun org-scan-tags (action matcher &optional todo-only)
8668 "Scan headline tags with inheritance and produce output ACTION.
8669 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8670 evaluated, testing if a given set of tags qualifies a headline for
8671 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8672 are included in the output."
8673 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8674 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8675 (org-re
8676 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8677 (props (list 'face nil
8678 'done-face 'org-done
8679 'undone-face nil
8680 'mouse-face 'highlight
8681 'org-not-done-regexp org-not-done-regexp
8682 'org-todo-regexp org-todo-regexp
8683 'keymap org-agenda-keymap
8684 'help-echo
8685 (format "mouse-2 or RET jump to org file %s"
8686 (abbreviate-file-name
8687 (or (buffer-file-name (buffer-base-buffer))
8688 (buffer-name (buffer-base-buffer)))))))
8689 (case-fold-search nil)
8690 lspos
8691 tags tags-list tags-alist (llast 0) rtn level category i txt
8692 todo marker entry priority)
8693 (save-excursion
8694 (goto-char (point-min))
8695 (when (eq action 'sparse-tree)
8696 (org-overview)
8697 (org-remove-occur-highlights))
8698 (while (re-search-forward re nil t)
8699 (catch :skip
8700 (setq todo (if (match-end 1) (match-string 2))
8701 tags (if (match-end 4) (match-string 4)))
8702 (goto-char (setq lspos (1+ (match-beginning 0))))
8703 (setq level (org-reduced-level (funcall outline-level))
8704 category (org-get-category))
8705 (setq i llast llast level)
8706 ;; remove tag lists from same and sublevels
8707 (while (>= i level)
8708 (when (setq entry (assoc i tags-alist))
8709 (setq tags-alist (delete entry tags-alist)))
8710 (setq i (1- i)))
8711 ;; add the next tags
8712 (when tags
8713 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8714 tags-alist
8715 (cons (cons level tags) tags-alist)))
8716 ;; compile tags for current headline
8717 (setq tags-list
8718 (if org-use-tag-inheritance
8719 (apply 'append (mapcar 'cdr tags-alist))
8720 tags))
8721 (when (and tags org-use-tag-inheritance
8722 (not (eq t org-use-tag-inheritance)))
8723 ;; selective inheritance, remove uninherited ones
8724 (setcdr (car tags-alist)
8725 (org-remove-uniherited-tags (cdar tags-alist))))
8726 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8727 (eval matcher)
8728 (or (not org-agenda-skip-archived-trees)
8729 (not (member org-archive-tag tags-list))))
8730 (and (eq action 'agenda) (org-agenda-skip))
8731 ;; list this headline
8733 (if (eq action 'sparse-tree)
8734 (progn
8735 (and org-highlight-sparse-tree-matches
8736 (org-get-heading) (match-end 0)
8737 (org-highlight-new-match
8738 (match-beginning 0) (match-beginning 1)))
8739 (org-show-context 'tags-tree))
8740 (setq txt (org-format-agenda-item
8742 (concat
8743 (if org-tags-match-list-sublevels
8744 (make-string (1- level) ?.) "")
8745 (org-get-heading))
8746 category tags-list)
8747 priority (org-get-priority txt))
8748 (goto-char lspos)
8749 (setq marker (org-agenda-new-marker))
8750 (org-add-props txt props
8751 'org-marker marker 'org-hd-marker marker 'org-category category
8752 'priority priority 'type "tagsmatch")
8753 (push txt rtn))
8754 ;; if we are to skip sublevels, jump to end of subtree
8755 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8756 (when (and (eq action 'sparse-tree)
8757 (not org-sparse-tree-open-archived-trees))
8758 (org-hide-archived-subtrees (point-min) (point-max)))
8759 (nreverse rtn)))
8761 (defun org-remove-uniherited-tags (tags)
8762 "Remove all tags that are not inherited from the list TAGS."
8763 (cond
8764 ((eq org-use-tag-inheritance t) tags)
8765 ((not org-use-tag-inheritance) nil)
8766 ((stringp org-use-tag-inheritance)
8767 (delq nil (mapcar
8768 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8769 tags)))
8770 ((listp org-use-tag-inheritance)
8771 (org-delete-all org-use-tag-inheritance tags))))
8773 (defvar todo-only) ;; dynamically scoped
8775 (defun org-tags-sparse-tree (&optional todo-only match)
8776 "Create a sparse tree according to tags string MATCH.
8777 MATCH can contain positive and negative selection of tags, like
8778 \"+WORK+URGENT-WITHBOSS\".
8779 If optional argument TODO_ONLY is non-nil, only select lines that are
8780 also TODO lines."
8781 (interactive "P")
8782 (org-prepare-agenda-buffers (list (current-buffer)))
8783 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8785 (defvar org-cached-props nil)
8786 (defun org-cached-entry-get (pom property)
8787 (if (or (eq t org-use-property-inheritance)
8788 (and (stringp org-use-property-inheritance)
8789 (string-match org-use-property-inheritance property))
8790 (and (listp org-use-property-inheritance)
8791 (member property org-use-property-inheritance)))
8792 ;; Caching is not possible, check it directly
8793 (org-entry-get pom property 'inherit)
8794 ;; Get all properties, so that we can do complicated checks easily
8795 (cdr (assoc property (or org-cached-props
8796 (setq org-cached-props
8797 (org-entry-properties pom)))))))
8799 (defun org-global-tags-completion-table (&optional files)
8800 "Return the list of all tags in all agenda buffer/files."
8801 (save-excursion
8802 (org-uniquify
8803 (delq nil
8804 (apply 'append
8805 (mapcar
8806 (lambda (file)
8807 (set-buffer (find-file-noselect file))
8808 (append (org-get-buffer-tags)
8809 (mapcar (lambda (x) (if (stringp (car-safe x))
8810 (list (car-safe x)) nil))
8811 org-tag-alist)))
8812 (if (and files (car files))
8813 files
8814 (org-agenda-files))))))))
8816 (defun org-make-tags-matcher (match)
8817 "Create the TAGS//TODO matcher form for the selection string MATCH."
8818 ;; todo-only is scoped dynamically into this function, and the function
8819 ;; may change it it the matcher asksk for it.
8820 (unless match
8821 ;; Get a new match request, with completion
8822 (let ((org-last-tags-completion-table
8823 (org-global-tags-completion-table)))
8824 (setq match (completing-read
8825 "Match: " 'org-tags-completion-function nil nil nil
8826 'org-tags-history))))
8828 ;; Parse the string and create a lisp form
8829 (let ((match0 match)
8830 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8831 minus tag mm
8832 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8833 orterms term orlist re-p str-p level-p level-op
8834 prop-p pn pv po cat-p gv)
8835 (if (string-match "/+" match)
8836 ;; match contains also a todo-matching request
8837 (progn
8838 (setq tagsmatch (substring match 0 (match-beginning 0))
8839 todomatch (substring match (match-end 0)))
8840 (if (string-match "^!" todomatch)
8841 (setq todo-only t todomatch (substring todomatch 1)))
8842 (if (string-match "^\\s-*$" todomatch)
8843 (setq todomatch nil)))
8844 ;; only matching tags
8845 (setq tagsmatch match todomatch nil))
8847 ;; Make the tags matcher
8848 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8849 (setq tagsmatcher t)
8850 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8851 (while (setq term (pop orterms))
8852 (while (and (equal (substring term -1) "\\") orterms)
8853 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8854 (while (string-match re term)
8855 (setq minus (and (match-end 1)
8856 (equal (match-string 1 term) "-"))
8857 tag (match-string 2 term)
8858 re-p (equal (string-to-char tag) ?{)
8859 level-p (match-end 4)
8860 prop-p (match-end 5)
8861 mm (cond
8862 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8863 (level-p
8864 (setq level-op (org-op-to-function (match-string 3 term)))
8865 `(,level-op level ,(string-to-number
8866 (match-string 4 term))))
8867 (prop-p
8868 (setq pn (match-string 5 term)
8869 po (match-string 6 term)
8870 pv (match-string 7 term)
8871 cat-p (equal pn "CATEGORY")
8872 re-p (equal (string-to-char pv) ?{)
8873 str-p (equal (string-to-char pv) ?\")
8874 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8875 (setq po (org-op-to-function po str-p))
8876 (if (equal pn "CATEGORY")
8877 (setq gv '(get-text-property (point) 'org-category))
8878 (setq gv `(org-cached-entry-get nil ,pn)))
8879 (if re-p
8880 (if (eq po 'org<>)
8881 `(not (string-match ,pv (or ,gv "")))
8882 `(string-match ,pv (or ,gv "")))
8883 (if str-p
8884 `(,po (or ,gv "") ,pv)
8885 `(,po (string-to-number (or ,gv ""))
8886 ,(string-to-number pv) ))))
8887 (t `(member ,(downcase tag) tags-list)))
8888 mm (if minus (list 'not mm) mm)
8889 term (substring term (match-end 0)))
8890 (push mm tagsmatcher))
8891 (push (if (> (length tagsmatcher) 1)
8892 (cons 'and tagsmatcher)
8893 (car tagsmatcher))
8894 orlist)
8895 (setq tagsmatcher nil))
8896 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8897 (setq tagsmatcher
8898 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8899 ;; Make the todo matcher
8900 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8901 (setq todomatcher t)
8902 (setq orterms (org-split-string todomatch "|") orlist nil)
8903 (while (setq term (pop orterms))
8904 (while (string-match re term)
8905 (setq minus (and (match-end 1)
8906 (equal (match-string 1 term) "-"))
8907 kwd (match-string 2 term)
8908 re-p (equal (string-to-char kwd) ?{)
8909 term (substring term (match-end 0))
8910 mm (if re-p
8911 `(string-match ,(substring kwd 1 -1) todo)
8912 (list 'equal 'todo kwd))
8913 mm (if minus (list 'not mm) mm))
8914 (push mm todomatcher))
8915 (push (if (> (length todomatcher) 1)
8916 (cons 'and todomatcher)
8917 (car todomatcher))
8918 orlist)
8919 (setq todomatcher nil))
8920 (setq todomatcher (if (> (length orlist) 1)
8921 (cons 'or orlist) (car orlist))))
8923 ;; Return the string and lisp forms of the matcher
8924 (setq matcher (if todomatcher
8925 (list 'and tagsmatcher todomatcher)
8926 tagsmatcher))
8927 (cons match0 matcher)))
8929 (defun org-op-to-function (op &optional stringp)
8930 (setq op
8931 (cond
8932 ((equal op "<" ) '(< string< ))
8933 ((equal op ">" ) '(> org-string> ))
8934 ((member op '("<=" "=<")) '(<= org-string<= ))
8935 ((member op '(">=" "=>")) '(>= org-string>= ))
8936 ((member op '("=" "==")) '(= string= ))
8937 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8938 (nth (if stringp 1 0) op))
8940 (defun org<> (a b) (not (= a b)))
8941 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8942 (defun org-string>= (a b) (not (string< a b)))
8943 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8944 (defun org-string<> (a b) (not (string= a b)))
8946 (defun org-match-any-p (re list)
8947 "Does re match any element of list?"
8948 (setq list (mapcar (lambda (x) (string-match re x)) list))
8949 (delq nil list))
8951 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8952 (defvar org-tags-overlay (org-make-overlay 1 1))
8953 (org-detach-overlay org-tags-overlay)
8955 (defun org-get-tags-at (&optional pos)
8956 "Get a list of all headline tags applicable at POS.
8957 POS defaults to point. If tags are inherited, the list contains
8958 the targets in the same sequence as the headlines appear, i.e.
8959 sthe tags of the current headline come last."
8960 (interactive)
8961 (let (tags ltags lastpos parent)
8962 (save-excursion
8963 (save-restriction
8964 (widen)
8965 (goto-char (or pos (point)))
8966 (save-match-data
8967 (condition-case nil
8968 (progn
8969 (org-back-to-heading t)
8970 (while (not (equal lastpos (point)))
8971 (setq lastpos (point))
8972 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8973 (setq ltags (org-split-string
8974 (org-match-string-no-properties 1) ":"))
8975 (setq tags (append (org-remove-uniherited-tags ltags)
8976 tags)))
8977 (or org-use-tag-inheritance (error ""))
8978 (org-up-heading-all 1)
8979 (setq parent t)))
8980 (error nil))))
8981 tags)))
8983 (defun org-toggle-tag (tag &optional onoff)
8984 "Toggle the tag TAG for the current line.
8985 If ONOFF is `on' or `off', don't toggle but set to this state."
8986 (unless (org-on-heading-p t) (error "Not on headling"))
8987 (let (res current)
8988 (save-excursion
8989 (beginning-of-line)
8990 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8991 (point-at-eol) t)
8992 (progn
8993 (setq current (match-string 1))
8994 (replace-match ""))
8995 (setq current ""))
8996 (setq current (nreverse (org-split-string current ":")))
8997 (cond
8998 ((eq onoff 'on)
8999 (setq res t)
9000 (or (member tag current) (push tag current)))
9001 ((eq onoff 'off)
9002 (or (not (member tag current)) (setq current (delete tag current))))
9003 (t (if (member tag current)
9004 (setq current (delete tag current))
9005 (setq res t)
9006 (push tag current))))
9007 (end-of-line 1)
9008 (if current
9009 (progn
9010 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9011 (org-set-tags nil t))
9012 (delete-horizontal-space))
9013 (run-hooks 'org-after-tags-change-hook))
9014 res))
9016 (defun org-align-tags-here (to-col)
9017 ;; Assumes that this is a headline
9018 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9019 (beginning-of-line 1)
9020 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9021 (< pos (match-beginning 2)))
9022 (progn
9023 (setq tags-l (- (match-end 2) (match-beginning 2)))
9024 (goto-char (match-beginning 1))
9025 (insert " ")
9026 (delete-region (point) (1+ (match-beginning 2)))
9027 (setq ncol (max (1+ (current-column))
9028 (1+ col)
9029 (if (> to-col 0)
9030 to-col
9031 (- (abs to-col) tags-l))))
9032 (setq p (point))
9033 (insert (make-string (- ncol (current-column)) ?\ ))
9034 (setq ncol (current-column))
9035 (tabify p (point-at-eol))
9036 (org-move-to-column (min ncol col) t))
9037 (goto-char pos))))
9039 (defun org-set-tags (&optional arg just-align)
9040 "Set the tags for the current headline.
9041 With prefix ARG, realign all tags in headings in the current buffer."
9042 (interactive "P")
9043 (let* ((re (concat "^" outline-regexp))
9044 (current (org-get-tags-string))
9045 (col (current-column))
9046 (org-setting-tags t)
9047 table current-tags inherited-tags ; computed below when needed
9048 tags p0 c0 c1 rpl)
9049 (if arg
9050 (save-excursion
9051 (goto-char (point-min))
9052 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9053 (while (re-search-forward re nil t)
9054 (org-set-tags nil t)
9055 (end-of-line 1)))
9056 (message "All tags realigned to column %d" org-tags-column))
9057 (if just-align
9058 (setq tags current)
9059 ;; Get a new set of tags from the user
9060 (save-excursion
9061 (setq table (or org-tag-alist (org-get-buffer-tags))
9062 org-last-tags-completion-table table
9063 current-tags (org-split-string current ":")
9064 inherited-tags (nreverse
9065 (nthcdr (length current-tags)
9066 (nreverse (org-get-tags-at))))
9067 tags
9068 (if (or (eq t org-use-fast-tag-selection)
9069 (and org-use-fast-tag-selection
9070 (delq nil (mapcar 'cdr table))))
9071 (org-fast-tag-selection
9072 current-tags inherited-tags table
9073 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9074 (let ((org-add-colon-after-tag-completion t))
9075 (org-trim
9076 (org-without-partial-completion
9077 (completing-read "Tags: " 'org-tags-completion-function
9078 nil nil current 'org-tags-history)))))))
9079 (while (string-match "[-+&]+" tags)
9080 ;; No boolean logic, just a list
9081 (setq tags (replace-match ":" t t tags))))
9083 (if (string-match "\\`[\t ]*\\'" tags)
9084 (setq tags "")
9085 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9086 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9088 ;; Insert new tags at the correct column
9089 (beginning-of-line 1)
9090 (cond
9091 ((and (equal current "") (equal tags "")))
9092 ((re-search-forward
9093 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9094 (point-at-eol) t)
9095 (if (equal tags "")
9096 (setq rpl "")
9097 (goto-char (match-beginning 0))
9098 (setq c0 (current-column) p0 (point)
9099 c1 (max (1+ c0) (if (> org-tags-column 0)
9100 org-tags-column
9101 (- (- org-tags-column) (length tags))))
9102 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9103 (replace-match rpl t t)
9104 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9105 tags)
9106 (t (error "Tags alignment failed")))
9107 (org-move-to-column col)
9108 (unless just-align
9109 (run-hooks 'org-after-tags-change-hook)))))
9111 (defun org-change-tag-in-region (beg end tag off)
9112 "Add or remove TAG for each entry in the region.
9113 This works in the agenda, and also in an org-mode buffer."
9114 (interactive
9115 (list (region-beginning) (region-end)
9116 (let ((org-last-tags-completion-table
9117 (if (org-mode-p)
9118 (org-get-buffer-tags)
9119 (org-global-tags-completion-table))))
9120 (completing-read
9121 "Tag: " 'org-tags-completion-function nil nil nil
9122 'org-tags-history))
9123 (progn
9124 (message "[s]et or [r]emove? ")
9125 (equal (read-char-exclusive) ?r))))
9126 (if (fboundp 'deactivate-mark) (deactivate-mark))
9127 (let ((agendap (equal major-mode 'org-agenda-mode))
9128 l1 l2 m buf pos newhead (cnt 0))
9129 (goto-char end)
9130 (setq l2 (1- (org-current-line)))
9131 (goto-char beg)
9132 (setq l1 (org-current-line))
9133 (loop for l from l1 to l2 do
9134 (goto-line l)
9135 (setq m (get-text-property (point) 'org-hd-marker))
9136 (when (or (and (org-mode-p) (org-on-heading-p))
9137 (and agendap m))
9138 (setq buf (if agendap (marker-buffer m) (current-buffer))
9139 pos (if agendap m (point)))
9140 (with-current-buffer buf
9141 (save-excursion
9142 (save-restriction
9143 (goto-char pos)
9144 (setq cnt (1+ cnt))
9145 (org-toggle-tag tag (if off 'off 'on))
9146 (setq newhead (org-get-heading)))))
9147 (and agendap (org-agenda-change-all-lines newhead m))))
9148 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9150 (defun org-tags-completion-function (string predicate &optional flag)
9151 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9152 (confirm (lambda (x) (stringp (car x)))))
9153 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9154 (setq s1 (match-string 1 string)
9155 s2 (match-string 2 string))
9156 (setq s1 "" s2 string))
9157 (cond
9158 ((eq flag nil)
9159 ;; try completion
9160 (setq rtn (try-completion s2 ctable confirm))
9161 (if (stringp rtn)
9162 (setq rtn
9163 (concat s1 s2 (substring rtn (length s2))
9164 (if (and org-add-colon-after-tag-completion
9165 (assoc rtn ctable))
9166 ":" ""))))
9167 rtn)
9168 ((eq flag t)
9169 ;; all-completions
9170 (all-completions s2 ctable confirm)
9172 ((eq flag 'lambda)
9173 ;; exact match?
9174 (assoc s2 ctable)))
9177 (defun org-fast-tag-insert (kwd tags face &optional end)
9178 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9179 (insert (format "%-12s" (concat kwd ":"))
9180 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9181 (or end "")))
9183 (defun org-fast-tag-show-exit (flag)
9184 (save-excursion
9185 (goto-line 3)
9186 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9187 (replace-match ""))
9188 (when flag
9189 (end-of-line 1)
9190 (org-move-to-column (- (window-width) 19) t)
9191 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9193 (defun org-set-current-tags-overlay (current prefix)
9194 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9195 (if (featurep 'xemacs)
9196 (org-overlay-display org-tags-overlay (concat prefix s)
9197 'secondary-selection)
9198 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9199 (org-overlay-display org-tags-overlay (concat prefix s)))))
9201 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9202 "Fast tag selection with single keys.
9203 CURRENT is the current list of tags in the headline, INHERITED is the
9204 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9205 possibly with grouping information. TODO-TABLE is a similar table with
9206 TODO keywords, should these have keys assigned to them.
9207 If the keys are nil, a-z are automatically assigned.
9208 Returns the new tags string, or nil to not change the current settings."
9209 (let* ((fulltable (append table todo-table))
9210 (maxlen (apply 'max (mapcar
9211 (lambda (x)
9212 (if (stringp (car x)) (string-width (car x)) 0))
9213 fulltable)))
9214 (buf (current-buffer))
9215 (expert (eq org-fast-tag-selection-single-key 'expert))
9216 (buffer-tags nil)
9217 (fwidth (+ maxlen 3 1 3))
9218 (ncol (/ (- (window-width) 4) fwidth))
9219 (i-face 'org-done)
9220 (c-face 'org-todo)
9221 tg cnt e c char c1 c2 ntable tbl rtn
9222 ov-start ov-end ov-prefix
9223 (exit-after-next org-fast-tag-selection-single-key)
9224 (done-keywords org-done-keywords)
9225 groups ingroup)
9226 (save-excursion
9227 (beginning-of-line 1)
9228 (if (looking-at
9229 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9230 (setq ov-start (match-beginning 1)
9231 ov-end (match-end 1)
9232 ov-prefix "")
9233 (setq ov-start (1- (point-at-eol))
9234 ov-end (1+ ov-start))
9235 (skip-chars-forward "^\n\r")
9236 (setq ov-prefix
9237 (concat
9238 (buffer-substring (1- (point)) (point))
9239 (if (> (current-column) org-tags-column)
9241 (make-string (- org-tags-column (current-column)) ?\ ))))))
9242 (org-move-overlay org-tags-overlay ov-start ov-end)
9243 (save-window-excursion
9244 (if expert
9245 (set-buffer (get-buffer-create " *Org tags*"))
9246 (delete-other-windows)
9247 (split-window-vertically)
9248 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9249 (erase-buffer)
9250 (org-set-local 'org-done-keywords done-keywords)
9251 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9252 (org-fast-tag-insert "Current" current c-face "\n\n")
9253 (org-fast-tag-show-exit exit-after-next)
9254 (org-set-current-tags-overlay current ov-prefix)
9255 (setq tbl fulltable char ?a cnt 0)
9256 (while (setq e (pop tbl))
9257 (cond
9258 ((equal e '(:startgroup))
9259 (push '() groups) (setq ingroup t)
9260 (when (not (= cnt 0))
9261 (setq cnt 0)
9262 (insert "\n"))
9263 (insert "{ "))
9264 ((equal e '(:endgroup))
9265 (setq ingroup nil cnt 0)
9266 (insert "}\n"))
9268 (setq tg (car e) c2 nil)
9269 (if (cdr e)
9270 (setq c (cdr e))
9271 ;; automatically assign a character.
9272 (setq c1 (string-to-char
9273 (downcase (substring
9274 tg (if (= (string-to-char tg) ?@) 1 0)))))
9275 (if (or (rassoc c1 ntable) (rassoc c1 table))
9276 (while (or (rassoc char ntable) (rassoc char table))
9277 (setq char (1+ char)))
9278 (setq c2 c1))
9279 (setq c (or c2 char)))
9280 (if ingroup (push tg (car groups)))
9281 (setq tg (org-add-props tg nil 'face
9282 (cond
9283 ((not (assoc tg table))
9284 (org-get-todo-face tg))
9285 ((member tg current) c-face)
9286 ((member tg inherited) i-face)
9287 (t nil))))
9288 (if (and (= cnt 0) (not ingroup)) (insert " "))
9289 (insert "[" c "] " tg (make-string
9290 (- fwidth 4 (length tg)) ?\ ))
9291 (push (cons tg c) ntable)
9292 (when (= (setq cnt (1+ cnt)) ncol)
9293 (insert "\n")
9294 (if ingroup (insert " "))
9295 (setq cnt 0)))))
9296 (setq ntable (nreverse ntable))
9297 (insert "\n")
9298 (goto-char (point-min))
9299 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9300 (fit-window-to-buffer))
9301 (setq rtn
9302 (catch 'exit
9303 (while t
9304 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9305 (if groups " [!] no groups" " [!]groups")
9306 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9307 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9308 (cond
9309 ((= c ?\r) (throw 'exit t))
9310 ((= c ?!)
9311 (setq groups (not groups))
9312 (goto-char (point-min))
9313 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9314 ((= c ?\C-c)
9315 (if (not expert)
9316 (org-fast-tag-show-exit
9317 (setq exit-after-next (not exit-after-next)))
9318 (setq expert nil)
9319 (delete-other-windows)
9320 (split-window-vertically)
9321 (org-switch-to-buffer-other-window " *Org tags*")
9322 (and (fboundp 'fit-window-to-buffer)
9323 (fit-window-to-buffer))))
9324 ((or (= c ?\C-g)
9325 (and (= c ?q) (not (rassoc c ntable))))
9326 (org-detach-overlay org-tags-overlay)
9327 (setq quit-flag t))
9328 ((= c ?\ )
9329 (setq current nil)
9330 (if exit-after-next (setq exit-after-next 'now)))
9331 ((= c ?\t)
9332 (condition-case nil
9333 (setq tg (completing-read
9334 "Tag: "
9335 (or buffer-tags
9336 (with-current-buffer buf
9337 (org-get-buffer-tags)))))
9338 (quit (setq tg "")))
9339 (when (string-match "\\S-" tg)
9340 (add-to-list 'buffer-tags (list tg))
9341 (if (member tg current)
9342 (setq current (delete tg current))
9343 (push tg current)))
9344 (if exit-after-next (setq exit-after-next 'now)))
9345 ((setq e (rassoc c todo-table) tg (car e))
9346 (with-current-buffer buf
9347 (save-excursion (org-todo tg)))
9348 (if exit-after-next (setq exit-after-next 'now)))
9349 ((setq e (rassoc c ntable) tg (car e))
9350 (if (member tg current)
9351 (setq current (delete tg current))
9352 (loop for g in groups do
9353 (if (member tg g)
9354 (mapc (lambda (x)
9355 (setq current (delete x current)))
9356 g)))
9357 (push tg current))
9358 (if exit-after-next (setq exit-after-next 'now))))
9360 ;; Create a sorted list
9361 (setq current
9362 (sort current
9363 (lambda (a b)
9364 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9365 (if (eq exit-after-next 'now) (throw 'exit t))
9366 (goto-char (point-min))
9367 (beginning-of-line 2)
9368 (delete-region (point) (point-at-eol))
9369 (org-fast-tag-insert "Current" current c-face)
9370 (org-set-current-tags-overlay current ov-prefix)
9371 (while (re-search-forward
9372 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9373 (setq tg (match-string 1))
9374 (add-text-properties
9375 (match-beginning 1) (match-end 1)
9376 (list 'face
9377 (cond
9378 ((member tg current) c-face)
9379 ((member tg inherited) i-face)
9380 (t (get-text-property (match-beginning 1) 'face))))))
9381 (goto-char (point-min)))))
9382 (org-detach-overlay org-tags-overlay)
9383 (if rtn
9384 (mapconcat 'identity current ":")
9385 nil))))
9387 (defun org-get-tags-string ()
9388 "Get the TAGS string in the current headline."
9389 (unless (org-on-heading-p t)
9390 (error "Not on a heading"))
9391 (save-excursion
9392 (beginning-of-line 1)
9393 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9394 (org-match-string-no-properties 1)
9395 "")))
9397 (defun org-get-tags ()
9398 "Get the list of tags specified in the current headline."
9399 (org-split-string (org-get-tags-string) ":"))
9401 (defun org-get-buffer-tags ()
9402 "Get a table of all tags used in the buffer, for completion."
9403 (let (tags)
9404 (save-excursion
9405 (goto-char (point-min))
9406 (while (re-search-forward
9407 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9408 (when (equal (char-after (point-at-bol 0)) ?*)
9409 (mapc (lambda (x) (add-to-list 'tags x))
9410 (org-split-string (org-match-string-no-properties 1) ":")))))
9411 (mapcar 'list tags)))
9414 ;;;; Properties
9416 ;;; Setting and retrieving properties
9418 (defconst org-special-properties
9419 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9420 "TIMESTAMP" "TIMESTAMP_IA")
9421 "The special properties valid in Org-mode.
9423 These are properties that are not defined in the property drawer,
9424 but in some other way.")
9426 (defconst org-default-properties
9427 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9428 "LOCATION" "LOGGING" "COLUMNS")
9429 "Some properties that are used by Org-mode for various purposes.
9430 Being in this list makes sure that they are offered for completion.")
9432 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9433 "Regular expression matching the first line of a property drawer.")
9435 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9436 "Regular expression matching the first line of a property drawer.")
9438 (defun org-property-action ()
9439 "Do an action on properties."
9440 (interactive)
9441 (let (c)
9442 (org-at-property-p)
9443 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9444 (setq c (read-char-exclusive))
9445 (cond
9446 ((equal c ?s)
9447 (call-interactively 'org-set-property))
9448 ((equal c ?d)
9449 (call-interactively 'org-delete-property))
9450 ((equal c ?D)
9451 (call-interactively 'org-delete-property-globally))
9452 ((equal c ?c)
9453 (call-interactively 'org-compute-property-at-point))
9454 (t (error "No such property action %c" c)))))
9456 (defun org-at-property-p ()
9457 "Is the cursor in a property line?"
9458 ;; FIXME: Does not check if we are actually in the drawer.
9459 ;; FIXME: also returns true on any drawers.....
9460 ;; This is used by C-c C-c for property action.
9461 (save-excursion
9462 (beginning-of-line 1)
9463 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9465 (defun org-get-property-block (&optional beg end force)
9466 "Return the (beg . end) range of the body of the property drawer.
9467 BEG and END can be beginning and end of subtree, if not given
9468 they will be found.
9469 If the drawer does not exist and FORCE is non-nil, create the drawer."
9470 (catch 'exit
9471 (save-excursion
9472 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9473 (end (or end (progn (outline-next-heading) (point)))))
9474 (goto-char beg)
9475 (if (re-search-forward org-property-start-re end t)
9476 (setq beg (1+ (match-end 0)))
9477 (if force
9478 (save-excursion
9479 (org-insert-property-drawer)
9480 (setq end (progn (outline-next-heading) (point))))
9481 (throw 'exit nil))
9482 (goto-char beg)
9483 (if (re-search-forward org-property-start-re end t)
9484 (setq beg (1+ (match-end 0)))))
9485 (if (re-search-forward org-property-end-re end t)
9486 (setq end (match-beginning 0))
9487 (or force (throw 'exit nil))
9488 (goto-char beg)
9489 (setq end beg)
9490 (org-indent-line-function)
9491 (insert ":END:\n"))
9492 (cons beg end)))))
9494 (defun org-entry-properties (&optional pom which)
9495 "Get all properties of the entry at point-or-marker POM.
9496 This includes the TODO keyword, the tags, time strings for deadline,
9497 scheduled, and clocking, and any additional properties defined in the
9498 entry. The return value is an alist, keys may occur multiple times
9499 if the property key was used several times.
9500 POM may also be nil, in which case the current entry is used.
9501 If WHICH is nil or `all', get all properties. If WHICH is
9502 `special' or `standard', only get that subclass."
9503 (setq which (or which 'all))
9504 (org-with-point-at pom
9505 (let ((clockstr (substring org-clock-string 0 -1))
9506 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9507 beg end range props sum-props key value string clocksum)
9508 (save-excursion
9509 (when (condition-case nil (org-back-to-heading t) (error nil))
9510 (setq beg (point))
9511 (setq sum-props (get-text-property (point) 'org-summaries))
9512 (setq clocksum (get-text-property (point) :org-clock-minutes))
9513 (outline-next-heading)
9514 (setq end (point))
9515 (when (memq which '(all special))
9516 ;; Get the special properties, like TODO and tags
9517 (goto-char beg)
9518 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9519 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9520 (when (looking-at org-priority-regexp)
9521 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9522 (when (and (setq value (org-get-tags-string))
9523 (string-match "\\S-" value))
9524 (push (cons "TAGS" value) props))
9525 (when (setq value (org-get-tags-at))
9526 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9527 props))
9528 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9529 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9530 string (if (equal key clockstr)
9531 (org-no-properties
9532 (org-trim
9533 (buffer-substring
9534 (match-beginning 3) (goto-char (point-at-eol)))))
9535 (substring (org-match-string-no-properties 3) 1 -1)))
9536 (unless key
9537 (if (= (char-after (match-beginning 3)) ?\[)
9538 (setq key "TIMESTAMP_IA")
9539 (setq key "TIMESTAMP")))
9540 (when (or (equal key clockstr) (not (assoc key props)))
9541 (push (cons key string) props)))
9545 (when (memq which '(all standard))
9546 ;; Get the standard properties, like :PORP: ...
9547 (setq range (org-get-property-block beg end))
9548 (when range
9549 (goto-char (car range))
9550 (while (re-search-forward
9551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9552 (cdr range) t)
9553 (setq key (org-match-string-no-properties 1)
9554 value (org-trim (or (org-match-string-no-properties 2) "")))
9555 (unless (member key excluded)
9556 (push (cons key (or value "")) props)))))
9557 (if clocksum
9558 (push (cons "CLOCKSUM"
9559 (org-columns-number-to-string (/ (float clocksum) 60.)
9560 'add_times))
9561 props))
9562 (append sum-props (nreverse props)))))))
9564 (defun org-entry-get (pom property &optional inherit)
9565 "Get value of PROPERTY for entry at point-or-marker POM.
9566 If INHERIT is non-nil and the entry does not have the property,
9567 then also check higher levels of the hierarchy.
9568 If INHERIT is the symbol `selective', use inheritance only if the setting
9569 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9570 If the property is present but empty, the return value is the empty string.
9571 If the property is not present at all, nil is returned."
9572 (org-with-point-at pom
9573 (if (and inherit (if (eq inherit 'selective)
9574 (org-property-inherit-p property)
9576 (org-entry-get-with-inheritance property)
9577 (if (member property org-special-properties)
9578 ;; We need a special property. Use brute force, get all properties.
9579 (cdr (assoc property (org-entry-properties nil 'special)))
9580 (let ((range (org-get-property-block)))
9581 (if (and range
9582 (goto-char (car range))
9583 (re-search-forward
9584 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9585 (cdr range) t))
9586 ;; Found the property, return it.
9587 (if (match-end 1)
9588 (org-match-string-no-properties 1)
9589 "")))))))
9591 (defun org-property-or-variable-value (var &optional inherit)
9592 "Check if there is a property fixing the value of VAR.
9593 If yes, return this value. If not, return the current value of the variable."
9594 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9595 (if (and prop (stringp prop) (string-match "\\S-" prop))
9596 (read prop)
9597 (symbol-value var))))
9599 (defun org-entry-delete (pom property)
9600 "Delete the property PROPERTY from entry at point-or-marker POM."
9601 (org-with-point-at pom
9602 (if (member property org-special-properties)
9603 nil ; cannot delete these properties.
9604 (let ((range (org-get-property-block)))
9605 (if (and range
9606 (goto-char (car range))
9607 (re-search-forward
9608 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9609 (cdr range) t))
9610 (progn
9611 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9613 nil)))))
9615 ;; Multi-values properties are properties that contain multiple values
9616 ;; These values are assumed to be single words, separated by whitespace.
9617 (defun org-entry-add-to-multivalued-property (pom property value)
9618 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9619 (let* ((old (org-entry-get pom property))
9620 (values (and old (org-split-string old "[ \t]"))))
9621 (unless (member value values)
9622 (setq values (cons value values))
9623 (org-entry-put pom property
9624 (mapconcat 'identity values " ")))))
9626 (defun org-entry-remove-from-multivalued-property (pom property value)
9627 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9628 (let* ((old (org-entry-get pom property))
9629 (values (and old (org-split-string old "[ \t]"))))
9630 (when (member value values)
9631 (setq values (delete value values))
9632 (org-entry-put pom property
9633 (mapconcat 'identity values " ")))))
9635 (defun org-entry-member-in-multivalued-property (pom property value)
9636 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9637 (let* ((old (org-entry-get pom property))
9638 (values (and old (org-split-string old "[ \t]"))))
9639 (member value values)))
9641 (defvar org-entry-property-inherited-from (make-marker))
9643 (defun org-entry-get-with-inheritance (property)
9644 "Get entry property, and search higher levels if not present."
9645 (let (tmp)
9646 (save-excursion
9647 (save-restriction
9648 (widen)
9649 (catch 'ex
9650 (while t
9651 (when (setq tmp (org-entry-get nil property))
9652 (org-back-to-heading t)
9653 (move-marker org-entry-property-inherited-from (point))
9654 (throw 'ex tmp))
9655 (or (org-up-heading-safe) (throw 'ex nil)))))
9656 (or tmp (cdr (assoc property org-local-properties))
9657 (cdr (assoc property org-global-properties))))))
9659 (defun org-entry-put (pom property value)
9660 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9661 (org-with-point-at pom
9662 (org-back-to-heading t)
9663 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9664 range)
9665 (cond
9666 ((equal property "TODO")
9667 (when (and (stringp value) (string-match "\\S-" value)
9668 (not (member value org-todo-keywords-1)))
9669 (error "\"%s\" is not a valid TODO state" value))
9670 (if (or (not value)
9671 (not (string-match "\\S-" value)))
9672 (setq value 'none))
9673 (org-todo value)
9674 (org-set-tags nil 'align))
9675 ((equal property "PRIORITY")
9676 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9677 (string-to-char value) ?\ ))
9678 (org-set-tags nil 'align))
9679 ((equal property "SCHEDULED")
9680 (if (re-search-forward org-scheduled-time-regexp end t)
9681 (cond
9682 ((eq value 'earlier) (org-timestamp-change -1 'day))
9683 ((eq value 'later) (org-timestamp-change 1 'day))
9684 (t (call-interactively 'org-schedule)))
9685 (call-interactively 'org-schedule)))
9686 ((equal property "DEADLINE")
9687 (if (re-search-forward org-deadline-time-regexp end t)
9688 (cond
9689 ((eq value 'earlier) (org-timestamp-change -1 'day))
9690 ((eq value 'later) (org-timestamp-change 1 'day))
9691 (t (call-interactively 'org-deadline)))
9692 (call-interactively 'org-deadline)))
9693 ((member property org-special-properties)
9694 (error "The %s property can not yet be set with `org-entry-put'"
9695 property))
9696 (t ; a non-special property
9697 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9698 (setq range (org-get-property-block beg end 'force))
9699 (goto-char (car range))
9700 (if (re-search-forward
9701 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9702 (progn
9703 (delete-region (match-beginning 1) (match-end 1))
9704 (goto-char (match-beginning 1)))
9705 (goto-char (cdr range))
9706 (insert "\n")
9707 (backward-char 1)
9708 (org-indent-line-function)
9709 (insert ":" property ":"))
9710 (and value (insert " " value))
9711 (org-indent-line-function)))))))
9713 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9714 "Get all property keys in the current buffer.
9715 With INCLUDE-SPECIALS, also list the special properties that relect things
9716 like tags and TODO state.
9717 With INCLUDE-DEFAULTS, also include properties that has special meaning
9718 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9719 With INCLUDE-COLUMNS, also include property names given in COLUMN
9720 formats in the current buffer."
9721 (let (rtn range cfmt cols s p)
9722 (save-excursion
9723 (save-restriction
9724 (widen)
9725 (goto-char (point-min))
9726 (while (re-search-forward org-property-start-re nil t)
9727 (setq range (org-get-property-block))
9728 (goto-char (car range))
9729 (while (re-search-forward
9730 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9731 (cdr range) t)
9732 (add-to-list 'rtn (org-match-string-no-properties 1)))
9733 (outline-next-heading))))
9735 (when include-specials
9736 (setq rtn (append org-special-properties rtn)))
9738 (when include-defaults
9739 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9741 (when include-columns
9742 (save-excursion
9743 (save-restriction
9744 (widen)
9745 (goto-char (point-min))
9746 (while (re-search-forward
9747 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9748 nil t)
9749 (setq cfmt (match-string 2) s 0)
9750 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9751 cfmt s)
9752 (setq s (match-end 0)
9753 p (match-string 1 cfmt))
9754 (unless (or (equal p "ITEM")
9755 (member p org-special-properties))
9756 (add-to-list 'rtn (match-string 1 cfmt))))))))
9758 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9760 (defun org-property-values (key)
9761 "Return a list of all values of property KEY."
9762 (save-excursion
9763 (save-restriction
9764 (widen)
9765 (goto-char (point-min))
9766 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9767 values)
9768 (while (re-search-forward re nil t)
9769 (add-to-list 'values (org-trim (match-string 1))))
9770 (delete "" values)))))
9772 (defun org-insert-property-drawer ()
9773 "Insert a property drawer into the current entry."
9774 (interactive)
9775 (org-back-to-heading t)
9776 (looking-at outline-regexp)
9777 (let ((indent (- (match-end 0)(match-beginning 0)))
9778 (beg (point))
9779 (re (concat "^[ \t]*" org-keyword-time-regexp))
9780 end hiddenp)
9781 (outline-next-heading)
9782 (setq end (point))
9783 (goto-char beg)
9784 (while (re-search-forward re end t))
9785 (setq hiddenp (org-invisible-p))
9786 (end-of-line 1)
9787 (and (equal (char-after) ?\n) (forward-char 1))
9788 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9789 (beginning-of-line 2))
9790 (org-skip-over-state-notes)
9791 (skip-chars-backward " \t\n\r")
9792 (if (eq (char-before) ?*) (forward-char 1))
9793 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9794 (beginning-of-line 0)
9795 (org-indent-to-column indent)
9796 (beginning-of-line 2)
9797 (org-indent-to-column indent)
9798 (beginning-of-line 0)
9799 (if hiddenp
9800 (save-excursion
9801 (org-back-to-heading t)
9802 (hide-entry))
9803 (org-flag-drawer t))))
9805 (defun org-set-property (property value)
9806 "In the current entry, set PROPERTY to VALUE.
9807 When called interactively, this will prompt for a property name, offering
9808 completion on existing and default properties. And then it will prompt
9809 for a value, offering competion either on allowed values (via an inherited
9810 xxx_ALL property) or on existing values in other instances of this property
9811 in the current file."
9812 (interactive
9813 (let* ((prop (completing-read
9814 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9815 (cur (org-entry-get nil prop))
9816 (allowed (org-property-get-allowed-values nil prop 'table))
9817 (existing (mapcar 'list (org-property-values prop)))
9818 (val (if allowed
9819 (completing-read "Value: " allowed nil 'req-match)
9820 (completing-read
9821 (concat "Value" (if (and cur (string-match "\\S-" cur))
9822 (concat "[" cur "]") "")
9823 ": ")
9824 existing nil nil "" nil cur))))
9825 (list prop (if (equal val "") cur val))))
9826 (unless (equal (org-entry-get nil property) value)
9827 (org-entry-put nil property value)))
9829 (defun org-delete-property (property)
9830 "In the current entry, delete PROPERTY."
9831 (interactive
9832 (let* ((prop (completing-read
9833 "Property: " (org-entry-properties nil 'standard))))
9834 (list prop)))
9835 (message "Property %s %s" property
9836 (if (org-entry-delete nil property)
9837 "deleted"
9838 "was not present in the entry")))
9840 (defun org-delete-property-globally (property)
9841 "Remove PROPERTY globally, from all entries."
9842 (interactive
9843 (let* ((prop (completing-read
9844 "Globally remove property: "
9845 (mapcar 'list (org-buffer-property-keys)))))
9846 (list prop)))
9847 (save-excursion
9848 (save-restriction
9849 (widen)
9850 (goto-char (point-min))
9851 (let ((cnt 0))
9852 (while (re-search-forward
9853 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9854 nil t)
9855 (setq cnt (1+ cnt))
9856 (replace-match ""))
9857 (message "Property \"%s\" removed from %d entries" property cnt)))))
9859 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9861 (defun org-compute-property-at-point ()
9862 "Compute the property at point.
9863 This looks for an enclosing column format, extracts the operator and
9864 then applies it to the proerty in the column format's scope."
9865 (interactive)
9866 (unless (org-at-property-p)
9867 (error "Not at a property"))
9868 (let ((prop (org-match-string-no-properties 2)))
9869 (org-columns-get-format-and-top-level)
9870 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9871 (error "No operator defined for property %s" prop))
9872 (org-columns-compute prop)))
9874 (defun org-property-get-allowed-values (pom property &optional table)
9875 "Get allowed values for the property PROPERTY.
9876 When TABLE is non-nil, return an alist that can directly be used for
9877 completion."
9878 (let (vals)
9879 (cond
9880 ((equal property "TODO")
9881 (setq vals (org-with-point-at pom
9882 (append org-todo-keywords-1 '("")))))
9883 ((equal property "PRIORITY")
9884 (let ((n org-lowest-priority))
9885 (while (>= n org-highest-priority)
9886 (push (char-to-string n) vals)
9887 (setq n (1- n)))))
9888 ((member property org-special-properties))
9890 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9892 (when (and vals (string-match "\\S-" vals))
9893 (setq vals (car (read-from-string (concat "(" vals ")"))))
9894 (setq vals (mapcar (lambda (x)
9895 (cond ((stringp x) x)
9896 ((numberp x) (number-to-string x))
9897 ((symbolp x) (symbol-name x))
9898 (t "???")))
9899 vals)))))
9900 (if table (mapcar 'list vals) vals)))
9902 (defun org-property-previous-allowed-value (&optional previous)
9903 "Switch to the next allowed value for this property."
9904 (interactive)
9905 (org-property-next-allowed-value t))
9907 (defun org-property-next-allowed-value (&optional previous)
9908 "Switch to the next allowed value for this property."
9909 (interactive)
9910 (unless (org-at-property-p)
9911 (error "Not at a property"))
9912 (let* ((key (match-string 2))
9913 (value (match-string 3))
9914 (allowed (or (org-property-get-allowed-values (point) key)
9915 (and (member value '("[ ]" "[-]" "[X]"))
9916 '("[ ]" "[X]"))))
9917 nval)
9918 (unless allowed
9919 (error "Allowed values for this property have not been defined"))
9920 (if previous (setq allowed (reverse allowed)))
9921 (if (member value allowed)
9922 (setq nval (car (cdr (member value allowed)))))
9923 (setq nval (or nval (car allowed)))
9924 (if (equal nval value)
9925 (error "Only one allowed value for this property"))
9926 (org-at-property-p)
9927 (replace-match (concat " :" key ": " nval) t t)
9928 (org-indent-line-function)
9929 (beginning-of-line 1)
9930 (skip-chars-forward " \t")))
9932 (defun org-find-entry-with-id (ident)
9933 "Locate the entry that contains the ID property with exact value IDENT.
9934 IDENT can be a string, a symbol or a number, this function will search for
9935 the string representation of it.
9936 Return the position where this entry starts, or nil if there is no such entry."
9937 (let ((id (cond
9938 ((stringp ident) ident)
9939 ((symbol-name ident) (symbol-name ident))
9940 ((numberp ident) (number-to-string ident))
9941 (t (error "IDENT %s must be a string, symbol or number" ident))))
9942 (case-fold-search nil))
9943 (save-excursion
9944 (save-restriction
9945 (widen)
9946 (goto-char (point-min))
9947 (when (re-search-forward
9948 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9949 nil t)
9950 (org-back-to-heading)
9951 (point))))))
9953 ;;;; Timestamps
9955 (defvar org-last-changed-timestamp nil)
9956 (defvar org-time-was-given) ; dynamically scoped parameter
9957 (defvar org-end-time-was-given) ; dynamically scoped parameter
9958 (defvar org-ts-what) ; dynamically scoped parameter
9960 (defun org-time-stamp (arg)
9961 "Prompt for a date/time and insert a time stamp.
9962 If the user specifies a time like HH:MM, or if this command is called
9963 with a prefix argument, the time stamp will contain date and time.
9964 Otherwise, only the date will be included. All parts of a date not
9965 specified by the user will be filled in from the current date/time.
9966 So if you press just return without typing anything, the time stamp
9967 will represent the current date/time. If there is already a timestamp
9968 at the cursor, it will be modified."
9969 (interactive "P")
9970 (let* ((ts nil)
9971 (default-time
9972 ;; Default time is either today, or, when entering a range,
9973 ;; the range start.
9974 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9975 (save-excursion
9976 (re-search-backward
9977 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9978 (- (point) 20) t)))
9979 (apply 'encode-time (org-parse-time-string (match-string 1)))
9980 (current-time)))
9981 (default-input (and ts (org-get-compact-tod ts)))
9982 org-time-was-given org-end-time-was-given time)
9983 (cond
9984 ((and (org-at-timestamp-p)
9985 (eq last-command 'org-time-stamp)
9986 (eq this-command 'org-time-stamp))
9987 (insert "--")
9988 (setq time (let ((this-command this-command))
9989 (org-read-date arg 'totime nil nil default-time default-input)))
9990 (org-insert-time-stamp time (or org-time-was-given arg)))
9991 ((org-at-timestamp-p)
9992 (setq time (let ((this-command this-command))
9993 (org-read-date arg 'totime nil nil default-time default-input)))
9994 (when (org-at-timestamp-p) ; just to get the match data
9995 (replace-match "")
9996 (setq org-last-changed-timestamp
9997 (org-insert-time-stamp
9998 time (or org-time-was-given arg)
9999 nil nil nil (list org-end-time-was-given))))
10000 (message "Timestamp updated"))
10002 (setq time (let ((this-command this-command))
10003 (org-read-date arg 'totime nil nil default-time default-input)))
10004 (org-insert-time-stamp time (or org-time-was-given arg)
10005 nil nil nil (list org-end-time-was-given))))))
10007 ;; FIXME: can we use this for something else, like computing time differences?
10008 (defun org-get-compact-tod (s)
10009 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10010 (let* ((t1 (match-string 1 s))
10011 (h1 (string-to-number (match-string 2 s)))
10012 (m1 (string-to-number (match-string 3 s)))
10013 (t2 (and (match-end 4) (match-string 5 s)))
10014 (h2 (and t2 (string-to-number (match-string 6 s))))
10015 (m2 (and t2 (string-to-number (match-string 7 s))))
10016 dh dm)
10017 (if (not t2)
10019 (setq dh (- h2 h1) dm (- m2 m1))
10020 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10021 (concat t1 "+" (number-to-string dh)
10022 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10024 (defun org-time-stamp-inactive (&optional arg)
10025 "Insert an inactive time stamp.
10026 An inactive time stamp is enclosed in square brackets instead of angle
10027 brackets. It is inactive in the sense that it does not trigger agenda entries,
10028 does not link to the calendar and cannot be changed with the S-cursor keys.
10029 So these are more for recording a certain time/date."
10030 (interactive "P")
10031 (let (org-time-was-given org-end-time-was-given time)
10032 (setq time (org-read-date arg 'totime))
10033 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10034 nil nil (list org-end-time-was-given))))
10036 (defvar org-date-ovl (org-make-overlay 1 1))
10037 (org-overlay-put org-date-ovl 'face 'org-warning)
10038 (org-detach-overlay org-date-ovl)
10040 (defvar org-ans1) ; dynamically scoped parameter
10041 (defvar org-ans2) ; dynamically scoped parameter
10043 (defvar org-plain-time-of-day-regexp) ; defined below
10045 (defvar org-read-date-overlay nil)
10046 (defvar org-dcst nil) ; dynamically scoped
10048 (defun org-read-date (&optional with-time to-time from-string prompt
10049 default-time default-input)
10050 "Read a date, possibly a time, and make things smooth for the user.
10051 The prompt will suggest to enter an ISO date, but you can also enter anything
10052 which will at least partially be understood by `parse-time-string'.
10053 Unrecognized parts of the date will default to the current day, month, year,
10054 hour and minute. If this command is called to replace a timestamp at point,
10055 of to enter the second timestamp of a range, the default time is taken from the
10056 existing stamp. For example,
10057 3-2-5 --> 2003-02-05
10058 feb 15 --> currentyear-02-15
10059 sep 12 9 --> 2009-09-12
10060 12:45 --> today 12:45
10061 22 sept 0:34 --> currentyear-09-22 0:34
10062 12 --> currentyear-currentmonth-12
10063 Fri --> nearest Friday (today or later)
10064 etc.
10066 Furthermore you can specify a relative date by giving, as the *first* thing
10067 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10068 change in days weeks, months, years.
10069 With a single plus or minus, the date is relative to today. With a double
10070 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10071 +4d --> four days from today
10072 +4 --> same as above
10073 +2w --> two weeks from today
10074 ++5 --> five days from default date
10076 The function understands only English month and weekday abbreviations,
10077 but this can be configured with the variables `parse-time-months' and
10078 `parse-time-weekdays'.
10080 While prompting, a calendar is popped up - you can also select the
10081 date with the mouse (button 1). The calendar shows a period of three
10082 months. To scroll it to other months, use the keys `>' and `<'.
10083 If you don't like the calendar, turn it off with
10084 \(setq org-read-date-popup-calendar nil)
10086 With optional argument TO-TIME, the date will immediately be converted
10087 to an internal time.
10088 With an optional argument WITH-TIME, the prompt will suggest to also
10089 insert a time. Note that when WITH-TIME is not set, you can still
10090 enter a time, and this function will inform the calling routine about
10091 this change. The calling routine may then choose to change the format
10092 used to insert the time stamp into the buffer to include the time.
10093 With optional argument FROM-STRING, read from this string instead from
10094 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10095 the time/date that is used for everything that is not specified by the
10096 user."
10097 (require 'parse-time)
10098 (let* ((org-time-stamp-rounding-minutes
10099 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10100 (org-dcst org-display-custom-times)
10101 (ct (org-current-time))
10102 (def (or default-time ct))
10103 (defdecode (decode-time def))
10104 (dummy (progn
10105 (when (< (nth 2 defdecode) org-extend-today-until)
10106 (setcar (nthcdr 2 defdecode) -1)
10107 (setcar (nthcdr 1 defdecode) 59)
10108 (setq def (apply 'encode-time defdecode)
10109 defdecode (decode-time def)))))
10110 (calendar-move-hook nil)
10111 (calendar-view-diary-initially-flag nil)
10112 (view-diary-entries-initially nil)
10113 (calendar-view-holidays-initially-flag nil)
10114 (view-calendar-holidays-initially nil)
10115 (timestr (format-time-string
10116 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10117 (prompt (concat (if prompt (concat prompt " ") "")
10118 (format "Date+time [%s]: " timestr)))
10119 ans (org-ans0 "") org-ans1 org-ans2 final)
10121 (cond
10122 (from-string (setq ans from-string))
10123 (org-read-date-popup-calendar
10124 (save-excursion
10125 (save-window-excursion
10126 (calendar)
10127 (calendar-forward-day (- (time-to-days def)
10128 (calendar-absolute-from-gregorian
10129 (calendar-current-date))))
10130 (org-eval-in-calendar nil t)
10131 (let* ((old-map (current-local-map))
10132 (map (copy-keymap calendar-mode-map))
10133 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10134 (org-defkey map (kbd "RET") 'org-calendar-select)
10135 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10136 'org-calendar-select-mouse)
10137 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10138 'org-calendar-select-mouse)
10139 (org-defkey minibuffer-local-map [(meta shift left)]
10140 (lambda () (interactive)
10141 (org-eval-in-calendar '(calendar-backward-month 1))))
10142 (org-defkey minibuffer-local-map [(meta shift right)]
10143 (lambda () (interactive)
10144 (org-eval-in-calendar '(calendar-forward-month 1))))
10145 (org-defkey minibuffer-local-map [(meta shift up)]
10146 (lambda () (interactive)
10147 (org-eval-in-calendar '(calendar-backward-year 1))))
10148 (org-defkey minibuffer-local-map [(meta shift down)]
10149 (lambda () (interactive)
10150 (org-eval-in-calendar '(calendar-forward-year 1))))
10151 (org-defkey minibuffer-local-map [(shift up)]
10152 (lambda () (interactive)
10153 (org-eval-in-calendar '(calendar-backward-week 1))))
10154 (org-defkey minibuffer-local-map [(shift down)]
10155 (lambda () (interactive)
10156 (org-eval-in-calendar '(calendar-forward-week 1))))
10157 (org-defkey minibuffer-local-map [(shift left)]
10158 (lambda () (interactive)
10159 (org-eval-in-calendar '(calendar-backward-day 1))))
10160 (org-defkey minibuffer-local-map [(shift right)]
10161 (lambda () (interactive)
10162 (org-eval-in-calendar '(calendar-forward-day 1))))
10163 (org-defkey minibuffer-local-map ">"
10164 (lambda () (interactive)
10165 (org-eval-in-calendar '(scroll-calendar-left 1))))
10166 (org-defkey minibuffer-local-map "<"
10167 (lambda () (interactive)
10168 (org-eval-in-calendar '(scroll-calendar-right 1))))
10169 (unwind-protect
10170 (progn
10171 (use-local-map map)
10172 (add-hook 'post-command-hook 'org-read-date-display)
10173 (setq org-ans0 (read-string prompt default-input nil nil))
10174 ;; org-ans0: from prompt
10175 ;; org-ans1: from mouse click
10176 ;; org-ans2: from calendar motion
10177 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10178 (remove-hook 'post-command-hook 'org-read-date-display)
10179 (use-local-map old-map)
10180 (when org-read-date-overlay
10181 (org-delete-overlay org-read-date-overlay)
10182 (setq org-read-date-overlay nil)))))))
10184 (t ; Naked prompt only
10185 (unwind-protect
10186 (setq ans (read-string prompt default-input nil timestr))
10187 (when org-read-date-overlay
10188 (org-delete-overlay org-read-date-overlay)
10189 (setq org-read-date-overlay nil)))))
10191 (setq final (org-read-date-analyze ans def defdecode))
10193 (if to-time
10194 (apply 'encode-time final)
10195 (if (and (boundp 'org-time-was-given) org-time-was-given)
10196 (format "%04d-%02d-%02d %02d:%02d"
10197 (nth 5 final) (nth 4 final) (nth 3 final)
10198 (nth 2 final) (nth 1 final))
10199 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10200 (defvar def)
10201 (defvar defdecode)
10202 (defvar with-time)
10203 (defun org-read-date-display ()
10204 "Display the currrent date prompt interpretation in the minibuffer."
10205 (when org-read-date-display-live
10206 (when org-read-date-overlay
10207 (org-delete-overlay org-read-date-overlay))
10208 (let ((p (point)))
10209 (end-of-line 1)
10210 (while (not (equal (buffer-substring
10211 (max (point-min) (- (point) 4)) (point))
10212 " "))
10213 (insert " "))
10214 (goto-char p))
10215 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10216 " " (or org-ans1 org-ans2)))
10217 (org-end-time-was-given nil)
10218 (f (org-read-date-analyze ans def defdecode))
10219 (fmts (if org-dcst
10220 org-time-stamp-custom-formats
10221 org-time-stamp-formats))
10222 (fmt (if (or with-time
10223 (and (boundp 'org-time-was-given) org-time-was-given))
10224 (cdr fmts)
10225 (car fmts)))
10226 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10227 (when (and org-end-time-was-given
10228 (string-match org-plain-time-of-day-regexp txt))
10229 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10230 org-end-time-was-given
10231 (substring txt (match-end 0)))))
10232 (setq org-read-date-overlay
10233 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10234 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10236 (defun org-read-date-analyze (ans def defdecode)
10237 "Analyze the combined answer of the date prompt."
10238 ;; FIXME: cleanup and comment
10239 (let (delta deltan deltaw deltadef year month day
10240 hour minute second wday pm h2 m2 tl wday1
10241 iso-year iso-weekday iso-week iso-year iso-date)
10243 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10244 (setq ans "+0"))
10246 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10247 (setq ans (replace-match "" t t ans)
10248 deltan (car delta)
10249 deltaw (nth 1 delta)
10250 deltadef (nth 2 delta)))
10252 ;; Check if there is an iso week date in there
10253 ;; If yes, sore the info and ostpone interpreting it until the rest
10254 ;; of the parsing is done
10255 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10256 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10257 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10258 iso-week (string-to-number (match-string 2 ans)))
10259 (setq ans (replace-match "" t t ans)))
10261 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10262 (when (string-match
10263 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10264 (setq year (if (match-end 2)
10265 (string-to-number (match-string 2 ans))
10266 (string-to-number (format-time-string "%Y")))
10267 month (string-to-number (match-string 3 ans))
10268 day (string-to-number (match-string 4 ans)))
10269 (if (< year 100) (setq year (+ 2000 year)))
10270 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10271 t nil ans)))
10272 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10273 ;; If there is a time with am/pm, and *no* time without it, we convert
10274 ;; so that matching will be successful.
10275 (loop for i from 1 to 2 do ; twice, for end time as well
10276 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10277 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10278 (setq hour (string-to-number (match-string 1 ans))
10279 minute (if (match-end 3)
10280 (string-to-number (match-string 3 ans))
10282 pm (equal ?p
10283 (string-to-char (downcase (match-string 4 ans)))))
10284 (if (and (= hour 12) (not pm))
10285 (setq hour 0)
10286 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10287 (setq ans (replace-match (format "%02d:%02d" hour minute)
10288 t t ans))))
10290 ;; Check if a time range is given as a duration
10291 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10292 (setq hour (string-to-number (match-string 1 ans))
10293 h2 (+ hour (string-to-number (match-string 3 ans)))
10294 minute (string-to-number (match-string 2 ans))
10295 m2 (+ minute (if (match-end 5) (string-to-number
10296 (match-string 5 ans))0)))
10297 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10298 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10299 t t ans)))
10301 ;; Check if there is a time range
10302 (when (boundp 'org-end-time-was-given)
10303 (setq org-time-was-given nil)
10304 (when (and (string-match org-plain-time-of-day-regexp ans)
10305 (match-end 8))
10306 (setq org-end-time-was-given (match-string 8 ans))
10307 (setq ans (concat (substring ans 0 (match-beginning 7))
10308 (substring ans (match-end 7))))))
10310 (setq tl (parse-time-string ans)
10311 day (or (nth 3 tl) (nth 3 defdecode))
10312 month (or (nth 4 tl)
10313 (if (and org-read-date-prefer-future
10314 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10315 (1+ (nth 4 defdecode))
10316 (nth 4 defdecode)))
10317 year (or (nth 5 tl)
10318 (if (and org-read-date-prefer-future
10319 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10320 (1+ (nth 5 defdecode))
10321 (nth 5 defdecode)))
10322 hour (or (nth 2 tl) (nth 2 defdecode))
10323 minute (or (nth 1 tl) (nth 1 defdecode))
10324 second (or (nth 0 tl) 0)
10325 wday (nth 6 tl))
10327 ;; Special date definitions below
10328 (cond
10329 (iso-week
10330 ;; There was an iso week
10331 (setq year (or iso-year year)
10332 day (or iso-weekday wday 1)
10333 wday nil ; to make sure that the trigger below does not match
10334 iso-date (calendar-gregorian-from-absolute
10335 (calendar-absolute-from-iso
10336 (list iso-week day year))))
10337 ; FIXME: Should we also push ISO weeks into the future?
10338 ; (when (and org-read-date-prefer-future
10339 ; (not iso-year)
10340 ; (< (calendar-absolute-from-gregorian iso-date)
10341 ; (time-to-days (current-time))))
10342 ; (setq year (1+ year)
10343 ; iso-date (calendar-gregorian-from-absolute
10344 ; (calendar-absolute-from-iso
10345 ; (list iso-week day year)))))
10346 (setq month (car iso-date)
10347 year (nth 2 iso-date)
10348 day (nth 1 iso-date)))
10349 (deltan
10350 (unless deltadef
10351 (let ((now (decode-time (current-time))))
10352 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10353 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10354 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10355 ((equal deltaw "m") (setq month (+ month deltan)))
10356 ((equal deltaw "y") (setq year (+ year deltan)))))
10357 ((and wday (not (nth 3 tl)))
10358 ;; Weekday was given, but no day, so pick that day in the week
10359 ;; on or after the derived date.
10360 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10361 (unless (equal wday wday1)
10362 (setq day (+ day (% (- wday wday1 -7) 7))))))
10363 (if (and (boundp 'org-time-was-given)
10364 (nth 2 tl))
10365 (setq org-time-was-given t))
10366 (if (< year 100) (setq year (+ 2000 year)))
10367 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10368 (list second minute hour day month year)))
10370 (defvar parse-time-weekdays)
10372 (defun org-read-date-get-relative (s today default)
10373 "Check string S for special relative date string.
10374 TODAY and DEFAULT are internal times, for today and for a default.
10375 Return shift list (N what def-flag)
10376 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10377 N is the number of WHATs to shift.
10378 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10379 the DEFAULT date rather than TODAY."
10380 (when (and
10381 (string-match
10382 (concat
10383 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10384 "\\([0-9]+\\)?"
10385 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10386 "\\([ \t]\\|$\\)") s)
10387 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10388 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10389 (string-to-char (substring (match-string 1 s) -1))
10390 ?+))
10391 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10392 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10393 (what (if (match-end 3) (match-string 3 s) "d"))
10394 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10395 (date (if rel default today))
10396 (wday (nth 6 (decode-time date)))
10397 delta)
10398 (if wday1
10399 (progn
10400 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10401 (if (= dir ?-) (setq delta (- delta 7)))
10402 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10403 (list delta "d" rel))
10404 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10406 (defun org-eval-in-calendar (form &optional keepdate)
10407 "Eval FORM in the calendar window and return to current window.
10408 Also, store the cursor date in variable org-ans2."
10409 (let ((sw (selected-window)))
10410 (select-window (get-buffer-window "*Calendar*"))
10411 (eval form)
10412 (when (and (not keepdate) (calendar-cursor-to-date))
10413 (let* ((date (calendar-cursor-to-date))
10414 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10415 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10416 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10417 (select-window sw)))
10419 ; ;; Update the prompt to show new default date
10420 ; (save-excursion
10421 ; (goto-char (point-min))
10422 ; (when (and org-ans2
10423 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10424 ; (get-text-property (match-end 0) 'field))
10425 ; (let ((inhibit-read-only t))
10426 ; (replace-match (concat "[" org-ans2 "]") t t)
10427 ; (add-text-properties (point-min) (1+ (match-end 0))
10428 ; (text-properties-at (1+ (point-min)))))))))
10430 (defun org-calendar-select ()
10431 "Return to `org-read-date' with the date currently selected.
10432 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10433 (interactive)
10434 (when (calendar-cursor-to-date)
10435 (let* ((date (calendar-cursor-to-date))
10436 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10437 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10438 (if (active-minibuffer-window) (exit-minibuffer))))
10440 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10441 "Insert a date stamp for the date given by the internal TIME.
10442 WITH-HM means, use the stamp format that includes the time of the day.
10443 INACTIVE means use square brackets instead of angular ones, so that the
10444 stamp will not contribute to the agenda.
10445 PRE and POST are optional strings to be inserted before and after the
10446 stamp.
10447 The command returns the inserted time stamp."
10448 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10449 stamp)
10450 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10451 (insert-before-markers (or pre ""))
10452 (insert-before-markers (setq stamp (format-time-string fmt time)))
10453 (when (listp extra)
10454 (setq extra (car extra))
10455 (if (and (stringp extra)
10456 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10457 (setq extra (format "-%02d:%02d"
10458 (string-to-number (match-string 1 extra))
10459 (string-to-number (match-string 2 extra))))
10460 (setq extra nil)))
10461 (when extra
10462 (backward-char 1)
10463 (insert-before-markers extra)
10464 (forward-char 1))
10465 (insert-before-markers (or post ""))
10466 stamp))
10468 (defun org-toggle-time-stamp-overlays ()
10469 "Toggle the use of custom time stamp formats."
10470 (interactive)
10471 (setq org-display-custom-times (not org-display-custom-times))
10472 (unless org-display-custom-times
10473 (let ((p (point-min)) (bmp (buffer-modified-p)))
10474 (while (setq p (next-single-property-change p 'display))
10475 (if (and (get-text-property p 'display)
10476 (eq (get-text-property p 'face) 'org-date))
10477 (remove-text-properties
10478 p (setq p (next-single-property-change p 'display))
10479 '(display t))))
10480 (set-buffer-modified-p bmp)))
10481 (if (featurep 'xemacs)
10482 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10483 (org-restart-font-lock)
10484 (setq org-table-may-need-update t)
10485 (if org-display-custom-times
10486 (message "Time stamps are overlayed with custom format")
10487 (message "Time stamp overlays removed")))
10489 (defun org-display-custom-time (beg end)
10490 "Overlay modified time stamp format over timestamp between BEG and END."
10491 (let* ((ts (buffer-substring beg end))
10492 t1 w1 with-hm tf time str w2 (off 0))
10493 (save-match-data
10494 (setq t1 (org-parse-time-string ts t))
10495 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10496 (setq off (- (match-end 0) (match-beginning 0)))))
10497 (setq end (- end off))
10498 (setq w1 (- end beg)
10499 with-hm (and (nth 1 t1) (nth 2 t1))
10500 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10501 time (org-fix-decoded-time t1)
10502 str (org-add-props
10503 (format-time-string
10504 (substring tf 1 -1) (apply 'encode-time time))
10505 nil 'mouse-face 'highlight)
10506 w2 (length str))
10507 (if (not (= w2 w1))
10508 (add-text-properties (1+ beg) (+ 2 beg)
10509 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10510 (if (featurep 'xemacs)
10511 (progn
10512 (put-text-property beg end 'invisible t)
10513 (put-text-property beg end 'end-glyph (make-glyph str)))
10514 (put-text-property beg end 'display str))))
10516 (defun org-translate-time (string)
10517 "Translate all timestamps in STRING to custom format.
10518 But do this only if the variable `org-display-custom-times' is set."
10519 (when org-display-custom-times
10520 (save-match-data
10521 (let* ((start 0)
10522 (re org-ts-regexp-both)
10523 t1 with-hm inactive tf time str beg end)
10524 (while (setq start (string-match re string start))
10525 (setq beg (match-beginning 0)
10526 end (match-end 0)
10527 t1 (save-match-data
10528 (org-parse-time-string (substring string beg end) t))
10529 with-hm (and (nth 1 t1) (nth 2 t1))
10530 inactive (equal (substring string beg (1+ beg)) "[")
10531 tf (funcall (if with-hm 'cdr 'car)
10532 org-time-stamp-custom-formats)
10533 time (org-fix-decoded-time t1)
10534 str (format-time-string
10535 (concat
10536 (if inactive "[" "<") (substring tf 1 -1)
10537 (if inactive "]" ">"))
10538 (apply 'encode-time time))
10539 string (replace-match str t t string)
10540 start (+ start (length str)))))))
10541 string)
10543 (defun org-fix-decoded-time (time)
10544 "Set 0 instead of nil for the first 6 elements of time.
10545 Don't touch the rest."
10546 (let ((n 0))
10547 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10549 (defun org-days-to-time (timestamp-string)
10550 "Difference between TIMESTAMP-STRING and now in days."
10551 (- (time-to-days (org-time-string-to-time timestamp-string))
10552 (time-to-days (current-time))))
10554 (defun org-deadline-close (timestamp-string &optional ndays)
10555 "Is the time in TIMESTAMP-STRING close to the current date?"
10556 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10557 (and (< (org-days-to-time timestamp-string) ndays)
10558 (not (org-entry-is-done-p))))
10560 (defun org-get-wdays (ts)
10561 "Get the deadline lead time appropriate for timestring TS."
10562 (cond
10563 ((<= org-deadline-warning-days 0)
10564 ;; 0 or negative, enforce this value no matter what
10565 (- org-deadline-warning-days))
10566 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10567 ;; lead time is specified.
10568 (floor (* (string-to-number (match-string 1 ts))
10569 (cdr (assoc (match-string 2 ts)
10570 '(("d" . 1) ("w" . 7)
10571 ("m" . 30.4) ("y" . 365.25)))))))
10572 ;; go for the default.
10573 (t org-deadline-warning-days)))
10575 (defun org-calendar-select-mouse (ev)
10576 "Return to `org-read-date' with the date currently selected.
10577 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10578 (interactive "e")
10579 (mouse-set-point ev)
10580 (when (calendar-cursor-to-date)
10581 (let* ((date (calendar-cursor-to-date))
10582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10583 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10584 (if (active-minibuffer-window) (exit-minibuffer))))
10586 (defun org-check-deadlines (ndays)
10587 "Check if there are any deadlines due or past due.
10588 A deadline is considered due if it happens within `org-deadline-warning-days'
10589 days from today's date. If the deadline appears in an entry marked DONE,
10590 it is not shown. The prefix arg NDAYS can be used to test that many
10591 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10592 (interactive "P")
10593 (let* ((org-warn-days
10594 (cond
10595 ((equal ndays '(4)) 100000)
10596 (ndays (prefix-numeric-value ndays))
10597 (t (abs org-deadline-warning-days))))
10598 (case-fold-search nil)
10599 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10600 (callback
10601 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10603 (message "%d deadlines past-due or due within %d days"
10604 (org-occur regexp nil callback)
10605 org-warn-days)))
10607 (defun org-check-before-date (date)
10608 "Check if there are deadlines or scheduled entries before DATE."
10609 (interactive (list (org-read-date)))
10610 (let ((case-fold-search nil)
10611 (regexp (concat "\\<\\(" org-deadline-string
10612 "\\|" org-scheduled-string
10613 "\\) *<\\([^>]+\\)>"))
10614 (callback
10615 (lambda () (time-less-p
10616 (org-time-string-to-time (match-string 2))
10617 (org-time-string-to-time date)))))
10618 (message "%d entries before %s"
10619 (org-occur regexp nil callback) date)))
10621 (defun org-evaluate-time-range (&optional to-buffer)
10622 "Evaluate a time range by computing the difference between start and end.
10623 Normally the result is just printed in the echo area, but with prefix arg
10624 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10625 If the time range is actually in a table, the result is inserted into the
10626 next column.
10627 For time difference computation, a year is assumed to be exactly 365
10628 days in order to avoid rounding problems."
10629 (interactive "P")
10631 (org-clock-update-time-maybe)
10632 (save-excursion
10633 (unless (org-at-date-range-p t)
10634 (goto-char (point-at-bol))
10635 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10636 (if (not (org-at-date-range-p t))
10637 (error "Not at a time-stamp range, and none found in current line")))
10638 (let* ((ts1 (match-string 1))
10639 (ts2 (match-string 2))
10640 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10641 (match-end (match-end 0))
10642 (time1 (org-time-string-to-time ts1))
10643 (time2 (org-time-string-to-time ts2))
10644 (t1 (time-to-seconds time1))
10645 (t2 (time-to-seconds time2))
10646 (diff (abs (- t2 t1)))
10647 (negative (< (- t2 t1) 0))
10648 ;; (ys (floor (* 365 24 60 60)))
10649 (ds (* 24 60 60))
10650 (hs (* 60 60))
10651 (fy "%dy %dd %02d:%02d")
10652 (fy1 "%dy %dd")
10653 (fd "%dd %02d:%02d")
10654 (fd1 "%dd")
10655 (fh "%02d:%02d")
10656 y d h m align)
10657 (if havetime
10658 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10660 d (floor (/ diff ds)) diff (mod diff ds)
10661 h (floor (/ diff hs)) diff (mod diff hs)
10662 m (floor (/ diff 60)))
10663 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10665 d (floor (+ (/ diff ds) 0.5))
10666 h 0 m 0))
10667 (if (not to-buffer)
10668 (message "%s" (org-make-tdiff-string y d h m))
10669 (if (org-at-table-p)
10670 (progn
10671 (goto-char match-end)
10672 (setq align t)
10673 (and (looking-at " *|") (goto-char (match-end 0))))
10674 (goto-char match-end))
10675 (if (looking-at
10676 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10677 (replace-match ""))
10678 (if negative (insert " -"))
10679 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10680 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10681 (insert " " (format fh h m))))
10682 (if align (org-table-align))
10683 (message "Time difference inserted")))))
10685 (defun org-make-tdiff-string (y d h m)
10686 (let ((fmt "")
10687 (l nil))
10688 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10689 l (push y l)))
10690 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10691 l (push d l)))
10692 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10693 l (push h l)))
10694 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10695 l (push m l)))
10696 (apply 'format fmt (nreverse l))))
10698 (defun org-time-string-to-time (s)
10699 (apply 'encode-time (org-parse-time-string s)))
10701 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10702 "Convert a time stamp to an absolute day number.
10703 If there is a specifyer for a cyclic time stamp, get the closest date to
10704 DAYNR.
10705 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10706 (cond
10707 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10708 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10709 daynr
10710 (+ daynr 1000)))
10711 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10712 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10713 (time-to-days (current-time))) (match-string 0 s)
10714 prefer show-all))
10715 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10717 (defun org-days-to-iso-week (days)
10718 "Return the iso week number."
10719 (require 'cal-iso)
10720 (car (calendar-iso-from-absolute days)))
10722 (defun org-small-year-to-year (year)
10723 "Convert 2-digit years into 4-digit years.
10724 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10725 The year 2000 cannot be abbreviated. Any year lager than 99
10726 is retrned unchanged."
10727 (if (< year 38)
10728 (setq year (+ 2000 year))
10729 (if (< year 100)
10730 (setq year (+ 1900 year))))
10731 year)
10733 (defun org-time-from-absolute (d)
10734 "Return the time corresponding to date D.
10735 D may be an absolute day number, or a calendar-type list (month day year)."
10736 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10737 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10739 (defun org-calendar-holiday ()
10740 "List of holidays, for Diary display in Org-mode."
10741 (require 'holidays)
10742 (let ((hl (funcall
10743 (if (fboundp 'calendar-check-holidays)
10744 'calendar-check-holidays 'check-calendar-holidays) date)))
10745 (if hl (mapconcat 'identity hl "; "))))
10747 (defun org-diary-sexp-entry (sexp entry date)
10748 "Process a SEXP diary ENTRY for DATE."
10749 (require 'diary-lib)
10750 (let ((result (if calendar-debug-sexp
10751 (let ((stack-trace-on-error t))
10752 (eval (car (read-from-string sexp))))
10753 (condition-case nil
10754 (eval (car (read-from-string sexp)))
10755 (error
10756 (beep)
10757 (message "Bad sexp at line %d in %s: %s"
10758 (org-current-line)
10759 (buffer-file-name) sexp)
10760 (sleep-for 2))))))
10761 (cond ((stringp result) result)
10762 ((and (consp result)
10763 (stringp (cdr result))) (cdr result))
10764 (result entry)
10765 (t nil))))
10767 (defun org-diary-to-ical-string (frombuf)
10768 "Get iCalendar entries from diary entries in buffer FROMBUF.
10769 This uses the icalendar.el library."
10770 (let* ((tmpdir (if (featurep 'xemacs)
10771 (temp-directory)
10772 temporary-file-directory))
10773 (tmpfile (make-temp-name
10774 (expand-file-name "orgics" tmpdir)))
10775 buf rtn b e)
10776 (save-excursion
10777 (set-buffer frombuf)
10778 (icalendar-export-region (point-min) (point-max) tmpfile)
10779 (setq buf (find-buffer-visiting tmpfile))
10780 (set-buffer buf)
10781 (goto-char (point-min))
10782 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10783 (setq b (match-beginning 0)))
10784 (goto-char (point-max))
10785 (if (re-search-backward "^END:VEVENT" nil t)
10786 (setq e (match-end 0)))
10787 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10788 (kill-buffer buf)
10789 (kill-buffer frombuf)
10790 (delete-file tmpfile)
10791 rtn))
10793 (defun org-closest-date (start current change prefer show-all)
10794 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10795 When PREFER is `past' return a date that is either CURRENT or past.
10796 When PREFER is `future', return a date that is either CURRENT or future.
10797 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10798 ;; Make the proper lists from the dates
10799 (catch 'exit
10800 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10801 dn dw sday cday n1 n2
10802 d m y y1 y2 date1 date2 nmonths nm ny m2)
10804 (setq start (org-date-to-gregorian start)
10805 current (org-date-to-gregorian
10806 (if show-all
10807 current
10808 (time-to-days (current-time))))
10809 sday (calendar-absolute-from-gregorian start)
10810 cday (calendar-absolute-from-gregorian current))
10812 (if (<= cday sday) (throw 'exit sday))
10814 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10815 (setq dn (string-to-number (match-string 1 change))
10816 dw (cdr (assoc (match-string 2 change) a1)))
10817 (error "Invalid change specifyer: %s" change))
10818 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10819 (cond
10820 ((eq dw 'day)
10821 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10822 n2 (+ n1 dn)))
10823 ((eq dw 'year)
10824 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10825 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10826 (setq date1 (list m d y1)
10827 n1 (calendar-absolute-from-gregorian date1)
10828 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10829 n2 (calendar-absolute-from-gregorian date2)))
10830 ((eq dw 'month)
10831 ;; approx number of month between the tow dates
10832 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10833 ;; How often does dn fit in there?
10834 (setq d (nth 1 start) m (car start) y (nth 2 start)
10835 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10836 m (+ m nm)
10837 ny (floor (/ m 12))
10838 y (+ y ny)
10839 m (- m (* ny 12)))
10840 (while (> m 12) (setq m (- m 12) y (1+ y)))
10841 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10842 (setq m2 (+ m dn) y2 y)
10843 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10844 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10845 (while (< n2 cday)
10846 (setq n1 n2 m m2 y y2)
10847 (setq m2 (+ m dn) y2 y)
10848 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10849 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10851 (if show-all
10852 (cond
10853 ((eq prefer 'past) n1)
10854 ((eq prefer 'future) (if (= cday n1) n1 n2))
10855 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10856 (cond
10857 ((eq prefer 'past) n1)
10858 ((eq prefer 'future) (if (= cday n1) n1 n2))
10859 (t (if (= cday n1) n1 n2)))))))
10861 (defun org-date-to-gregorian (date)
10862 "Turn any specification of DATE into a gregorian date for the calendar."
10863 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10864 ((and (listp date) (= (length date) 3)) date)
10865 ((stringp date)
10866 (setq date (org-parse-time-string date))
10867 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10868 ((listp date)
10869 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10871 (defun org-parse-time-string (s &optional nodefault)
10872 "Parse the standard Org-mode time string.
10873 This should be a lot faster than the normal `parse-time-string'.
10874 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10875 hour and minute fields will be nil if not given."
10876 (if (string-match org-ts-regexp0 s)
10877 (list 0
10878 (if (or (match-beginning 8) (not nodefault))
10879 (string-to-number (or (match-string 8 s) "0")))
10880 (if (or (match-beginning 7) (not nodefault))
10881 (string-to-number (or (match-string 7 s) "0")))
10882 (string-to-number (match-string 4 s))
10883 (string-to-number (match-string 3 s))
10884 (string-to-number (match-string 2 s))
10885 nil nil nil)
10886 (make-list 9 0)))
10888 (defun org-timestamp-up (&optional arg)
10889 "Increase the date item at the cursor by one.
10890 If the cursor is on the year, change the year. If it is on the month or
10891 the day, change that.
10892 With prefix ARG, change by that many units."
10893 (interactive "p")
10894 (org-timestamp-change (prefix-numeric-value arg)))
10896 (defun org-timestamp-down (&optional arg)
10897 "Decrease the date item at the cursor by one.
10898 If the cursor is on the year, change the year. If it is on the month or
10899 the day, change that.
10900 With prefix ARG, change by that many units."
10901 (interactive "p")
10902 (org-timestamp-change (- (prefix-numeric-value arg))))
10904 (defun org-timestamp-up-day (&optional arg)
10905 "Increase the date in the time stamp by one day.
10906 With prefix ARG, change that many days."
10907 (interactive "p")
10908 (if (and (not (org-at-timestamp-p t))
10909 (org-on-heading-p))
10910 (org-todo 'up)
10911 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10913 (defun org-timestamp-down-day (&optional arg)
10914 "Decrease the date in the time stamp by one day.
10915 With prefix ARG, change that many days."
10916 (interactive "p")
10917 (if (and (not (org-at-timestamp-p t))
10918 (org-on-heading-p))
10919 (org-todo 'down)
10920 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10922 (defun org-at-timestamp-p (&optional inactive-ok)
10923 "Determine if the cursor is in or at a timestamp."
10924 (interactive)
10925 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10926 (pos (point))
10927 (ans (or (looking-at tsr)
10928 (save-excursion
10929 (skip-chars-backward "^[<\n\r\t")
10930 (if (> (point) (point-min)) (backward-char 1))
10931 (and (looking-at tsr)
10932 (> (- (match-end 0) pos) -1))))))
10933 (and ans
10934 (boundp 'org-ts-what)
10935 (setq org-ts-what
10936 (cond
10937 ((= pos (match-beginning 0)) 'bracket)
10938 ((= pos (1- (match-end 0))) 'bracket)
10939 ((org-pos-in-match-range pos 2) 'year)
10940 ((org-pos-in-match-range pos 3) 'month)
10941 ((org-pos-in-match-range pos 7) 'hour)
10942 ((org-pos-in-match-range pos 8) 'minute)
10943 ((or (org-pos-in-match-range pos 4)
10944 (org-pos-in-match-range pos 5)) 'day)
10945 ((and (> pos (or (match-end 8) (match-end 5)))
10946 (< pos (match-end 0)))
10947 (- pos (or (match-end 8) (match-end 5))))
10948 (t 'day))))
10949 ans))
10951 (defun org-toggle-timestamp-type ()
10952 "Toggle the type (<active> or [inactive]) of a time stamp."
10953 (interactive)
10954 (when (org-at-timestamp-p t)
10955 (save-excursion
10956 (goto-char (match-beginning 0))
10957 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10958 (goto-char (1- (match-end 0)))
10959 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10960 (message "Timestamp is now %sactive"
10961 (if (equal (char-before) ?>) "in" ""))))
10963 (defun org-timestamp-change (n &optional what)
10964 "Change the date in the time stamp at point.
10965 The date will be changed by N times WHAT. WHAT can be `day', `month',
10966 `year', `minute', `second'. If WHAT is not given, the cursor position
10967 in the timestamp determines what will be changed."
10968 (let ((pos (point))
10969 with-hm inactive
10970 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10971 org-ts-what
10972 extra rem
10973 ts time time0)
10974 (if (not (org-at-timestamp-p t))
10975 (error "Not at a timestamp"))
10976 (if (and (not what) (eq org-ts-what 'bracket))
10977 (org-toggle-timestamp-type)
10978 (if (and (not what) (not (eq org-ts-what 'day))
10979 org-display-custom-times
10980 (get-text-property (point) 'display)
10981 (not (get-text-property (1- (point)) 'display)))
10982 (setq org-ts-what 'day))
10983 (setq org-ts-what (or what org-ts-what)
10984 inactive (= (char-after (match-beginning 0)) ?\[)
10985 ts (match-string 0))
10986 (replace-match "")
10987 (if (string-match
10988 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10990 (setq extra (match-string 1 ts)))
10991 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10992 (setq with-hm t))
10993 (setq time0 (org-parse-time-string ts))
10994 (when (and (eq org-ts-what 'minute)
10995 (eq current-prefix-arg nil))
10996 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10997 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10998 (setcar (cdr time0) (+ (nth 1 time0)
10999 (if (> n 0) (- rem) (- dm rem))))))
11000 (setq time
11001 (encode-time (or (car time0) 0)
11002 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11003 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11004 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11005 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11006 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11007 (nthcdr 6 time0)))
11008 (when (integerp org-ts-what)
11009 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11010 (if (eq what 'calendar)
11011 (let ((cal-date (org-get-date-from-calendar)))
11012 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11013 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11014 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11015 (setcar time0 (or (car time0) 0))
11016 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11017 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11018 (setq time (apply 'encode-time time0))))
11019 (setq org-last-changed-timestamp
11020 (org-insert-time-stamp time with-hm inactive nil nil extra))
11021 (org-clock-update-time-maybe)
11022 (goto-char pos)
11023 ;; Try to recenter the calendar window, if any
11024 (if (and org-calendar-follow-timestamp-change
11025 (get-buffer-window "*Calendar*" t)
11026 (memq org-ts-what '(day month year)))
11027 (org-recenter-calendar (time-to-days time))))))
11029 (defun org-modify-ts-extra (s pos n dm)
11030 "Change the different parts of the lead-time and repeat fields in timestamp."
11031 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11032 ng h m new rem)
11033 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11034 (cond
11035 ((or (org-pos-in-match-range pos 2)
11036 (org-pos-in-match-range pos 3))
11037 (setq m (string-to-number (match-string 3 s))
11038 h (string-to-number (match-string 2 s)))
11039 (if (org-pos-in-match-range pos 2)
11040 (setq h (+ h n))
11041 (setq n (* dm (org-no-warnings (signum n))))
11042 (when (not (= 0 (setq rem (% m dm))))
11043 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11044 (setq m (+ m n)))
11045 (if (< m 0) (setq m (+ m 60) h (1- h)))
11046 (if (> m 59) (setq m (- m 60) h (1+ h)))
11047 (setq h (min 24 (max 0 h)))
11048 (setq ng 1 new (format "-%02d:%02d" h m)))
11049 ((org-pos-in-match-range pos 6)
11050 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11051 ((org-pos-in-match-range pos 5)
11052 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11054 ((org-pos-in-match-range pos 9)
11055 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11056 ((org-pos-in-match-range pos 8)
11057 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11059 (when ng
11060 (setq s (concat
11061 (substring s 0 (match-beginning ng))
11063 (substring s (match-end ng))))))
11066 (defun org-recenter-calendar (date)
11067 "If the calendar is visible, recenter it to DATE."
11068 (let* ((win (selected-window))
11069 (cwin (get-buffer-window "*Calendar*" t))
11070 (calendar-move-hook nil))
11071 (when cwin
11072 (select-window cwin)
11073 (calendar-goto-date (if (listp date) date
11074 (calendar-gregorian-from-absolute date)))
11075 (select-window win))))
11077 (defun org-goto-calendar (&optional arg)
11078 "Go to the Emacs calendar at the current date.
11079 If there is a time stamp in the current line, go to that date.
11080 A prefix ARG can be used to force the current date."
11081 (interactive "P")
11082 (let ((tsr org-ts-regexp) diff
11083 (calendar-move-hook nil)
11084 (calendar-view-holidays-initially-flag nil)
11085 (view-calendar-holidays-initially nil)
11086 (calendar-view-diary-initially-flag nil)
11087 (view-diary-entries-initially nil))
11088 (if (or (org-at-timestamp-p)
11089 (save-excursion
11090 (beginning-of-line 1)
11091 (looking-at (concat ".*" tsr))))
11092 (let ((d1 (time-to-days (current-time)))
11093 (d2 (time-to-days
11094 (org-time-string-to-time (match-string 1)))))
11095 (setq diff (- d2 d1))))
11096 (calendar)
11097 (calendar-goto-today)
11098 (if (and diff (not arg)) (calendar-forward-day diff))))
11100 (defun org-get-date-from-calendar ()
11101 "Return a list (month day year) of date at point in calendar."
11102 (with-current-buffer "*Calendar*"
11103 (save-match-data
11104 (calendar-cursor-to-date))))
11106 (defun org-date-from-calendar ()
11107 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11108 If there is already a time stamp at the cursor position, update it."
11109 (interactive)
11110 (if (org-at-timestamp-p t)
11111 (org-timestamp-change 0 'calendar)
11112 (let ((cal-date (org-get-date-from-calendar)))
11113 (org-insert-time-stamp
11114 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11116 (defun org-minutes-to-hh:mm-string (m)
11117 "Compute H:MM from a number of minutes."
11118 (let ((h (/ m 60)))
11119 (setq m (- m (* 60 h)))
11120 (format "%d:%02d" h m)))
11122 (defun org-hh:mm-string-to-minutes (s)
11123 "Convert a string H:MM to a number of minutes."
11124 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11125 (+ (* (string-to-number (match-string 1 s)) 60)
11126 (string-to-number (match-string 2 s)))
11129 ;;;; Agenda files
11131 ;;;###autoload
11132 (defun org-iswitchb (&optional arg)
11133 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11134 With a prefix argument, restrict available to files.
11135 With two prefix arguments, restrict available buffers to agenda files.
11137 Due to some yet unresolved reason, global function
11138 `iswitchb-mode' needs to be active for this function to work."
11139 (interactive "P")
11140 (require 'iswitchb)
11141 (let ((enabled iswitchb-mode) blist)
11142 (or enabled (iswitchb-mode 1))
11143 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11144 ((equal arg '(16)) (org-buffer-list 'agenda))
11145 (t (org-buffer-list))))
11146 (unwind-protect
11147 (let ((iswitchb-make-buflist-hook
11148 (lambda ()
11149 (setq iswitchb-temp-buflist
11150 (mapcar 'buffer-name blist)))))
11151 (switch-to-buffer
11152 (iswitchb-read-buffer
11153 "Switch-to: " nil t))
11154 (or enabled (iswitchb-mode -1))))))
11156 (defun org-buffer-list (&optional predicate tmp)
11157 "Return a list of Org buffers.
11158 PREDICATE can be either 'export, 'files or 'agenda.
11160 'export restrict the list to Export buffers.
11161 'files restrict the list to buffers visiting Org files.
11162 'agenda restrict the list to buffers visiting agenda files.
11164 If TMP is non-nil, don't include temporary buffers."
11165 (let (filter blist)
11166 (setq filter
11167 (cond ((eq predicate 'files) "\.org$")
11168 ((eq predicate 'export) "\*Org .*Export")
11169 (t "\*Org \\|\.org$")))
11170 (setq blist
11171 (mapcar
11172 (lambda(b)
11173 (let ((bname (buffer-name b))
11174 (bfile (buffer-file-name b)))
11175 (if (and (string-match filter bname)
11176 (if (eq predicate 'agenda)
11177 (member bfile
11178 (mapcar (lambda(f) (file-truename f))
11179 org-agenda-files)) t)
11180 (if tmp (not (string-match "tmp" bname)) t)) b)))
11181 (buffer-list)))
11182 (delete nil blist)))
11184 (defun org-agenda-files (&optional unrestricted ext)
11185 "Get the list of agenda files.
11186 Optional UNRESTRICTED means return the full list even if a restriction
11187 is currently in place.
11188 When EXT is non-nil, try to add all files that are created by adding EXT
11189 to the file nemes. Basically, this is a way to add the archive files
11190 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11191 a string, \"_archive\" will be used."
11192 (let ((files
11193 (cond
11194 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11195 ((stringp org-agenda-files) (org-read-agenda-file-list))
11196 ((listp org-agenda-files) org-agenda-files)
11197 (t (error "Invalid value of `org-agenda-files'")))))
11198 (setq files (apply 'append
11199 (mapcar (lambda (f)
11200 (if (file-directory-p f)
11201 (directory-files
11202 f t org-agenda-file-regexp)
11203 (list f)))
11204 files)))
11205 (when org-agenda-skip-unavailable-files
11206 (setq files (delq nil
11207 (mapcar (function
11208 (lambda (file)
11209 (and (file-readable-p file) file)))
11210 files))))
11211 (when ext
11212 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11213 ext "_archive"))
11214 (setq files (apply 'append
11215 (mapcar
11216 (lambda (f)
11217 (if (file-exists-p (concat f ext))
11218 (list f (concat f ext))
11219 (list f)))
11220 files))))
11221 files))
11223 (defun org-edit-agenda-file-list ()
11224 "Edit the list of agenda files.
11225 Depending on setup, this either uses customize to edit the variable
11226 `org-agenda-files', or it visits the file that is holding the list. In the
11227 latter case, the buffer is set up in a way that saving it automatically kills
11228 the buffer and restores the previous window configuration."
11229 (interactive)
11230 (if (stringp org-agenda-files)
11231 (let ((cw (current-window-configuration)))
11232 (find-file org-agenda-files)
11233 (org-set-local 'org-window-configuration cw)
11234 (org-add-hook 'after-save-hook
11235 (lambda ()
11236 (set-window-configuration
11237 (prog1 org-window-configuration
11238 (kill-buffer (current-buffer))))
11239 (org-install-agenda-files-menu)
11240 (message "New agenda file list installed"))
11241 nil 'local)
11242 (message "%s" (substitute-command-keys
11243 "Edit list and finish with \\[save-buffer]")))
11244 (customize-variable 'org-agenda-files)))
11246 (defun org-store-new-agenda-file-list (list)
11247 "Set new value for the agenda file list and save it correcly."
11248 (if (stringp org-agenda-files)
11249 (let ((f org-agenda-files) b)
11250 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11251 (with-temp-file f
11252 (insert (mapconcat 'identity list "\n") "\n")))
11253 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11254 (setq org-agenda-files list)
11255 (customize-save-variable 'org-agenda-files org-agenda-files))))
11257 (defun org-read-agenda-file-list ()
11258 "Read the list of agenda files from a file."
11259 (when (file-directory-p org-agenda-files)
11260 (error "`org-agenda-files' cannot be a single directory"))
11261 (when (stringp org-agenda-files)
11262 (with-temp-buffer
11263 (insert-file-contents org-agenda-files)
11264 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11267 ;;;###autoload
11268 (defun org-cycle-agenda-files ()
11269 "Cycle through the files in `org-agenda-files'.
11270 If the current buffer visits an agenda file, find the next one in the list.
11271 If the current buffer does not, find the first agenda file."
11272 (interactive)
11273 (let* ((fs (org-agenda-files t))
11274 (files (append fs (list (car fs))))
11275 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11276 file)
11277 (unless files (error "No agenda files"))
11278 (catch 'exit
11279 (while (setq file (pop files))
11280 (if (equal (file-truename file) tcf)
11281 (when (car files)
11282 (find-file (car files))
11283 (throw 'exit t))))
11284 (find-file (car fs)))
11285 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11287 (defun org-agenda-file-to-front (&optional to-end)
11288 "Move/add the current file to the top of the agenda file list.
11289 If the file is not present in the list, it is added to the front. If it is
11290 present, it is moved there. With optional argument TO-END, add/move to the
11291 end of the list."
11292 (interactive "P")
11293 (let ((org-agenda-skip-unavailable-files nil)
11294 (file-alist (mapcar (lambda (x)
11295 (cons (file-truename x) x))
11296 (org-agenda-files t)))
11297 (ctf (file-truename buffer-file-name))
11298 x had)
11299 (setq x (assoc ctf file-alist) had x)
11301 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11302 (if to-end
11303 (setq file-alist (append (delq x file-alist) (list x)))
11304 (setq file-alist (cons x (delq x file-alist))))
11305 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11306 (org-install-agenda-files-menu)
11307 (message "File %s to %s of agenda file list"
11308 (if had "moved" "added") (if to-end "end" "front"))))
11310 (defun org-remove-file (&optional file)
11311 "Remove current file from the list of files in variable `org-agenda-files'.
11312 These are the files which are being checked for agenda entries.
11313 Optional argument FILE means, use this file instead of the current."
11314 (interactive)
11315 (let* ((org-agenda-skip-unavailable-files nil)
11316 (file (or file buffer-file-name))
11317 (true-file (file-truename file))
11318 (afile (abbreviate-file-name file))
11319 (files (delq nil (mapcar
11320 (lambda (x)
11321 (if (equal true-file
11322 (file-truename x))
11323 nil x))
11324 (org-agenda-files t)))))
11325 (if (not (= (length files) (length (org-agenda-files t))))
11326 (progn
11327 (org-store-new-agenda-file-list files)
11328 (org-install-agenda-files-menu)
11329 (message "Removed file: %s" afile))
11330 (message "File was not in list: %s (not removed)" afile))))
11332 (defun org-file-menu-entry (file)
11333 (vector file (list 'find-file file) t))
11335 (defun org-check-agenda-file (file)
11336 "Make sure FILE exists. If not, ask user what to do."
11337 (when (not (file-exists-p file))
11338 (message "non-existent file %s. [R]emove from list or [A]bort?"
11339 (abbreviate-file-name file))
11340 (let ((r (downcase (read-char-exclusive))))
11341 (cond
11342 ((equal r ?r)
11343 (org-remove-file file)
11344 (throw 'nextfile t))
11345 (t (error "Abort"))))))
11347 (defun org-get-agenda-file-buffer (file)
11348 "Get a buffer visiting FILE. If the buffer needs to be created, add
11349 it to the list of buffers which might be released later."
11350 (let ((buf (org-find-base-buffer-visiting file)))
11351 (if buf
11352 buf ; just return it
11353 ;; Make a new buffer and remember it
11354 (setq buf (find-file-noselect file))
11355 (if buf (push buf org-agenda-new-buffers))
11356 buf)))
11358 (defun org-release-buffers (blist)
11359 "Release all buffers in list, asking the user for confirmation when needed.
11360 When a buffer is unmodified, it is just killed. When modified, it is saved
11361 \(if the user agrees) and then killed."
11362 (let (buf file)
11363 (while (setq buf (pop blist))
11364 (setq file (buffer-file-name buf))
11365 (when (and (buffer-modified-p buf)
11366 file
11367 (y-or-n-p (format "Save file %s? " file)))
11368 (with-current-buffer buf (save-buffer)))
11369 (kill-buffer buf))))
11371 (defun org-prepare-agenda-buffers (files)
11372 "Create buffers for all agenda files, protect archived trees and comments."
11373 (interactive)
11374 (let ((pa '(:org-archived t))
11375 (pc '(:org-comment t))
11376 (pall '(:org-archived t :org-comment t))
11377 (inhibit-read-only t)
11378 (rea (concat ":" org-archive-tag ":"))
11379 bmp file re)
11380 (save-excursion
11381 (save-restriction
11382 (while (setq file (pop files))
11383 (if (bufferp file)
11384 (set-buffer file)
11385 (org-check-agenda-file file)
11386 (set-buffer (org-get-agenda-file-buffer file)))
11387 (widen)
11388 (setq bmp (buffer-modified-p))
11389 (org-refresh-category-properties)
11390 (setq org-todo-keywords-for-agenda
11391 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11392 (setq org-done-keywords-for-agenda
11393 (append org-done-keywords-for-agenda org-done-keywords))
11394 (save-excursion
11395 (remove-text-properties (point-min) (point-max) pall)
11396 (when org-agenda-skip-archived-trees
11397 (goto-char (point-min))
11398 (while (re-search-forward rea nil t)
11399 (if (org-on-heading-p t)
11400 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11401 (goto-char (point-min))
11402 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11403 (while (re-search-forward re nil t)
11404 (add-text-properties
11405 (match-beginning 0) (org-end-of-subtree t) pc)))
11406 (set-buffer-modified-p bmp))))))
11408 ;;;; Embedded LaTeX
11410 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11411 "Keymap for the minor `org-cdlatex-mode'.")
11413 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11414 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11415 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11416 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11417 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11419 (defvar org-cdlatex-texmathp-advice-is-done nil
11420 "Flag remembering if we have applied the advice to texmathp already.")
11422 (define-minor-mode org-cdlatex-mode
11423 "Toggle the minor `org-cdlatex-mode'.
11424 This mode supports entering LaTeX environment and math in LaTeX fragments
11425 in Org-mode.
11426 \\{org-cdlatex-mode-map}"
11427 nil " OCDL" nil
11428 (when org-cdlatex-mode (require 'cdlatex))
11429 (unless org-cdlatex-texmathp-advice-is-done
11430 (setq org-cdlatex-texmathp-advice-is-done t)
11431 (defadvice texmathp (around org-math-always-on activate)
11432 "Always return t in org-mode buffers.
11433 This is because we want to insert math symbols without dollars even outside
11434 the LaTeX math segments. If Orgmode thinks that point is actually inside
11435 en embedded LaTeX fragement, let texmathp do its job.
11436 \\[org-cdlatex-mode-map]"
11437 (interactive)
11438 (let (p)
11439 (cond
11440 ((not (org-mode-p)) ad-do-it)
11441 ((eq this-command 'cdlatex-math-symbol)
11442 (setq ad-return-value t
11443 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11445 (let ((p (org-inside-LaTeX-fragment-p)))
11446 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11447 (setq ad-return-value t
11448 texmathp-why '("Org-mode embedded math" . 0))
11449 (if p ad-do-it)))))))))
11451 (defun turn-on-org-cdlatex ()
11452 "Unconditionally turn on `org-cdlatex-mode'."
11453 (org-cdlatex-mode 1))
11455 (defun org-inside-LaTeX-fragment-p ()
11456 "Test if point is inside a LaTeX fragment.
11457 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11458 sequence appearing also before point.
11459 Even though the matchers for math are configurable, this function assumes
11460 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11461 delimiters are skipped when they have been removed by customization.
11462 The return value is nil, or a cons cell with the delimiter and
11463 and the position of this delimiter.
11465 This function does a reasonably good job, but can locally be fooled by
11466 for example currency specifications. For example it will assume being in
11467 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11468 fragments that are properly closed, but during editing, we have to live
11469 with the uncertainty caused by missing closing delimiters. This function
11470 looks only before point, not after."
11471 (catch 'exit
11472 (let ((pos (point))
11473 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11474 (lim (progn
11475 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11476 (point)))
11477 dd-on str (start 0) m re)
11478 (goto-char pos)
11479 (when dodollar
11480 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11481 re (nth 1 (assoc "$" org-latex-regexps)))
11482 (while (string-match re str start)
11483 (cond
11484 ((= (match-end 0) (length str))
11485 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11486 ((= (match-end 0) (- (length str) 5))
11487 (throw 'exit nil))
11488 (t (setq start (match-end 0))))))
11489 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11490 (goto-char pos)
11491 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11492 (and (match-beginning 2) (throw 'exit nil))
11493 ;; count $$
11494 (while (re-search-backward "\\$\\$" lim t)
11495 (setq dd-on (not dd-on)))
11496 (goto-char pos)
11497 (if dd-on (cons "$$" m))))))
11500 (defun org-try-cdlatex-tab ()
11501 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11502 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11503 - inside a LaTeX fragment, or
11504 - after the first word in a line, where an abbreviation expansion could
11505 insert a LaTeX environment."
11506 (when org-cdlatex-mode
11507 (cond
11508 ((save-excursion
11509 (skip-chars-backward "a-zA-Z0-9*")
11510 (skip-chars-backward " \t")
11511 (bolp))
11512 (cdlatex-tab) t)
11513 ((org-inside-LaTeX-fragment-p)
11514 (cdlatex-tab) t)
11515 (t nil))))
11517 (defun org-cdlatex-underscore-caret (&optional arg)
11518 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11519 Revert to the normal definition outside of these fragments."
11520 (interactive "P")
11521 (if (org-inside-LaTeX-fragment-p)
11522 (call-interactively 'cdlatex-sub-superscript)
11523 (let (org-cdlatex-mode)
11524 (call-interactively (key-binding (vector last-input-event))))))
11526 (defun org-cdlatex-math-modify (&optional arg)
11527 "Execute `cdlatex-math-modify' in LaTeX fragments.
11528 Revert to the normal definition outside of these fragments."
11529 (interactive "P")
11530 (if (org-inside-LaTeX-fragment-p)
11531 (call-interactively 'cdlatex-math-modify)
11532 (let (org-cdlatex-mode)
11533 (call-interactively (key-binding (vector last-input-event))))))
11535 (defvar org-latex-fragment-image-overlays nil
11536 "List of overlays carrying the images of latex fragments.")
11537 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11539 (defun org-remove-latex-fragment-image-overlays ()
11540 "Remove all overlays with LaTeX fragment images in current buffer."
11541 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11542 (setq org-latex-fragment-image-overlays nil))
11544 (defun org-preview-latex-fragment (&optional subtree)
11545 "Preview the LaTeX fragment at point, or all locally or globally.
11546 If the cursor is in a LaTeX fragment, create the image and overlay
11547 it over the source code. If there is no fragment at point, display
11548 all fragments in the current text, from one headline to the next. With
11549 prefix SUBTREE, display all fragments in the current subtree. With a
11550 double prefix `C-u C-u', or when the cursor is before the first headline,
11551 display all fragments in the buffer.
11552 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11553 (interactive "P")
11554 (org-remove-latex-fragment-image-overlays)
11555 (save-excursion
11556 (save-restriction
11557 (let (beg end at msg)
11558 (cond
11559 ((or (equal subtree '(16))
11560 (not (save-excursion
11561 (re-search-backward (concat "^" outline-regexp) nil t))))
11562 (setq beg (point-min) end (point-max)
11563 msg "Creating images for buffer...%s"))
11564 ((equal subtree '(4))
11565 (org-back-to-heading)
11566 (setq beg (point) end (org-end-of-subtree t)
11567 msg "Creating images for subtree...%s"))
11569 (if (setq at (org-inside-LaTeX-fragment-p))
11570 (goto-char (max (point-min) (- (cdr at) 2)))
11571 (org-back-to-heading))
11572 (setq beg (point) end (progn (outline-next-heading) (point))
11573 msg (if at "Creating image...%s"
11574 "Creating images for entry...%s"))))
11575 (message msg "")
11576 (narrow-to-region beg end)
11577 (goto-char beg)
11578 (org-format-latex
11579 (concat "ltxpng/" (file-name-sans-extension
11580 (file-name-nondirectory
11581 buffer-file-name)))
11582 default-directory 'overlays msg at 'forbuffer)
11583 (message msg "done. Use `C-c C-c' to remove images.")))))
11585 (defvar org-latex-regexps
11586 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11587 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11588 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11589 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11590 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11591 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11592 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11593 "Regular expressions for matching embedded LaTeX.")
11595 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11596 "Replace LaTeX fragments with links to an image, and produce images."
11597 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11598 (let* ((prefixnodir (file-name-nondirectory prefix))
11599 (absprefix (expand-file-name prefix dir))
11600 (todir (file-name-directory absprefix))
11601 (opt org-format-latex-options)
11602 (matchers (plist-get opt :matchers))
11603 (re-list org-latex-regexps)
11604 (cnt 0) txt link beg end re e checkdir
11605 m n block linkfile movefile ov)
11606 ;; Check if there are old images files with this prefix, and remove them
11607 (when (file-directory-p todir)
11608 (mapc 'delete-file
11609 (directory-files
11610 todir 'full
11611 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11612 ;; Check the different regular expressions
11613 (while (setq e (pop re-list))
11614 (setq m (car e) re (nth 1 e) n (nth 2 e)
11615 block (if (nth 3 e) "\n\n" ""))
11616 (when (member m matchers)
11617 (goto-char (point-min))
11618 (while (re-search-forward re nil t)
11619 (when (or (not at) (equal (cdr at) (match-beginning n)))
11620 (setq txt (match-string n)
11621 beg (match-beginning n) end (match-end n)
11622 cnt (1+ cnt)
11623 linkfile (format "%s_%04d.png" prefix cnt)
11624 movefile (format "%s_%04d.png" absprefix cnt)
11625 link (concat block "[[file:" linkfile "]]" block))
11626 (if msg (message msg cnt))
11627 (goto-char beg)
11628 (unless checkdir ; make sure the directory exists
11629 (setq checkdir t)
11630 (or (file-directory-p todir) (make-directory todir)))
11631 (org-create-formula-image
11632 txt movefile opt forbuffer)
11633 (if overlays
11634 (progn
11635 (setq ov (org-make-overlay beg end))
11636 (if (featurep 'xemacs)
11637 (progn
11638 (org-overlay-put ov 'invisible t)
11639 (org-overlay-put
11640 ov 'end-glyph
11641 (make-glyph (vector 'png :file movefile))))
11642 (org-overlay-put
11643 ov 'display
11644 (list 'image :type 'png :file movefile :ascent 'center)))
11645 (push ov org-latex-fragment-image-overlays)
11646 (goto-char end))
11647 (delete-region beg end)
11648 (insert link))))))))
11650 ;; This function borrows from Ganesh Swami's latex2png.el
11651 (defun org-create-formula-image (string tofile options buffer)
11652 (let* ((tmpdir (if (featurep 'xemacs)
11653 (temp-directory)
11654 temporary-file-directory))
11655 (texfilebase (make-temp-name
11656 (expand-file-name "orgtex" tmpdir)))
11657 (texfile (concat texfilebase ".tex"))
11658 (dvifile (concat texfilebase ".dvi"))
11659 (pngfile (concat texfilebase ".png"))
11660 (fnh (if (featurep 'xemacs)
11661 (font-height (get-face-font 'default))
11662 (face-attribute 'default :height nil)))
11663 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11664 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11665 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11666 "Black"))
11667 (bg (or (plist-get options (if buffer :background :html-background))
11668 "Transparent")))
11669 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11670 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11671 (with-temp-file texfile
11672 (insert org-format-latex-header
11673 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11674 (let ((dir default-directory))
11675 (condition-case nil
11676 (progn
11677 (cd tmpdir)
11678 (call-process "latex" nil nil nil texfile))
11679 (error nil))
11680 (cd dir))
11681 (if (not (file-exists-p dvifile))
11682 (progn (message "Failed to create dvi file from %s" texfile) nil)
11683 (call-process "dvipng" nil nil nil
11684 "-E" "-fg" fg "-bg" bg
11685 "-D" dpi
11686 ;;"-x" scale "-y" scale
11687 "-T" "tight"
11688 "-o" pngfile
11689 dvifile)
11690 (if (not (file-exists-p pngfile))
11691 (progn (message "Failed to create png file from %s" texfile) nil)
11692 ;; Use the requested file name and clean up
11693 (copy-file pngfile tofile 'replace)
11694 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11695 (delete-file (concat texfilebase e)))
11696 pngfile))))
11698 (defun org-dvipng-color (attr)
11699 "Return an rgb color specification for dvipng."
11700 (apply 'format "rgb %s %s %s"
11701 (mapcar 'org-normalize-color
11702 (color-values (face-attribute 'default attr nil)))))
11704 (defun org-normalize-color (value)
11705 "Return string to be used as color value for an RGB component."
11706 (format "%g" (/ value 65535.0)))
11709 ;;;; Key bindings
11711 ;; Make `C-c C-x' a prefix key
11712 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11714 ;; TAB key with modifiers
11715 (org-defkey org-mode-map "\C-i" 'org-cycle)
11716 (org-defkey org-mode-map [(tab)] 'org-cycle)
11717 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11718 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11719 (org-defkey org-mode-map "\M-\t" 'org-complete)
11720 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11721 ;; The following line is necessary under Suse GNU/Linux
11722 (unless (featurep 'xemacs)
11723 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11724 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11725 (define-key org-mode-map [backtab] 'org-shifttab)
11727 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11728 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11729 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11731 ;; Cursor keys with modifiers
11732 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11733 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11734 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11735 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11737 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11738 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11739 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11740 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11742 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11743 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11744 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11745 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11747 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11748 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11750 ;;; Extra keys for tty access.
11751 ;; We only set them when really needed because otherwise the
11752 ;; menus don't show the simple keys
11754 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11755 (not window-system))
11756 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11757 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11758 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11759 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11760 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11761 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11762 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11763 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11764 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11765 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11766 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11767 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11768 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11769 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11770 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11771 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11772 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11773 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11774 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11775 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11776 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11777 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11779 ;; All the other keys
11781 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11782 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11783 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11784 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11785 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11786 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11787 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11788 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11789 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11790 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11791 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11792 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11793 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11794 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11795 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11796 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11797 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11798 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11799 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11800 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11801 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11802 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11803 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11804 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11805 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11806 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11807 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11808 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11809 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11810 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11811 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11812 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11813 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11814 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11815 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11816 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11817 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11818 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11819 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11820 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11821 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11822 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11823 (org-defkey org-mode-map "\C-c^" 'org-sort)
11824 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11825 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11826 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11827 (org-defkey org-mode-map "\C-m" 'org-return)
11828 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11829 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11830 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11831 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11832 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11833 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11834 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11835 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11836 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11837 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11838 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11839 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11840 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11841 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11842 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11843 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11845 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11846 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11847 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11848 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11850 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11851 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11852 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11853 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11854 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11855 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11856 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11857 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11858 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11859 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11860 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11861 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11863 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11865 (when (featurep 'xemacs)
11866 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11868 (defvar org-table-auto-blank-field) ; defined in org-table.el
11869 (defun org-self-insert-command (N)
11870 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11871 If the cursor is in a table looking at whitespace, the whitespace is
11872 overwritten, and the table is not marked as requiring realignment."
11873 (interactive "p")
11874 (if (and (org-table-p)
11875 (progn
11876 ;; check if we blank the field, and if that triggers align
11877 (and (featurep 'org-table) org-table-auto-blank-field
11878 (member last-command
11879 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11880 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11881 ;; got extra space, this field does not determine column width
11882 (let (org-table-may-need-update) (org-table-blank-field))
11883 ;; no extra space, this field may determine column width
11884 (org-table-blank-field)))
11886 (eq N 1)
11887 (looking-at "[^|\n]* |"))
11888 (let (org-table-may-need-update)
11889 (goto-char (1- (match-end 0)))
11890 (delete-backward-char 1)
11891 (goto-char (match-beginning 0))
11892 (self-insert-command N))
11893 (setq org-table-may-need-update t)
11894 (self-insert-command N)
11895 (org-fix-tags-on-the-fly)))
11897 (defun org-fix-tags-on-the-fly ()
11898 (when (and (equal (char-after (point-at-bol)) ?*)
11899 (org-on-heading-p))
11900 (org-align-tags-here org-tags-column)))
11902 (defun org-delete-backward-char (N)
11903 "Like `delete-backward-char', insert whitespace at field end in tables.
11904 When deleting backwards, in tables this function will insert whitespace in
11905 front of the next \"|\" separator, to keep the table aligned. The table will
11906 still be marked for re-alignment if the field did fill the entire column,
11907 because, in this case the deletion might narrow the column."
11908 (interactive "p")
11909 (if (and (org-table-p)
11910 (eq N 1)
11911 (string-match "|" (buffer-substring (point-at-bol) (point)))
11912 (looking-at ".*?|"))
11913 (let ((pos (point))
11914 (noalign (looking-at "[^|\n\r]* |"))
11915 (c org-table-may-need-update))
11916 (backward-delete-char N)
11917 (skip-chars-forward "^|")
11918 (insert " ")
11919 (goto-char (1- pos))
11920 ;; noalign: if there were two spaces at the end, this field
11921 ;; does not determine the width of the column.
11922 (if noalign (setq org-table-may-need-update c)))
11923 (backward-delete-char N)
11924 (org-fix-tags-on-the-fly)))
11926 (defun org-delete-char (N)
11927 "Like `delete-char', but insert whitespace at field end in tables.
11928 When deleting characters, in tables this function will insert whitespace in
11929 front of the next \"|\" separator, to keep the table aligned. The table will
11930 still be marked for re-alignment if the field did fill the entire column,
11931 because, in this case the deletion might narrow the column."
11932 (interactive "p")
11933 (if (and (org-table-p)
11934 (not (bolp))
11935 (not (= (char-after) ?|))
11936 (eq N 1))
11937 (if (looking-at ".*?|")
11938 (let ((pos (point))
11939 (noalign (looking-at "[^|\n\r]* |"))
11940 (c org-table-may-need-update))
11941 (replace-match (concat
11942 (substring (match-string 0) 1 -1)
11943 " |"))
11944 (goto-char pos)
11945 ;; noalign: if there were two spaces at the end, this field
11946 ;; does not determine the width of the column.
11947 (if noalign (setq org-table-may-need-update c)))
11948 (delete-char N))
11949 (delete-char N)
11950 (org-fix-tags-on-the-fly)))
11952 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11953 (put 'org-self-insert-command 'delete-selection t)
11954 (put 'orgtbl-self-insert-command 'delete-selection t)
11955 (put 'org-delete-char 'delete-selection 'supersede)
11956 (put 'org-delete-backward-char 'delete-selection 'supersede)
11958 ;; Make `flyspell-mode' delay after some commands
11959 (put 'org-self-insert-command 'flyspell-delayed t)
11960 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11961 (put 'org-delete-char 'flyspell-delayed t)
11962 (put 'org-delete-backward-char 'flyspell-delayed t)
11964 ;; Make pabbrev-mode expand after org-mode commands
11965 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11966 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11968 ;; How to do this: Measure non-white length of current string
11969 ;; If equal to column width, we should realign.
11971 (defun org-remap (map &rest commands)
11972 "In MAP, remap the functions given in COMMANDS.
11973 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11974 (let (new old)
11975 (while commands
11976 (setq old (pop commands) new (pop commands))
11977 (if (fboundp 'command-remapping)
11978 (org-defkey map (vector 'remap old) new)
11979 (substitute-key-definition old new map global-map)))))
11981 (when (eq org-enable-table-editor 'optimized)
11982 ;; If the user wants maximum table support, we need to hijack
11983 ;; some standard editing functions
11984 (org-remap org-mode-map
11985 'self-insert-command 'org-self-insert-command
11986 'delete-char 'org-delete-char
11987 'delete-backward-char 'org-delete-backward-char)
11988 (org-defkey org-mode-map "|" 'org-force-self-insert))
11990 (defun org-shiftcursor-error ()
11991 "Throw an error because Shift-Cursor command was applied in wrong context."
11992 (error "This command is active in special context like tables, headlines or timestamps"))
11994 (defun org-shifttab (&optional arg)
11995 "Global visibility cycling or move to previous table field.
11996 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11997 on context.
11998 See the individual commands for more information."
11999 (interactive "P")
12000 (cond
12001 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12002 (arg (message "Content view to level: ")
12003 (org-content (prefix-numeric-value arg))
12004 (setq org-cycle-global-status 'overview))
12005 (t (call-interactively 'org-global-cycle))))
12007 (defun org-shiftmetaleft ()
12008 "Promote subtree or delete table column.
12009 Calls `org-promote-subtree', `org-outdent-item',
12010 or `org-table-delete-column', depending on context.
12011 See the individual commands for more information."
12012 (interactive)
12013 (cond
12014 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12015 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12016 ((org-at-item-p) (call-interactively 'org-outdent-item))
12017 (t (org-shiftcursor-error))))
12019 (defun org-shiftmetaright ()
12020 "Demote subtree or insert table column.
12021 Calls `org-demote-subtree', `org-indent-item',
12022 or `org-table-insert-column', depending on context.
12023 See the individual commands for more information."
12024 (interactive)
12025 (cond
12026 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12027 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12028 ((org-at-item-p) (call-interactively 'org-indent-item))
12029 (t (org-shiftcursor-error))))
12031 (defun org-shiftmetaup (&optional arg)
12032 "Move subtree up or kill table row.
12033 Calls `org-move-subtree-up' or `org-table-kill-row' or
12034 `org-move-item-up' depending on context. See the individual commands
12035 for more information."
12036 (interactive "P")
12037 (cond
12038 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12039 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12040 ((org-at-item-p) (call-interactively 'org-move-item-up))
12041 (t (org-shiftcursor-error))))
12042 (defun org-shiftmetadown (&optional arg)
12043 "Move subtree down or insert table row.
12044 Calls `org-move-subtree-down' or `org-table-insert-row' or
12045 `org-move-item-down', depending on context. See the individual
12046 commands for more information."
12047 (interactive "P")
12048 (cond
12049 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12050 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12051 ((org-at-item-p) (call-interactively 'org-move-item-down))
12052 (t (org-shiftcursor-error))))
12054 (defun org-metaleft (&optional arg)
12055 "Promote heading or move table column to left.
12056 Calls `org-do-promote' or `org-table-move-column', depending on context.
12057 With no specific context, calls the Emacs default `backward-word'.
12058 See the individual commands for more information."
12059 (interactive "P")
12060 (cond
12061 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12062 ((or (org-on-heading-p) (org-region-active-p))
12063 (call-interactively 'org-do-promote))
12064 ((org-at-item-p) (call-interactively 'org-outdent-item))
12065 (t (call-interactively 'backward-word))))
12067 (defun org-metaright (&optional arg)
12068 "Demote subtree or move table column to right.
12069 Calls `org-do-demote' or `org-table-move-column', depending on context.
12070 With no specific context, calls the Emacs default `forward-word'.
12071 See the individual commands for more information."
12072 (interactive "P")
12073 (cond
12074 ((org-at-table-p) (call-interactively 'org-table-move-column))
12075 ((or (org-on-heading-p) (org-region-active-p))
12076 (call-interactively 'org-do-demote))
12077 ((org-at-item-p) (call-interactively 'org-indent-item))
12078 (t (call-interactively 'forward-word))))
12080 (defun org-metaup (&optional arg)
12081 "Move subtree up or move table row up.
12082 Calls `org-move-subtree-up' or `org-table-move-row' or
12083 `org-move-item-up', depending on context. See the individual commands
12084 for more information."
12085 (interactive "P")
12086 (cond
12087 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12088 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12089 ((org-at-item-p) (call-interactively 'org-move-item-up))
12090 (t (transpose-lines 1) (beginning-of-line -1))))
12092 (defun org-metadown (&optional arg)
12093 "Move subtree down or move table row down.
12094 Calls `org-move-subtree-down' or `org-table-move-row' or
12095 `org-move-item-down', depending on context. See the individual
12096 commands for more information."
12097 (interactive "P")
12098 (cond
12099 ((org-at-table-p) (call-interactively 'org-table-move-row))
12100 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12101 ((org-at-item-p) (call-interactively 'org-move-item-down))
12102 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12104 (defun org-shiftup (&optional arg)
12105 "Increase item in timestamp or increase priority of current headline.
12106 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12107 depending on context. See the individual commands for more information."
12108 (interactive "P")
12109 (cond
12110 ((org-at-timestamp-p t)
12111 (call-interactively (if org-edit-timestamp-down-means-later
12112 'org-timestamp-down 'org-timestamp-up)))
12113 ((org-on-heading-p) (call-interactively 'org-priority-up))
12114 ((org-at-item-p) (call-interactively 'org-previous-item))
12115 ((org-clocktable-try-shift 'up arg))
12116 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12118 (defun org-shiftdown (&optional arg)
12119 "Decrease item in timestamp or decrease priority of current headline.
12120 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12121 depending on context. See the individual commands for more information."
12122 (interactive "P")
12123 (cond
12124 ((org-at-timestamp-p t)
12125 (call-interactively (if org-edit-timestamp-down-means-later
12126 'org-timestamp-up 'org-timestamp-down)))
12127 ((org-on-heading-p) (call-interactively 'org-priority-down))
12128 ((org-clocktable-try-shift 'down arg))
12129 (t (call-interactively 'org-next-item))))
12131 (defun org-shiftright (&optional arg)
12132 "Next TODO keyword or timestamp one day later, depending on context."
12133 (interactive "P")
12134 (cond
12135 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12136 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12137 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12138 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12139 ((org-clocktable-try-shift 'right arg))
12140 (t (org-shiftcursor-error))))
12142 (defun org-shiftleft (&optional arg)
12143 "Previous TODO keyword or timestamp one day earlier, depending on context."
12144 (interactive "P")
12145 (cond
12146 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12147 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12148 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12149 ((org-at-property-p)
12150 (call-interactively 'org-property-previous-allowed-value))
12151 ((org-clocktable-try-shift 'left arg))
12152 (t (org-shiftcursor-error))))
12154 (defun org-shiftcontrolright ()
12155 "Switch to next TODO set."
12156 (interactive)
12157 (cond
12158 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12159 (t (org-shiftcursor-error))))
12161 (defun org-shiftcontrolleft ()
12162 "Switch to previous TODO set."
12163 (interactive)
12164 (cond
12165 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12166 (t (org-shiftcursor-error))))
12168 (defun org-ctrl-c-ret ()
12169 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12170 (interactive)
12171 (cond
12172 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12173 (t (call-interactively 'org-insert-heading))))
12175 (defun org-copy-special ()
12176 "Copy region in table or copy current subtree.
12177 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12178 See the individual commands for more information."
12179 (interactive)
12180 (call-interactively
12181 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12183 (defun org-cut-special ()
12184 "Cut region in table or cut current subtree.
12185 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12186 See the individual commands for more information."
12187 (interactive)
12188 (call-interactively
12189 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12191 (defun org-paste-special (arg)
12192 "Paste rectangular region into table, or past subtree relative to level.
12193 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12194 See the individual commands for more information."
12195 (interactive "P")
12196 (if (org-at-table-p)
12197 (org-table-paste-rectangle)
12198 (org-paste-subtree arg)))
12200 (defun org-ctrl-c-ctrl-c (&optional arg)
12201 "Set tags in headline, or update according to changed information at point.
12203 This command does many different things, depending on context:
12205 - If the cursor is in a headline, prompt for tags and insert them
12206 into the current line, aligned to `org-tags-column'. When called
12207 with prefix arg, realign all tags in the current buffer.
12209 - If the cursor is in one of the special #+KEYWORD lines, this
12210 triggers scanning the buffer for these lines and updating the
12211 information.
12213 - If the cursor is inside a table, realign the table. This command
12214 works even if the automatic table editor has been turned off.
12216 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12217 the entire table.
12219 - If the cursor is a the beginning of a dynamic block, update it.
12221 - If the cursor is inside a table created by the table.el package,
12222 activate that table.
12224 - If the current buffer is a remember buffer, close note and file it.
12225 with a prefix argument, file it without further interaction to the default
12226 location.
12228 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12229 links in this buffer.
12231 - If the cursor is on a numbered item in a plain list, renumber the
12232 ordered list.
12234 - If the cursor is on a checkbox, toggle it."
12235 (interactive "P")
12236 (let ((org-enable-table-editor t))
12237 (cond
12238 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12239 org-occur-highlights
12240 org-latex-fragment-image-overlays)
12241 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12242 (org-remove-occur-highlights)
12243 (org-remove-latex-fragment-image-overlays)
12244 (message "Temporary highlights/overlays removed from current buffer"))
12245 ((and (local-variable-p 'org-finish-function (current-buffer))
12246 (fboundp org-finish-function))
12247 (funcall org-finish-function))
12248 ((org-at-property-p)
12249 (call-interactively 'org-property-action))
12250 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12251 ((org-on-heading-p) (call-interactively 'org-set-tags))
12252 ((org-at-table.el-p)
12253 (require 'table)
12254 (beginning-of-line 1)
12255 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12256 (call-interactively 'table-recognize-table))
12257 ((org-at-table-p)
12258 (org-table-maybe-eval-formula)
12259 (if arg
12260 (call-interactively 'org-table-recalculate)
12261 (org-table-maybe-recalculate-line))
12262 (call-interactively 'org-table-align))
12263 ((org-at-item-checkbox-p)
12264 (call-interactively 'org-toggle-checkbox))
12265 ((org-at-item-p)
12266 (call-interactively 'org-maybe-renumber-ordered-list))
12267 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12268 ;; Dynamic block
12269 (beginning-of-line 1)
12270 (org-update-dblock))
12271 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12272 (cond
12273 ((equal (match-string 1) "TBLFM")
12274 ;; Recalculate the table before this line
12275 (save-excursion
12276 (beginning-of-line 1)
12277 (skip-chars-backward " \r\n\t")
12278 (if (org-at-table-p)
12279 (org-call-with-arg 'org-table-recalculate t))))
12281 (call-interactively 'org-mode-restart))))
12282 (t (error "C-c C-c can do nothing useful at this location.")))))
12284 (defun org-mode-restart ()
12285 "Restart Org-mode, to scan again for special lines.
12286 Also updates the keyword regular expressions."
12287 (interactive)
12288 (let ((org-inhibit-startup t)) (org-mode))
12289 (message "Org-mode restarted to refresh keyword and special line setup"))
12291 (defun org-kill-note-or-show-branches ()
12292 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12293 (interactive)
12294 (if (not org-finish-function)
12295 (call-interactively 'show-branches)
12296 (let ((org-note-abort t))
12297 (funcall org-finish-function))))
12299 (defun org-return (&optional indent)
12300 "Goto next table row or insert a newline.
12301 Calls `org-table-next-row' or `newline', depending on context.
12302 See the individual commands for more information."
12303 (interactive)
12304 (cond
12305 ((bobp) (if indent (newline-and-indent) (newline)))
12306 ((and (org-at-heading-p)
12307 (looking-at
12308 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12309 (org-show-entry)
12310 (end-of-line 1)
12311 (newline))
12312 ((org-at-table-p)
12313 (org-table-justify-field-maybe)
12314 (call-interactively 'org-table-next-row))
12315 (t (if indent (newline-and-indent) (newline)))))
12317 (defun org-return-indent ()
12318 "Goto next table row or insert a newline and indent.
12319 Calls `org-table-next-row' or `newline-and-indent', depending on
12320 context. See the individual commands for more information."
12321 (interactive)
12322 (org-return t))
12324 (defun org-ctrl-c-star ()
12325 "Compute table, or change heading status of lines.
12326 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12327 depending on context. This will also turn a plain list item or a normal
12328 line into a subheading."
12329 (interactive)
12330 (cond
12331 ((org-at-table-p)
12332 (call-interactively 'org-table-recalculate))
12333 ((org-region-active-p)
12334 ;; Convert all lines in region to list items
12335 (call-interactively 'org-toggle-region-headings))
12336 ((org-on-heading-p)
12337 (org-toggle-region-headings (point-at-bol)
12338 (min (1+ (point-at-eol)) (point-max))))
12339 ((org-at-item-p)
12340 ;; Convert to heading
12341 (let ((level (save-match-data
12342 (save-excursion
12343 (condition-case nil
12344 (progn
12345 (org-back-to-heading t)
12346 (funcall outline-level))
12347 (error 0))))))
12348 (replace-match
12349 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12350 (t (org-toggle-region-headings (point-at-bol)
12351 (min (1+ (point-at-eol)) (point-max))))))
12353 (defun org-ctrl-c-minus ()
12354 "Insert separator line in table or modify bullet status of line.
12355 Also turns a plain line or a region of lines into list items.
12356 Calls `org-table-insert-hline', `org-toggle-region-items', or
12357 `org-cycle-list-bullet', depending on context."
12358 (interactive)
12359 (cond
12360 ((org-at-table-p)
12361 (call-interactively 'org-table-insert-hline))
12362 ((org-on-heading-p)
12363 ;; Convert to item
12364 (save-excursion
12365 (beginning-of-line 1)
12366 (if (looking-at "\\*+ ")
12367 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12368 ((org-region-active-p)
12369 ;; Convert all lines in region to list items
12370 (call-interactively 'org-toggle-region-items))
12371 ((org-in-item-p)
12372 (call-interactively 'org-cycle-list-bullet))
12373 (t (org-toggle-region-items (point-at-bol)
12374 (min (1+ (point-at-eol)) (point-max))))))
12376 (defun org-toggle-region-items (beg end)
12377 "Convert all lines in region to list items.
12378 If the first line is already an item, convert all list items in the region
12379 to normal lines."
12380 (interactive "r")
12381 (let (l2 l)
12382 (save-excursion
12383 (goto-char end)
12384 (setq l2 (org-current-line))
12385 (goto-char beg)
12386 (beginning-of-line 1)
12387 (setq l (1- (org-current-line)))
12388 (if (org-at-item-p)
12389 ;; We already have items, de-itemize
12390 (while (< (setq l (1+ l)) l2)
12391 (when (org-at-item-p)
12392 (goto-char (match-beginning 2))
12393 (delete-region (match-beginning 2) (match-end 2))
12394 (and (looking-at "[ \t]+") (replace-match "")))
12395 (beginning-of-line 2))
12396 (while (< (setq l (1+ l)) l2)
12397 (unless (org-at-item-p)
12398 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12399 (replace-match "\\1- \\2")))
12400 (beginning-of-line 2))))))
12402 (defun org-toggle-region-headings (beg end)
12403 "Convert all lines in region to list items.
12404 If the first line is already an item, convert all list items in the region
12405 to normal lines."
12406 (interactive "r")
12407 (let (l2 l)
12408 (save-excursion
12409 (goto-char end)
12410 (setq l2 (org-current-line))
12411 (goto-char beg)
12412 (beginning-of-line 1)
12413 (setq l (1- (org-current-line)))
12414 (if (org-on-heading-p)
12415 ;; We already have headlines, de-star them
12416 (while (< (setq l (1+ l)) l2)
12417 (when (org-on-heading-p t)
12418 (and (looking-at outline-regexp) (replace-match "")))
12419 (beginning-of-line 2))
12420 (let* ((stars (save-excursion
12421 (re-search-backward org-complex-heading-regexp nil t)
12422 (or (match-string 1) "*")))
12423 (add-stars (if org-odd-levels-only "**" "*"))
12424 (rpl (concat stars add-stars " \\2")))
12425 (while (< (setq l (1+ l)) l2)
12426 (unless (org-on-heading-p)
12427 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12428 (replace-match rpl)))
12429 (beginning-of-line 2)))))))
12431 (defun org-meta-return (&optional arg)
12432 "Insert a new heading or wrap a region in a table.
12433 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12434 See the individual commands for more information."
12435 (interactive "P")
12436 (cond
12437 ((org-at-table-p)
12438 (call-interactively 'org-table-wrap-region))
12439 (t (call-interactively 'org-insert-heading))))
12441 ;;; Menu entries
12443 ;; Define the Org-mode menus
12444 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12445 '("Tbl"
12446 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12447 ["Next Field" org-cycle (org-at-table-p)]
12448 ["Previous Field" org-shifttab (org-at-table-p)]
12449 ["Next Row" org-return (org-at-table-p)]
12450 "--"
12451 ["Blank Field" org-table-blank-field (org-at-table-p)]
12452 ["Edit Field" org-table-edit-field (org-at-table-p)]
12453 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12454 "--"
12455 ("Column"
12456 ["Move Column Left" org-metaleft (org-at-table-p)]
12457 ["Move Column Right" org-metaright (org-at-table-p)]
12458 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12459 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12460 ("Row"
12461 ["Move Row Up" org-metaup (org-at-table-p)]
12462 ["Move Row Down" org-metadown (org-at-table-p)]
12463 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12464 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12465 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12466 "--"
12467 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12468 ("Rectangle"
12469 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12470 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12471 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12472 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12473 "--"
12474 ("Calculate"
12475 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12476 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12477 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12478 "--"
12479 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12480 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12481 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12482 "--"
12483 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12484 "--"
12485 ["Sum Column/Rectangle" org-table-sum
12486 (or (org-at-table-p) (org-region-active-p))]
12487 ["Which Column?" org-table-current-column (org-at-table-p)])
12488 ["Debug Formulas"
12489 org-table-toggle-formula-debugger
12490 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12491 ["Show Col/Row Numbers"
12492 org-table-toggle-coordinate-overlays
12493 :style toggle
12494 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12495 "--"
12496 ["Create" org-table-create (and (not (org-at-table-p))
12497 org-enable-table-editor)]
12498 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12499 ["Import from File" org-table-import (not (org-at-table-p))]
12500 ["Export to File" org-table-export (org-at-table-p)]
12501 "--"
12502 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12504 (easy-menu-define org-org-menu org-mode-map "Org menu"
12505 '("Org"
12506 ("Show/Hide"
12507 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12508 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12509 ["Sparse Tree..." org-sparse-tree t]
12510 ["Reveal Context" org-reveal t]
12511 ["Show All" show-all t]
12512 "--"
12513 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12514 "--"
12515 ["New Heading" org-insert-heading t]
12516 ("Navigate Headings"
12517 ["Up" outline-up-heading t]
12518 ["Next" outline-next-visible-heading t]
12519 ["Previous" outline-previous-visible-heading t]
12520 ["Next Same Level" outline-forward-same-level t]
12521 ["Previous Same Level" outline-backward-same-level t]
12522 "--"
12523 ["Jump" org-goto t])
12524 ("Edit Structure"
12525 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12526 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12527 "--"
12528 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12529 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12530 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12531 "--"
12532 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12533 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12534 ["Demote Heading" org-metaright (not (org-at-table-p))]
12535 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12536 "--"
12537 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12538 "--"
12539 ["Convert to odd levels" org-convert-to-odd-levels t]
12540 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12541 ("Editing"
12542 ["Emphasis..." org-emphasize t])
12543 ("Archive"
12544 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12545 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12546 ; :active t :keys "C-u C-c C-x C-a"]
12547 ["Sparse trees open ARCHIVE trees"
12548 (setq org-sparse-tree-open-archived-trees
12549 (not org-sparse-tree-open-archived-trees))
12550 :style toggle :selected org-sparse-tree-open-archived-trees]
12551 ["Cycling opens ARCHIVE trees"
12552 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12553 :style toggle :selected org-cycle-open-archived-trees]
12554 ["Agenda includes ARCHIVE trees"
12555 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12556 :style toggle :selected (not org-agenda-skip-archived-trees)]
12557 "--"
12558 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12559 ; ["Check and Move Children" (org-archive-subtree '(4))
12560 ; :active t :keys "C-u C-c C-x C-s"]
12562 "--"
12563 ("TODO Lists"
12564 ["TODO/DONE/-" org-todo t]
12565 ("Select keyword"
12566 ["Next keyword" org-shiftright (org-on-heading-p)]
12567 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12568 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12569 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12570 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12571 ["Show TODO Tree" org-show-todo-tree t]
12572 ["Global TODO list" org-todo-list t]
12573 "--"
12574 ["Set Priority" org-priority t]
12575 ["Priority Up" org-shiftup t]
12576 ["Priority Down" org-shiftdown t])
12577 ("TAGS and Properties"
12578 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12579 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12580 "--"
12581 ["Set property" 'org-set-property t]
12582 ["Column view of properties" org-columns t]
12583 ["Insert Column View DBlock" org-insert-columns-dblock t])
12584 ("Dates and Scheduling"
12585 ["Timestamp" org-time-stamp t]
12586 ["Timestamp (inactive)" org-time-stamp-inactive t]
12587 ("Change Date"
12588 ["1 Day Later" org-shiftright t]
12589 ["1 Day Earlier" org-shiftleft t]
12590 ["1 ... Later" org-shiftup t]
12591 ["1 ... Earlier" org-shiftdown t])
12592 ["Compute Time Range" org-evaluate-time-range t]
12593 ["Schedule Item" org-schedule t]
12594 ["Deadline" org-deadline t]
12595 "--"
12596 ["Custom time format" org-toggle-time-stamp-overlays
12597 :style radio :selected org-display-custom-times]
12598 "--"
12599 ["Goto Calendar" org-goto-calendar t]
12600 ["Date from Calendar" org-date-from-calendar t])
12601 ("Logging work"
12602 ["Clock in" org-clock-in t]
12603 ["Clock out" org-clock-out t]
12604 ["Clock cancel" org-clock-cancel t]
12605 ["Goto running clock" org-clock-goto t]
12606 ["Display times" org-clock-display t]
12607 ["Create clock table" org-clock-report t]
12608 "--"
12609 ["Record DONE time"
12610 (progn (setq org-log-done (not org-log-done))
12611 (message "Switching to %s will %s record a timestamp"
12612 (car org-done-keywords)
12613 (if org-log-done "automatically" "not")))
12614 :style toggle :selected org-log-done])
12615 "--"
12616 ["Agenda Command..." org-agenda t]
12617 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12618 ("File List for Agenda")
12619 ("Special views current file"
12620 ["TODO Tree" org-show-todo-tree t]
12621 ["Check Deadlines" org-check-deadlines t]
12622 ["Timeline" org-timeline t]
12623 ["Tags Tree" org-tags-sparse-tree t])
12624 "--"
12625 ("Hyperlinks"
12626 ["Store Link (Global)" org-store-link t]
12627 ["Insert Link" org-insert-link t]
12628 ["Follow Link" org-open-at-point t]
12629 "--"
12630 ["Next link" org-next-link t]
12631 ["Previous link" org-previous-link t]
12632 "--"
12633 ["Descriptive Links"
12634 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12635 :style radio
12636 :selected (member '(org-link) buffer-invisibility-spec)]
12637 ["Literal Links"
12638 (progn
12639 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12640 :style radio
12641 :selected (not (member '(org-link) buffer-invisibility-spec))])
12642 "--"
12643 ["Export/Publish..." org-export t]
12644 ("LaTeX"
12645 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12646 :selected org-cdlatex-mode]
12647 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12648 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12649 ["Modify math symbol" org-cdlatex-math-modify
12650 (org-inside-LaTeX-fragment-p)]
12651 ["Export LaTeX fragments as images"
12652 (if (featurep 'org-exp)
12653 (setq org-export-with-LaTeX-fragments
12654 (not org-export-with-LaTeX-fragments))
12655 (require 'org-exp))
12656 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12657 org-export-with-LaTeX-fragments)])
12658 "--"
12659 ("Documentation"
12660 ["Show Version" org-version t]
12661 ["Info Documentation" org-info t])
12662 ("Customize"
12663 ["Browse Org Group" org-customize t]
12664 "--"
12665 ["Expand This Menu" org-create-customize-menu
12666 (fboundp 'customize-menu-create)])
12667 "--"
12668 ["Refresh setup" org-mode-restart t]
12671 (defun org-info (&optional node)
12672 "Read documentation for Org-mode in the info system.
12673 With optional NODE, go directly to that node."
12674 (interactive)
12675 (info (format "(org)%s" (or node ""))))
12677 (defun org-install-agenda-files-menu ()
12678 (let ((bl (buffer-list)))
12679 (save-excursion
12680 (while bl
12681 (set-buffer (pop bl))
12682 (if (org-mode-p) (setq bl nil)))
12683 (when (org-mode-p)
12684 (easy-menu-change
12685 '("Org") "File List for Agenda"
12686 (append
12687 (list
12688 ["Edit File List" (org-edit-agenda-file-list) t]
12689 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12690 ["Remove Current File from List" org-remove-file t]
12691 ["Cycle through agenda files" org-cycle-agenda-files t]
12692 ["Occur in all agenda files" org-occur-in-agenda-files t]
12693 "--")
12694 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12696 ;;;; Documentation
12698 (defun org-require-autoloaded-modules ()
12699 (interactive)
12700 (mapc 'require
12701 '(org-agenda org-archive org-clock org-colview
12702 org-exp org-export-latex org-publish
12703 org-remember org-table)))
12705 (defun org-customize ()
12706 "Call the customize function with org as argument."
12707 (interactive)
12708 (org-load-modules-maybe)
12709 (org-require-autoloaded-modules)
12710 (customize-browse 'org))
12712 (defun org-create-customize-menu ()
12713 "Create a full customization menu for Org-mode, insert it into the menu."
12714 (interactive)
12715 (org-load-modules-maybe)
12716 (org-require-autoloaded-modules)
12717 (if (fboundp 'customize-menu-create)
12718 (progn
12719 (easy-menu-change
12720 '("Org") "Customize"
12721 `(["Browse Org group" org-customize t]
12722 "--"
12723 ,(customize-menu-create 'org)
12724 ["Set" Custom-set t]
12725 ["Save" Custom-save t]
12726 ["Reset to Current" Custom-reset-current t]
12727 ["Reset to Saved" Custom-reset-saved t]
12728 ["Reset to Standard Settings" Custom-reset-standard t]))
12729 (message "\"Org\"-menu now contains full customization menu"))
12730 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12732 ;;;; Miscellaneous stuff
12734 ;;; Generally useful functions
12736 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12737 "Display the given MESSAGE as a warning."
12738 (if (fboundp 'display-warning)
12739 (display-warning 'org message
12740 (if (featurep 'xemacs)
12741 'warning
12742 :warning))
12743 (let ((buf (get-buffer-create "*Org warnings*")))
12744 (with-current-buffer buf
12745 (goto-char (point-max))
12746 (insert "Warning (Org): " message)
12747 (unless (bolp)
12748 (newline)))
12749 (display-buffer buf)
12750 (sit-for 0))))
12752 (defun org-plist-delete (plist property)
12753 "Delete PROPERTY from PLIST.
12754 This is in contrast to merely setting it to 0."
12755 (let (p)
12756 (while plist
12757 (if (not (eq property (car plist)))
12758 (setq p (plist-put p (car plist) (nth 1 plist))))
12759 (setq plist (cddr plist)))
12762 (defun org-force-self-insert (N)
12763 "Needed to enforce self-insert under remapping."
12764 (interactive "p")
12765 (self-insert-command N))
12767 (defun org-string-width (s)
12768 "Compute width of string, ignoring invisible characters.
12769 This ignores character with invisibility property `org-link', and also
12770 characters with property `org-cwidth', because these will become invisible
12771 upon the next fontification round."
12772 (let (b l)
12773 (when (or (eq t buffer-invisibility-spec)
12774 (assq 'org-link buffer-invisibility-spec))
12775 (while (setq b (text-property-any 0 (length s)
12776 'invisible 'org-link s))
12777 (setq s (concat (substring s 0 b)
12778 (substring s (or (next-single-property-change
12779 b 'invisible s) (length s)))))))
12780 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12781 (setq s (concat (substring s 0 b)
12782 (substring s (or (next-single-property-change
12783 b 'org-cwidth s) (length s))))))
12784 (setq l (string-width s) b -1)
12785 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12786 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12789 (defun org-base-buffer (buffer)
12790 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12791 (if (not buffer)
12792 buffer
12793 (or (buffer-base-buffer buffer)
12794 buffer)))
12796 (defun org-trim (s)
12797 "Remove whitespace at beginning and end of string."
12798 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12799 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12802 (defun org-wrap (string &optional width lines)
12803 "Wrap string to either a number of lines, or a width in characters.
12804 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12805 that costs. If there is a word longer than WIDTH, the text is actually
12806 wrapped to the length of that word.
12807 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12808 many lines, whatever width that takes.
12809 The return value is a list of lines, without newlines at the end."
12810 (let* ((words (org-split-string string "[ \t\n]+"))
12811 (maxword (apply 'max (mapcar 'org-string-width words)))
12812 w ll)
12813 (cond (width
12814 (org-do-wrap words (max maxword width)))
12815 (lines
12816 (setq w maxword)
12817 (setq ll (org-do-wrap words maxword))
12818 (if (<= (length ll) lines)
12820 (setq ll words)
12821 (while (> (length ll) lines)
12822 (setq w (1+ w))
12823 (setq ll (org-do-wrap words w)))
12824 ll))
12825 (t (error "Cannot wrap this")))))
12827 (defun org-do-wrap (words width)
12828 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12829 (let (lines line)
12830 (while words
12831 (setq line (pop words))
12832 (while (and words (< (+ (length line) (length (car words))) width))
12833 (setq line (concat line " " (pop words))))
12834 (setq lines (push line lines)))
12835 (nreverse lines)))
12837 (defun org-split-string (string &optional separators)
12838 "Splits STRING into substrings at SEPARATORS.
12839 No empty strings are returned if there are matches at the beginning
12840 and end of string."
12841 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12842 (start 0)
12843 notfirst
12844 (list nil))
12845 (while (and (string-match rexp string
12846 (if (and notfirst
12847 (= start (match-beginning 0))
12848 (< start (length string)))
12849 (1+ start) start))
12850 (< (match-beginning 0) (length string)))
12851 (setq notfirst t)
12852 (or (eq (match-beginning 0) 0)
12853 (and (eq (match-beginning 0) (match-end 0))
12854 (eq (match-beginning 0) start))
12855 (setq list
12856 (cons (substring string start (match-beginning 0))
12857 list)))
12858 (setq start (match-end 0)))
12859 (or (eq start (length string))
12860 (setq list
12861 (cons (substring string start)
12862 list)))
12863 (nreverse list)))
12865 (defun org-context ()
12866 "Return a list of contexts of the current cursor position.
12867 If several contexts apply, all are returned.
12868 Each context entry is a list with a symbol naming the context, and
12869 two positions indicating start and end of the context. Possible
12870 contexts are:
12872 :headline anywhere in a headline
12873 :headline-stars on the leading stars in a headline
12874 :todo-keyword on a TODO keyword (including DONE) in a headline
12875 :tags on the TAGS in a headline
12876 :priority on the priority cookie in a headline
12877 :item on the first line of a plain list item
12878 :item-bullet on the bullet/number of a plain list item
12879 :checkbox on the checkbox in a plain list item
12880 :table in an org-mode table
12881 :table-special on a special filed in a table
12882 :table-table in a table.el table
12883 :link on a hyperlink
12884 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12885 :target on a <<target>>
12886 :radio-target on a <<<radio-target>>>
12887 :latex-fragment on a LaTeX fragment
12888 :latex-preview on a LaTeX fragment with overlayed preview image
12890 This function expects the position to be visible because it uses font-lock
12891 faces as a help to recognize the following contexts: :table-special, :link,
12892 and :keyword."
12893 (let* ((f (get-text-property (point) 'face))
12894 (faces (if (listp f) f (list f)))
12895 (p (point)) clist o)
12896 ;; First the large context
12897 (cond
12898 ((org-on-heading-p t)
12899 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12900 (when (progn
12901 (beginning-of-line 1)
12902 (looking-at org-todo-line-tags-regexp))
12903 (push (org-point-in-group p 1 :headline-stars) clist)
12904 (push (org-point-in-group p 2 :todo-keyword) clist)
12905 (push (org-point-in-group p 4 :tags) clist))
12906 (goto-char p)
12907 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12908 (if (looking-at "\\[#[A-Z0-9]\\]")
12909 (push (org-point-in-group p 0 :priority) clist)))
12911 ((org-at-item-p)
12912 (push (org-point-in-group p 2 :item-bullet) clist)
12913 (push (list :item (point-at-bol)
12914 (save-excursion (org-end-of-item) (point)))
12915 clist)
12916 (and (org-at-item-checkbox-p)
12917 (push (org-point-in-group p 0 :checkbox) clist)))
12919 ((org-at-table-p)
12920 (push (list :table (org-table-begin) (org-table-end)) clist)
12921 (if (memq 'org-formula faces)
12922 (push (list :table-special
12923 (previous-single-property-change p 'face)
12924 (next-single-property-change p 'face)) clist)))
12925 ((org-at-table-p 'any)
12926 (push (list :table-table) clist)))
12927 (goto-char p)
12929 ;; Now the small context
12930 (cond
12931 ((org-at-timestamp-p)
12932 (push (org-point-in-group p 0 :timestamp) clist))
12933 ((memq 'org-link faces)
12934 (push (list :link
12935 (previous-single-property-change p 'face)
12936 (next-single-property-change p 'face)) clist))
12937 ((memq 'org-special-keyword faces)
12938 (push (list :keyword
12939 (previous-single-property-change p 'face)
12940 (next-single-property-change p 'face)) clist))
12941 ((org-on-target-p)
12942 (push (org-point-in-group p 0 :target) clist)
12943 (goto-char (1- (match-beginning 0)))
12944 (if (looking-at org-radio-target-regexp)
12945 (push (org-point-in-group p 0 :radio-target) clist))
12946 (goto-char p))
12947 ((setq o (car (delq nil
12948 (mapcar
12949 (lambda (x)
12950 (if (memq x org-latex-fragment-image-overlays) x))
12951 (org-overlays-at (point))))))
12952 (push (list :latex-fragment
12953 (org-overlay-start o) (org-overlay-end o)) clist)
12954 (push (list :latex-preview
12955 (org-overlay-start o) (org-overlay-end o)) clist))
12956 ((org-inside-LaTeX-fragment-p)
12957 ;; FIXME: positions wrong.
12958 (push (list :latex-fragment (point) (point)) clist)))
12960 (setq clist (nreverse (delq nil clist)))
12961 clist))
12963 ;; FIXME: Compare with at-regexp-p Do we need both?
12964 (defun org-in-regexp (re &optional nlines visually)
12965 "Check if point is inside a match of regexp.
12966 Normally only the current line is checked, but you can include NLINES extra
12967 lines both before and after point into the search.
12968 If VISUALLY is set, require that the cursor is not after the match but
12969 really on, so that the block visually is on the match."
12970 (catch 'exit
12971 (let ((pos (point))
12972 (eol (point-at-eol (+ 1 (or nlines 0))))
12973 (inc (if visually 1 0)))
12974 (save-excursion
12975 (beginning-of-line (- 1 (or nlines 0)))
12976 (while (re-search-forward re eol t)
12977 (if (and (<= (match-beginning 0) pos)
12978 (>= (+ inc (match-end 0)) pos))
12979 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12981 (defun org-at-regexp-p (regexp)
12982 "Is point inside a match of REGEXP in the current line?"
12983 (catch 'exit
12984 (save-excursion
12985 (let ((pos (point)) (end (point-at-eol)))
12986 (beginning-of-line 1)
12987 (while (re-search-forward regexp end t)
12988 (if (and (<= (match-beginning 0) pos)
12989 (>= (match-end 0) pos))
12990 (throw 'exit t)))
12991 nil))))
12993 (defun org-occur-in-agenda-files (regexp &optional nlines)
12994 "Call `multi-occur' with buffers for all agenda files."
12995 (interactive "sOrg-files matching: \np")
12996 (let* ((files (org-agenda-files))
12997 (tnames (mapcar 'file-truename files))
12998 (extra org-agenda-text-search-extra-files)
13000 (when (eq (car extra) 'agenda-archives)
13001 (setq extra (cdr extra))
13002 (setq files (org-add-archive-files files)))
13003 (while (setq f (pop extra))
13004 (unless (member (file-truename f) tnames)
13005 (add-to-list 'files f 'append)
13006 (add-to-list 'tnames (file-truename f) 'append)))
13007 (multi-occur
13008 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13009 regexp)))
13011 (if (boundp 'occur-mode-find-occurrence-hook)
13012 ;; Emacs 23
13013 (add-hook 'occur-mode-find-occurrence-hook
13014 (lambda ()
13015 (when (org-mode-p)
13016 (org-reveal))))
13017 ;; Emacs 22
13018 (defadvice occur-mode-goto-occurrence
13019 (after org-occur-reveal activate)
13020 (and (org-mode-p) (org-reveal)))
13021 (defadvice occur-mode-goto-occurrence-other-window
13022 (after org-occur-reveal activate)
13023 (and (org-mode-p) (org-reveal)))
13024 (defadvice occur-mode-display-occurrence
13025 (after org-occur-reveal activate)
13026 (when (org-mode-p)
13027 (let ((pos (occur-mode-find-occurrence)))
13028 (with-current-buffer (marker-buffer pos)
13029 (save-excursion
13030 (goto-char pos)
13031 (org-reveal)))))))
13033 (defun org-uniquify (list)
13034 "Remove duplicate elements from LIST."
13035 (let (res)
13036 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13037 res))
13039 (defun org-delete-all (elts list)
13040 "Remove all elements in ELTS from LIST."
13041 (while elts
13042 (setq list (delete (pop elts) list)))
13043 list)
13045 (defun org-back-over-empty-lines ()
13046 "Move backwards over witespace, to the beginning of the first empty line.
13047 Returns the number of empty lines passed."
13048 (let ((pos (point)))
13049 (skip-chars-backward " \t\n\r")
13050 (beginning-of-line 2)
13051 (goto-char (min (point) pos))
13052 (count-lines (point) pos)))
13054 (defun org-skip-whitespace ()
13055 (skip-chars-forward " \t\n\r"))
13057 (defun org-point-in-group (point group &optional context)
13058 "Check if POINT is in match-group GROUP.
13059 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13060 match. If the match group does ot exist or point is not inside it,
13061 return nil."
13062 (and (match-beginning group)
13063 (>= point (match-beginning group))
13064 (<= point (match-end group))
13065 (if context
13066 (list context (match-beginning group) (match-end group))
13067 t)))
13069 (defun org-switch-to-buffer-other-window (&rest args)
13070 "Switch to buffer in a second window on the current frame.
13071 In particular, do not allow pop-up frames."
13072 (let (pop-up-frames special-display-buffer-names special-display-regexps
13073 special-display-function)
13074 (apply 'switch-to-buffer-other-window args)))
13076 (defun org-combine-plists (&rest plists)
13077 "Create a single property list from all plists in PLISTS.
13078 The process starts by copying the first list, and then setting properties
13079 from the other lists. Settings in the last list are the most significant
13080 ones and overrule settings in the other lists."
13081 (let ((rtn (copy-sequence (pop plists)))
13082 p v ls)
13083 (while plists
13084 (setq ls (pop plists))
13085 (while ls
13086 (setq p (pop ls) v (pop ls))
13087 (setq rtn (plist-put rtn p v))))
13088 rtn))
13090 (defun org-move-line-down (arg)
13091 "Move the current line down. With prefix argument, move it past ARG lines."
13092 (interactive "p")
13093 (let ((col (current-column))
13094 beg end pos)
13095 (beginning-of-line 1) (setq beg (point))
13096 (beginning-of-line 2) (setq end (point))
13097 (beginning-of-line (+ 1 arg))
13098 (setq pos (move-marker (make-marker) (point)))
13099 (insert (delete-and-extract-region beg end))
13100 (goto-char pos)
13101 (org-move-to-column col)))
13103 (defun org-move-line-up (arg)
13104 "Move the current line up. With prefix argument, move it past ARG lines."
13105 (interactive "p")
13106 (let ((col (current-column))
13107 beg end pos)
13108 (beginning-of-line 1) (setq beg (point))
13109 (beginning-of-line 2) (setq end (point))
13110 (beginning-of-line (- arg))
13111 (setq pos (move-marker (make-marker) (point)))
13112 (insert (delete-and-extract-region beg end))
13113 (goto-char pos)
13114 (org-move-to-column col)))
13116 (defun org-replace-escapes (string table)
13117 "Replace %-escapes in STRING with values in TABLE.
13118 TABLE is an association list with keys like \"%a\" and string values.
13119 The sequences in STRING may contain normal field width and padding information,
13120 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13121 so values can contain further %-escapes if they are define later in TABLE."
13122 (let ((case-fold-search nil)
13123 e re rpl)
13124 (while (setq e (pop table))
13125 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13126 (while (string-match re string)
13127 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13128 (cdr e)))
13129 (setq string (replace-match rpl t t string))))
13130 string))
13133 (defun org-sublist (list start end)
13134 "Return a section of LIST, from START to END.
13135 Counting starts at 1."
13136 (let (rtn (c start))
13137 (setq list (nthcdr (1- start) list))
13138 (while (and list (<= c end))
13139 (push (pop list) rtn)
13140 (setq c (1+ c)))
13141 (nreverse rtn)))
13143 (defun org-find-base-buffer-visiting (file)
13144 "Like `find-buffer-visiting' but alway return the base buffer and
13145 not an indirect buffer."
13146 (let ((buf (find-buffer-visiting file)))
13147 (if buf
13148 (or (buffer-base-buffer buf) buf)
13149 nil)))
13151 (defun org-image-file-name-regexp ()
13152 "Return regexp matching the file names of images."
13153 (if (fboundp 'image-file-name-regexp)
13154 (image-file-name-regexp)
13155 (let ((image-file-name-extensions
13156 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13157 "xbm" "xpm" "pbm" "pgm" "ppm")))
13158 (concat "\\."
13159 (regexp-opt (nconc (mapcar 'upcase
13160 image-file-name-extensions)
13161 image-file-name-extensions)
13163 "\\'"))))
13165 (defun org-file-image-p (file)
13166 "Return non-nil if FILE is an image."
13167 (save-match-data
13168 (string-match (org-image-file-name-regexp) file)))
13170 ;;; Paragraph filling stuff.
13171 ;; We want this to be just right, so use the full arsenal.
13173 (defun org-indent-line-function ()
13174 "Indent line like previous, but further if previous was headline or item."
13175 (interactive)
13176 (let* ((pos (point))
13177 (itemp (org-at-item-p))
13178 column bpos bcol tpos tcol bullet btype bullet-type)
13179 ;; Find the previous relevant line
13180 (beginning-of-line 1)
13181 (cond
13182 ((looking-at "#") (setq column 0))
13183 ((looking-at "\\*+ ") (setq column 0))
13185 (beginning-of-line 0)
13186 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13187 (beginning-of-line 0))
13188 (cond
13189 ((looking-at "\\*+[ \t]+")
13190 (goto-char (match-end 0))
13191 (setq column (current-column)))
13192 ((org-in-item-p)
13193 (org-beginning-of-item)
13194 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13195 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13196 (setq bpos (match-beginning 1) tpos (match-end 0)
13197 bcol (progn (goto-char bpos) (current-column))
13198 tcol (progn (goto-char tpos) (current-column))
13199 bullet (match-string 1)
13200 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13201 (if (not itemp)
13202 (setq column tcol)
13203 (goto-char pos)
13204 (beginning-of-line 1)
13205 (if (looking-at "\\S-")
13206 (progn
13207 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13208 (setq bullet (match-string 1)
13209 btype (if (string-match "[0-9]" bullet) "n" bullet))
13210 (setq column (if (equal btype bullet-type) bcol tcol)))
13211 (setq column (org-get-indentation)))))
13212 (t (setq column (org-get-indentation))))))
13213 (goto-char pos)
13214 (if (<= (current-column) (current-indentation))
13215 (org-indent-line-to column)
13216 (save-excursion (org-indent-line-to column)))
13217 (setq column (current-column))
13218 (beginning-of-line 1)
13219 (if (looking-at
13220 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13221 (replace-match (concat "\\1" (format org-property-format
13222 (match-string 2) (match-string 3)))
13223 t nil))
13224 (org-move-to-column column)))
13226 (defun org-set-autofill-regexps ()
13227 (interactive)
13228 ;; In the paragraph separator we include headlines, because filling
13229 ;; text in a line directly attached to a headline would otherwise
13230 ;; fill the headline as well.
13231 (org-set-local 'comment-start-skip "^#+[ \t]*")
13232 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13233 ;; The paragraph starter includes hand-formatted lists.
13234 (org-set-local 'paragraph-start
13235 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13236 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13237 ;; But only if the user has not turned off tables or fixed-width regions
13238 (org-set-local
13239 'auto-fill-inhibit-regexp
13240 (concat "\\*+ \\|#\\+"
13241 "\\|[ \t]*" org-keyword-time-regexp
13242 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13243 (concat
13244 "\\|[ \t]*["
13245 (if org-enable-table-editor "|" "")
13246 (if org-enable-fixed-width-editor ":" "")
13247 "]"))))
13248 ;; We use our own fill-paragraph function, to make sure that tables
13249 ;; and fixed-width regions are not wrapped. That function will pass
13250 ;; through to `fill-paragraph' when appropriate.
13251 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13252 ; Adaptive filling: To get full control, first make sure that
13253 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13254 (org-set-local 'adaptive-fill-regexp "\000")
13255 (org-set-local 'adaptive-fill-function
13256 'org-adaptive-fill-function)
13257 (org-set-local
13258 'align-mode-rules-list
13259 '((org-in-buffer-settings
13260 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13261 (modes . '(org-mode))))))
13263 (defun org-fill-paragraph (&optional justify)
13264 "Re-align a table, pass through to fill-paragraph if no table."
13265 (let ((table-p (org-at-table-p))
13266 (table.el-p (org-at-table.el-p)))
13267 (cond ((and (equal (char-after (point-at-bol)) ?*)
13268 (save-excursion (goto-char (point-at-bol))
13269 (looking-at outline-regexp)))
13270 t) ; skip headlines
13271 (table.el-p t) ; skip table.el tables
13272 (table-p (org-table-align) t) ; align org-mode tables
13273 (t nil)))) ; call paragraph-fill
13275 ;; For reference, this is the default value of adaptive-fill-regexp
13276 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13278 (defun org-adaptive-fill-function ()
13279 "Return a fill prefix for org-mode files.
13280 In particular, this makes sure hanging paragraphs for hand-formatted lists
13281 work correctly."
13282 (cond ((looking-at "#[ \t]+")
13283 (match-string 0))
13284 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13285 (save-excursion
13286 (goto-char (match-end 0))
13287 (make-string (current-column) ?\ )))
13288 (t nil)))
13290 ;;; Other stuff.
13292 (defun org-toggle-fixed-width-section (arg)
13293 "Toggle the fixed-width export.
13294 If there is no active region, the QUOTE keyword at the current headline is
13295 inserted or removed. When present, it causes the text between this headline
13296 and the next to be exported as fixed-width text, and unmodified.
13297 If there is an active region, this command adds or removes a colon as the
13298 first character of this line. If the first character of a line is a colon,
13299 this line is also exported in fixed-width font."
13300 (interactive "P")
13301 (let* ((cc 0)
13302 (regionp (org-region-active-p))
13303 (beg (if regionp (region-beginning) (point)))
13304 (end (if regionp (region-end)))
13305 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13306 (case-fold-search nil)
13307 (re "[ \t]*\\(:\\)")
13308 off)
13309 (if regionp
13310 (save-excursion
13311 (goto-char beg)
13312 (setq cc (current-column))
13313 (beginning-of-line 1)
13314 (setq off (looking-at re))
13315 (while (> nlines 0)
13316 (setq nlines (1- nlines))
13317 (beginning-of-line 1)
13318 (cond
13319 (arg
13320 (org-move-to-column cc t)
13321 (insert ":\n")
13322 (forward-line -1))
13323 ((and off (looking-at re))
13324 (replace-match "" t t nil 1))
13325 ((not off) (org-move-to-column cc t) (insert ":")))
13326 (forward-line 1)))
13327 (save-excursion
13328 (org-back-to-heading)
13329 (if (looking-at (concat outline-regexp
13330 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13331 (replace-match "" t t nil 1)
13332 (if (looking-at outline-regexp)
13333 (progn
13334 (goto-char (match-end 0))
13335 (insert org-quote-string " "))))))))
13337 ;;;; Functions extending outline functionality
13339 (defun org-beginning-of-line (&optional arg)
13340 "Go to the beginning of the current line. If that is invisible, continue
13341 to a visible line beginning. This makes the function of C-a more intuitive.
13342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13343 first attempt, and only move to after the tags when the cursor is already
13344 beyond the end of the headline."
13345 (interactive "P")
13346 (let ((pos (point)))
13347 (beginning-of-line 1)
13348 (if (bobp)
13350 (backward-char 1)
13351 (if (org-invisible-p)
13352 (while (and (not (bobp)) (org-invisible-p))
13353 (backward-char 1)
13354 (beginning-of-line 1))
13355 (forward-char 1)))
13356 (when org-special-ctrl-a/e
13357 (cond
13358 ((and (looking-at org-todo-line-regexp)
13359 (= (char-after (match-end 1)) ?\ ))
13360 (goto-char
13361 (if (eq org-special-ctrl-a/e t)
13362 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13363 ((= pos (point)) (match-beginning 3))
13364 (t (point)))
13365 (cond ((> pos (point)) (point))
13366 ((not (eq last-command this-command)) (point))
13367 (t (match-beginning 3))))))
13368 ((org-at-item-p)
13369 (goto-char
13370 (if (eq org-special-ctrl-a/e t)
13371 (cond ((> pos (match-end 4)) (match-end 4))
13372 ((= pos (point)) (match-end 4))
13373 (t (point)))
13374 (cond ((> pos (point)) (point))
13375 ((not (eq last-command this-command)) (point))
13376 (t (match-end 4))))))))))
13378 (defun org-end-of-line (&optional arg)
13379 "Go to the end of the line.
13380 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13381 first attempt, and only move to after the tags when the cursor is already
13382 beyond the end of the headline."
13383 (interactive "P")
13384 (if (or (not org-special-ctrl-a/e)
13385 (not (org-on-heading-p)))
13386 (end-of-line arg)
13387 (let ((pos (point)))
13388 (beginning-of-line 1)
13389 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13390 (if (eq org-special-ctrl-a/e t)
13391 (if (or (< pos (match-beginning 1))
13392 (= pos (match-end 0)))
13393 (goto-char (match-beginning 1))
13394 (goto-char (match-end 0)))
13395 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13396 (goto-char (match-end 0))
13397 (goto-char (match-beginning 1))))
13398 (end-of-line arg)))))
13400 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13401 (define-key org-mode-map "\C-e" 'org-end-of-line)
13403 (defun org-kill-line (&optional arg)
13404 "Kill line, to tags or end of line."
13405 (interactive "P")
13406 (cond
13407 ((or (not org-special-ctrl-k)
13408 (bolp)
13409 (not (org-on-heading-p)))
13410 (call-interactively 'kill-line))
13411 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13412 (kill-region (point) (match-beginning 1))
13413 (org-set-tags nil t))
13414 (t (kill-region (point) (point-at-eol)))))
13416 (define-key org-mode-map "\C-k" 'org-kill-line)
13418 (defun org-invisible-p ()
13419 "Check if point is at a character currently not visible."
13420 ;; Early versions of noutline don't have `outline-invisible-p'.
13421 (if (fboundp 'outline-invisible-p)
13422 (outline-invisible-p)
13423 (get-char-property (point) 'invisible)))
13425 (defun org-invisible-p2 ()
13426 "Check if point is at a character currently not visible."
13427 (save-excursion
13428 (if (and (eolp) (not (bobp))) (backward-char 1))
13429 ;; Early versions of noutline don't have `outline-invisible-p'.
13430 (if (fboundp 'outline-invisible-p)
13431 (outline-invisible-p)
13432 (get-char-property (point) 'invisible))))
13434 (defalias 'org-back-to-heading 'outline-back-to-heading)
13435 (defalias 'org-on-heading-p 'outline-on-heading-p)
13436 (defalias 'org-at-heading-p 'outline-on-heading-p)
13437 (defun org-at-heading-or-item-p ()
13438 (or (org-on-heading-p) (org-at-item-p)))
13440 (defun org-on-target-p ()
13441 (or (org-in-regexp org-radio-target-regexp)
13442 (org-in-regexp org-target-regexp)))
13444 (defun org-up-heading-all (arg)
13445 "Move to the heading line of which the present line is a subheading.
13446 This function considers both visible and invisible heading lines.
13447 With argument, move up ARG levels."
13448 (if (fboundp 'outline-up-heading-all)
13449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13452 (defun org-up-heading-safe ()
13453 "Move to the heading line of which the present line is a subheading.
13454 This version will not throw an error. It will return the level of the
13455 headline found, or nil if no higher level is found."
13456 (let ((pos (point)) start-level level
13457 (re (concat "^" outline-regexp)))
13458 (catch 'exit
13459 (outline-back-to-heading t)
13460 (setq start-level (funcall outline-level))
13461 (if (equal start-level 1) (throw 'exit nil))
13462 (while (re-search-backward re nil t)
13463 (setq level (funcall outline-level))
13464 (if (< level start-level) (throw 'exit level)))
13465 nil)))
13467 (defun org-first-sibling-p ()
13468 "Is this heading the first child of its parents?"
13469 (interactive)
13470 (let ((re (concat "^" outline-regexp))
13471 level l)
13472 (unless (org-at-heading-p t)
13473 (error "Not at a heading"))
13474 (setq level (funcall outline-level))
13475 (save-excursion
13476 (if (not (re-search-backward re nil t))
13478 (setq l (funcall outline-level))
13479 (< l level)))))
13481 (defun org-goto-sibling (&optional previous)
13482 "Goto the next sibling, even if it is invisible.
13483 When PREVIOUS is set, go to the previous sibling instead. Returns t
13484 when a sibling was found. When none is found, return nil and don't
13485 move point."
13486 (let ((fun (if previous 're-search-backward 're-search-forward))
13487 (pos (point))
13488 (re (concat "^" outline-regexp))
13489 level l)
13490 (when (condition-case nil (org-back-to-heading t) (error nil))
13491 (setq level (funcall outline-level))
13492 (catch 'exit
13493 (or previous (forward-char 1))
13494 (while (funcall fun re nil t)
13495 (setq l (funcall outline-level))
13496 (when (< l level) (goto-char pos) (throw 'exit nil))
13497 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13498 (goto-char pos)
13499 nil))))
13501 (defun org-show-siblings ()
13502 "Show all siblings of the current headline."
13503 (save-excursion
13504 (while (org-goto-sibling) (org-flag-heading nil)))
13505 (save-excursion
13506 (while (org-goto-sibling 'previous)
13507 (org-flag-heading nil))))
13509 (defun org-show-hidden-entry ()
13510 "Show an entry where even the heading is hidden."
13511 (save-excursion
13512 (org-show-entry)))
13514 (defun org-flag-heading (flag &optional entry)
13515 "Flag the current heading. FLAG non-nil means make invisible.
13516 When ENTRY is non-nil, show the entire entry."
13517 (save-excursion
13518 (org-back-to-heading t)
13519 ;; Check if we should show the entire entry
13520 (if entry
13521 (progn
13522 (org-show-entry)
13523 (save-excursion
13524 (and (outline-next-heading)
13525 (org-flag-heading nil))))
13526 (outline-flag-region (max (point-min) (1- (point)))
13527 (save-excursion (outline-end-of-heading) (point))
13528 flag))))
13530 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13531 ;; This is an exact copy of the original function, but it uses
13532 ;; `org-back-to-heading', to make it work also in invisible
13533 ;; trees. And is uses an invisible-OK argument.
13534 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13535 (org-back-to-heading invisible-OK)
13536 (let ((first t)
13537 (level (funcall outline-level)))
13538 (while (and (not (eobp))
13539 (or first (> (funcall outline-level) level)))
13540 (setq first nil)
13541 (outline-next-heading))
13542 (unless to-heading
13543 (if (memq (preceding-char) '(?\n ?\^M))
13544 (progn
13545 ;; Go to end of line before heading
13546 (forward-char -1)
13547 (if (memq (preceding-char) '(?\n ?\^M))
13548 ;; leave blank line before heading
13549 (forward-char -1))))))
13550 (point))
13552 (defun org-show-subtree ()
13553 "Show everything after this heading at deeper levels."
13554 (outline-flag-region
13555 (point)
13556 (save-excursion
13557 (outline-end-of-subtree) (outline-next-heading) (point))
13558 nil))
13560 (defun org-show-entry ()
13561 "Show the body directly following this heading.
13562 Show the heading too, if it is currently invisible."
13563 (interactive)
13564 (save-excursion
13565 (condition-case nil
13566 (progn
13567 (org-back-to-heading t)
13568 (outline-flag-region
13569 (max (point-min) (1- (point)))
13570 (save-excursion
13571 (re-search-forward
13572 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13573 (or (match-beginning 1) (point-max)))
13574 nil))
13575 (error nil))))
13577 (defun org-make-options-regexp (kwds)
13578 "Make a regular expression for keyword lines."
13579 (concat
13581 "#?[ \t]*\\+\\("
13582 (mapconcat 'regexp-quote kwds "\\|")
13583 "\\):[ \t]*"
13584 "\\(.+\\)"))
13586 ;; Make isearch reveal the necessary context
13587 (defun org-isearch-end ()
13588 "Reveal context after isearch exits."
13589 (when isearch-success ; only if search was successful
13590 (if (featurep 'xemacs)
13591 ;; Under XEmacs, the hook is run in the correct place,
13592 ;; we directly show the context.
13593 (org-show-context 'isearch)
13594 ;; In Emacs the hook runs *before* restoring the overlays.
13595 ;; So we have to use a one-time post-command-hook to do this.
13596 ;; (Emacs 22 has a special variable, see function `org-mode')
13597 (unless (and (boundp 'isearch-mode-end-hook-quit)
13598 isearch-mode-end-hook-quit)
13599 ;; Only when the isearch was not quitted.
13600 (org-add-hook 'post-command-hook 'org-isearch-post-command
13601 'append 'local)))))
13603 (defun org-isearch-post-command ()
13604 "Remove self from hook, and show context."
13605 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13606 (org-show-context 'isearch))
13609 ;;;; Integration with and fixes for other packages
13611 ;;; Imenu support
13613 (defvar org-imenu-markers nil
13614 "All markers currently used by Imenu.")
13615 (make-variable-buffer-local 'org-imenu-markers)
13617 (defun org-imenu-new-marker (&optional pos)
13618 "Return a new marker for use by Imenu, and remember the marker."
13619 (let ((m (make-marker)))
13620 (move-marker m (or pos (point)))
13621 (push m org-imenu-markers)
13624 (defun org-imenu-get-tree ()
13625 "Produce the index for Imenu."
13626 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13627 (setq org-imenu-markers nil)
13628 (let* ((n org-imenu-depth)
13629 (re (concat "^" outline-regexp))
13630 (subs (make-vector (1+ n) nil))
13631 (last-level 0)
13632 m tree level head)
13633 (save-excursion
13634 (save-restriction
13635 (widen)
13636 (goto-char (point-max))
13637 (while (re-search-backward re nil t)
13638 (setq level (org-reduced-level (funcall outline-level)))
13639 (when (<= level n)
13640 (looking-at org-complex-heading-regexp)
13641 (setq head (org-match-string-no-properties 4)
13642 m (org-imenu-new-marker))
13643 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13644 (if (>= level last-level)
13645 (push (cons head m) (aref subs level))
13646 (push (cons head (aref subs (1+ level))) (aref subs level))
13647 (loop for i from (1+ level) to n do (aset subs i nil)))
13648 (setq last-level level)))))
13649 (aref subs 1)))
13651 (eval-after-load "imenu"
13652 '(progn
13653 (add-hook 'imenu-after-jump-hook
13654 (lambda () (org-show-context 'org-goto)))))
13656 ;; Speedbar support
13658 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13659 "Overlay marking the agenda restriction line in speedbar.")
13660 (org-overlay-put org-speedbar-restriction-lock-overlay
13661 'face 'org-agenda-restriction-lock)
13662 (org-overlay-put org-speedbar-restriction-lock-overlay
13663 'help-echo "Agendas are currently limited to this item.")
13664 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13666 (defun org-speedbar-set-agenda-restriction ()
13667 "Restrict future agenda commands to the location at point in speedbar.
13668 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13669 (interactive)
13670 (require 'org-agenda)
13671 (let (p m tp np dir txt w)
13672 (cond
13673 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13674 'org-imenu t))
13675 (setq m (get-text-property p 'org-imenu-marker))
13676 (save-excursion
13677 (save-restriction
13678 (set-buffer (marker-buffer m))
13679 (goto-char m)
13680 (org-agenda-set-restriction-lock 'subtree))))
13681 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13682 'speedbar-function 'speedbar-find-file))
13683 (setq tp (previous-single-property-change
13684 (1+ p) 'speedbar-function)
13685 np (next-single-property-change
13686 tp 'speedbar-function)
13687 dir (speedbar-line-directory)
13688 txt (buffer-substring-no-properties (or tp (point-min))
13689 (or np (point-max))))
13690 (save-excursion
13691 (save-restriction
13692 (set-buffer (find-file-noselect
13693 (let ((default-directory dir))
13694 (expand-file-name txt))))
13695 (unless (org-mode-p)
13696 (error "Cannot restrict to non-Org-mode file"))
13697 (org-agenda-set-restriction-lock 'file))))
13698 (t (error "Don't know how to restrict Org-mode's agenda")))
13699 (org-move-overlay org-speedbar-restriction-lock-overlay
13700 (point-at-bol) (point-at-eol))
13701 (setq current-prefix-arg nil)
13702 (org-agenda-maybe-redo)))
13704 (eval-after-load "speedbar"
13705 '(progn
13706 (speedbar-add-supported-extension ".org")
13707 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13708 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13709 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13710 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13711 (add-hook 'speedbar-visiting-tag-hook
13712 (lambda () (org-show-context 'org-goto)))))
13715 ;;; Fixes and Hacks for problems with other packages
13717 ;; Make flyspell not check words in links, to not mess up our keymap
13718 (defun org-mode-flyspell-verify ()
13719 "Don't let flyspell put overlays at active buttons."
13720 (not (get-text-property (point) 'keymap)))
13722 ;; Make `bookmark-jump' show the jump location if it was hidden.
13723 (eval-after-load "bookmark"
13724 '(if (boundp 'bookmark-after-jump-hook)
13725 ;; We can use the hook
13726 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13727 ;; Hook not available, use advice
13728 (defadvice bookmark-jump (after org-make-visible activate)
13729 "Make the position visible."
13730 (org-bookmark-jump-unhide))))
13732 (defun org-bookmark-jump-unhide ()
13733 "Unhide the current position, to show the bookmark location."
13734 (and (org-mode-p)
13735 (or (org-invisible-p)
13736 (save-excursion (goto-char (max (point-min) (1- (point))))
13737 (org-invisible-p)))
13738 (org-show-context 'bookmark-jump)))
13740 ;; Make session.el ignore our circular variable
13741 (eval-after-load "session"
13742 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13744 ;;;; Experimental code
13746 (defun org-closed-in-range ()
13747 "Sparse tree of items closed in a certain time range.
13748 Still experimental, may disappear in the future."
13749 (interactive)
13750 ;; Get the time interval from the user.
13751 (let* ((time1 (time-to-seconds
13752 (org-read-date nil 'to-time nil "Starting date: ")))
13753 (time2 (time-to-seconds
13754 (org-read-date nil 'to-time nil "End date:")))
13755 ;; callback function
13756 (callback (lambda ()
13757 (let ((time
13758 (time-to-seconds
13759 (apply 'encode-time
13760 (org-parse-time-string
13761 (match-string 1))))))
13762 ;; check if time in interval
13763 (and (>= time time1) (<= time time2))))))
13764 ;; make tree, check each match with the callback
13765 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13768 ;;;; Finish up
13770 (provide 'org)
13772 (run-hooks 'org-load-hook)
13774 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13776 ;;; org.el ends here