Improvements to contrib/lisp/org-eval.el
[org-mode.git] / lisp / org.el
bloba34d7e91ceeef350784017e3698f0ce7a415d88e
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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.02b"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (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)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C eval: Include command output as text" org-eval)
178 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
179 (const :tag "C id: Global id's for identifying entries" org-id)
180 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
181 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
182 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
183 (const :tag "C mew: Support for links to messages in Mew" org-mew)
184 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
185 (const :tag "C registry: A registry for Org links" org-registry)
186 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
187 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
188 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
189 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
190 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
193 (defgroup org-startup nil
194 "Options concerning startup of Org-mode."
195 :tag "Org Startup"
196 :group 'org)
198 (defcustom org-startup-folded t
199 "Non-nil means, entering Org-mode will switch to OVERVIEW.
200 This can also be configured on a per-file basis by adding one of
201 the following lines anywhere in the buffer:
203 #+STARTUP: fold
204 #+STARTUP: nofold
205 #+STARTUP: content"
206 :group 'org-startup
207 :type '(choice
208 (const :tag "nofold: show all" nil)
209 (const :tag "fold: overview" t)
210 (const :tag "content: all headlines" content)))
212 (defcustom org-startup-truncated t
213 "Non-nil means, entering Org-mode will set `truncate-lines'.
214 This is useful since some lines containing links can be very long and
215 uninteresting. Also tables look terrible when wrapped."
216 :group 'org-startup
217 :type 'boolean)
219 (defcustom org-startup-align-all-tables nil
220 "Non-nil means, align all tables when visiting a file.
221 This is useful when the column width in tables is forced with <N> cookies
222 in table fields. Such tables will look correct only after the first re-align.
223 This can also be configured on a per-file basis by adding one of
224 the following lines anywhere in the buffer:
225 #+STARTUP: align
226 #+STARTUP: noalign"
227 :group 'org-startup
228 :type 'boolean)
230 (defcustom org-insert-mode-line-in-empty-file nil
231 "Non-nil means insert the first line setting Org-mode in empty files.
232 When the function `org-mode' is called interactively in an empty file, this
233 normally means that the file name does not automatically trigger Org-mode.
234 To ensure that the file will always be in Org-mode in the future, a
235 line enforcing Org-mode will be inserted into the buffer, if this option
236 has been set."
237 :group 'org-startup
238 :type 'boolean)
240 (defcustom org-replace-disputed-keys nil
241 "Non-nil means use alternative key bindings for some keys.
242 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
243 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
244 If you want to use Org-mode together with one of these other modes,
245 or more generally if you would like to move some Org-mode commands to
246 other keys, set this variable and configure the keys with the variable
247 `org-disputed-keys'.
249 This option is only relevant at load-time of Org-mode, and must be set
250 *before* org.el is loaded. Changing it requires a restart of Emacs to
251 become effective."
252 :group 'org-startup
253 :type 'boolean)
255 (if (fboundp 'defvaralias)
256 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
258 (defcustom org-disputed-keys
259 '(([(shift up)] . [(meta p)])
260 ([(shift down)] . [(meta n)])
261 ([(shift left)] . [(meta -)])
262 ([(shift right)] . [(meta +)])
263 ([(control shift right)] . [(meta shift +)])
264 ([(control shift left)] . [(meta shift -)]))
265 "Keys for which Org-mode and other modes compete.
266 This is an alist, cars are the default keys, second element specifies
267 the alternative to use when `org-replace-disputed-keys' is t.
269 Keys can be specified in any syntax supported by `define-key'.
270 The value of this option takes effect only at Org-mode's startup,
271 therefore you'll have to restart Emacs to apply it after changing."
272 :group 'org-startup
273 :type 'alist)
275 (defun org-key (key)
276 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
277 Or return the original if not disputed."
278 (if org-replace-disputed-keys
279 (let* ((nkey (key-description key))
280 (x (org-find-if (lambda (x)
281 (equal (key-description (car x)) nkey))
282 org-disputed-keys)))
283 (if x (cdr x) key))
284 key))
286 (defun org-find-if (predicate seq)
287 (catch 'exit
288 (while seq
289 (if (funcall predicate (car seq))
290 (throw 'exit (car seq))
291 (pop seq)))))
293 (defun org-defkey (keymap key def)
294 "Define a key, possibly translated, as returned by `org-key'."
295 (define-key keymap (org-key key) def))
297 (defcustom org-ellipsis nil
298 "The ellipsis to use in the Org-mode outline.
299 When nil, just use the standard three dots. When a string, use that instead,
300 When a face, use the standart 3 dots, but with the specified face.
301 The change affects only Org-mode (which will then use its own display table).
302 Changing this requires executing `M-x org-mode' in a buffer to become
303 effective."
304 :group 'org-startup
305 :type '(choice (const :tag "Default" nil)
306 (face :tag "Face" :value org-warning)
307 (string :tag "String" :value "...#")))
309 (defvar org-display-table nil
310 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
312 (defgroup org-keywords nil
313 "Keywords in Org-mode."
314 :tag "Org Keywords"
315 :group 'org)
317 (defcustom org-deadline-string "DEADLINE:"
318 "String to mark deadline entries.
319 A deadline is this string, followed by a time stamp. Should be a word,
320 terminated by a colon. You can insert a schedule keyword and
321 a timestamp with \\[org-deadline].
322 Changes become only effective after restarting Emacs."
323 :group 'org-keywords
324 :type 'string)
326 (defcustom org-scheduled-string "SCHEDULED:"
327 "String to mark scheduled TODO entries.
328 A schedule is this string, followed by a time stamp. Should be a word,
329 terminated by a colon. You can insert a schedule keyword and
330 a timestamp with \\[org-schedule].
331 Changes become only effective after restarting Emacs."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-closed-string "CLOSED:"
336 "String used as the prefix for timestamps logging closing a TODO entry."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-clock-string "CLOCK:"
341 "String used as prefix for timestamps clocking work hours on an item."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-comment-string "COMMENT"
346 "Entries starting with this keyword will never be exported.
347 An entry can be toggled between COMMENT and normal with
348 \\[org-toggle-comment].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-quote-string "QUOTE"
354 "Entries starting with this keyword will be exported in fixed-width font.
355 Quoting applies only to the text in the entry following the headline, and does
356 not extend beyond the next headline, even if that is lower level.
357 An entry can be toggled between QUOTE and normal with
358 \\[org-toggle-fixed-width-section]."
359 :group 'org-keywords
360 :type 'string)
362 (defconst org-repeat-re
363 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
364 "Regular expression for specifying repeated events.
365 After a match, group 1 contains the repeat expression.")
367 (defgroup org-structure nil
368 "Options concerning the general structure of Org-mode files."
369 :tag "Org Structure"
370 :group 'org)
372 (defgroup org-reveal-location nil
373 "Options about how to make context of a location visible."
374 :tag "Org Reveal Location"
375 :group 'org-structure)
377 (defconst org-context-choice
378 '(choice
379 (const :tag "Always" t)
380 (const :tag "Never" nil)
381 (repeat :greedy t :tag "Individual contexts"
382 (cons
383 (choice :tag "Context"
384 (const agenda)
385 (const org-goto)
386 (const occur-tree)
387 (const tags-tree)
388 (const link-search)
389 (const mark-goto)
390 (const bookmark-jump)
391 (const isearch)
392 (const default))
393 (boolean))))
394 "Contexts for the reveal options.")
396 (defcustom org-show-hierarchy-above '((default . t))
397 "Non-nil means, show full hierarchy when revealing a location.
398 Org-mode often shows locations in an org-mode file which might have
399 been invisible before. When this is set, the hierarchy of headings
400 above the exposed location is shown.
401 Turning this off for example for sparse trees makes them very compact.
402 Instead of t, this can also be an alist specifying this option for different
403 contexts. Valid contexts are
404 agenda when exposing an entry from the agenda
405 org-goto when using the command `org-goto' on key C-c C-j
406 occur-tree when using the command `org-occur' on key C-c /
407 tags-tree when constructing a sparse tree based on tags matches
408 link-search when exposing search matches associated with a link
409 mark-goto when exposing the jump goal of a mark
410 bookmark-jump when exposing a bookmark location
411 isearch when exiting from an incremental search
412 default default for all contexts not set explicitly"
413 :group 'org-reveal-location
414 :type org-context-choice)
416 (defcustom org-show-following-heading '((default . nil))
417 "Non-nil means, show following heading when revealing a location.
418 Org-mode often shows locations in an org-mode file which might have
419 been invisible before. When this is set, the heading following the
420 match is shown.
421 Turning this off for example for sparse trees makes them very compact,
422 but makes it harder to edit the location of the match. In such a case,
423 use the command \\[org-reveal] to show more context.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. See `org-show-hierarchy-above' for valid contexts."
426 :group 'org-reveal-location
427 :type org-context-choice)
429 (defcustom org-show-siblings '((default . nil) (isearch t))
430 "Non-nil means, show all sibling heading when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the sibling of the current entry
433 heading are all made visible. If `org-show-hierarchy-above' is t,
434 the same happens on each level of the hierarchy above the current entry.
436 By default this is on for the isearch context, off for all other contexts.
437 Turning this off for example for sparse trees makes them very compact,
438 but makes it harder to edit the location of the match. In such a case,
439 use the command \\[org-reveal] to show more context.
440 Instead of t, this can also be an alist specifying this option for different
441 contexts. See `org-show-hierarchy-above' for valid contexts."
442 :group 'org-reveal-location
443 :type org-context-choice)
445 (defcustom org-show-entry-below '((default . nil))
446 "Non-nil means, show the entry below a headline when revealing a location.
447 Org-mode often shows locations in an org-mode file which might have
448 been invisible before. When this is set, the text below the headline that is
449 exposed is also shown.
451 By default this is off for all contexts.
452 Instead of t, this can also be an alist specifying this option for different
453 contexts. See `org-show-hierarchy-above' for valid contexts."
454 :group 'org-reveal-location
455 :type org-context-choice)
457 (defcustom org-indirect-buffer-display 'other-window
458 "How should indirect tree buffers be displayed?
459 This applies to indirect buffers created with the commands
460 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
461 Valid values are:
462 current-window Display in the current window
463 other-window Just display in another window.
464 dedicated-frame Create one new frame, and re-use it each time.
465 new-frame Make a new frame each time. Note that in this case
466 previously-made indirect buffers are kept, and you need to
467 kill these buffers yourself."
468 :group 'org-structure
469 :group 'org-agenda-windows
470 :type '(choice
471 (const :tag "In current window" current-window)
472 (const :tag "In current frame, other window" other-window)
473 (const :tag "Each time a new frame" new-frame)
474 (const :tag "One dedicated frame" dedicated-frame)))
476 (defgroup org-cycle nil
477 "Options concerning visibility cycling in Org-mode."
478 :tag "Org Cycle"
479 :group 'org-structure)
481 (defcustom org-drawers '("PROPERTIES" "CLOCK")
482 "Names of drawers. Drawers are not opened by cycling on the headline above.
483 Drawers only open with a TAB on the drawer line itself. A drawer looks like
484 this:
485 :DRAWERNAME:
486 .....
487 :END:
488 The drawer \"PROPERTIES\" is special for capturing properties through
489 the property API.
491 Drawers can be defined on the per-file basis with a line like:
493 #+DRAWERS: HIDDEN STATE PROPERTIES"
494 :group 'org-structure
495 :type '(repeat (string :tag "Drawer Name")))
497 (defcustom org-cycle-global-at-bob nil
498 "Cycle globally if cursor is at beginning of buffer and not at a headline.
499 This makes it possible to do global cycling without having to use S-TAB or
500 C-u TAB. For this special case to work, the first line of the buffer
501 must not be a headline - it may be empty ot some other text. When used in
502 this way, `org-cycle-hook' is disables temporarily, to make sure the
503 cursor stays at the beginning of the buffer.
504 When this option is nil, don't do anything special at the beginning
505 of the buffer."
506 :group 'org-cycle
507 :type 'boolean)
509 (defcustom org-cycle-emulate-tab t
510 "Where should `org-cycle' emulate TAB.
511 nil Never
512 white Only in completely white lines
513 whitestart Only at the beginning of lines, before the first non-white char
514 t Everywhere except in headlines
515 exc-hl-bol Everywhere except at the start of a headline
516 If TAB is used in a place where it does not emulate TAB, the current subtree
517 visibility is cycled."
518 :group 'org-cycle
519 :type '(choice (const :tag "Never" nil)
520 (const :tag "Only in completely white lines" white)
521 (const :tag "Before first char in a line" whitestart)
522 (const :tag "Everywhere except in headlines" t)
523 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
526 (defcustom org-cycle-separator-lines 2
527 "Number of empty lines needed to keep an empty line between collapsed trees.
528 If you leave an empty line between the end of a subtree and the following
529 headline, this empty line is hidden when the subtree is folded.
530 Org-mode will leave (exactly) one empty line visible if the number of
531 empty lines is equal or larger to the number given in this variable.
532 So the default 2 means, at least 2 empty lines after the end of a subtree
533 are needed to produce free space between a collapsed subtree and the
534 following headline.
536 Special case: when 0, never leave empty lines in collapsed view."
537 :group 'org-cycle
538 :type 'integer)
540 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
541 org-cycle-hide-drawers
542 org-cycle-show-empty-lines
543 org-optimize-window-after-visibility-change)
544 "Hook that is run after `org-cycle' has changed the buffer visibility.
545 The function(s) in this hook must accept a single argument which indicates
546 the new state that was set by the most recent `org-cycle' command. The
547 argument is a symbol. After a global state change, it can have the values
548 `overview', `content', or `all'. After a local state change, it can have
549 the values `folded', `children', or `subtree'."
550 :group 'org-cycle
551 :type 'hook)
553 (defgroup org-edit-structure nil
554 "Options concerning structure editing in Org-mode."
555 :tag "Org Edit Structure"
556 :group 'org-structure)
558 (defcustom org-odd-levels-only nil
559 "Non-nil means, skip even levels and only use odd levels for the outline.
560 This has the effect that two stars are being added/taken away in
561 promotion/demotion commands. It also influences how levels are
562 handled by the exporters.
563 Changing it requires restart of `font-lock-mode' to become effective
564 for fontification also in regions already fontified.
565 You may also set this on a per-file basis by adding one of the following
566 lines to the buffer:
568 #+STARTUP: odd
569 #+STARTUP: oddeven"
570 :group 'org-edit-structure
571 :group 'org-font-lock
572 :type 'boolean)
574 (defcustom org-adapt-indentation t
575 "Non-nil means, adapt indentation when promoting and demoting.
576 When this is set and the *entire* text in an entry is indented, the
577 indentation is increased by one space in a demotion command, and
578 decreased by one in a promotion command. If any line in the entry
579 body starts at column 0, indentation is not changed at all."
580 :group 'org-edit-structure
581 :type 'boolean)
583 (defcustom org-special-ctrl-a/e nil
584 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
585 When t, `C-a' will bring back the cursor to the beginning of the
586 headline text, i.e. after the stars and after a possible TODO keyword.
587 In an item, this will be the position after the bullet.
588 When the cursor is already at that position, another `C-a' will bring
589 it to the beginning of the line.
590 `C-e' will jump to the end of the headline, ignoring the presence of tags
591 in the headline. A second `C-e' will then jump to the true end of the
592 line, after any tags.
593 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
594 and only a directly following, identical keypress will bring the cursor
595 to the special positions."
596 :group 'org-edit-structure
597 :type '(choice
598 (const :tag "off" nil)
599 (const :tag "after bullet first" t)
600 (const :tag "border first" reversed)))
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
605 (defcustom org-special-ctrl-k nil
606 "Non-nil means `C-k' will behave specially in headlines.
607 When nil, `C-k' will call the default `kill-line' command.
608 When t, the following will happen while the cursor is in the headline:
610 - When the cursor is at the beginning of a headline, kill the entire
611 line and possible the folded subtree below the line.
612 - When in the middle of the headline text, kill the headline up to the tags.
613 - When after the headline text, kill the tags."
614 :group 'org-edit-structure
615 :type 'boolean)
617 (defcustom org-M-RET-may-split-line '((default . t))
618 "Non-nil means, M-RET will split the line at the cursor position.
619 When nil, it will go to the end of the line before making a
620 new line.
621 You may also set this option in a different way for different
622 contexts. Valid contexts are:
624 headline when creating a new headline
625 item when creating a new item
626 table in a table field
627 default the value to be used for all contexts not explicitly
628 customized"
629 :group 'org-structure
630 :group 'org-table
631 :type '(choice
632 (const :tag "Always" t)
633 (const :tag "Never" nil)
634 (repeat :greedy t :tag "Individual contexts"
635 (cons
636 (choice :tag "Context"
637 (const headline)
638 (const item)
639 (const table)
640 (const default))
641 (boolean)))))
644 (defcustom org-blank-before-new-entry '((heading . nil)
645 (plain-list-item . nil))
646 "Should `org-insert-heading' leave a blank line before new heading/item?
647 The value is an alist, with `heading' and `plain-list-item' as car,
648 and a boolean flag as cdr."
649 :group 'org-edit-structure
650 :type '(list
651 (cons (const heading) (boolean))
652 (cons (const plain-list-item) (boolean))))
654 (defcustom org-insert-heading-hook nil
655 "Hook being run after inserting a new heading."
656 :group 'org-edit-structure
657 :type 'hook)
659 (defcustom org-enable-fixed-width-editor t
660 "Non-nil means, lines starting with \":\" are treated as fixed-width.
661 This currently only means, they are never auto-wrapped.
662 When nil, such lines will be treated like ordinary lines.
663 See also the QUOTE keyword."
664 :group 'org-edit-structure
665 :type 'boolean)
667 (defcustom org-goto-auto-isearch t
668 "Non-nil means, typing characters in org-goto starts incremental search."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defgroup org-sparse-trees nil
673 "Options concerning sparse trees in Org-mode."
674 :tag "Org Sparse Trees"
675 :group 'org-structure)
677 (defcustom org-highlight-sparse-tree-matches t
678 "Non-nil means, highlight all matches that define a sparse tree.
679 The highlights will automatically disappear the next time the buffer is
680 changed by an edit command."
681 :group 'org-sparse-trees
682 :type 'boolean)
684 (defcustom org-remove-highlights-with-change t
685 "Non-nil means, any change to the buffer will remove temporary highlights.
686 Such highlights are created by `org-occur' and `org-clock-display'.
687 When nil, `C-c C-c needs to be used to get rid of the highlights.
688 The highlights created by `org-preview-latex-fragment' always need
689 `C-c C-c' to be removed."
690 :group 'org-sparse-trees
691 :group 'org-time
692 :type 'boolean)
695 (defcustom org-occur-hook '(org-first-headline-recenter)
696 "Hook that is run after `org-occur' has constructed a sparse tree.
697 This can be used to recenter the window to show as much of the structure
698 as possible."
699 :group 'org-sparse-trees
700 :type 'hook)
702 (defgroup org-plain-lists nil
703 "Options concerning plain lists in Org-mode."
704 :tag "Org Plain lists"
705 :group 'org-structure)
707 (defcustom org-cycle-include-plain-lists nil
708 "Non-nil means, include plain lists into visibility cycling.
709 This means that during cycling, plain list items will *temporarily* be
710 interpreted as outline headlines with a level given by 1000+i where i is the
711 indentation of the bullet. In all other operations, plain list items are
712 not seen as headlines. For example, you cannot assign a TODO keyword to
713 such an item."
714 :group 'org-plain-lists
715 :type 'boolean)
717 (defcustom org-plain-list-ordered-item-terminator t
718 "The character that makes a line with leading number an ordered list item.
719 Valid values are ?. and ?\). To get both terminators, use t. While
720 ?. may look nicer, it creates the danger that a line with leading
721 number may be incorrectly interpreted as an item. ?\) therefore is
722 the safe choice."
723 :group 'org-plain-lists
724 :type '(choice (const :tag "dot like in \"2.\"" ?.)
725 (const :tag "paren like in \"2)\"" ?\))
726 (const :tab "both" t)))
728 (defcustom org-empty-line-terminates-plain-lists nil
729 "Non-nil means, an empty line ends all plain list levels.
730 When nil, empty lines are part of the preceeding item."
731 :group 'org-plain-lists
732 :type 'boolean)
734 (defcustom org-auto-renumber-ordered-lists t
735 "Non-nil means, automatically renumber ordered plain lists.
736 Renumbering happens when the sequence have been changed with
737 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
738 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
739 :group 'org-plain-lists
740 :type 'boolean)
742 (defcustom org-provide-checkbox-statistics t
743 "Non-nil means, update checkbox statistics after insert and toggle.
744 When this is set, checkbox statistics is updated each time you either insert
745 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
746 with \\[org-ctrl-c-ctrl-c\\]."
747 :group 'org-plain-lists
748 :type 'boolean)
751 (defgroup org-imenu-and-speedbar nil
752 "Options concerning imenu and speedbar in Org-mode."
753 :tag "Org Imenu and Speedbar"
754 :group 'org-structure)
756 (defcustom org-imenu-depth 2
757 "The maximum level for Imenu access to Org-mode headlines.
758 This also applied for speedbar access."
759 :group 'org-imenu-and-speedbar
760 :type 'number)
762 (defgroup org-table nil
763 "Options concerning tables in Org-mode."
764 :tag "Org Table"
765 :group 'org)
767 (defcustom org-enable-table-editor 'optimized
768 "Non-nil means, lines starting with \"|\" are handled by the table editor.
769 When nil, such lines will be treated like ordinary lines.
771 When equal to the symbol `optimized', the table editor will be optimized to
772 do the following:
773 - Automatic overwrite mode in front of whitespace in table fields.
774 This makes the structure of the table stay in tact as long as the edited
775 field does not exceed the column width.
776 - Minimize the number of realigns. Normally, the table is aligned each time
777 TAB or RET are pressed to move to another field. With optimization this
778 happens only if changes to a field might have changed the column width.
779 Optimization requires replacing the functions `self-insert-command',
780 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
781 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
782 very good at guessing when a re-align will be necessary, but you can always
783 force one with \\[org-ctrl-c-ctrl-c].
785 If you would like to use the optimized version in Org-mode, but the
786 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
788 This variable can be used to turn on and off the table editor during a session,
789 but in order to toggle optimization, a restart is required.
791 See also the variable `org-table-auto-blank-field'."
792 :group 'org-table
793 :type '(choice
794 (const :tag "off" nil)
795 (const :tag "on" t)
796 (const :tag "on, optimized" optimized)))
798 (defcustom org-table-tab-recognizes-table.el t
799 "Non-nil means, TAB will automatically notice a table.el table.
800 When it sees such a table, it moves point into it and - if necessary -
801 calls `table-recognize-table'."
802 :group 'org-table-editing
803 :type 'boolean)
805 (defgroup org-link nil
806 "Options concerning links in Org-mode."
807 :tag "Org Link"
808 :group 'org)
810 (defvar org-link-abbrev-alist-local nil
811 "Buffer-local version of `org-link-abbrev-alist', which see.
812 The value of this is taken from the #+LINK lines.")
813 (make-variable-buffer-local 'org-link-abbrev-alist-local)
815 (defcustom org-link-abbrev-alist nil
816 "Alist of link abbreviations.
817 The car of each element is a string, to be replaced at the start of a link.
818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
819 links in Org-mode buffers can have an optional tag after a double colon, e.g.
821 [[linkkey:tag][description]]
823 If REPLACE is a string, the tag will simply be appended to create the link.
824 If the string contains \"%s\", the tag will be inserted there.
826 REPLACE may also be a function that will be called with the tag as the
827 only argument to create the link, which should be returned as a string.
829 See the manual for examples."
830 :group 'org-link
831 :type 'alist)
833 (defcustom org-descriptive-links t
834 "Non-nil means, hide link part and only show description of bracket links.
835 Bracket links are like [[link][descritpion]]. This variable sets the initial
836 state in new org-mode buffers. The setting can then be toggled on a
837 per-buffer basis from the Org->Hyperlinks menu."
838 :group 'org-link
839 :type 'boolean)
841 (defcustom org-link-file-path-type 'adaptive
842 "How the path name in file links should be stored.
843 Valid values are:
845 relative Relative to the current directory, i.e. the directory of the file
846 into which the link is being inserted.
847 absolute Absolute path, if possible with ~ for home directory.
848 noabbrev Absolute path, no abbreviation of home directory.
849 adaptive Use relative path for files in the current directory and sub-
850 directories of it. For other files, use an absolute path."
851 :group 'org-link
852 :type '(choice
853 (const relative)
854 (const absolute)
855 (const noabbrev)
856 (const adaptive)))
858 (defcustom org-activate-links '(bracket angle plain radio tag date)
859 "Types of links that should be activated in Org-mode files.
860 This is a list of symbols, each leading to the activation of a certain link
861 type. In principle, it does not hurt to turn on most link types - there may
862 be a small gain when turning off unused link types. The types are:
864 bracket The recommended [[link][description]] or [[link]] links with hiding.
865 angular Links in angular brackes that may contain whitespace like
866 <bbdb:Carsten Dominik>.
867 plain Plain links in normal text, no whitespace, like http://google.com.
868 radio Text that is matched by a radio target, see manual for details.
869 tag Tag settings in a headline (link to tag search).
870 date Time stamps (link to calendar).
872 Changing this variable requires a restart of Emacs to become effective."
873 :group 'org-link
874 :type '(set (const :tag "Double bracket links (new style)" bracket)
875 (const :tag "Angular bracket links (old style)" angular)
876 (const :tag "Plain text links" plain)
877 (const :tag "Radio target matches" radio)
878 (const :tag "Tags" tag)
879 (const :tag "Timestamps" date)))
881 (defcustom org-make-link-description-function nil
882 "Function to use to generate link descriptions from links. If
883 nil the link location will be used. This function must take two
884 parameters; the first is the link and the second the description
885 org-insert-link has generated, and should return the description
886 to use."
887 :group 'org-link
888 :type 'function)
890 (defgroup org-link-store nil
891 "Options concerning storing links in Org-mode."
892 :tag "Org Store Link"
893 :group 'org-link)
895 (defcustom org-email-link-description-format "Email %c: %.30s"
896 "Format of the description part of a link to an email or usenet message.
897 The following %-excapes will be replaced by corresponding information:
899 %F full \"From\" field
900 %f name, taken from \"From\" field, address if no name
901 %T full \"To\" field
902 %t first name in \"To\" field, address if no name
903 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
904 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
905 %s subject
906 %m message-id.
908 You may use normal field width specification between the % and the letter.
909 This is for example useful to limit the length of the subject.
911 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
912 :group 'org-link-store
913 :type 'string)
915 (defcustom org-from-is-user-regexp
916 (let (r1 r2)
917 (when (and user-mail-address (not (string= user-mail-address "")))
918 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
919 (when (and user-full-name (not (string= user-full-name "")))
920 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
921 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
922 "Regexp mached against the \"From:\" header of an email or usenet message.
923 It should match if the message is from the user him/herself."
924 :group 'org-link-store
925 :type 'regexp)
927 (defcustom org-context-in-file-links t
928 "Non-nil means, file links from `org-store-link' contain context.
929 A search string will be added to the file name with :: as separator and
930 used to find the context when the link is activated by the command
931 `org-open-at-point'.
932 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
933 negates this setting for the duration of the command."
934 :group 'org-link-store
935 :type 'boolean)
937 (defcustom org-keep-stored-link-after-insertion nil
938 "Non-nil means, keep link in list for entire session.
940 The command `org-store-link' adds a link pointing to the current
941 location to an internal list. These links accumulate during a session.
942 The command `org-insert-link' can be used to insert links into any
943 Org-mode file (offering completion for all stored links). When this
944 option is nil, every link which has been inserted once using \\[org-insert-link]
945 will be removed from the list, to make completing the unused links
946 more efficient."
947 :group 'org-link-store
948 :type 'boolean)
950 (defgroup org-link-follow nil
951 "Options concerning following links in Org-mode."
952 :tag "Org Follow Link"
953 :group 'org-link)
955 (defcustom org-follow-link-hook nil
956 "Hook that is run after a link has been followed."
957 :group 'org-link-follow
958 :type 'hook)
960 (defcustom org-tab-follows-link nil
961 "Non-nil means, on links TAB will follow the link.
962 Needs to be set before org.el is loaded."
963 :group 'org-link-follow
964 :type 'boolean)
966 (defcustom org-return-follows-link nil
967 "Non-nil means, on links RET will follow the link.
968 Needs to be set before org.el is loaded."
969 :group 'org-link-follow
970 :type 'boolean)
972 (defcustom org-mouse-1-follows-link
973 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
974 "Non-nil means, mouse-1 on a link will follow the link.
975 A longer mouse click will still set point. Does not work on XEmacs.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-mark-ring-length 4
981 "Number of different positions to be recorded in the ring
982 Changing this requires a restart of Emacs to work correctly."
983 :group 'org-link-follow
984 :type 'interger)
986 (defcustom org-link-frame-setup
987 '((vm . vm-visit-folder-other-frame)
988 (gnus . gnus-other-frame)
989 (file . find-file-other-window))
990 "Setup the frame configuration for following links.
991 When following a link with Emacs, it may often be useful to display
992 this link in another window or frame. This variable can be used to
993 set this up for the different types of links.
994 For VM, use any of
995 `vm-visit-folder'
996 `vm-visit-folder-other-frame'
997 For Gnus, use any of
998 `gnus'
999 `gnus-other-frame'
1000 For FILE, use any of
1001 `find-file'
1002 `find-file-other-window'
1003 `find-file-other-frame'
1004 For the calendar, use the variable `calendar-setup'.
1005 For BBDB, it is currently only possible to display the matches in
1006 another window."
1007 :group 'org-link-follow
1008 :type '(list
1009 (cons (const vm)
1010 (choice
1011 (const vm-visit-folder)
1012 (const vm-visit-folder-other-window)
1013 (const vm-visit-folder-other-frame)))
1014 (cons (const gnus)
1015 (choice
1016 (const gnus)
1017 (const gnus-other-frame)))
1018 (cons (const file)
1019 (choice
1020 (const find-file)
1021 (const find-file-other-window)
1022 (const find-file-other-frame)))))
1024 (defcustom org-display-internal-link-with-indirect-buffer nil
1025 "Non-nil means, use indirect buffer to display infile links.
1026 Activating internal links (from one location in a file to another location
1027 in the same file) normally just jumps to the location. When the link is
1028 activated with a C-u prefix (or with mouse-3), the link is displayed in
1029 another window. When this option is set, the other window actually displays
1030 an indirect buffer clone of the current buffer, to avoid any visibility
1031 changes to the current buffer."
1032 :group 'org-link-follow
1033 :type 'boolean)
1035 (defcustom org-open-non-existing-files nil
1036 "Non-nil means, `org-open-file' will open non-existing files.
1037 When nil, an error will be generated."
1038 :group 'org-link-follow
1039 :type 'boolean)
1041 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1042 "Function and arguments to call for following mailto links.
1043 This is a list with the first element being a lisp function, and the
1044 remaining elements being arguments to the function. In string arguments,
1045 %a will be replaced by the address, and %s will be replaced by the subject
1046 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1047 :group 'org-link-follow
1048 :type '(choice
1049 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1050 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1051 (const :tag "message-mail" (message-mail "%a" "%s"))
1052 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1054 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1055 "Non-nil means, ask for confirmation before executing shell links.
1056 Shell links can be dangerous: just think about a link
1058 [[shell:rm -rf ~/*][Google Search]]
1060 This link would show up in your Org-mode document as \"Google Search\",
1061 but really it would remove your entire home directory.
1062 Therefore we advise against setting this variable to nil.
1063 Just change it to `y-or-n-p' of you want to confirm with a
1064 single keystroke rather than having to type \"yes\"."
1065 :group 'org-link-follow
1066 :type '(choice
1067 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1068 (const :tag "with y-or-n (faster)" y-or-n-p)
1069 (const :tag "no confirmation (dangerous)" nil)))
1071 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1072 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1073 Elisp links can be dangerous: just think about a link
1075 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1077 This link would show up in your Org-mode document as \"Google Search\",
1078 but really it would remove your entire home directory.
1079 Therefore we advise against setting this variable to nil.
1080 Just change it to `y-or-n-p' of you want to confirm with a
1081 single keystroke rather than having to type \"yes\"."
1082 :group 'org-link-follow
1083 :type '(choice
1084 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1085 (const :tag "with y-or-n (faster)" y-or-n-p)
1086 (const :tag "no confirmation (dangerous)" nil)))
1088 (defconst org-file-apps-defaults-gnu
1089 '((remote . emacs)
1090 (t . mailcap))
1091 "Default file applications on a UNIX or GNU/Linux system.
1092 See `org-file-apps'.")
1094 (defconst org-file-apps-defaults-macosx
1095 '((remote . emacs)
1096 (t . "open %s")
1097 ("ps" . "gv %s")
1098 ("ps.gz" . "gv %s")
1099 ("eps" . "gv %s")
1100 ("eps.gz" . "gv %s")
1101 ("dvi" . "xdvi %s")
1102 ("fig" . "xfig %s"))
1103 "Default file applications on a MacOS X system.
1104 The system \"open\" is known as a default, but we use X11 applications
1105 for some files for which the OS does not have a good default.
1106 See `org-file-apps'.")
1108 (defconst org-file-apps-defaults-windowsnt
1109 (list
1110 '(remote . emacs)
1111 (cons t
1112 (list (if (featurep 'xemacs)
1113 'mswindows-shell-execute
1114 'w32-shell-execute)
1115 "open" 'file)))
1116 "Default file applications on a Windows NT system.
1117 The system \"open\" is used for most files.
1118 See `org-file-apps'.")
1120 (defcustom org-file-apps
1122 ("txt" . emacs)
1123 ("tex" . emacs)
1124 ("ltx" . emacs)
1125 ("org" . emacs)
1126 ("el" . emacs)
1127 ("bib" . emacs)
1129 "External applications for opening `file:path' items in a document.
1130 Org-mode uses system defaults for different file types, but
1131 you can use this variable to set the application for a given file
1132 extension. The entries in this list are cons cells where the car identifies
1133 files and the cdr the corresponding command. Possible values for the
1134 file identifier are
1135 \"ext\" A string identifying an extension
1136 `directory' Matches a directory
1137 `remote' Matches a remote file, accessible through tramp or efs.
1138 Remote files most likely should be visited through Emacs
1139 because external applications cannot handle such paths.
1140 t Default for all remaining files
1142 Possible values for the command are:
1143 `emacs' The file will be visited by the current Emacs process.
1144 `default' Use the default application for this file type.
1145 string A command to be executed by a shell; %s will be replaced
1146 by the path to the file.
1147 sexp A Lisp form which will be evaluated. The file path will
1148 be available in the Lisp variable `file'.
1149 For more examples, see the system specific constants
1150 `org-file-apps-defaults-macosx'
1151 `org-file-apps-defaults-windowsnt'
1152 `org-file-apps-defaults-gnu'."
1153 :group 'org-link-follow
1154 :type '(repeat
1155 (cons (choice :value ""
1156 (string :tag "Extension")
1157 (const :tag "Default for unrecognized files" t)
1158 (const :tag "Remote file" remote)
1159 (const :tag "Links to a directory" directory))
1160 (choice :value ""
1161 (const :tag "Visit with Emacs" emacs)
1162 (const :tag "Use system default" default)
1163 (string :tag "Command")
1164 (sexp :tag "Lisp form")))))
1166 (defgroup org-refile nil
1167 "Options concerning refiling entries in Org-mode."
1168 :tag "Org Remember"
1169 :group 'org)
1171 (defcustom org-directory "~/org"
1172 "Directory with org files.
1173 This directory will be used as default to prompt for org files.
1174 Used by the hooks for remember.el."
1175 :group 'org-refile
1176 :group 'org-remember
1177 :type 'directory)
1179 (defcustom org-default-notes-file "~/.notes"
1180 "Default target for storing notes.
1181 Used by the hooks for remember.el. This can be a string, or nil to mean
1182 the value of `remember-data-file'.
1183 You can set this on a per-template basis with the variable
1184 `org-remember-templates'."
1185 :group 'org-refile
1186 :group 'org-remember
1187 :type '(choice
1188 (const :tag "Default from remember-data-file" nil)
1189 file))
1191 (defcustom org-goto-interface 'outline
1192 "The default interface to be used for `org-goto'.
1193 Allowed vaues are:
1194 outline The interface shows an outline of the relevant file
1195 and the correct heading is found by moving through
1196 the outline or by searching with incremental search.
1197 outline-path-completion Headlines in the current buffer are offered via
1198 completion."
1199 :group 'org-refile
1200 :type '(choice
1201 (const :tag "Outline" outline)
1202 (const :tag "Outline-path-completion" outline-path-completion)))
1204 (defcustom org-reverse-note-order nil
1205 "Non-nil means, store new notes at the beginning of a file or entry.
1206 When nil, new notes will be filed to the end of a file or entry.
1207 This can also be a list with cons cells of regular expressions that
1208 are matched against file names, and values."
1209 :group 'org-remember
1210 :type '(choice
1211 (const :tag "Reverse always" t)
1212 (const :tag "Reverse never" nil)
1213 (repeat :tag "By file name regexp"
1214 (cons regexp boolean))))
1216 (defcustom org-refile-targets nil
1217 "Targets for refiling entries with \\[org-refile].
1218 This is list of cons cells. Each cell contains:
1219 - a specification of the files to be considered, either a list of files,
1220 or a symbol whose function or variable value will be used to retrieve
1221 a file name or a list of file names. Nil means, refile to a different
1222 heading in the current buffer.
1223 - A specification of how to find candidate refile targets. This may be
1224 any of
1225 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1226 This tag has to be present in all target headlines, inheritance will
1227 not be considered.
1228 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1229 todo keyword.
1230 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1231 headlines that are refiling targets.
1232 - a cons cell (:level . N). Any headline of level N is considered a target.
1233 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1234 :group 'org-remember
1235 :type '(repeat
1236 (cons
1237 (choice :value org-agenda-files
1238 (const :tag "All agenda files" org-agenda-files)
1239 (const :tag "Current buffer" nil)
1240 (function) (variable) (file))
1241 (choice :tag "Identify target headline by"
1242 (cons :tag "Specific tag" (const :tag) (string))
1243 (cons :tag "TODO keyword" (const :todo) (string))
1244 (cons :tag "Regular expression" (const :regexp) (regexp))
1245 (cons :tag "Level number" (const :level) (integer))
1246 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1248 (defcustom org-refile-use-outline-path nil
1249 "Non-nil means, provide refile targets as paths.
1250 So a level 3 headline will be available as level1/level2/level3.
1251 When the value is `file', also include the file name (without directory)
1252 into the path. When `full-file-path', include the full file path."
1253 :group 'org-remember
1254 :type '(choice
1255 (const :tag "Not" nil)
1256 (const :tag "Yes" t)
1257 (const :tag "Start with file name" file)
1258 (const :tag "Start with full file path" full-file-path)))
1260 (defgroup org-todo nil
1261 "Options concerning TODO items in Org-mode."
1262 :tag "Org TODO"
1263 :group 'org)
1265 (defgroup org-progress nil
1266 "Options concerning Progress logging in Org-mode."
1267 :tag "Org Progress"
1268 :group 'org-time)
1270 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1271 "List of TODO entry keyword sequences and their interpretation.
1272 \\<org-mode-map>This is a list of sequences.
1274 Each sequence starts with a symbol, either `sequence' or `type',
1275 indicating if the keywords should be interpreted as a sequence of
1276 action steps, or as different types of TODO items. The first
1277 keywords are states requiring action - these states will select a headline
1278 for inclusion into the global TODO list Org-mode produces. If one of
1279 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1280 signify that no further action is necessary. If \"|\" is not found,
1281 the last keyword is treated as the only DONE state of the sequence.
1283 The command \\[org-todo] cycles an entry through these states, and one
1284 additional state where no keyword is present. For details about this
1285 cycling, see the manual.
1287 TODO keywords and interpretation can also be set on a per-file basis with
1288 the special #+SEQ_TODO and #+TYP_TODO lines.
1290 Each keyword can optionally specify a character for fast state selection
1291 \(in combination with the variable `org-use-fast-todo-selection')
1292 and specifiers for state change logging, using the same syntax
1293 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1294 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1295 indicates to record a time stamp each time this state is selected.
1297 Each keyword may also specify if a timestamp or a note should be
1298 recorded when entering or leaving the state, by adding additional
1299 characters in the parenthesis after the keyword. This looks like this:
1300 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1301 record only the time of the state change. With X and Y being either
1302 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1303 Y when leaving the state if and only if the *target* state does not
1304 define X. You may omit any of the fast-selection key or X or /Y,
1305 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1307 For backward compatibility, this variable may also be just a list
1308 of keywords - in this case the interptetation (sequence or type) will be
1309 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1310 :group 'org-todo
1311 :group 'org-keywords
1312 :type '(choice
1313 (repeat :tag "Old syntax, just keywords"
1314 (string :tag "Keyword"))
1315 (repeat :tag "New syntax"
1316 (cons
1317 (choice
1318 :tag "Interpretation"
1319 (const :tag "Sequence (cycling hits every state)" sequence)
1320 (const :tag "Type (cycling directly to DONE)" type))
1321 (repeat
1322 (string :tag "Keyword"))))))
1324 (defvar org-todo-keywords-1 nil
1325 "All TODO and DONE keywords active in a buffer.")
1326 (make-variable-buffer-local 'org-todo-keywords-1)
1327 (defvar org-todo-keywords-for-agenda nil)
1328 (defvar org-done-keywords-for-agenda nil)
1329 (defvar org-agenda-contributing-files nil)
1330 (defvar org-not-done-keywords nil)
1331 (make-variable-buffer-local 'org-not-done-keywords)
1332 (defvar org-done-keywords nil)
1333 (make-variable-buffer-local 'org-done-keywords)
1334 (defvar org-todo-heads nil)
1335 (make-variable-buffer-local 'org-todo-heads)
1336 (defvar org-todo-sets nil)
1337 (make-variable-buffer-local 'org-todo-sets)
1338 (defvar org-todo-log-states nil)
1339 (make-variable-buffer-local 'org-todo-log-states)
1340 (defvar org-todo-kwd-alist nil)
1341 (make-variable-buffer-local 'org-todo-kwd-alist)
1342 (defvar org-todo-key-alist nil)
1343 (make-variable-buffer-local 'org-todo-key-alist)
1344 (defvar org-todo-key-trigger nil)
1345 (make-variable-buffer-local 'org-todo-key-trigger)
1347 (defcustom org-todo-interpretation 'sequence
1348 "Controls how TODO keywords are interpreted.
1349 This variable is in principle obsolete and is only used for
1350 backward compatibility, if the interpretation of todo keywords is
1351 not given already in `org-todo-keywords'. See that variable for
1352 more information."
1353 :group 'org-todo
1354 :group 'org-keywords
1355 :type '(choice (const sequence)
1356 (const type)))
1358 (defcustom org-use-fast-todo-selection 'prefix
1359 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1360 This variable describes if and under what circumstances the cycling
1361 mechanism for TODO keywords will be replaced by a single-key, direct
1362 selection scheme.
1364 When nil, fast selection is never used.
1366 When the symbol `prefix', it will be used when `org-todo' is called with
1367 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1368 in an agenda buffer.
1370 When t, fast selection is used by default. In this case, the prefix
1371 argument forces cycling instead.
1373 In all cases, the special interface is only used if access keys have actually
1374 been assigned by the user, i.e. if keywords in the configuration are followed
1375 by a letter in parenthesis, like TODO(t)."
1376 :group 'org-todo
1377 :type '(choice
1378 (const :tag "Never" nil)
1379 (const :tag "By default" t)
1380 (const :tag "Only with C-u C-c C-t" prefix)))
1382 (defcustom org-after-todo-state-change-hook nil
1383 "Hook which is run after the state of a TODO item was changed.
1384 The new state (a string with a TODO keyword, or nil) is available in the
1385 Lisp variable `state'."
1386 :group 'org-todo
1387 :type 'hook)
1389 (defcustom org-log-done nil
1390 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1391 When equal to the list (done), also prompt for a closing note.
1392 This can also be configured on a per-file basis by adding one of
1393 the following lines anywhere in the buffer:
1395 #+STARTUP: logdone
1396 #+STARTUP: lognotedone
1397 #+STARTUP: nologdone"
1398 :group 'org-todo
1399 :group 'org-progress
1400 :type '(choice
1401 (const :tag "No logging" nil)
1402 (const :tag "Record CLOSED timestamp" time)
1403 (const :tag "Record CLOSED timestamp with closing note." note)))
1405 ;; Normalize old uses of org-log-done.
1406 (cond
1407 ((eq org-log-done t) (setq org-log-done 'time))
1408 ((and (listp org-log-done) (memq 'done org-log-done))
1409 (setq org-log-done 'note)))
1411 (defcustom org-log-note-clock-out nil
1412 "Non-nil means, recored a note when clocking out of an item.
1413 This can also be configured on a per-file basis by adding one of
1414 the following lines anywhere in the buffer:
1416 #+STARTUP: lognoteclock-out
1417 #+STARTUP: nolognoteclock-out"
1418 :group 'org-todo
1419 :group 'org-progress
1420 :type 'boolean)
1422 (defcustom org-log-done-with-time t
1423 "Non-nil means, the CLOSED time stamp will contain date and time.
1424 When nil, only the date will be recorded."
1425 :group 'org-progress
1426 :type 'boolean)
1428 (defcustom org-log-note-headings
1429 '((done . "CLOSING NOTE %t")
1430 (state . "State %-12s %t")
1431 (note . "Note taken on %t")
1432 (clock-out . ""))
1433 "Headings for notes added to entries.
1434 The value is an alist, with the car being a symbol indicating the note
1435 context, and the cdr is the heading to be used. The heading may also be the
1436 empty string.
1437 %t in the heading will be replaced by a time stamp.
1438 %s will be replaced by the new TODO state, in double quotes.
1439 %u will be replaced by the user name.
1440 %U will be replaced by the full user name."
1441 :group 'org-todo
1442 :group 'org-progress
1443 :type '(list :greedy t
1444 (cons (const :tag "Heading when closing an item" done) string)
1445 (cons (const :tag
1446 "Heading when changing todo state (todo sequence only)"
1447 state) string)
1448 (cons (const :tag "Heading when just taking a note" note) string)
1449 (cons (const :tag "Heading when clocking out" clock-out) string)))
1451 (unless (assq 'note org-log-note-headings)
1452 (push '(note . "%t") org-log-note-headings))
1454 (defcustom org-log-states-order-reversed t
1455 "Non-nil means, the latest state change note will be directly after heading.
1456 When nil, the notes will be orderer according to time."
1457 :group 'org-todo
1458 :group 'org-progress
1459 :type 'boolean)
1461 (defcustom org-log-repeat 'time
1462 "Non-nil means, record moving through the DONE state when triggering repeat.
1463 An auto-repeating tasks is immediately switched back to TODO when marked
1464 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1465 the TODO keyword definition, or recording a closing note by setting
1466 `org-log-done', there will be no record of the task moving through DONE.
1467 This variable forces taking a note anyway. Possible values are:
1469 nil Don't force a record
1470 time Record a time stamp
1471 note Record a note
1473 This option can also be set with on a per-file-basis with
1475 #+STARTUP: logrepeat
1476 #+STARTUP: lognoterepeat
1477 #+STARTUP: nologrepeat
1479 You can have local logging settings for a subtree by setting the LOGGING
1480 property to one or more of these keywords."
1481 :group 'org-todo
1482 :group 'org-progress
1483 :type '(choice
1484 (const :tag "Don't force a record" nil)
1485 (const :tag "Force recording the DONE state" time)
1486 (const :tag "Force recording a note with the DONE state" note)))
1489 (defgroup org-priorities nil
1490 "Priorities in Org-mode."
1491 :tag "Org Priorities"
1492 :group 'org-todo)
1494 (defcustom org-highest-priority ?A
1495 "The highest priority of TODO items. A character like ?A, ?B etc.
1496 Must have a smaller ASCII number than `org-lowest-priority'."
1497 :group 'org-priorities
1498 :type 'character)
1500 (defcustom org-lowest-priority ?C
1501 "The lowest priority of TODO items. A character like ?A, ?B etc.
1502 Must have a larger ASCII number than `org-highest-priority'."
1503 :group 'org-priorities
1504 :type 'character)
1506 (defcustom org-default-priority ?B
1507 "The default priority of TODO items.
1508 This is the priority an item get if no explicit priority is given."
1509 :group 'org-priorities
1510 :type 'character)
1512 (defcustom org-priority-start-cycle-with-default t
1513 "Non-nil means, start with default priority when starting to cycle.
1514 When this is nil, the first step in the cycle will be (depending on the
1515 command used) one higher or lower that the default priority."
1516 :group 'org-priorities
1517 :type 'boolean)
1519 (defgroup org-time nil
1520 "Options concerning time stamps and deadlines in Org-mode."
1521 :tag "Org Time"
1522 :group 'org)
1524 (defcustom org-insert-labeled-timestamps-at-point nil
1525 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1526 When nil, these labeled time stamps are forces into the second line of an
1527 entry, just after the headline. When scheduling from the global TODO list,
1528 the time stamp will always be forced into the second line."
1529 :group 'org-time
1530 :type 'boolean)
1532 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1533 "Formats for `format-time-string' which are used for time stamps.
1534 It is not recommended to change this constant.")
1536 (defcustom org-time-stamp-rounding-minutes '(0 5)
1537 "Number of minutes to round time stamps to.
1538 These are two values, the first applies when first creating a time stamp.
1539 The second applies when changing it with the commands `S-up' and `S-down'.
1540 When changing the time stamp, this means that it will change in steps
1541 of N minutes, as given by the second value.
1543 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1544 numbers should be factors of 60, so for example 5, 10, 15.
1546 When this is larger than 1, you can still force an exact time-stamp by using
1547 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1548 and by using a prefix arg to `S-up/down' to specify the exact number
1549 of minutes to shift."
1550 :group 'org-time
1551 :get '(lambda (var) ; Make sure all entries have 5 elements
1552 (if (integerp (default-value var))
1553 (list (default-value var) 5)
1554 (default-value var)))
1555 :type '(list
1556 (integer :tag "when inserting times")
1557 (integer :tag "when modifying times")))
1559 ;; Normalize old customizations of this variable.
1560 (when (integerp org-time-stamp-rounding-minutes)
1561 (setq org-time-stamp-rounding-minutes
1562 (list org-time-stamp-rounding-minutes
1563 org-time-stamp-rounding-minutes)))
1565 (defcustom org-display-custom-times nil
1566 "Non-nil means, overlay custom formats over all time stamps.
1567 The formats are defined through the variable `org-time-stamp-custom-formats'.
1568 To turn this on on a per-file basis, insert anywhere in the file:
1569 #+STARTUP: customtime"
1570 :group 'org-time
1571 :set 'set-default
1572 :type 'sexp)
1573 (make-variable-buffer-local 'org-display-custom-times)
1575 (defcustom org-time-stamp-custom-formats
1576 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1577 "Custom formats for time stamps. See `format-time-string' for the syntax.
1578 These are overlayed over the default ISO format if the variable
1579 `org-display-custom-times' is set. Time like %H:%M should be at the
1580 end of the second format."
1581 :group 'org-time
1582 :type 'sexp)
1584 (defun org-time-stamp-format (&optional long inactive)
1585 "Get the right format for a time string."
1586 (let ((f (if long (cdr org-time-stamp-formats)
1587 (car org-time-stamp-formats))))
1588 (if inactive
1589 (concat "[" (substring f 1 -1) "]")
1590 f)))
1592 (defcustom org-deadline-warning-days 14
1593 "No. of days before expiration during which a deadline becomes active.
1594 This variable governs the display in sparse trees and in the agenda.
1595 When 0 or negative, it means use this number (the absolute value of it)
1596 even if a deadline has a different individual lead time specified."
1597 :group 'org-time
1598 :group 'org-agenda-daily/weekly
1599 :type 'number)
1601 (defcustom org-read-date-prefer-future t
1602 "Non-nil means, assume future for incomplete date input from user.
1603 This affects the following situations:
1604 1. The user gives a day, but no month.
1605 For example, if today is the 15th, and you enter \"3\", Org-mode will
1606 read this as the third of *next* month. However, if you enter \"17\",
1607 it will be considered as *this* month.
1608 2. The user gives a month but not a year.
1609 For example, if it is april and you enter \"feb 2\", this will be read
1610 as feb 2, *next* year. \"May 5\", however, will be this year.
1612 Currently this does not work for ISO week specifications.
1614 When this option is nil, the current month and year will always be used
1615 as defaults."
1616 :group 'org-time
1617 :type 'boolean)
1619 (defcustom org-read-date-display-live t
1620 "Non-nil means, display current interpretation of date prompt live.
1621 This display will be in an overlay, in the minibuffer."
1622 :group 'org-time
1623 :type 'boolean)
1625 (defcustom org-read-date-popup-calendar t
1626 "Non-nil means, pop up a calendar when prompting for a date.
1627 In the calendar, the date can be selected with mouse-1. However, the
1628 minibuffer will also be active, and you can simply enter the date as well.
1629 When nil, only the minibuffer will be available."
1630 :group 'org-time
1631 :type 'boolean)
1632 (if (fboundp 'defvaralias)
1633 (defvaralias 'org-popup-calendar-for-date-prompt
1634 'org-read-date-popup-calendar))
1636 (defcustom org-extend-today-until 0
1637 "The hour when your day really ends.
1638 This has influence for the following applications:
1639 - When switching the agenda to \"today\". It it is still earlier than
1640 the time given here, the day recognized as TODAY is actually yesterday.
1641 - When a date is read from the user and it is still before the time given
1642 here, the current date and time will be assumed to be yesterday, 23:59.
1644 FIXME:
1645 IMPORTANT: This is still a very experimental feature, it may disappear
1646 again or it may be extended to mean more things."
1647 :group 'org-time
1648 :type 'number)
1650 (defcustom org-edit-timestamp-down-means-later nil
1651 "Non-nil means, S-down will increase the time in a time stamp.
1652 When nil, S-up will increase."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-calendar-follow-timestamp-change t
1657 "Non-nil means, make the calendar window follow timestamp changes.
1658 When a timestamp is modified and the calendar window is visible, it will be
1659 moved to the new date."
1660 :group 'org-time
1661 :type 'boolean)
1663 (defgroup org-tags nil
1664 "Options concerning tags in Org-mode."
1665 :tag "Org Tags"
1666 :group 'org)
1668 (defcustom org-tag-alist nil
1669 "List of tags allowed in Org-mode files.
1670 When this list is nil, Org-mode will base TAG input on what is already in the
1671 buffer.
1672 The value of this variable is an alist, the car of each entry must be a
1673 keyword as a string, the cdr may be a character that is used to select
1674 that tag through the fast-tag-selection interface.
1675 See the manual for details."
1676 :group 'org-tags
1677 :type '(repeat
1678 (choice
1679 (cons (string :tag "Tag name")
1680 (character :tag "Access char"))
1681 (const :tag "Start radio group" (:startgroup))
1682 (const :tag "End radio group" (:endgroup)))))
1684 (defcustom org-use-fast-tag-selection 'auto
1685 "Non-nil means, use fast tag selection scheme.
1686 This is a special interface to select and deselect tags with single keys.
1687 When nil, fast selection is never used.
1688 When the symbol `auto', fast selection is used if and only if selection
1689 characters for tags have been configured, either through the variable
1690 `org-tag-alist' or through a #+TAGS line in the buffer.
1691 When t, fast selection is always used and selection keys are assigned
1692 automatically if necessary."
1693 :group 'org-tags
1694 :type '(choice
1695 (const :tag "Always" t)
1696 (const :tag "Never" nil)
1697 (const :tag "When selection characters are configured" 'auto)))
1699 (defcustom org-fast-tag-selection-single-key nil
1700 "Non-nil means, fast tag selection exits after first change.
1701 When nil, you have to press RET to exit it.
1702 During fast tag selection, you can toggle this flag with `C-c'.
1703 This variable can also have the value `expert'. In this case, the window
1704 displaying the tags menu is not even shown, until you press C-c again."
1705 :group 'org-tags
1706 :type '(choice
1707 (const :tag "No" nil)
1708 (const :tag "Yes" t)
1709 (const :tag "Expert" expert)))
1711 (defvar org-fast-tag-selection-include-todo nil
1712 "Non-nil means, fast tags selection interface will also offer TODO states.
1713 This is an undocumented feature, you should not rely on it.")
1715 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1716 "The column to which tags should be indented in a headline.
1717 If this number is positive, it specifies the column. If it is negative,
1718 it means that the tags should be flushright to that column. For example,
1719 -80 works well for a normal 80 character screen."
1720 :group 'org-tags
1721 :type 'integer)
1723 (defcustom org-auto-align-tags t
1724 "Non-nil means, realign tags after pro/demotion of TODO state change.
1725 These operations change the length of a headline and therefore shift
1726 the tags around. With this options turned on, after each such operation
1727 the tags are again aligned to `org-tags-column'."
1728 :group 'org-tags
1729 :type 'boolean)
1731 (defcustom org-use-tag-inheritance t
1732 "Non-nil means, tags in levels apply also for sublevels.
1733 When nil, only the tags directly given in a specific line apply there.
1734 If you turn off this option, you very likely want to turn on the
1735 companion option `org-tags-match-list-sublevels'.
1737 This may also be a list of tags that should be inherited, or a regexp that
1738 matches tags that should be inherited."
1739 :group 'org-tags
1740 :type '(choice
1741 (const :tag "Not" nil)
1742 (const :tag "Always" t)
1743 (repeat :tag "Specific tags" (string :tag "Tag"))
1744 (regexp :tag "Tags matched by regexp")))
1746 (defun org-tag-inherit-p (tag)
1747 "Check if TAG is one that should be inherited."
1748 (cond
1749 ((eq org-use-tag-inheritance t) t)
1750 ((not org-use-tag-inheritance) nil)
1751 ((stringp org-use-tag-inheritance)
1752 (string-match org-use-tag-inheritance tag))
1753 ((listp org-use-tag-inheritance)
1754 (member tag org-use-tag-inheritance))
1755 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1757 (defcustom org-tags-match-list-sublevels nil
1758 "Non-nil means list also sublevels of headlines matching tag search.
1759 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1760 the sublevels of a headline matching a tag search often also match
1761 the same search. Listing all of them can create very long lists.
1762 Setting this variable to nil causes subtrees of a match to be skipped.
1763 This option is off by default, because inheritance in on. If you turn
1764 inheritance off, you very likely want to turn this option on.
1766 As a special case, if the tag search is restricted to TODO items, the
1767 value of this variable is ignored and sublevels are always checked, to
1768 make sure all corresponding TODO items find their way into the list."
1769 :group 'org-tags
1770 :type 'boolean)
1772 (defvar org-tags-history nil
1773 "History of minibuffer reads for tags.")
1774 (defvar org-last-tags-completion-table nil
1775 "The last used completion table for tags.")
1776 (defvar org-after-tags-change-hook nil
1777 "Hook that is run after the tags in a line have changed.")
1779 (defgroup org-properties nil
1780 "Options concerning properties in Org-mode."
1781 :tag "Org Properties"
1782 :group 'org)
1784 (defcustom org-property-format "%-10s %s"
1785 "How property key/value pairs should be formatted by `indent-line'.
1786 When `indent-line' hits a property definition, it will format the line
1787 according to this format, mainly to make sure that the values are
1788 lined-up with respect to each other."
1789 :group 'org-properties
1790 :type 'string)
1792 (defcustom org-use-property-inheritance nil
1793 "Non-nil means, properties apply also for sublevels.
1795 This setting is chiefly used during property searches. Turning it on can
1796 cause significant overhead when doing a search, which is why it is not
1797 on by default.
1799 When nil, only the properties directly given in the current entry count.
1800 When t, every property is inherited. The value may also be a list of
1801 properties that should have inheritance, or a regular expression matching
1802 properties that should be inherited.
1804 However, note that some special properties use inheritance under special
1805 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1806 and the properties ending in \"_ALL\" when they are used as descriptor
1807 for valid values of a property.
1809 Note for programmers:
1810 When querying an entry with `org-entry-get', you can control if inheritance
1811 should be used. By default, `org-entry-get' looks only at the local
1812 properties. You can request inheritance by setting the inherit argument
1813 to t (to force inheritance) or to `selective' (to respect the setting
1814 in this variable)."
1815 :group 'org-properties
1816 :type '(choice
1817 (const :tag "Not" nil)
1818 (const :tag "Always" t)
1819 (repeat :tag "Specific properties" (string :tag "Property"))
1820 (regexp :tag "Properties matched by regexp")))
1822 (defun org-property-inherit-p (property)
1823 "Check if PROPERTY is one that should be inherited."
1824 (cond
1825 ((eq org-use-property-inheritance t) t)
1826 ((not org-use-property-inheritance) nil)
1827 ((stringp org-use-property-inheritance)
1828 (string-match org-use-property-inheritance property))
1829 ((listp org-use-property-inheritance)
1830 (member property org-use-property-inheritance))
1831 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1833 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1834 "The default column format, if no other format has been defined.
1835 This variable can be set on the per-file basis by inserting a line
1837 #+COLUMNS: %25ITEM ....."
1838 :group 'org-properties
1839 :type 'string)
1841 (defcustom org-effort-property "Effort"
1842 "The property that is being used to keep track of effort estimates.
1843 Effort estimates given in this property need to have the format H:MM."
1844 :group 'org-properties
1845 :group 'org-progress
1846 :type '(string :tag "Property"))
1848 (defcustom org-global-properties nil
1849 "List of property/value pairs that can be inherited by any entry.
1850 You can set buffer-local values for this by adding lines like
1852 #+PROPERTY: NAME VALUE"
1853 :group 'org-properties
1854 :type '(repeat
1855 (cons (string :tag "Property")
1856 (string :tag "Value"))))
1858 (defvar org-local-properties nil
1859 "List of property/value pairs that can be inherited by any entry.
1860 Valid for the current buffer.
1861 This variable is populated from #+PROPERTY lines.")
1863 (defgroup org-agenda nil
1864 "Options concerning agenda views in Org-mode."
1865 :tag "Org Agenda"
1866 :group 'org)
1868 (defvar org-category nil
1869 "Variable used by org files to set a category for agenda display.
1870 Such files should use a file variable to set it, for example
1872 # -*- mode: org; org-category: \"ELisp\"
1874 or contain a special line
1876 #+CATEGORY: ELisp
1878 If the file does not specify a category, then file's base name
1879 is used instead.")
1880 (make-variable-buffer-local 'org-category)
1882 (defcustom org-agenda-files nil
1883 "The files to be used for agenda display.
1884 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1885 \\[org-remove-file]. You can also use customize to edit the list.
1887 If an entry is a directory, all files in that directory that are matched by
1888 `org-agenda-file-regexp' will be part of the file list.
1890 If the value of the variable is not a list but a single file name, then
1891 the list of agenda files is actually stored and maintained in that file, one
1892 agenda file per line."
1893 :group 'org-agenda
1894 :type '(choice
1895 (repeat :tag "List of files and directories" file)
1896 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1898 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1899 "Regular expression to match files for `org-agenda-files'.
1900 If any element in the list in that variable contains a directory instead
1901 of a normal file, all files in that directory that are matched by this
1902 regular expression will be included."
1903 :group 'org-agenda
1904 :type 'regexp)
1906 (defcustom org-agenda-text-search-extra-files nil
1907 "List of extra files to be searched by text search commands.
1908 These files will be search in addition to the agenda files by the
1909 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1910 Note that these files will only be searched for text search commands,
1911 not for the other agenda views like todo lists, tag searches or the weekly
1912 agenda. This variable is intended to list notes and possibly archive files
1913 that should also be searched by these two commands.
1914 In fact, if the first element in the list is the symbol `agenda-archives',
1915 than all archive files of all agenda files will be added to the search
1916 scope."
1917 :group 'org-agenda
1918 :type '(set :greedy t
1919 (const :tag "Agenda Archives" agenda-archives)
1920 (repeat :inline t (file))))
1922 (if (fboundp 'defvaralias)
1923 (defvaralias 'org-agenda-multi-occur-extra-files
1924 'org-agenda-text-search-extra-files))
1926 (defcustom org-agenda-skip-unavailable-files nil
1927 "t means to just skip non-reachable files in `org-agenda-files'.
1928 Nil means to remove them, after a query, from the list."
1929 :group 'org-agenda
1930 :type 'boolean)
1932 (defcustom org-calendar-to-agenda-key [?c]
1933 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1934 The command `org-calendar-goto-agenda' will be bound to this key. The
1935 default is the character `c' because then `c' can be used to switch back and
1936 forth between agenda and calendar."
1937 :group 'org-agenda
1938 :type 'sexp)
1940 (eval-after-load "calendar"
1941 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1942 'org-calendar-goto-agenda))
1944 (defgroup org-latex nil
1945 "Options for embedding LaTeX code into Org-mode."
1946 :tag "Org LaTeX"
1947 :group 'org)
1949 (defcustom org-format-latex-options
1950 '(:foreground default :background default :scale 1.0
1951 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1952 :matchers ("begin" "$" "$$" "\\(" "\\["))
1953 "Options for creating images from LaTeX fragments.
1954 This is a property list with the following properties:
1955 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1956 `default' means use the forground of the default face.
1957 :background the background color, or \"Transparent\".
1958 `default' means use the background of the default face.
1959 :scale a scaling factor for the size of the images
1960 :html-foreground, :html-background, :html-scale
1961 The same numbers for HTML export.
1962 :matchers a list indicating which matchers should be used to
1963 find LaTeX fragments. Valid members of this list are:
1964 \"begin\" find environments
1965 \"$\" find math expressions surrounded by $...$
1966 \"$$\" find math expressions surrounded by $$....$$
1967 \"\\(\" find math expressions surrounded by \\(...\\)
1968 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1969 :group 'org-latex
1970 :type 'plist)
1972 (defcustom org-format-latex-header "\\documentclass{article}
1973 \\usepackage{fullpage} % do not remove
1974 \\usepackage{amssymb}
1975 \\usepackage[usenames]{color}
1976 \\usepackage{amsmath}
1977 \\usepackage{latexsym}
1978 \\usepackage[mathscr]{eucal}
1979 \\pagestyle{empty} % do not remove"
1980 "The document header used for processing LaTeX fragments."
1981 :group 'org-latex
1982 :type 'string)
1985 (defgroup org-font-lock nil
1986 "Font-lock settings for highlighting in Org-mode."
1987 :tag "Org Font Lock"
1988 :group 'org)
1990 (defcustom org-level-color-stars-only nil
1991 "Non-nil means fontify only the stars in each headline.
1992 When nil, the entire headline is fontified.
1993 Changing it requires restart of `font-lock-mode' to become effective
1994 also in regions already fontified."
1995 :group 'org-font-lock
1996 :type 'boolean)
1998 (defcustom org-hide-leading-stars nil
1999 "Non-nil means, hide the first N-1 stars in a headline.
2000 This works by using the face `org-hide' for these stars. This
2001 face is white for a light background, and black for a dark
2002 background. You may have to customize the face `org-hide' to
2003 make this work.
2004 Changing it requires restart of `font-lock-mode' to become effective
2005 also in regions already fontified.
2006 You may also set this on a per-file basis by adding one of the following
2007 lines to the buffer:
2009 #+STARTUP: hidestars
2010 #+STARTUP: showstars"
2011 :group 'org-font-lock
2012 :type 'boolean)
2014 (defcustom org-fontify-done-headline nil
2015 "Non-nil means, change the face of a headline if it is marked DONE.
2016 Normally, only the TODO/DONE keyword indicates the state of a headline.
2017 When this is non-nil, the headline after the keyword is set to the
2018 `org-headline-done' as an additional indication."
2019 :group 'org-font-lock
2020 :type 'boolean)
2022 (defcustom org-fontify-emphasized-text t
2023 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2024 Changing this variable requires a restart of Emacs to take effect."
2025 :group 'org-font-lock
2026 :type 'boolean)
2028 (defcustom org-highlight-latex-fragments-and-specials nil
2029 "Non-nil means, fontify what is treated specially by the exporters."
2030 :group 'org-font-lock
2031 :type 'boolean)
2033 (defcustom org-hide-emphasis-markers nil
2034 "Non-nil mean font-lock should hide the emphasis marker characters."
2035 :group 'org-font-lock
2036 :type 'boolean)
2038 (defvar org-emph-re nil
2039 "Regular expression for matching emphasis.")
2040 (defvar org-verbatim-re nil
2041 "Regular expression for matching verbatim text.")
2042 (defvar org-emphasis-regexp-components) ; defined just below
2043 (defvar org-emphasis-alist) ; defined just below
2044 (defun org-set-emph-re (var val)
2045 "Set variable and compute the emphasis regular expression."
2046 (set var val)
2047 (when (and (boundp 'org-emphasis-alist)
2048 (boundp 'org-emphasis-regexp-components)
2049 org-emphasis-alist org-emphasis-regexp-components)
2050 (let* ((e org-emphasis-regexp-components)
2051 (pre (car e))
2052 (post (nth 1 e))
2053 (border (nth 2 e))
2054 (body (nth 3 e))
2055 (nl (nth 4 e))
2056 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2057 (body1 (concat body "*?"))
2058 (markers (mapconcat 'car org-emphasis-alist ""))
2059 (vmarkers (mapconcat
2060 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2061 org-emphasis-alist "")))
2062 ;; make sure special characters appear at the right position in the class
2063 (if (string-match "\\^" markers)
2064 (setq markers (concat (replace-match "" t t markers) "^")))
2065 (if (string-match "-" markers)
2066 (setq markers (concat (replace-match "" t t markers) "-")))
2067 (if (string-match "\\^" vmarkers)
2068 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2069 (if (string-match "-" vmarkers)
2070 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2071 (if (> nl 0)
2072 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2073 (int-to-string nl) "\\}")))
2074 ;; Make the regexp
2075 (setq org-emph-re
2076 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2077 "\\("
2078 "\\([" markers "]\\)"
2079 "\\("
2080 "[^" border "]\\|"
2081 "[^" border (if (and nil stacked) markers) "]"
2082 body1
2083 "[^" border (if (and nil stacked) markers) "]"
2084 "\\)"
2085 "\\3\\)"
2086 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2087 (setq org-verbatim-re
2088 (concat "\\([" pre "]\\|^\\)"
2089 "\\("
2090 "\\([" vmarkers "]\\)"
2091 "\\("
2092 "[^" border "]\\|"
2093 "[^" border "]"
2094 body1
2095 "[^" border "]"
2096 "\\)"
2097 "\\3\\)"
2098 "\\([" post "]\\|$\\)")))))
2100 (defcustom org-emphasis-regexp-components
2101 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2102 "Components used to build the regular expression for emphasis.
2103 This is a list with 6 entries. Terminology: In an emphasis string
2104 like \" *strong word* \", we call the initial space PREMATCH, the final
2105 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2106 and \"trong wor\" is the body. The different components in this variable
2107 specify what is allowed/forbidden in each part:
2109 pre Chars allowed as prematch. Beginning of line will be allowed too.
2110 post Chars allowed as postmatch. End of line will be allowed too.
2111 border The chars *forbidden* as border characters.
2112 body-regexp A regexp like \".\" to match a body character. Don't use
2113 non-shy groups here, and don't allow newline here.
2114 newline The maximum number of newlines allowed in an emphasis exp.
2116 Use customize to modify this, or restart Emacs after changing it."
2117 :group 'org-font-lock
2118 :set 'org-set-emph-re
2119 :type '(list
2120 (sexp :tag "Allowed chars in pre ")
2121 (sexp :tag "Allowed chars in post ")
2122 (sexp :tag "Forbidden chars in border ")
2123 (sexp :tag "Regexp for body ")
2124 (integer :tag "number of newlines allowed")
2125 (option (boolean :tag "Stacking (DISABLED) "))))
2127 (defcustom org-emphasis-alist
2128 `(("*" bold "<b>" "</b>")
2129 ("/" italic "<i>" "</i>")
2130 ("_" underline "<u>" "</u>")
2131 ("=" org-code "<code>" "</code>" verbatim)
2132 ("~" org-verbatim "" "" verbatim)
2133 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2134 "<del>" "</del>")
2136 "Special syntax for emphasized text.
2137 Text starting and ending with a special character will be emphasized, for
2138 example *bold*, _underlined_ and /italic/. This variable sets the marker
2139 characters, the face to be used by font-lock for highlighting in Org-mode
2140 Emacs buffers, and the HTML tags to be used for this.
2141 Use customize to modify this, or restart Emacs after changing it."
2142 :group 'org-font-lock
2143 :set 'org-set-emph-re
2144 :type '(repeat
2145 (list
2146 (string :tag "Marker character")
2147 (choice
2148 (face :tag "Font-lock-face")
2149 (plist :tag "Face property list"))
2150 (string :tag "HTML start tag")
2151 (string :tag "HTML end tag")
2152 (option (const verbatim)))))
2154 ;;; Miscellaneous options
2156 (defgroup org-completion nil
2157 "Completion in Org-mode."
2158 :tag "Org Completion"
2159 :group 'org)
2161 (defcustom org-completion-fallback-command 'hippie-expand
2162 "The expansion command called by \\[org-complete] in normal context.
2163 Normal means, no org-mode-specific context."
2164 :group 'org-completion
2165 :type 'function)
2167 ;;; Functions and variables from ther packages
2168 ;; Declared here to avoid compiler warnings
2170 ;; XEmacs only
2171 (defvar outline-mode-menu-heading)
2172 (defvar outline-mode-menu-show)
2173 (defvar outline-mode-menu-hide)
2174 (defvar zmacs-regions) ; XEmacs regions
2176 ;; Emacs only
2177 (defvar mark-active)
2179 ;; Various packages
2180 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2181 (declare-function calendar-forward-day "cal-move" (arg))
2182 (declare-function calendar-goto-date "cal-move" (date))
2183 (declare-function calendar-goto-today "cal-move" ())
2184 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2185 (defvar calc-embedded-close-formula)
2186 (defvar calc-embedded-open-formula)
2187 (declare-function cdlatex-tab "ext:cdlatex" ())
2188 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2189 (defvar font-lock-unfontify-region-function)
2190 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2191 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2192 (defvar iswitchb-temp-buflist)
2193 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2194 (declare-function org-agenda-skip "org-agenda" ())
2195 (declare-function org-format-agenda-item "org-agenda"
2196 (extra txt &optional category tags dotime noprefix remove-re))
2197 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2198 (declare-function org-agenda-change-all-lines "org-agenda"
2199 (newhead hdmarker &optional fixface))
2200 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2201 (declare-function org-agenda-maybe-redo "org-agenda" ())
2202 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2203 (beg end))
2204 (declare-function parse-time-string "parse-time" (string))
2205 (declare-function remember "remember" (&optional initial))
2206 (declare-function remember-buffer-desc "remember" ())
2207 (declare-function remember-finalize "remember" ())
2208 (defvar remember-save-after-remembering)
2209 (defvar remember-data-file)
2210 (defvar remember-register)
2211 (defvar remember-buffer)
2212 (defvar remember-handler-functions)
2213 (defvar remember-annotation-functions)
2214 (defvar texmathp-why)
2215 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2216 (declare-function table--at-cell-p "table" (position &optional object at-column))
2218 (defvar w3m-current-url)
2219 (defvar w3m-current-title)
2221 (defvar org-latex-regexps)
2223 ;;; Autoload and prepare some org modules
2225 ;; Some table stuff that needs to be defined here, because it is used
2226 ;; by the functions setting up org-mode or checking for table context.
2228 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2229 "Detects an org-type or table-type table.")
2230 (defconst org-table-line-regexp "^[ \t]*|"
2231 "Detects an org-type table line.")
2232 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2233 "Detects an org-type table line.")
2234 (defconst org-table-hline-regexp "^[ \t]*|-"
2235 "Detects an org-type table hline.")
2236 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2237 "Detects a table-type table hline.")
2238 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2239 "Searching from within a table (any type) this finds the first line
2240 outside the table.")
2242 ;; Autoload the functions in org-table.el that are needed by functions here.
2244 (eval-and-compile
2245 (org-autoload "org-table"
2246 '(org-table-align org-table-begin org-table-blank-field
2247 org-table-convert org-table-convert-region org-table-copy-down
2248 org-table-copy-region org-table-create
2249 org-table-create-or-convert-from-region
2250 org-table-create-with-table.el org-table-current-dline
2251 org-table-cut-region org-table-delete-column org-table-edit-field
2252 org-table-edit-formulas org-table-end org-table-eval-formula
2253 org-table-export org-table-field-info
2254 org-table-get-stored-formulas org-table-goto-column
2255 org-table-hline-and-move org-table-import org-table-insert-column
2256 org-table-insert-hline org-table-insert-row org-table-iterate
2257 org-table-justify-field-maybe org-table-kill-row
2258 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2259 org-table-move-column org-table-move-column-left
2260 org-table-move-column-right org-table-move-row
2261 org-table-move-row-down org-table-move-row-up
2262 org-table-next-field org-table-next-row org-table-paste-rectangle
2263 org-table-previous-field org-table-recalculate
2264 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2265 org-table-toggle-coordinate-overlays
2266 org-table-toggle-formula-debugger org-table-wrap-region
2267 orgtbl-mode turn-on-orgtbl)))
2269 (defun org-at-table-p (&optional table-type)
2270 "Return t if the cursor is inside an org-type table.
2271 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2272 (if org-enable-table-editor
2273 (save-excursion
2274 (beginning-of-line 1)
2275 (looking-at (if table-type org-table-any-line-regexp
2276 org-table-line-regexp)))
2277 nil))
2278 (defsubst org-table-p () (org-at-table-p))
2280 (defun org-at-table.el-p ()
2281 "Return t if and only if we are at a table.el table."
2282 (and (org-at-table-p 'any)
2283 (save-excursion
2284 (goto-char (org-table-begin 'any))
2285 (looking-at org-table1-hline-regexp))))
2286 (defun org-table-recognize-table.el ()
2287 "If there is a table.el table nearby, recognize it and move into it."
2288 (if org-table-tab-recognizes-table.el
2289 (if (org-at-table.el-p)
2290 (progn
2291 (beginning-of-line 1)
2292 (if (looking-at org-table-dataline-regexp)
2294 (if (looking-at org-table1-hline-regexp)
2295 (progn
2296 (beginning-of-line 2)
2297 (if (looking-at org-table-any-border-regexp)
2298 (beginning-of-line -1)))))
2299 (if (re-search-forward "|" (org-table-end t) t)
2300 (progn
2301 (require 'table)
2302 (if (table--at-cell-p (point))
2304 (message "recognizing table.el table...")
2305 (table-recognize-table)
2306 (message "recognizing table.el table...done")))
2307 (error "This should not happen..."))
2309 nil)
2310 nil))
2312 (defun org-at-table-hline-p ()
2313 "Return t if the cursor is inside a hline in a table."
2314 (if org-enable-table-editor
2315 (save-excursion
2316 (beginning-of-line 1)
2317 (looking-at org-table-hline-regexp))
2318 nil))
2320 (defvar org-table-clean-did-remove-column nil)
2322 (defun org-table-map-tables (function)
2323 "Apply FUNCTION to the start of all tables in the buffer."
2324 (save-excursion
2325 (save-restriction
2326 (widen)
2327 (goto-char (point-min))
2328 (while (re-search-forward org-table-any-line-regexp nil t)
2329 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2330 (beginning-of-line 1)
2331 (if (looking-at org-table-line-regexp)
2332 (save-excursion (funcall function)))
2333 (re-search-forward org-table-any-border-regexp nil 1))))
2334 (message "Mapping tables: done"))
2336 ;; Declare and autoload functions from org-exp.el
2338 (declare-function org-default-export-plist "org-exp")
2339 (declare-function org-infile-export-plist "org-exp")
2340 (declare-function org-get-current-options "org-exp")
2341 (eval-and-compile
2342 (org-autoload "org-exp"
2343 '(org-export org-export-as-ascii org-export-visible
2344 org-insert-export-options-template org-export-as-html-and-open
2345 org-export-as-html-batch org-export-as-html-to-buffer
2346 org-replace-region-by-html org-export-region-as-html
2347 org-export-as-html org-export-icalendar-this-file
2348 org-export-icalendar-all-agenda-files
2349 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2351 ;; Declare and autoload functions from org-exp.el
2353 (eval-and-compile
2354 (org-autoload "org-exp"
2355 '(org-agenda org-agenda-list org-search-view
2356 org-todo-list org-tags-view org-agenda-list-stuck-projects
2357 org-diary org-agenda-to-appt)))
2359 ;; Autoload org-remember
2361 (eval-and-compile
2362 (org-autoload "org-remember"
2363 '(org-remember-insinuate org-remember-annotation
2364 org-remember-apply-template org-remember org-remember-handler)))
2366 ;; Autoload org-clock.el
2369 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2370 (beg end))
2371 (defvar org-clock-marker (make-marker)
2372 "Marker recording the last clock-in.")
2374 (eval-and-compile
2375 (org-autoload
2376 "org-clock"
2377 '(org-clock-in org-clock-out org-clock-cancel
2378 org-clock-goto org-clock-sum org-clock-display
2379 org-remove-clock-overlays org-clock-report
2380 org-clocktable-shift org-dblock-write:clocktable
2381 org-get-clocktable)))
2383 (defun org-clock-update-time-maybe ()
2384 "If this is a CLOCK line, update it and return t.
2385 Otherwise, return nil."
2386 (interactive)
2387 (save-excursion
2388 (beginning-of-line 1)
2389 (skip-chars-forward " \t")
2390 (when (looking-at org-clock-string)
2391 (let ((re (concat "[ \t]*" org-clock-string
2392 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2393 "\\([ \t]*=>.*\\)?"))
2394 ts te h m s)
2395 (if (not (looking-at re))
2397 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2398 (end-of-line 1)
2399 (setq ts (match-string 1)
2400 te (match-string 2))
2401 (setq s (- (time-to-seconds
2402 (apply 'encode-time (org-parse-time-string te)))
2403 (time-to-seconds
2404 (apply 'encode-time (org-parse-time-string ts))))
2405 h (floor (/ s 3600))
2406 s (- s (* 3600 h))
2407 m (floor (/ s 60))
2408 s (- s (* 60 s)))
2409 (insert " => " (format "%2d:%02d" h m))
2410 t)))))
2412 (defun org-check-running-clock ()
2413 "Check if the current buffer contains the running clock.
2414 If yes, offer to stop it and to save the buffer with the changes."
2415 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2416 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2417 (buffer-name))))
2418 (org-clock-out)
2419 (when (y-or-n-p "Save changed buffer?")
2420 (save-buffer))))
2422 (defun org-clocktable-try-shift (dir n)
2423 "Check if this line starts a clock table, if yes, shift the time block."
2424 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2425 (org-clocktable-shift dir n)))
2427 ;; Autoload archiving code
2428 ;; The stuff that is needed for cycling and tags has to be defined here.
2430 (defgroup org-archive nil
2431 "Options concerning archiving in Org-mode."
2432 :tag "Org Archive"
2433 :group 'org-structure)
2435 (defcustom org-archive-location "%s_archive::"
2436 "The location where subtrees should be archived.
2438 Otherwise, the value of this variable is a string, consisting of two
2439 parts, separated by a double-colon.
2441 The first part is a file name - when omitted, archiving happens in the same
2442 file. %s will be replaced by the current file name (without directory part).
2443 Archiving to a different file is useful to keep archived entries from
2444 contributing to the Org-mode Agenda.
2446 The part after the double colon is a headline. The archived entries will be
2447 filed under that headline. When omitted, the subtrees are simply filed away
2448 at the end of the file, as top-level entries.
2450 Here are a few examples:
2451 \"%s_archive::\"
2452 If the current file is Projects.org, archive in file
2453 Projects.org_archive, as top-level trees. This is the default.
2455 \"::* Archived Tasks\"
2456 Archive in the current file, under the top-level headline
2457 \"* Archived Tasks\".
2459 \"~/org/archive.org::\"
2460 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2462 \"basement::** Finished Tasks\"
2463 Archive in file ./basement (relative path), as level 3 trees
2464 below the level 2 heading \"** Finished Tasks\".
2466 You may set this option on a per-file basis by adding to the buffer a
2467 line like
2469 #+ARCHIVE: basement::** Finished Tasks
2471 You may also define it locally for a subtree by setting an ARCHIVE property
2472 in the entry. If such a property is found in an entry, or anywhere up
2473 the hierarchy, it will be used."
2474 :group 'org-archive
2475 :type 'string)
2477 (defcustom org-archive-tag "ARCHIVE"
2478 "The tag that marks a subtree as archived.
2479 An archived subtree does not open during visibility cycling, and does
2480 not contribute to the agenda listings.
2481 After changing this, font-lock must be restarted in the relevant buffers to
2482 get the proper fontification."
2483 :group 'org-archive
2484 :group 'org-keywords
2485 :type 'string)
2487 (defcustom org-agenda-skip-archived-trees t
2488 "Non-nil means, the agenda will skip any items located in archived trees.
2489 An archived tree is a tree marked with the tag ARCHIVE."
2490 :group 'org-archive
2491 :group 'org-agenda-skip
2492 :type 'boolean)
2494 (defcustom org-cycle-open-archived-trees nil
2495 "Non-nil means, `org-cycle' will open archived trees.
2496 An archived tree is a tree marked with the tag ARCHIVE.
2497 When nil, archived trees will stay folded. You can still open them with
2498 normal outline commands like `show-all', but not with the cycling commands."
2499 :group 'org-archive
2500 :group 'org-cycle
2501 :type 'boolean)
2503 (defcustom org-sparse-tree-open-archived-trees nil
2504 "Non-nil means sparse tree construction shows matches in archived trees.
2505 When nil, matches in these trees are highlighted, but the trees are kept in
2506 collapsed state."
2507 :group 'org-archive
2508 :group 'org-sparse-trees
2509 :type 'boolean)
2511 (defun org-cycle-hide-archived-subtrees (state)
2512 "Re-hide all archived subtrees after a visibility state change."
2513 (when (and (not org-cycle-open-archived-trees)
2514 (not (memq state '(overview folded))))
2515 (save-excursion
2516 (let* ((globalp (memq state '(contents all)))
2517 (beg (if globalp (point-min) (point)))
2518 (end (if globalp (point-max) (org-end-of-subtree t))))
2519 (org-hide-archived-subtrees beg end)
2520 (goto-char beg)
2521 (if (looking-at (concat ".*:" org-archive-tag ":"))
2522 (message "%s" (substitute-command-keys
2523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2525 (defun org-force-cycle-archived ()
2526 "Cycle subtree even if it is archived."
2527 (interactive)
2528 (setq this-command 'org-cycle)
2529 (let ((org-cycle-open-archived-trees t))
2530 (call-interactively 'org-cycle)))
2532 (defun org-hide-archived-subtrees (beg end)
2533 "Re-hide all archived subtrees after a visibility state change."
2534 (save-excursion
2535 (let* ((re (concat ":" org-archive-tag ":")))
2536 (goto-char beg)
2537 (while (re-search-forward re end t)
2538 (and (org-on-heading-p) (hide-subtree))
2539 (org-end-of-subtree t)))))
2541 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2543 (eval-and-compile
2544 (org-autoload "org-archive"
2545 '(org-add-archive-files org-archive-subtree
2546 org-archive-to-archive-sibling org-toggle-archive-tag)))
2548 ;; Autoload Column View Code
2550 (declare-function org-columns-number-to-string "org-colview")
2551 (declare-function org-columns-get-format-and-top-level "org-colview")
2552 (declare-function org-columns-compute "org-colview")
2554 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2555 '(org-columns-number-to-string org-columns-get-format-and-top-level
2556 org-columns-compute org-agenda-columns org-columns-remove-overlays
2557 org-columns org-insert-columns-dblock))
2559 ;;; Variables for pre-computed regular expressions, all buffer local
2561 (defvar org-drawer-regexp nil
2562 "Matches first line of a hidden block.")
2563 (make-variable-buffer-local 'org-drawer-regexp)
2564 (defvar org-todo-regexp nil
2565 "Matches any of the TODO state keywords.")
2566 (make-variable-buffer-local 'org-todo-regexp)
2567 (defvar org-not-done-regexp nil
2568 "Matches any of the TODO state keywords except the last one.")
2569 (make-variable-buffer-local 'org-not-done-regexp)
2570 (defvar org-todo-line-regexp nil
2571 "Matches a headline and puts TODO state into group 2 if present.")
2572 (make-variable-buffer-local 'org-todo-line-regexp)
2573 (defvar org-complex-heading-regexp nil
2574 "Matches a headline and puts everything into groups:
2575 group 1: the stars
2576 group 2: The todo keyword, maybe
2577 group 3: Priority cookie
2578 group 4: True headline
2579 group 5: Tags")
2580 (make-variable-buffer-local 'org-complex-heading-regexp)
2581 (defvar org-todo-line-tags-regexp nil
2582 "Matches a headline and puts TODO state into group 2 if present.
2583 Also put tags into group 4 if tags are present.")
2584 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2585 (defvar org-nl-done-regexp nil
2586 "Matches newline followed by a headline with the DONE keyword.")
2587 (make-variable-buffer-local 'org-nl-done-regexp)
2588 (defvar org-looking-at-done-regexp nil
2589 "Matches the DONE keyword a point.")
2590 (make-variable-buffer-local 'org-looking-at-done-regexp)
2591 (defvar org-ds-keyword-length 12
2592 "Maximum length of the Deadline and SCHEDULED keywords.")
2593 (make-variable-buffer-local 'org-ds-keyword-length)
2594 (defvar org-deadline-regexp nil
2595 "Matches the DEADLINE keyword.")
2596 (make-variable-buffer-local 'org-deadline-regexp)
2597 (defvar org-deadline-time-regexp nil
2598 "Matches the DEADLINE keyword together with a time stamp.")
2599 (make-variable-buffer-local 'org-deadline-time-regexp)
2600 (defvar org-deadline-line-regexp nil
2601 "Matches the DEADLINE keyword and the rest of the line.")
2602 (make-variable-buffer-local 'org-deadline-line-regexp)
2603 (defvar org-scheduled-regexp nil
2604 "Matches the SCHEDULED keyword.")
2605 (make-variable-buffer-local 'org-scheduled-regexp)
2606 (defvar org-scheduled-time-regexp nil
2607 "Matches the SCHEDULED keyword together with a time stamp.")
2608 (make-variable-buffer-local 'org-scheduled-time-regexp)
2609 (defvar org-closed-time-regexp nil
2610 "Matches the CLOSED keyword together with a time stamp.")
2611 (make-variable-buffer-local 'org-closed-time-regexp)
2613 (defvar org-keyword-time-regexp nil
2614 "Matches any of the 4 keywords, together with the time stamp.")
2615 (make-variable-buffer-local 'org-keyword-time-regexp)
2616 (defvar org-keyword-time-not-clock-regexp nil
2617 "Matches any of the 3 keywords, together with the time stamp.")
2618 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2619 (defvar org-maybe-keyword-time-regexp nil
2620 "Matches a timestamp, possibly preceeded by a keyword.")
2621 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2622 (defvar org-planning-or-clock-line-re nil
2623 "Matches a line with planning or clock info.")
2624 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2626 (defconst org-plain-time-of-day-regexp
2627 (concat
2628 "\\(\\<[012]?[0-9]"
2629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2630 "\\(--?"
2631 "\\(\\<[012]?[0-9]"
2632 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2633 "\\)?")
2634 "Regular expression to match a plain time or time range.
2635 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2636 groups carry important information:
2637 0 the full match
2638 1 the first time, range or not
2639 8 the second time, if it is a range.")
2641 (defconst org-plain-time-extension-regexp
2642 (concat
2643 "\\(\\<[012]?[0-9]"
2644 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2645 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2646 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2647 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2648 groups carry important information:
2649 0 the full match
2650 7 hours of duration
2651 9 minutes of duration")
2653 (defconst org-stamp-time-of-day-regexp
2654 (concat
2655 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2656 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2657 "\\(--?"
2658 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2659 "Regular expression to match a timestamp time or time range.
2660 After a match, the following groups carry important information:
2661 0 the full match
2662 1 date plus weekday, for backreferencing to make sure both times on same day
2663 2 the first time, range or not
2664 4 the second time, if it is a range.")
2666 (defconst org-startup-options
2667 '(("fold" org-startup-folded t)
2668 ("overview" org-startup-folded t)
2669 ("nofold" org-startup-folded nil)
2670 ("showall" org-startup-folded nil)
2671 ("content" org-startup-folded content)
2672 ("hidestars" org-hide-leading-stars t)
2673 ("showstars" org-hide-leading-stars nil)
2674 ("odd" org-odd-levels-only t)
2675 ("oddeven" org-odd-levels-only nil)
2676 ("align" org-startup-align-all-tables t)
2677 ("noalign" org-startup-align-all-tables nil)
2678 ("customtime" org-display-custom-times t)
2679 ("logdone" org-log-done time)
2680 ("lognotedone" org-log-done note)
2681 ("nologdone" org-log-done nil)
2682 ("lognoteclock-out" org-log-note-clock-out t)
2683 ("nolognoteclock-out" org-log-note-clock-out nil)
2684 ("logrepeat" org-log-repeat state)
2685 ("lognoterepeat" org-log-repeat note)
2686 ("nologrepeat" org-log-repeat nil)
2687 ("constcgs" constants-unit-system cgs)
2688 ("constSI" constants-unit-system SI))
2689 "Variable associated with STARTUP options for org-mode.
2690 Each element is a list of three items: The startup options as written
2691 in the #+STARTUP line, the corresponding variable, and the value to
2692 set this variable to if the option is found. An optional forth element PUSH
2693 means to push this value onto the list in the variable.")
2695 (defun org-set-regexps-and-options ()
2696 "Precompute regular expressions for current buffer."
2697 (when (org-mode-p)
2698 (org-set-local 'org-todo-kwd-alist nil)
2699 (org-set-local 'org-todo-key-alist nil)
2700 (org-set-local 'org-todo-key-trigger nil)
2701 (org-set-local 'org-todo-keywords-1 nil)
2702 (org-set-local 'org-done-keywords nil)
2703 (org-set-local 'org-todo-heads nil)
2704 (org-set-local 'org-todo-sets nil)
2705 (org-set-local 'org-todo-log-states nil)
2706 (let ((re (org-make-options-regexp
2707 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2708 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2709 "CONSTANTS" "PROPERTY" "DRAWERS")))
2710 (splitre "[ \t]+")
2711 kwds kws0 kwsa key log value cat arch tags const links hw dws
2712 tail sep kws1 prio props drawers)
2713 (save-excursion
2714 (save-restriction
2715 (widen)
2716 (goto-char (point-min))
2717 (while (re-search-forward re nil t)
2718 (setq key (match-string 1) value (org-match-string-no-properties 2))
2719 (cond
2720 ((equal key "CATEGORY")
2721 (if (string-match "[ \t]+$" value)
2722 (setq value (replace-match "" t t value)))
2723 (setq cat value))
2724 ((member key '("SEQ_TODO" "TODO"))
2725 (push (cons 'sequence (org-split-string value splitre)) kwds))
2726 ((equal key "TYP_TODO")
2727 (push (cons 'type (org-split-string value splitre)) kwds))
2728 ((equal key "TAGS")
2729 (setq tags (append tags (org-split-string value splitre))))
2730 ((equal key "COLUMNS")
2731 (org-set-local 'org-columns-default-format value))
2732 ((equal key "LINK")
2733 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2734 (push (cons (match-string 1 value)
2735 (org-trim (match-string 2 value)))
2736 links)))
2737 ((equal key "PRIORITIES")
2738 (setq prio (org-split-string value " +")))
2739 ((equal key "PROPERTY")
2740 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2741 (push (cons (match-string 1 value) (match-string 2 value))
2742 props)))
2743 ((equal key "DRAWERS")
2744 (setq drawers (org-split-string value splitre)))
2745 ((equal key "CONSTANTS")
2746 (setq const (append const (org-split-string value splitre))))
2747 ((equal key "STARTUP")
2748 (let ((opts (org-split-string value splitre))
2749 l var val)
2750 (while (setq l (pop opts))
2751 (when (setq l (assoc l org-startup-options))
2752 (setq var (nth 1 l) val (nth 2 l))
2753 (if (not (nth 3 l))
2754 (set (make-local-variable var) val)
2755 (if (not (listp (symbol-value var)))
2756 (set (make-local-variable var) nil))
2757 (set (make-local-variable var) (symbol-value var))
2758 (add-to-list var val))))))
2759 ((equal key "ARCHIVE")
2760 (string-match " *$" value)
2761 (setq arch (replace-match "" t t value))
2762 (remove-text-properties 0 (length arch)
2763 '(face t fontified t) arch)))
2765 (when cat
2766 (org-set-local 'org-category (intern cat))
2767 (push (cons "CATEGORY" cat) props))
2768 (when prio
2769 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2770 (setq prio (mapcar 'string-to-char prio))
2771 (org-set-local 'org-highest-priority (nth 0 prio))
2772 (org-set-local 'org-lowest-priority (nth 1 prio))
2773 (org-set-local 'org-default-priority (nth 2 prio)))
2774 (and props (org-set-local 'org-local-properties (nreverse props)))
2775 (and drawers (org-set-local 'org-drawers drawers))
2776 (and arch (org-set-local 'org-archive-location arch))
2777 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2778 ;; Process the TODO keywords
2779 (unless kwds
2780 ;; Use the global values as if they had been given locally.
2781 (setq kwds (default-value 'org-todo-keywords))
2782 (if (stringp (car kwds))
2783 (setq kwds (list (cons org-todo-interpretation
2784 (default-value 'org-todo-keywords)))))
2785 (setq kwds (reverse kwds)))
2786 (setq kwds (nreverse kwds))
2787 (let (inter kws kw)
2788 (while (setq kws (pop kwds))
2789 (setq inter (pop kws) sep (member "|" kws)
2790 kws0 (delete "|" (copy-sequence kws))
2791 kwsa nil
2792 kws1 (mapcar
2793 (lambda (x)
2794 ;; 1 2
2795 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2796 (progn
2797 (setq kw (match-string 1 x)
2798 key (and (match-end 2) (match-string 2 x))
2799 log (org-extract-log-state-settings x))
2800 (push (cons kw (and key (string-to-char key))) kwsa)
2801 (and log (push log org-todo-log-states))
2803 (error "Invalid TODO keyword %s" x)))
2804 kws0)
2805 kwsa (if kwsa (append '((:startgroup))
2806 (nreverse kwsa)
2807 '((:endgroup))))
2808 hw (car kws1)
2809 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2810 tail (list inter hw (car dws) (org-last dws)))
2811 (add-to-list 'org-todo-heads hw 'append)
2812 (push kws1 org-todo-sets)
2813 (setq org-done-keywords (append org-done-keywords dws nil))
2814 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2815 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2816 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2817 (setq org-todo-sets (nreverse org-todo-sets)
2818 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2819 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2820 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2821 ;; Process the constants
2822 (when const
2823 (let (e cst)
2824 (while (setq e (pop const))
2825 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2826 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2827 (setq org-table-formula-constants-local cst)))
2829 ;; Process the tags.
2830 (when tags
2831 (let (e tgs)
2832 (while (setq e (pop tags))
2833 (cond
2834 ((equal e "{") (push '(:startgroup) tgs))
2835 ((equal e "}") (push '(:endgroup) tgs))
2836 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2837 (push (cons (match-string 1 e)
2838 (string-to-char (match-string 2 e)))
2839 tgs))
2840 (t (push (list e) tgs))))
2841 (org-set-local 'org-tag-alist nil)
2842 (while (setq e (pop tgs))
2843 (or (and (stringp (car e))
2844 (assoc (car e) org-tag-alist))
2845 (push e org-tag-alist))))))
2847 ;; Compute the regular expressions and other local variables
2848 (if (not org-done-keywords)
2849 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2850 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2851 (length org-scheduled-string)
2852 (length org-clock-string)
2853 (length org-closed-string)))
2854 org-drawer-regexp
2855 (concat "^[ \t]*:\\("
2856 (mapconcat 'regexp-quote org-drawers "\\|")
2857 "\\):[ \t]*$")
2858 org-not-done-keywords
2859 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2860 org-todo-regexp
2861 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2862 "\\|") "\\)\\>")
2863 org-not-done-regexp
2864 (concat "\\<\\("
2865 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2866 "\\)\\>")
2867 org-todo-line-regexp
2868 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2869 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2870 "\\)\\>\\)?[ \t]*\\(.*\\)")
2871 org-complex-heading-regexp
2872 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2873 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2874 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2875 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2876 org-nl-done-regexp
2877 (concat "\n\\*+[ \t]+"
2878 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2879 "\\)" "\\>")
2880 org-todo-line-tags-regexp
2881 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2882 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2883 (org-re
2884 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2885 org-looking-at-done-regexp
2886 (concat "^" "\\(?:"
2887 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2888 "\\>")
2889 org-deadline-regexp (concat "\\<" org-deadline-string)
2890 org-deadline-time-regexp
2891 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2892 org-deadline-line-regexp
2893 (concat "\\<\\(" org-deadline-string "\\).*")
2894 org-scheduled-regexp
2895 (concat "\\<" org-scheduled-string)
2896 org-scheduled-time-regexp
2897 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2898 org-closed-time-regexp
2899 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2900 org-keyword-time-regexp
2901 (concat "\\<\\(" org-scheduled-string
2902 "\\|" org-deadline-string
2903 "\\|" org-closed-string
2904 "\\|" org-clock-string "\\)"
2905 " *[[<]\\([^]>]+\\)[]>]")
2906 org-keyword-time-not-clock-regexp
2907 (concat "\\<\\(" org-scheduled-string
2908 "\\|" org-deadline-string
2909 "\\|" org-closed-string
2910 "\\)"
2911 " *[[<]\\([^]>]+\\)[]>]")
2912 org-maybe-keyword-time-regexp
2913 (concat "\\(\\<\\(" org-scheduled-string
2914 "\\|" org-deadline-string
2915 "\\|" org-closed-string
2916 "\\|" org-clock-string "\\)\\)?"
2917 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2918 org-planning-or-clock-line-re
2919 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2920 "\\|" org-deadline-string
2921 "\\|" org-closed-string "\\|" org-clock-string
2922 "\\)\\>\\)")
2924 (org-compute-latex-and-specials-regexp)
2925 (org-set-font-lock-defaults)))
2927 (defun org-extract-log-state-settings (x)
2928 "Extract the log state setting from a TODO keyword string.
2929 This will extract info from a string like \"WAIT(w@/!)\"."
2930 (let (kw key log1 log2)
2931 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2932 (setq kw (match-string 1 x)
2933 key (and (match-end 2) (match-string 2 x))
2934 log1 (and (match-end 3) (match-string 3 x))
2935 log2 (and (match-end 4) (match-string 4 x)))
2936 (and (or log1 log2)
2937 (list kw
2938 (and log1 (if (equal log1 "!") 'time 'note))
2939 (and log2 (if (equal log2 "!") 'time 'note)))))))
2941 (defun org-remove-keyword-keys (list)
2942 "Remove a pair of parenthesis at the end of each string in LIST."
2943 (mapcar (lambda (x)
2944 (if (string-match "(.*)$" x)
2945 (substring x 0 (match-beginning 0))
2947 list))
2949 ;; FIXME: this could be done much better, using second characters etc.
2950 (defun org-assign-fast-keys (alist)
2951 "Assign fast keys to a keyword-key alist.
2952 Respect keys that are already there."
2953 (let (new e k c c1 c2 (char ?a))
2954 (while (setq e (pop alist))
2955 (cond
2956 ((equal e '(:startgroup)) (push e new))
2957 ((equal e '(:endgroup)) (push e new))
2959 (setq k (car e) c2 nil)
2960 (if (cdr e)
2961 (setq c (cdr e))
2962 ;; automatically assign a character.
2963 (setq c1 (string-to-char
2964 (downcase (substring
2965 k (if (= (string-to-char k) ?@) 1 0)))))
2966 (if (or (rassoc c1 new) (rassoc c1 alist))
2967 (while (or (rassoc char new) (rassoc char alist))
2968 (setq char (1+ char)))
2969 (setq c2 c1))
2970 (setq c (or c2 char)))
2971 (push (cons k c) new))))
2972 (nreverse new)))
2974 ;;; Some variables used in various places
2976 (defvar org-window-configuration nil
2977 "Used in various places to store a window configuration.")
2978 (defvar org-finish-function nil
2979 "Function to be called when `C-c C-c' is used.
2980 This is for getting out of special buffers like remember.")
2983 ;; FIXME: Occasionally check by commenting these, to make sure
2984 ;; no other functions uses these, forgetting to let-bind them.
2985 (defvar entry)
2986 (defvar state)
2987 (defvar last-state)
2988 (defvar date)
2989 (defvar description)
2991 ;; Defined somewhere in this file, but used before definition.
2992 (defvar org-html-entities)
2993 (defvar org-struct-menu)
2994 (defvar org-org-menu)
2995 (defvar org-tbl-menu)
2996 (defvar org-agenda-keymap)
2998 ;;;; Define the Org-mode
3000 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3001 (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."))
3004 ;; We use a before-change function to check if a table might need
3005 ;; an update.
3006 (defvar org-table-may-need-update t
3007 "Indicates that a table might need an update.
3008 This variable is set by `org-before-change-function'.
3009 `org-table-align' sets it back to nil.")
3010 (defun org-before-change-function (beg end)
3011 "Every change indicates that a table might need an update."
3012 (setq org-table-may-need-update t))
3013 (defvar org-mode-map)
3014 (defvar org-mode-hook nil)
3015 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3016 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3017 (defvar org-table-buffer-is-an nil)
3018 (defconst org-outline-regexp "\\*+ ")
3020 ;;;###autoload
3021 (define-derived-mode org-mode outline-mode "Org"
3022 "Outline-based notes management and organizer, alias
3023 \"Carsten's outline-mode for keeping track of everything.\"
3025 Org-mode develops organizational tasks around a NOTES file which
3026 contains information about projects as plain text. Org-mode is
3027 implemented on top of outline-mode, which is ideal to keep the content
3028 of large files well structured. It supports ToDo items, deadlines and
3029 time stamps, which magically appear in the diary listing of the Emacs
3030 calendar. Tables are easily created with a built-in table editor.
3031 Plain text URL-like links connect to websites, emails (VM), Usenet
3032 messages (Gnus), BBDB entries, and any files related to the project.
3033 For printing and sharing of notes, an Org-mode file (or a part of it)
3034 can be exported as a structured ASCII or HTML file.
3036 The following commands are available:
3038 \\{org-mode-map}"
3040 ;; Get rid of Outline menus, they are not needed
3041 ;; Need to do this here because define-derived-mode sets up
3042 ;; the keymap so late. Still, it is a waste to call this each time
3043 ;; we switch another buffer into org-mode.
3044 (if (featurep 'xemacs)
3045 (when (boundp 'outline-mode-menu-heading)
3046 ;; Assume this is Greg's port, it used easymenu
3047 (easy-menu-remove outline-mode-menu-heading)
3048 (easy-menu-remove outline-mode-menu-show)
3049 (easy-menu-remove outline-mode-menu-hide))
3050 (define-key org-mode-map [menu-bar headings] 'undefined)
3051 (define-key org-mode-map [menu-bar hide] 'undefined)
3052 (define-key org-mode-map [menu-bar show] 'undefined))
3054 (org-load-modules-maybe)
3055 (easy-menu-add org-org-menu)
3056 (easy-menu-add org-tbl-menu)
3057 (org-install-agenda-files-menu)
3058 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3059 (org-add-to-invisibility-spec '(org-cwidth))
3060 (when (featurep 'xemacs)
3061 (org-set-local 'line-move-ignore-invisible t))
3062 (org-set-local 'outline-regexp org-outline-regexp)
3063 (org-set-local 'outline-level 'org-outline-level)
3064 (when (and org-ellipsis
3065 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3066 (fboundp 'make-glyph-code))
3067 (unless org-display-table
3068 (setq org-display-table (make-display-table)))
3069 (set-display-table-slot
3070 org-display-table 4
3071 (vconcat (mapcar
3072 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3073 org-ellipsis)))
3074 (if (stringp org-ellipsis) org-ellipsis "..."))))
3075 (setq buffer-display-table org-display-table))
3076 (org-set-regexps-and-options)
3077 ;; Calc embedded
3078 (org-set-local 'calc-embedded-open-mode "# ")
3079 (modify-syntax-entry ?# "<")
3080 (modify-syntax-entry ?@ "w")
3081 (if org-startup-truncated (setq truncate-lines t))
3082 (org-set-local 'font-lock-unfontify-region-function
3083 'org-unfontify-region)
3084 ;; Activate before-change-function
3085 (org-set-local 'org-table-may-need-update t)
3086 (org-add-hook 'before-change-functions 'org-before-change-function nil
3087 'local)
3088 ;; Check for running clock before killing a buffer
3089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3090 ;; Paragraphs and auto-filling
3091 (org-set-autofill-regexps)
3092 (setq indent-line-function 'org-indent-line-function)
3093 (org-update-radio-target-regexp)
3095 ;; Comment characters
3096 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3097 (org-set-local 'comment-padding " ")
3099 ;; Align options lines
3100 (org-set-local
3101 'align-mode-rules-list
3102 '((org-in-buffer-settings
3103 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3104 (modes . '(org-mode)))))
3106 ;; Imenu
3107 (org-set-local 'imenu-create-index-function
3108 'org-imenu-get-tree)
3110 ;; Make isearch reveal context
3111 (if (or (featurep 'xemacs)
3112 (not (boundp 'outline-isearch-open-invisible-function)))
3113 ;; Emacs 21 and XEmacs make use of the hook
3114 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3115 ;; Emacs 22 deals with this through a special variable
3116 (org-set-local 'outline-isearch-open-invisible-function
3117 (lambda (&rest ignore) (org-show-context 'isearch))))
3119 ;; If empty file that did not turn on org-mode automatically, make it to.
3120 (if (and org-insert-mode-line-in-empty-file
3121 (interactive-p)
3122 (= (point-min) (point-max)))
3123 (insert "# -*- mode: org -*-\n\n"))
3125 (unless org-inhibit-startup
3126 (when org-startup-align-all-tables
3127 (let ((bmp (buffer-modified-p)))
3128 (org-table-map-tables 'org-table-align)
3129 (set-buffer-modified-p bmp)))
3130 (org-cycle-hide-drawers 'all)
3131 (cond
3132 ((eq org-startup-folded t)
3133 (org-cycle '(4)))
3134 ((eq org-startup-folded 'content)
3135 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3136 (org-cycle '(4)) (org-cycle '(4)))))))
3138 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3140 (defun org-current-time ()
3141 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3142 (if (> (car org-time-stamp-rounding-minutes) 1)
3143 (let ((r (car org-time-stamp-rounding-minutes))
3144 (time (decode-time)))
3145 (apply 'encode-time
3146 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3147 (nthcdr 2 time))))
3148 (current-time)))
3150 ;;;; Font-Lock stuff, including the activators
3152 (defvar org-mouse-map (make-sparse-keymap))
3153 (org-defkey org-mouse-map
3154 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3155 (org-defkey org-mouse-map
3156 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3157 (when org-mouse-1-follows-link
3158 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3159 (when org-tab-follows-link
3160 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3161 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3162 (when org-return-follows-link
3163 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3164 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3166 (require 'font-lock)
3168 (defconst org-non-link-chars "]\t\n\r<>")
3169 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3170 "shell" "elisp"))
3171 (defvar org-link-types-re nil
3172 "Matches a link that has a url-like prefix like \"http:\"")
3173 (defvar org-link-re-with-space nil
3174 "Matches a link with spaces, optional angular brackets around it.")
3175 (defvar org-link-re-with-space2 nil
3176 "Matches a link with spaces, optional angular brackets around it.")
3177 (defvar org-angle-link-re nil
3178 "Matches link with angular brackets, spaces are allowed.")
3179 (defvar org-plain-link-re nil
3180 "Matches plain link, without spaces.")
3181 (defvar org-bracket-link-regexp nil
3182 "Matches a link in double brackets.")
3183 (defvar org-bracket-link-analytic-regexp nil
3184 "Regular expression used to analyze links.
3185 Here is what the match groups contain after a match:
3186 1: http:
3187 2: http
3188 3: path
3189 4: [desc]
3190 5: desc")
3191 (defvar org-any-link-re nil
3192 "Regular expression matching any link.")
3194 (defun org-make-link-regexps ()
3195 "Update the link regular expressions.
3196 This should be called after the variable `org-link-types' has changed."
3197 (setq org-link-types-re
3198 (concat
3199 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3200 org-link-re-with-space
3201 (concat
3202 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3203 "\\([^" org-non-link-chars " ]"
3204 "[^" org-non-link-chars "]*"
3205 "[^" org-non-link-chars " ]\\)>?")
3206 org-link-re-with-space2
3207 (concat
3208 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3209 "\\([^" org-non-link-chars " ]"
3210 "[^]\t\n\r]*"
3211 "[^" org-non-link-chars " ]\\)>?")
3212 org-angle-link-re
3213 (concat
3214 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3215 "\\([^" org-non-link-chars " ]"
3216 "[^" org-non-link-chars "]*"
3217 "\\)>")
3218 org-plain-link-re
3219 (concat
3220 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3221 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3222 org-bracket-link-regexp
3223 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3224 org-bracket-link-analytic-regexp
3225 (concat
3226 "\\[\\["
3227 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3228 "\\([^]]+\\)"
3229 "\\]"
3230 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3231 "\\]")
3232 org-any-link-re
3233 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3234 org-angle-link-re "\\)\\|\\("
3235 org-plain-link-re "\\)")))
3237 (org-make-link-regexps)
3239 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3240 "Regular expression for fast time stamp matching.")
3241 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3242 "Regular expression for fast time stamp matching.")
3243 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3244 "Regular expression matching time strings for analysis.
3245 This one does not require the space after the date, so it can be used
3246 on a string that terminates immediately after the date.")
3247 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3248 "Regular expression matching time strings for analysis.")
3249 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3250 "Regular expression matching time stamps, with groups.")
3251 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3252 "Regular expression matching time stamps (also [..]), with groups.")
3253 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3254 "Regular expression matching a time stamp range.")
3255 (defconst org-tr-regexp-both
3256 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3257 "Regular expression matching a time stamp range.")
3258 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3259 org-ts-regexp "\\)?")
3260 "Regular expression matching a time stamp or time stamp range.")
3261 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3262 org-ts-regexp-both "\\)?")
3263 "Regular expression matching a time stamp or time stamp range.
3264 The time stamps may be either active or inactive.")
3266 (defvar org-emph-face nil)
3268 (defun org-do-emphasis-faces (limit)
3269 "Run through the buffer and add overlays to links."
3270 (let (rtn)
3271 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3272 (if (not (= (char-after (match-beginning 3))
3273 (char-after (match-beginning 4))))
3274 (progn
3275 (setq rtn t)
3276 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3277 'face
3278 (nth 1 (assoc (match-string 3)
3279 org-emphasis-alist)))
3280 (add-text-properties (match-beginning 2) (match-end 2)
3281 '(font-lock-multiline t))
3282 (when org-hide-emphasis-markers
3283 (add-text-properties (match-end 4) (match-beginning 5)
3284 '(invisible org-link))
3285 (add-text-properties (match-beginning 3) (match-end 3)
3286 '(invisible org-link)))))
3287 (backward-char 1))
3288 rtn))
3290 (defun org-emphasize (&optional char)
3291 "Insert or change an emphasis, i.e. a font like bold or italic.
3292 If there is an active region, change that region to a new emphasis.
3293 If there is no region, just insert the marker characters and position
3294 the cursor between them.
3295 CHAR should be either the marker character, or the first character of the
3296 HTML tag associated with that emphasis. If CHAR is a space, the means
3297 to remove the emphasis of the selected region.
3298 If char is not given (for example in an interactive call) it
3299 will be prompted for."
3300 (interactive)
3301 (let ((eal org-emphasis-alist) e det
3302 (erc org-emphasis-regexp-components)
3303 (prompt "")
3304 (string "") beg end move tag c s)
3305 (if (org-region-active-p)
3306 (setq beg (region-beginning) end (region-end)
3307 string (buffer-substring beg end))
3308 (setq move t))
3310 (while (setq e (pop eal))
3311 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3312 c (aref tag 0))
3313 (push (cons c (string-to-char (car e))) det)
3314 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3315 (substring tag 1)))))
3316 (unless char
3317 (message "%s" (concat "Emphasis marker or tag:" prompt))
3318 (setq char (read-char-exclusive)))
3319 (setq char (or (cdr (assoc char det)) char))
3320 (if (equal char ?\ )
3321 (setq s "" move nil)
3322 (unless (assoc (char-to-string char) org-emphasis-alist)
3323 (error "No such emphasis marker: \"%c\"" char))
3324 (setq s (char-to-string char)))
3325 (while (and (> (length string) 1)
3326 (equal (substring string 0 1) (substring string -1))
3327 (assoc (substring string 0 1) org-emphasis-alist))
3328 (setq string (substring string 1 -1)))
3329 (setq string (concat s string s))
3330 (if beg (delete-region beg end))
3331 (unless (or (bolp)
3332 (string-match (concat "[" (nth 0 erc) "\n]")
3333 (char-to-string (char-before (point)))))
3334 (insert " "))
3335 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3336 (char-to-string (char-after (point))))
3337 (insert " ") (backward-char 1))
3338 (insert string)
3339 (and move (backward-char 1))))
3341 (defconst org-nonsticky-props
3342 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3345 (defun org-activate-plain-links (limit)
3346 "Run through the buffer and add overlays to links."
3347 (catch 'exit
3348 (let (f)
3349 (while (re-search-forward org-plain-link-re limit t)
3350 (setq f (get-text-property (match-beginning 0) 'face))
3351 (if (or (eq f 'org-tag)
3352 (and (listp f) (memq 'org-tag f)))
3354 (add-text-properties (match-beginning 0) (match-end 0)
3355 (list 'mouse-face 'highlight
3356 'rear-nonsticky org-nonsticky-props
3357 'keymap org-mouse-map
3359 (throw 'exit t))))))
3361 (defun org-activate-code (limit)
3362 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3363 (unless (get-text-property (match-beginning 1) 'face)
3364 (remove-text-properties (match-beginning 0) (match-end 0)
3365 '(display t invisible t intangible t))
3366 t)))
3368 (defun org-activate-angle-links (limit)
3369 "Run through the buffer and add overlays to links."
3370 (if (re-search-forward org-angle-link-re limit t)
3371 (progn
3372 (add-text-properties (match-beginning 0) (match-end 0)
3373 (list 'mouse-face 'highlight
3374 'rear-nonsticky org-nonsticky-props
3375 'keymap org-mouse-map
3377 t)))
3379 (defun org-activate-bracket-links (limit)
3380 "Run through the buffer and add overlays to bracketed links."
3381 (if (re-search-forward org-bracket-link-regexp limit t)
3382 (let* ((help (concat "LINK: "
3383 (org-match-string-no-properties 1)))
3384 ;; FIXME: above we should remove the escapes.
3385 ;; but that requires another match, protecting match data,
3386 ;; a lot of overhead for font-lock.
3387 (ip (org-maybe-intangible
3388 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3389 'keymap org-mouse-map 'mouse-face 'highlight
3390 'font-lock-multiline t 'help-echo help)))
3391 (vp (list 'rear-nonsticky org-nonsticky-props
3392 'keymap org-mouse-map 'mouse-face 'highlight
3393 ' font-lock-multiline t 'help-echo help)))
3394 ;; We need to remove the invisible property here. Table narrowing
3395 ;; may have made some of this invisible.
3396 (remove-text-properties (match-beginning 0) (match-end 0)
3397 '(invisible nil))
3398 (if (match-end 3)
3399 (progn
3400 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3401 (add-text-properties (match-beginning 3) (match-end 3) vp)
3402 (add-text-properties (match-end 3) (match-end 0) ip))
3403 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3404 (add-text-properties (match-beginning 1) (match-end 1) vp)
3405 (add-text-properties (match-end 1) (match-end 0) ip))
3406 t)))
3408 (defun org-activate-dates (limit)
3409 "Run through the buffer and add overlays to dates."
3410 (if (re-search-forward org-tsr-regexp-both limit t)
3411 (progn
3412 (add-text-properties (match-beginning 0) (match-end 0)
3413 (list 'mouse-face 'highlight
3414 'rear-nonsticky org-nonsticky-props
3415 'keymap org-mouse-map))
3416 (when org-display-custom-times
3417 (if (match-end 3)
3418 (org-display-custom-time (match-beginning 3) (match-end 3)))
3419 (org-display-custom-time (match-beginning 1) (match-end 1)))
3420 t)))
3422 (defvar org-target-link-regexp nil
3423 "Regular expression matching radio targets in plain text.")
3424 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3425 "Regular expression matching a link target.")
3426 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3427 "Regular expression matching a radio target.")
3428 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3429 "Regular expression matching any target.")
3431 (defun org-activate-target-links (limit)
3432 "Run through the buffer and add overlays to target matches."
3433 (when org-target-link-regexp
3434 (let ((case-fold-search t))
3435 (if (re-search-forward org-target-link-regexp limit t)
3436 (progn
3437 (add-text-properties (match-beginning 0) (match-end 0)
3438 (list 'mouse-face 'highlight
3439 'rear-nonsticky org-nonsticky-props
3440 'keymap org-mouse-map
3441 'help-echo "Radio target link"
3442 'org-linked-text t))
3443 t)))))
3445 (defun org-update-radio-target-regexp ()
3446 "Find all radio targets in this file and update the regular expression."
3447 (interactive)
3448 (when (memq 'radio org-activate-links)
3449 (setq org-target-link-regexp
3450 (org-make-target-link-regexp (org-all-targets 'radio)))
3451 (org-restart-font-lock)))
3453 (defun org-hide-wide-columns (limit)
3454 (let (s e)
3455 (setq s (text-property-any (point) (or limit (point-max))
3456 'org-cwidth t))
3457 (when s
3458 (setq e (next-single-property-change s 'org-cwidth))
3459 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3460 (goto-char e)
3461 t)))
3463 (defvar org-latex-and-specials-regexp nil
3464 "Regular expression for highlighting export special stuff.")
3465 (defvar org-match-substring-regexp)
3466 (defvar org-match-substring-with-braces-regexp)
3467 (defvar org-export-html-special-string-regexps)
3469 (defun org-compute-latex-and-specials-regexp ()
3470 "Compute regular expression for stuff treated specially by exporters."
3471 (if (not org-highlight-latex-fragments-and-specials)
3472 (org-set-local 'org-latex-and-specials-regexp nil)
3473 (require 'org-exp)
3474 (let*
3475 ((matchers (plist-get org-format-latex-options :matchers))
3476 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3477 org-latex-regexps)))
3478 (options (org-combine-plists (org-default-export-plist)
3479 (org-infile-export-plist)))
3480 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3481 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3482 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3483 (org-export-html-expand (plist-get options :expand-quoted-html))
3484 (org-export-with-special-strings (plist-get options :special-strings))
3485 (re-sub
3486 (cond
3487 ((equal org-export-with-sub-superscripts '{})
3488 (list org-match-substring-with-braces-regexp))
3489 (org-export-with-sub-superscripts
3490 (list org-match-substring-regexp))
3491 (t nil)))
3492 (re-latex
3493 (if org-export-with-LaTeX-fragments
3494 (mapcar (lambda (x) (nth 1 x)) latexs)))
3495 (re-macros
3496 (if org-export-with-TeX-macros
3497 (list (concat "\\\\"
3498 (regexp-opt
3499 (append (mapcar 'car org-html-entities)
3500 (if (boundp 'org-latex-entities)
3501 org-latex-entities nil))
3502 'words))) ; FIXME
3504 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3505 (re-special (if org-export-with-special-strings
3506 (mapcar (lambda (x) (car x))
3507 org-export-html-special-string-regexps)))
3508 (re-rest
3509 (delq nil
3510 (list
3511 (if org-export-html-expand "@<[^>\n]+>")
3512 ))))
3513 (org-set-local
3514 'org-latex-and-specials-regexp
3515 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3516 re-rest) "\\|")))))
3518 (defun org-do-latex-and-special-faces (limit)
3519 "Run through the buffer and add overlays to links."
3520 (when org-latex-and-specials-regexp
3521 (let (rtn d)
3522 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3523 limit t))
3524 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3525 'face))
3526 '(org-code org-verbatim underline)))
3527 (progn
3528 (setq rtn t
3529 d (cond ((member (char-after (1+ (match-beginning 0)))
3530 '(?_ ?^)) 1)
3531 (t 0)))
3532 (font-lock-prepend-text-property
3533 (+ d (match-beginning 0)) (match-end 0)
3534 'face 'org-latex-and-export-specials)
3535 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3536 '(font-lock-multiline t)))))
3537 rtn)))
3539 (defun org-restart-font-lock ()
3540 "Restart font-lock-mode, to force refontification."
3541 (when (and (boundp 'font-lock-mode) font-lock-mode)
3542 (font-lock-mode -1)
3543 (font-lock-mode 1)))
3545 (defun org-all-targets (&optional radio)
3546 "Return a list of all targets in this file.
3547 With optional argument RADIO, only find radio targets."
3548 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3549 rtn)
3550 (save-excursion
3551 (goto-char (point-min))
3552 (while (re-search-forward re nil t)
3553 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3554 rtn)))
3556 (defun org-make-target-link-regexp (targets)
3557 "Make regular expression matching all strings in TARGETS.
3558 The regular expression finds the targets also if there is a line break
3559 between words."
3560 (and targets
3561 (concat
3562 "\\<\\("
3563 (mapconcat
3564 (lambda (x)
3565 (while (string-match " +" x)
3566 (setq x (replace-match "\\s-+" t t x)))
3568 targets
3569 "\\|")
3570 "\\)\\>")))
3572 (defun org-activate-tags (limit)
3573 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3574 (progn
3575 (add-text-properties (match-beginning 1) (match-end 1)
3576 (list 'mouse-face 'highlight
3577 'rear-nonsticky org-nonsticky-props
3578 'keymap org-mouse-map))
3579 t)))
3581 (defun org-outline-level ()
3582 (save-excursion
3583 (looking-at outline-regexp)
3584 (if (match-beginning 1)
3585 (+ (org-get-string-indentation (match-string 1)) 1000)
3586 (1- (- (match-end 0) (match-beginning 0))))))
3588 (defvar org-font-lock-keywords nil)
3590 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3591 "Regular expression matching a property line.")
3593 (defvar org-font-lock-hook nil
3594 "Functions to be called for special font loch stuff.")
3596 (defun org-font-lock-hook (limit)
3597 (run-hook-with-args 'org-font-lock-hook limit))
3599 (defun org-set-font-lock-defaults ()
3600 (let* ((em org-fontify-emphasized-text)
3601 (lk org-activate-links)
3602 (org-font-lock-extra-keywords
3603 (list
3604 ;; Call the hook
3605 '(org-font-lock-hook)
3606 ;; Headlines
3607 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3608 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3609 ;; Table lines
3610 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3611 (1 'org-table t))
3612 ;; Table internals
3613 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3614 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3615 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3616 ;; Drawers
3617 (list org-drawer-regexp '(0 'org-special-keyword t))
3618 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3619 ;; Properties
3620 (list org-property-re
3621 '(1 'org-special-keyword t)
3622 '(3 'org-property-value t))
3623 (if org-format-transports-properties-p
3624 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3625 ;; Links
3626 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3627 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3628 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3629 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3630 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3631 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3632 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3633 '(org-hide-wide-columns (0 nil append))
3634 ;; TODO lines
3635 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3636 '(1 (org-get-todo-face 1) t))
3637 ;; DONE
3638 (if org-fontify-done-headline
3639 (list (concat "^[*]+ +\\<\\("
3640 (mapconcat 'regexp-quote org-done-keywords "\\|")
3641 "\\)\\(.*\\)")
3642 '(2 'org-headline-done t))
3643 nil)
3644 ;; Priorities
3645 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3646 ;; Special keywords
3647 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3648 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3649 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3650 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3651 ;; Emphasis
3652 (if em
3653 (if (featurep 'xemacs)
3654 '(org-do-emphasis-faces (0 nil append))
3655 '(org-do-emphasis-faces)))
3656 ;; Checkboxes
3657 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3658 2 'bold prepend)
3659 (if org-provide-checkbox-statistics
3660 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3661 (0 (org-get-checkbox-statistics-face) t)))
3662 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3663 '(1 'org-archived prepend))
3664 ;; Specials
3665 '(org-do-latex-and-special-faces)
3666 ;; Code
3667 '(org-activate-code (1 'org-code t))
3668 ;; COMMENT
3669 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3670 "\\|" org-quote-string "\\)\\>")
3671 '(1 'org-special-keyword t))
3672 '("^#.*" (0 'font-lock-comment-face t))
3674 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3675 ;; Now set the full font-lock-keywords
3676 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3677 (org-set-local 'font-lock-defaults
3678 '(org-font-lock-keywords t nil nil backward-paragraph))
3679 (kill-local-variable 'font-lock-keywords) nil))
3681 (defvar org-m nil)
3682 (defvar org-l nil)
3683 (defvar org-f nil)
3684 (defun org-get-level-face (n)
3685 "Get the right face for match N in font-lock matching of healdines."
3686 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3687 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3688 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3689 (cond
3690 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3691 ((eq n 2) org-f)
3692 (t (if org-level-color-stars-only nil org-f))))
3694 (defun org-get-todo-face (kwd)
3695 "Get the right face for a TODO keyword KWD.
3696 If KWD is a number, get the corresponding match group."
3697 (if (numberp kwd) (setq kwd (match-string kwd)))
3698 (or (cdr (assoc kwd org-todo-keyword-faces))
3699 (and (member kwd org-done-keywords) 'org-done)
3700 'org-todo))
3702 (defun org-unfontify-region (beg end &optional maybe_loudly)
3703 "Remove fontification and activation overlays from links."
3704 (font-lock-default-unfontify-region beg end)
3705 (let* ((buffer-undo-list t)
3706 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3707 (inhibit-modification-hooks t)
3708 deactivate-mark buffer-file-name buffer-file-truename)
3709 (remove-text-properties beg end
3710 '(mouse-face t keymap t org-linked-text t
3711 invisible t intangible t))))
3713 ;;;; Visibility cycling, including org-goto and indirect buffer
3715 ;;; Cycling
3717 (defvar org-cycle-global-status nil)
3718 (make-variable-buffer-local 'org-cycle-global-status)
3719 (defvar org-cycle-subtree-status nil)
3720 (make-variable-buffer-local 'org-cycle-subtree-status)
3722 ;;;###autoload
3723 (defun org-cycle (&optional arg)
3724 "Visibility cycling for Org-mode.
3726 - When this function is called with a prefix argument, rotate the entire
3727 buffer through 3 states (global cycling)
3728 1. OVERVIEW: Show only top-level headlines.
3729 2. CONTENTS: Show all headlines of all levels, but no body text.
3730 3. SHOW ALL: Show everything.
3732 - When point is at the beginning of a headline, rotate the subtree started
3733 by this line through 3 different states (local cycling)
3734 1. FOLDED: Only the main headline is shown.
3735 2. CHILDREN: The main headline and the direct children are shown.
3736 From this state, you can move to one of the children
3737 and zoom in further.
3738 3. SUBTREE: Show the entire subtree, including body text.
3740 - When there is a numeric prefix, go up to a heading with level ARG, do
3741 a `show-subtree' and return to the previous cursor position. If ARG
3742 is negative, go up that many levels.
3744 - When point is not at the beginning of a headline, execute
3745 `indent-relative', like TAB normally does. See the option
3746 `org-cycle-emulate-tab' for details.
3748 - Special case: if point is at the beginning of the buffer and there is
3749 no headline in line 1, this function will act as if called with prefix arg.
3750 But only if also the variable `org-cycle-global-at-bob' is t."
3751 (interactive "P")
3752 (org-load-modules-maybe)
3753 (let* ((outline-regexp
3754 (if (and (org-mode-p) org-cycle-include-plain-lists)
3755 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3756 outline-regexp))
3757 (bob-special (and org-cycle-global-at-bob (bobp)
3758 (not (looking-at outline-regexp))))
3759 (org-cycle-hook
3760 (if bob-special
3761 (delq 'org-optimize-window-after-visibility-change
3762 (copy-sequence org-cycle-hook))
3763 org-cycle-hook))
3764 (pos (point)))
3766 (if (or bob-special (equal arg '(4)))
3767 ;; special case: use global cycling
3768 (setq arg t))
3770 (cond
3772 ((org-at-table-p 'any)
3773 ;; Enter the table or move to the next field in the table
3774 (or (org-table-recognize-table.el)
3775 (progn
3776 (if arg (org-table-edit-field t)
3777 (org-table-justify-field-maybe)
3778 (call-interactively 'org-table-next-field)))))
3780 ((eq arg t) ;; Global cycling
3782 (cond
3783 ((and (eq last-command this-command)
3784 (eq org-cycle-global-status 'overview))
3785 ;; We just created the overview - now do table of contents
3786 ;; This can be slow in very large buffers, so indicate action
3787 (message "CONTENTS...")
3788 (org-content)
3789 (message "CONTENTS...done")
3790 (setq org-cycle-global-status 'contents)
3791 (run-hook-with-args 'org-cycle-hook 'contents))
3793 ((and (eq last-command this-command)
3794 (eq org-cycle-global-status 'contents))
3795 ;; We just showed the table of contents - now show everything
3796 (show-all)
3797 (message "SHOW ALL")
3798 (setq org-cycle-global-status 'all)
3799 (run-hook-with-args 'org-cycle-hook 'all))
3802 ;; Default action: go to overview
3803 (org-overview)
3804 (message "OVERVIEW")
3805 (setq org-cycle-global-status 'overview)
3806 (run-hook-with-args 'org-cycle-hook 'overview))))
3808 ((and org-drawers org-drawer-regexp
3809 (save-excursion
3810 (beginning-of-line 1)
3811 (looking-at org-drawer-regexp)))
3812 ;; Toggle block visibility
3813 (org-flag-drawer
3814 (not (get-char-property (match-end 0) 'invisible))))
3816 ((integerp arg)
3817 ;; Show-subtree, ARG levels up from here.
3818 (save-excursion
3819 (org-back-to-heading)
3820 (outline-up-heading (if (< arg 0) (- arg)
3821 (- (funcall outline-level) arg)))
3822 (org-show-subtree)))
3824 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3825 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3826 ;; At a heading: rotate between three different views
3827 (org-back-to-heading)
3828 (let ((goal-column 0) eoh eol eos)
3829 ;; First, some boundaries
3830 (save-excursion
3831 (org-back-to-heading)
3832 (save-excursion
3833 (beginning-of-line 2)
3834 (while (and (not (eobp)) ;; this is like `next-line'
3835 (get-char-property (1- (point)) 'invisible))
3836 (beginning-of-line 2)) (setq eol (point)))
3837 (outline-end-of-heading) (setq eoh (point))
3838 (org-end-of-subtree t)
3839 (unless (eobp)
3840 (skip-chars-forward " \t\n")
3841 (beginning-of-line 1) ; in case this is an item
3843 (setq eos (1- (point))))
3844 ;; Find out what to do next and set `this-command'
3845 (cond
3846 ((= eos eoh)
3847 ;; Nothing is hidden behind this heading
3848 (message "EMPTY ENTRY")
3849 (setq org-cycle-subtree-status nil)
3850 (save-excursion
3851 (goto-char eos)
3852 (outline-next-heading)
3853 (if (org-invisible-p) (org-flag-heading nil))))
3854 ((or (>= eol eos)
3855 (not (string-match "\\S-" (buffer-substring eol eos))))
3856 ;; Entire subtree is hidden in one line: open it
3857 (org-show-entry)
3858 (show-children)
3859 (message "CHILDREN")
3860 (save-excursion
3861 (goto-char eos)
3862 (outline-next-heading)
3863 (if (org-invisible-p) (org-flag-heading nil)))
3864 (setq org-cycle-subtree-status 'children)
3865 (run-hook-with-args 'org-cycle-hook 'children))
3866 ((and (eq last-command this-command)
3867 (eq org-cycle-subtree-status 'children))
3868 ;; We just showed the children, now show everything.
3869 (org-show-subtree)
3870 (message "SUBTREE")
3871 (setq org-cycle-subtree-status 'subtree)
3872 (run-hook-with-args 'org-cycle-hook 'subtree))
3874 ;; Default action: hide the subtree.
3875 (hide-subtree)
3876 (message "FOLDED")
3877 (setq org-cycle-subtree-status 'folded)
3878 (run-hook-with-args 'org-cycle-hook 'folded)))))
3880 ;; TAB emulation
3881 (buffer-read-only (org-back-to-heading))
3883 ((org-try-cdlatex-tab))
3885 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3886 (or (not (bolp))
3887 (not (looking-at outline-regexp))))
3888 (call-interactively (global-key-binding "\t")))
3890 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3891 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3892 (or (and (eq org-cycle-emulate-tab 'white)
3893 (= (match-end 0) (point-at-eol)))
3894 (and (eq org-cycle-emulate-tab 'whitestart)
3895 (>= (match-end 0) pos))))
3897 (eq org-cycle-emulate-tab t))
3898 (call-interactively (global-key-binding "\t")))
3900 (t (save-excursion
3901 (org-back-to-heading)
3902 (org-cycle))))))
3904 ;;;###autoload
3905 (defun org-global-cycle (&optional arg)
3906 "Cycle the global visibility. For details see `org-cycle'."
3907 (interactive "P")
3908 (let ((org-cycle-include-plain-lists
3909 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3910 (if (integerp arg)
3911 (progn
3912 (show-all)
3913 (hide-sublevels arg)
3914 (setq org-cycle-global-status 'contents))
3915 (org-cycle '(4)))))
3917 (defun org-overview ()
3918 "Switch to overview mode, shoing only top-level headlines.
3919 Really, this shows all headlines with level equal or greater than the level
3920 of the first headline in the buffer. This is important, because if the
3921 first headline is not level one, then (hide-sublevels 1) gives confusing
3922 results."
3923 (interactive)
3924 (let ((level (save-excursion
3925 (goto-char (point-min))
3926 (if (re-search-forward (concat "^" outline-regexp) nil t)
3927 (progn
3928 (goto-char (match-beginning 0))
3929 (funcall outline-level))))))
3930 (and level (hide-sublevels level))))
3932 (defun org-content (&optional arg)
3933 "Show all headlines in the buffer, like a table of contents.
3934 With numerical argument N, show content up to level N."
3935 (interactive "P")
3936 (save-excursion
3937 ;; Visit all headings and show their offspring
3938 (and (integerp arg) (org-overview))
3939 (goto-char (point-max))
3940 (catch 'exit
3941 (while (and (progn (condition-case nil
3942 (outline-previous-visible-heading 1)
3943 (error (goto-char (point-min))))
3945 (looking-at outline-regexp))
3946 (if (integerp arg)
3947 (show-children (1- arg))
3948 (show-branches))
3949 (if (bobp) (throw 'exit nil))))))
3952 (defun org-optimize-window-after-visibility-change (state)
3953 "Adjust the window after a change in outline visibility.
3954 This function is the default value of the hook `org-cycle-hook'."
3955 (when (get-buffer-window (current-buffer))
3956 (cond
3957 ; ((eq state 'overview) (org-first-headline-recenter 1))
3958 ; ((eq state 'overview) (org-beginning-of-line))
3959 ((eq state 'content) nil)
3960 ((eq state 'all) nil)
3961 ((eq state 'folded) nil)
3962 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3963 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3965 (defun org-compact-display-after-subtree-move ()
3966 (let (beg end)
3967 (save-excursion
3968 (if (org-up-heading-safe)
3969 (progn
3970 (hide-subtree)
3971 (show-entry)
3972 (show-children)
3973 (org-cycle-show-empty-lines 'children)
3974 (org-cycle-hide-drawers 'children))
3975 (org-overview)))))
3977 (defun org-cycle-show-empty-lines (state)
3978 "Show empty lines above all visible headlines.
3979 The region to be covered depends on STATE when called through
3980 `org-cycle-hook'. Lisp program can use t for STATE to get the
3981 entire buffer covered. Note that an empty line is only shown if there
3982 are at least `org-cycle-separator-lines' empty lines before the headeline."
3983 (when (> org-cycle-separator-lines 0)
3984 (save-excursion
3985 (let* ((n org-cycle-separator-lines)
3986 (re (cond
3987 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3988 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3989 (t (let ((ns (number-to-string (- n 2))))
3990 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3991 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3992 beg end)
3993 (cond
3994 ((memq state '(overview contents t))
3995 (setq beg (point-min) end (point-max)))
3996 ((memq state '(children folded))
3997 (setq beg (point) end (progn (org-end-of-subtree t t)
3998 (beginning-of-line 2)
3999 (point)))))
4000 (when beg
4001 (goto-char beg)
4002 (while (re-search-forward re end t)
4003 (if (not (get-char-property (match-end 1) 'invisible))
4004 (outline-flag-region
4005 (match-beginning 1) (match-end 1) nil)))))))
4006 ;; Never hide empty lines at the end of the file.
4007 (save-excursion
4008 (goto-char (point-max))
4009 (outline-previous-heading)
4010 (outline-end-of-heading)
4011 (if (and (looking-at "[ \t\n]+")
4012 (= (match-end 0) (point-max)))
4013 (outline-flag-region (point) (match-end 0) nil))))
4015 (defun org-cycle-hide-drawers (state)
4016 "Re-hide all drawers after a visibility state change."
4017 (when (and (org-mode-p)
4018 (not (memq state '(overview folded))))
4019 (save-excursion
4020 (let* ((globalp (memq state '(contents all)))
4021 (beg (if globalp (point-min) (point)))
4022 (end (if globalp (point-max) (org-end-of-subtree t))))
4023 (goto-char beg)
4024 (while (re-search-forward org-drawer-regexp end t)
4025 (org-flag-drawer t))))))
4027 (defun org-flag-drawer (flag)
4028 (save-excursion
4029 (beginning-of-line 1)
4030 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4031 (let ((b (match-end 0))
4032 (outline-regexp org-outline-regexp))
4033 (if (re-search-forward
4034 "^[ \t]*:END:"
4035 (save-excursion (outline-next-heading) (point)) t)
4036 (outline-flag-region b (point-at-eol) flag)
4037 (error ":END: line missing"))))))
4039 (defun org-subtree-end-visible-p ()
4040 "Is the end of the current subtree visible?"
4041 (pos-visible-in-window-p
4042 (save-excursion (org-end-of-subtree t) (point))))
4044 (defun org-first-headline-recenter (&optional N)
4045 "Move cursor to the first headline and recenter the headline.
4046 Optional argument N means, put the headline into the Nth line of the window."
4047 (goto-char (point-min))
4048 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4049 (beginning-of-line)
4050 (recenter (prefix-numeric-value N))))
4052 ;;; Org-goto
4054 (defvar org-goto-window-configuration nil)
4055 (defvar org-goto-marker nil)
4056 (defvar org-goto-map
4057 (let ((map (make-sparse-keymap)))
4058 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4059 (while (setq cmd (pop cmds))
4060 (substitute-key-definition cmd cmd map global-map)))
4061 (suppress-keymap map)
4062 (org-defkey map "\C-m" 'org-goto-ret)
4063 (org-defkey map [(return)] 'org-goto-ret)
4064 (org-defkey map [(left)] 'org-goto-left)
4065 (org-defkey map [(right)] 'org-goto-right)
4066 (org-defkey map [(control ?g)] 'org-goto-quit)
4067 (org-defkey map "\C-i" 'org-cycle)
4068 (org-defkey map [(tab)] 'org-cycle)
4069 (org-defkey map [(down)] 'outline-next-visible-heading)
4070 (org-defkey map [(up)] 'outline-previous-visible-heading)
4071 (if org-goto-auto-isearch
4072 (if (fboundp 'define-key-after)
4073 (define-key-after map [t] 'org-goto-local-auto-isearch)
4074 nil)
4075 (org-defkey map "q" 'org-goto-quit)
4076 (org-defkey map "n" 'outline-next-visible-heading)
4077 (org-defkey map "p" 'outline-previous-visible-heading)
4078 (org-defkey map "f" 'outline-forward-same-level)
4079 (org-defkey map "b" 'outline-backward-same-level)
4080 (org-defkey map "u" 'outline-up-heading))
4081 (org-defkey map "/" 'org-occur)
4082 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4083 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4084 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4085 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4086 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4087 map))
4089 (defconst org-goto-help
4090 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4091 RET=jump to location [Q]uit and return to previous location
4092 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4094 (defvar org-goto-start-pos) ; dynamically scoped parameter
4096 (defun org-goto (&optional alternative-interface)
4097 "Look up a different location in the current file, keeping current visibility.
4099 When you want look-up or go to a different location in a document, the
4100 fastest way is often to fold the entire buffer and then dive into the tree.
4101 This method has the disadvantage, that the previous location will be folded,
4102 which may not be what you want.
4104 This command works around this by showing a copy of the current buffer
4105 in an indirect buffer, in overview mode. You can dive into the tree in
4106 that copy, use org-occur and incremental search to find a location.
4107 When pressing RET or `Q', the command returns to the original buffer in
4108 which the visibility is still unchanged. After RET is will also jump to
4109 the location selected in the indirect buffer and expose the
4110 the headline hierarchy above."
4111 (interactive "P")
4112 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4113 (org-refile-use-outline-path t)
4114 (interface
4115 (if (not alternative-interface)
4116 org-goto-interface
4117 (if (eq org-goto-interface 'outline)
4118 'outline-path-completion
4119 'outline)))
4120 (org-goto-start-pos (point))
4121 (selected-point
4122 (if (eq interface 'outline)
4123 (car (org-get-location (current-buffer) org-goto-help))
4124 (nth 3 (org-refile-get-location "Goto: ")))))
4125 (if selected-point
4126 (progn
4127 (org-mark-ring-push org-goto-start-pos)
4128 (goto-char selected-point)
4129 (if (or (org-invisible-p) (org-invisible-p2))
4130 (org-show-context 'org-goto)))
4131 (message "Quit"))))
4133 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4134 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4135 (defvar org-goto-local-auto-isearch-map) ; defined below
4137 (defun org-get-location (buf help)
4138 "Let the user select a location in the Org-mode buffer BUF.
4139 This function uses a recursive edit. It returns the selected position
4140 or nil."
4141 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4142 (isearch-hide-immediately nil)
4143 (isearch-search-fun-function
4144 (lambda () 'org-goto-local-search-forward-headings))
4145 (org-goto-selected-point org-goto-exit-command))
4146 (save-excursion
4147 (save-window-excursion
4148 (delete-other-windows)
4149 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4150 (switch-to-buffer
4151 (condition-case nil
4152 (make-indirect-buffer (current-buffer) "*org-goto*")
4153 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4154 (with-output-to-temp-buffer "*Help*"
4155 (princ help))
4156 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4157 (setq buffer-read-only nil)
4158 (let ((org-startup-truncated t)
4159 (org-startup-folded nil)
4160 (org-startup-align-all-tables nil))
4161 (org-mode)
4162 (org-overview))
4163 (setq buffer-read-only t)
4164 (if (and (boundp 'org-goto-start-pos)
4165 (integer-or-marker-p org-goto-start-pos))
4166 (let ((org-show-hierarchy-above t)
4167 (org-show-siblings t)
4168 (org-show-following-heading t))
4169 (goto-char org-goto-start-pos)
4170 (and (org-invisible-p) (org-show-context)))
4171 (goto-char (point-min)))
4172 (org-beginning-of-line)
4173 (message "Select location and press RET")
4174 (use-local-map org-goto-map)
4175 (recursive-edit)
4177 (kill-buffer "*org-goto*")
4178 (cons org-goto-selected-point org-goto-exit-command)))
4180 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4181 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4182 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4183 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4185 (defun org-goto-local-search-forward-headings (string bound noerror)
4186 "Search and make sure that anu matches are in headlines."
4187 (catch 'return
4188 (while (search-forward string bound noerror)
4189 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4190 (and (member :headline context)
4191 (not (member :tags context))))
4192 (throw 'return (point))))))
4194 (defun org-goto-local-auto-isearch ()
4195 "Start isearch."
4196 (interactive)
4197 (goto-char (point-min))
4198 (let ((keys (this-command-keys)))
4199 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4200 (isearch-mode t)
4201 (isearch-process-search-char (string-to-char keys)))))
4203 (defun org-goto-ret (&optional arg)
4204 "Finish `org-goto' by going to the new location."
4205 (interactive "P")
4206 (setq org-goto-selected-point (point)
4207 org-goto-exit-command 'return)
4208 (throw 'exit nil))
4210 (defun org-goto-left ()
4211 "Finish `org-goto' by going to the new location."
4212 (interactive)
4213 (if (org-on-heading-p)
4214 (progn
4215 (beginning-of-line 1)
4216 (setq org-goto-selected-point (point)
4217 org-goto-exit-command 'left)
4218 (throw 'exit nil))
4219 (error "Not on a heading")))
4221 (defun org-goto-right ()
4222 "Finish `org-goto' by going to the new location."
4223 (interactive)
4224 (if (org-on-heading-p)
4225 (progn
4226 (setq org-goto-selected-point (point)
4227 org-goto-exit-command 'right)
4228 (throw 'exit nil))
4229 (error "Not on a heading")))
4231 (defun org-goto-quit ()
4232 "Finish `org-goto' without cursor motion."
4233 (interactive)
4234 (setq org-goto-selected-point nil)
4235 (setq org-goto-exit-command 'quit)
4236 (throw 'exit nil))
4238 ;;; Indirect buffer display of subtrees
4240 (defvar org-indirect-dedicated-frame nil
4241 "This is the frame being used for indirect tree display.")
4242 (defvar org-last-indirect-buffer nil)
4244 (defun org-tree-to-indirect-buffer (&optional arg)
4245 "Create indirect buffer and narrow it to current subtree.
4246 With numerical prefix ARG, go up to this level and then take that tree.
4247 If ARG is negative, go up that many levels.
4248 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4249 indirect buffer previously made with this command, to avoid proliferation of
4250 indirect buffers. However, when you call the command with a `C-u' prefix, or
4251 when `org-indirect-buffer-display' is `new-frame', the last buffer
4252 is kept so that you can work with several indirect buffers at the same time.
4253 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4254 requests that a new frame be made for the new buffer, so that the dedicated
4255 frame is not changed."
4256 (interactive "P")
4257 (let ((cbuf (current-buffer))
4258 (cwin (selected-window))
4259 (pos (point))
4260 beg end level heading ibuf)
4261 (save-excursion
4262 (org-back-to-heading t)
4263 (when (numberp arg)
4264 (setq level (org-outline-level))
4265 (if (< arg 0) (setq arg (+ level arg)))
4266 (while (> (setq level (org-outline-level)) arg)
4267 (outline-up-heading 1 t)))
4268 (setq beg (point)
4269 heading (org-get-heading))
4270 (org-end-of-subtree t) (setq end (point)))
4271 (if (and (buffer-live-p org-last-indirect-buffer)
4272 (not (eq org-indirect-buffer-display 'new-frame))
4273 (not arg))
4274 (kill-buffer org-last-indirect-buffer))
4275 (setq ibuf (org-get-indirect-buffer cbuf)
4276 org-last-indirect-buffer ibuf)
4277 (cond
4278 ((or (eq org-indirect-buffer-display 'new-frame)
4279 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4280 (select-frame (make-frame))
4281 (delete-other-windows)
4282 (switch-to-buffer ibuf)
4283 (org-set-frame-title heading))
4284 ((eq org-indirect-buffer-display 'dedicated-frame)
4285 (raise-frame
4286 (select-frame (or (and org-indirect-dedicated-frame
4287 (frame-live-p org-indirect-dedicated-frame)
4288 org-indirect-dedicated-frame)
4289 (setq org-indirect-dedicated-frame (make-frame)))))
4290 (delete-other-windows)
4291 (switch-to-buffer ibuf)
4292 (org-set-frame-title (concat "Indirect: " heading)))
4293 ((eq org-indirect-buffer-display 'current-window)
4294 (switch-to-buffer ibuf))
4295 ((eq org-indirect-buffer-display 'other-window)
4296 (pop-to-buffer ibuf))
4297 (t (error "Invalid value.")))
4298 (if (featurep 'xemacs)
4299 (save-excursion (org-mode) (turn-on-font-lock)))
4300 (narrow-to-region beg end)
4301 (show-all)
4302 (goto-char pos)
4303 (and (window-live-p cwin) (select-window cwin))))
4305 (defun org-get-indirect-buffer (&optional buffer)
4306 (setq buffer (or buffer (current-buffer)))
4307 (let ((n 1) (base (buffer-name buffer)) bname)
4308 (while (buffer-live-p
4309 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4310 (setq n (1+ n)))
4311 (condition-case nil
4312 (make-indirect-buffer buffer bname 'clone)
4313 (error (make-indirect-buffer buffer bname)))))
4315 (defun org-set-frame-title (title)
4316 "Set the title of the current frame to the string TITLE."
4317 ;; FIXME: how to name a single frame in XEmacs???
4318 (unless (featurep 'xemacs)
4319 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4321 ;;;; Structure editing
4323 ;;; Inserting headlines
4325 (defun org-insert-heading (&optional force-heading)
4326 "Insert a new heading or item with same depth at point.
4327 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4328 If point is at the beginning of a headline, insert a sibling before the
4329 current headline. If point is not at the beginning, do not split the line,
4330 but create the new hedline after the current line."
4331 (interactive "P")
4332 (if (= (buffer-size) 0)
4333 (insert "\n* ")
4334 (when (or force-heading (not (org-insert-item)))
4335 (let* ((head (save-excursion
4336 (condition-case nil
4337 (progn
4338 (org-back-to-heading)
4339 (match-string 0))
4340 (error "*"))))
4341 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4342 pos)
4343 (cond
4344 ((and (org-on-heading-p) (bolp)
4345 (or (bobp)
4346 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4347 ;; insert before the current line
4348 (open-line (if blank 2 1)))
4349 ((and (bolp)
4350 (or (bobp)
4351 (save-excursion
4352 (backward-char 1) (not (org-invisible-p)))))
4353 ;; insert right here
4354 nil)
4356 ;; in the middle of the line
4357 (org-show-entry)
4358 (let ((split
4359 (org-get-alist-option org-M-RET-may-split-line 'headline))
4360 tags pos)
4361 (if (org-on-heading-p)
4362 (progn
4363 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4364 (setq tags (and (match-end 2) (match-string 2)))
4365 (and (match-end 1)
4366 (delete-region (match-beginning 1) (match-end 1)))
4367 (setq pos (point-at-bol))
4368 (or split (end-of-line 1))
4369 (delete-horizontal-space)
4370 (newline (if blank 2 1))
4371 (when tags
4372 (save-excursion
4373 (goto-char pos)
4374 (end-of-line 1)
4375 (insert " " tags)
4376 (org-set-tags nil 'align))))
4377 (or split (end-of-line 1))
4378 (newline (if blank 2 1))))))
4379 (insert head) (just-one-space)
4380 (setq pos (point))
4381 (end-of-line 1)
4382 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4383 (run-hooks 'org-insert-heading-hook)))))
4385 (defun org-get-heading (&optional no-tags)
4386 "Return the heading of the current entry, without the stars."
4387 (save-excursion
4388 (org-back-to-heading t)
4389 (if (looking-at
4390 (if no-tags
4391 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4392 "\\*+[ \t]+\\([^\r\n]*\\)"))
4393 (match-string 1) "")))
4395 (defun org-insert-heading-after-current ()
4396 "Insert a new heading with same level as current, after current subtree."
4397 (interactive)
4398 (org-back-to-heading)
4399 (org-insert-heading)
4400 (org-move-subtree-down)
4401 (end-of-line 1))
4403 (defun org-insert-todo-heading (arg)
4404 "Insert a new heading with the same level and TODO state as current heading.
4405 If the heading has no TODO state, or if the state is DONE, use the first
4406 state (TODO by default). Also with prefix arg, force first state."
4407 (interactive "P")
4408 (when (not (org-insert-item 'checkbox))
4409 (org-insert-heading)
4410 (save-excursion
4411 (org-back-to-heading)
4412 (outline-previous-heading)
4413 (looking-at org-todo-line-regexp))
4414 (if (or arg
4415 (not (match-beginning 2))
4416 (member (match-string 2) org-done-keywords))
4417 (insert (car org-todo-keywords-1) " ")
4418 (insert (match-string 2) " "))))
4420 (defun org-insert-subheading (arg)
4421 "Insert a new subheading and demote it.
4422 Works for outline headings and for plain lists alike."
4423 (interactive "P")
4424 (org-insert-heading arg)
4425 (cond
4426 ((org-on-heading-p) (org-do-demote))
4427 ((org-at-item-p) (org-indent-item 1))))
4429 (defun org-insert-todo-subheading (arg)
4430 "Insert a new subheading with TODO keyword or checkbox and demote it.
4431 Works for outline headings and for plain lists alike."
4432 (interactive "P")
4433 (org-insert-todo-heading arg)
4434 (cond
4435 ((org-on-heading-p) (org-do-demote))
4436 ((org-at-item-p) (org-indent-item 1))))
4438 ;;; Promotion and Demotion
4440 (defun org-promote-subtree ()
4441 "Promote the entire subtree.
4442 See also `org-promote'."
4443 (interactive)
4444 (save-excursion
4445 (org-map-tree 'org-promote))
4446 (org-fix-position-after-promote))
4448 (defun org-demote-subtree ()
4449 "Demote the entire subtree. See `org-demote'.
4450 See also `org-promote'."
4451 (interactive)
4452 (save-excursion
4453 (org-map-tree 'org-demote))
4454 (org-fix-position-after-promote))
4457 (defun org-do-promote ()
4458 "Promote the current heading higher up the tree.
4459 If the region is active in `transient-mark-mode', promote all headings
4460 in the region."
4461 (interactive)
4462 (save-excursion
4463 (if (org-region-active-p)
4464 (org-map-region 'org-promote (region-beginning) (region-end))
4465 (org-promote)))
4466 (org-fix-position-after-promote))
4468 (defun org-do-demote ()
4469 "Demote the current heading lower down the tree.
4470 If the region is active in `transient-mark-mode', demote all headings
4471 in the region."
4472 (interactive)
4473 (save-excursion
4474 (if (org-region-active-p)
4475 (org-map-region 'org-demote (region-beginning) (region-end))
4476 (org-demote)))
4477 (org-fix-position-after-promote))
4479 (defun org-fix-position-after-promote ()
4480 "Make sure that after pro/demotion cursor position is right."
4481 (let ((pos (point)))
4482 (when (save-excursion
4483 (beginning-of-line 1)
4484 (looking-at org-todo-line-regexp)
4485 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4486 (cond ((eobp) (insert " "))
4487 ((eolp) (insert " "))
4488 ((equal (char-after) ?\ ) (forward-char 1))))))
4490 (defun org-reduced-level (l)
4491 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4493 (defun org-get-valid-level (level &optional change)
4494 "Rectify a level change under the influence of `org-odd-levels-only'
4495 LEVEL is a current level, CHANGE is by how much the level should be
4496 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4497 even level numbers will become the next higher odd number."
4498 (if org-odd-levels-only
4499 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4500 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4501 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4502 (max 1 (+ level change))))
4504 (if (boundp 'define-obsolete-function-alias)
4505 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4506 (define-obsolete-function-alias 'org-get-legal-level
4507 'org-get-valid-level)
4508 (define-obsolete-function-alias 'org-get-legal-level
4509 'org-get-valid-level "23.1")))
4511 (defun org-promote ()
4512 "Promote the current heading higher up the tree.
4513 If the region is active in `transient-mark-mode', promote all headings
4514 in the region."
4515 (org-back-to-heading t)
4516 (let* ((level (save-match-data (funcall outline-level)))
4517 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4518 (diff (abs (- level (length up-head) -1))))
4519 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4520 (replace-match up-head nil t)
4521 ;; Fixup tag positioning
4522 (and org-auto-align-tags (org-set-tags nil t))
4523 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4525 (defun org-demote ()
4526 "Demote the current heading lower down the tree.
4527 If the region is active in `transient-mark-mode', demote all headings
4528 in the region."
4529 (org-back-to-heading t)
4530 (let* ((level (save-match-data (funcall outline-level)))
4531 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4532 (diff (abs (- level (length down-head) -1))))
4533 (replace-match down-head nil t)
4534 ;; Fixup tag positioning
4535 (and org-auto-align-tags (org-set-tags nil t))
4536 (if org-adapt-indentation (org-fixup-indentation diff))))
4538 (defun org-map-tree (fun)
4539 "Call FUN for every heading underneath the current one."
4540 (org-back-to-heading)
4541 (let ((level (funcall outline-level)))
4542 (save-excursion
4543 (funcall fun)
4544 (while (and (progn
4545 (outline-next-heading)
4546 (> (funcall outline-level) level))
4547 (not (eobp)))
4548 (funcall fun)))))
4550 (defun org-map-region (fun beg end)
4551 "Call FUN for every heading between BEG and END."
4552 (let ((org-ignore-region t))
4553 (save-excursion
4554 (setq end (copy-marker end))
4555 (goto-char beg)
4556 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4557 (< (point) end))
4558 (funcall fun))
4559 (while (and (progn
4560 (outline-next-heading)
4561 (< (point) end))
4562 (not (eobp)))
4563 (funcall fun)))))
4565 (defun org-fixup-indentation (diff)
4566 "Change the indentation in the current entry by DIFF
4567 However, if any line in the current entry has no indentation, or if it
4568 would end up with no indentation after the change, nothing at all is done."
4569 (save-excursion
4570 (let ((end (save-excursion (outline-next-heading)
4571 (point-marker)))
4572 (prohibit (if (> diff 0)
4573 "^\\S-"
4574 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4575 col)
4576 (unless (save-excursion (end-of-line 1)
4577 (re-search-forward prohibit end t))
4578 (while (and (< (point) end)
4579 (re-search-forward "^[ \t]+" end t))
4580 (goto-char (match-end 0))
4581 (setq col (current-column))
4582 (if (< diff 0) (replace-match ""))
4583 (indent-to (+ diff col))))
4584 (move-marker end nil))))
4586 (defun org-convert-to-odd-levels ()
4587 "Convert an org-mode file with all levels allowed to one with odd levels.
4588 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4589 level 5 etc."
4590 (interactive)
4591 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4592 (let ((org-odd-levels-only nil) n)
4593 (save-excursion
4594 (goto-char (point-min))
4595 (while (re-search-forward "^\\*\\*+ " nil t)
4596 (setq n (- (length (match-string 0)) 2))
4597 (while (>= (setq n (1- n)) 0)
4598 (org-demote))
4599 (end-of-line 1))))))
4602 (defun org-convert-to-oddeven-levels ()
4603 "Convert an org-mode file with only odd levels to one with odd and even levels.
4604 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4605 section with an even level, conversion would destroy the structure of the file. An error
4606 is signaled in this case."
4607 (interactive)
4608 (goto-char (point-min))
4609 ;; First check if there are no even levels
4610 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4611 (org-show-context t)
4612 (error "Not all levels are odd in this file. Conversion not possible."))
4613 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4614 (let ((org-odd-levels-only nil) n)
4615 (save-excursion
4616 (goto-char (point-min))
4617 (while (re-search-forward "^\\*\\*+ " nil t)
4618 (setq n (/ (1- (length (match-string 0))) 2))
4619 (while (>= (setq n (1- n)) 0)
4620 (org-promote))
4621 (end-of-line 1))))))
4623 (defun org-tr-level (n)
4624 "Make N odd if required."
4625 (if org-odd-levels-only (1+ (/ n 2)) n))
4627 ;;; Vertical tree motion, cutting and pasting of subtrees
4629 (defun org-move-subtree-up (&optional arg)
4630 "Move the current subtree up past ARG headlines of the same level."
4631 (interactive "p")
4632 (org-move-subtree-down (- (prefix-numeric-value arg))))
4634 (defun org-move-subtree-down (&optional arg)
4635 "Move the current subtree down past ARG headlines of the same level."
4636 (interactive "p")
4637 (setq arg (prefix-numeric-value arg))
4638 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4639 'outline-get-last-sibling))
4640 (ins-point (make-marker))
4641 (cnt (abs arg))
4642 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4643 ;; Select the tree
4644 (org-back-to-heading)
4645 (setq beg0 (point))
4646 (save-excursion
4647 (setq ne-beg (org-back-over-empty-lines))
4648 (setq beg (point)))
4649 (save-match-data
4650 (save-excursion (outline-end-of-heading)
4651 (setq folded (org-invisible-p)))
4652 (outline-end-of-subtree))
4653 (outline-next-heading)
4654 (setq ne-end (org-back-over-empty-lines))
4655 (setq end (point))
4656 (goto-char beg0)
4657 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4658 ;; include less whitespace
4659 (save-excursion
4660 (goto-char beg)
4661 (forward-line (- ne-beg ne-end))
4662 (setq beg (point))))
4663 ;; Find insertion point, with error handling
4664 (while (> cnt 0)
4665 (or (and (funcall movfunc) (looking-at outline-regexp))
4666 (progn (goto-char beg0)
4667 (error "Cannot move past superior level or buffer limit")))
4668 (setq cnt (1- cnt)))
4669 (if (> arg 0)
4670 ;; Moving forward - still need to move over subtree
4671 (progn (org-end-of-subtree t t)
4672 (save-excursion
4673 (org-back-over-empty-lines)
4674 (or (bolp) (newline)))))
4675 (setq ne-ins (org-back-over-empty-lines))
4676 (move-marker ins-point (point))
4677 (setq txt (buffer-substring beg end))
4678 (org-save-markers-in-region beg end)
4679 (delete-region beg end)
4680 (outline-flag-region (1- beg) beg nil)
4681 (outline-flag-region (1- (point)) (point) nil)
4682 (let ((bbb (point)))
4683 (insert-before-markers txt)
4684 (org-reinstall-markers-in-region bbb)
4685 (move-marker ins-point bbb))
4686 (or (bolp) (insert "\n"))
4687 (setq ins-end (point))
4688 (goto-char ins-point)
4689 (org-skip-whitespace)
4690 (when (and (< arg 0)
4691 (org-first-sibling-p)
4692 (> ne-ins ne-beg))
4693 ;; Move whitespace back to beginning
4694 (save-excursion
4695 (goto-char ins-end)
4696 (let ((kill-whole-line t))
4697 (kill-line (- ne-ins ne-beg)) (point)))
4698 (insert (make-string (- ne-ins ne-beg) ?\n)))
4699 (move-marker ins-point nil)
4700 (org-compact-display-after-subtree-move)
4701 (unless folded
4702 (org-show-entry)
4703 (show-children)
4704 (org-cycle-hide-drawers 'children))))
4706 (defvar org-subtree-clip ""
4707 "Clipboard for cut and paste of subtrees.
4708 This is actually only a copy of the kill, because we use the normal kill
4709 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4711 (defvar org-subtree-clip-folded nil
4712 "Was the last copied subtree folded?
4713 This is used to fold the tree back after pasting.")
4715 (defun org-cut-subtree (&optional n)
4716 "Cut the current subtree into the clipboard.
4717 With prefix arg N, cut this many sequential subtrees.
4718 This is a short-hand for marking the subtree and then cutting it."
4719 (interactive "p")
4720 (org-copy-subtree n 'cut))
4722 (defun org-copy-subtree (&optional n cut force-store-markers)
4723 "Cut the current subtree into the clipboard.
4724 With prefix arg N, cut this many sequential subtrees.
4725 This is a short-hand for marking the subtree and then copying it.
4726 If CUT is non-nil, actually cut the subtree.
4727 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4728 of some markers in the region, even if CUT is non-nil. This is
4729 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4730 (interactive "p")
4731 (let (beg end folded (beg0 (point)))
4732 (if (interactive-p)
4733 (org-back-to-heading nil) ; take what looks like a subtree
4734 (org-back-to-heading t)) ; take what is really there
4735 (org-back-over-empty-lines)
4736 (setq beg (point))
4737 (skip-chars-forward " \t\r\n")
4738 (save-match-data
4739 (save-excursion (outline-end-of-heading)
4740 (setq folded (org-invisible-p)))
4741 (condition-case nil
4742 (outline-forward-same-level (1- n))
4743 (error nil))
4744 (org-end-of-subtree t t))
4745 (org-back-over-empty-lines)
4746 (setq end (point))
4747 (goto-char beg0)
4748 (when (> end beg)
4749 (setq org-subtree-clip-folded folded)
4750 (when (or cut force-store-markers)
4751 (org-save-markers-in-region beg end))
4752 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4753 (setq org-subtree-clip (current-kill 0))
4754 (message "%s: Subtree(s) with %d characters"
4755 (if cut "Cut" "Copied")
4756 (length org-subtree-clip)))))
4758 (defun org-paste-subtree (&optional level tree)
4759 "Paste the clipboard as a subtree, with modification of headline level.
4760 The entire subtree is promoted or demoted in order to match a new headline
4761 level. By default, the new level is derived from the visible headings
4762 before and after the insertion point, and taken to be the inferior headline
4763 level of the two. So if the previous visible heading is level 3 and the
4764 next is level 4 (or vice versa), level 4 will be used for insertion.
4765 This makes sure that the subtree remains an independent subtree and does
4766 not swallow low level entries.
4768 You can also force a different level, either by using a numeric prefix
4769 argument, or by inserting the heading marker by hand. For example, if the
4770 cursor is after \"*****\", then the tree will be shifted to level 5.
4772 If you want to insert the tree as is, just use \\[yank].
4774 If optional TREE is given, use this text instead of the kill ring."
4775 (interactive "P")
4776 (unless (org-kill-is-subtree-p tree)
4777 (error "%s"
4778 (substitute-command-keys
4779 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4780 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4781 (^re (concat "^\\(" outline-regexp "\\)"))
4782 (re (concat "\\(" outline-regexp "\\)"))
4783 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4785 (old-level (if (string-match ^re txt)
4786 (- (match-end 0) (match-beginning 0) 1)
4787 -1))
4788 (force-level (cond (level (prefix-numeric-value level))
4789 ((string-match
4790 ^re_ (buffer-substring (point-at-bol) (point)))
4791 (- (match-end 1) (match-beginning 1)))
4792 (t nil)))
4793 (previous-level (save-excursion
4794 (condition-case nil
4795 (progn
4796 (outline-previous-visible-heading 1)
4797 (if (looking-at re)
4798 (- (match-end 0) (match-beginning 0) 1)
4800 (error 1))))
4801 (next-level (save-excursion
4802 (condition-case nil
4803 (progn
4804 (or (looking-at outline-regexp)
4805 (outline-next-visible-heading 1))
4806 (if (looking-at re)
4807 (- (match-end 0) (match-beginning 0) 1)
4809 (error 1))))
4810 (new-level (or force-level (max previous-level next-level)))
4811 (shift (if (or (= old-level -1)
4812 (= new-level -1)
4813 (= old-level new-level))
4815 (- new-level old-level)))
4816 (delta (if (> shift 0) -1 1))
4817 (func (if (> shift 0) 'org-demote 'org-promote))
4818 (org-odd-levels-only nil)
4819 beg end)
4820 ;; Remove the forced level indicator
4821 (if force-level
4822 (delete-region (point-at-bol) (point)))
4823 ;; Paste
4824 (beginning-of-line 1)
4825 (org-back-over-empty-lines)
4826 (setq beg (point))
4827 (insert-before-markers txt)
4828 (unless (string-match "\n\\'" txt) (insert "\n"))
4829 (org-reinstall-markers-in-region beg)
4830 (setq end (point))
4831 (goto-char beg)
4832 (skip-chars-forward " \t\n\r")
4833 (setq beg (point))
4834 ;; Shift if necessary
4835 (unless (= shift 0)
4836 (save-restriction
4837 (narrow-to-region beg end)
4838 (while (not (= shift 0))
4839 (org-map-region func (point-min) (point-max))
4840 (setq shift (+ delta shift)))
4841 (goto-char (point-min))))
4842 (when (interactive-p)
4843 (message "Clipboard pasted as level %d subtree" new-level))
4844 (if (and kill-ring
4845 (eq org-subtree-clip (current-kill 0))
4846 org-subtree-clip-folded)
4847 ;; The tree was folded before it was killed/copied
4848 (hide-subtree))))
4850 (defun org-kill-is-subtree-p (&optional txt)
4851 "Check if the current kill is an outline subtree, or a set of trees.
4852 Returns nil if kill does not start with a headline, or if the first
4853 headline level is not the largest headline level in the tree.
4854 So this will actually accept several entries of equal levels as well,
4855 which is OK for `org-paste-subtree'.
4856 If optional TXT is given, check this string instead of the current kill."
4857 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4858 (start-level (and kill
4859 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4860 org-outline-regexp "\\)")
4861 kill)
4862 (- (match-end 2) (match-beginning 2) 1)))
4863 (re (concat "^" org-outline-regexp))
4864 (start (1+ (match-beginning 2))))
4865 (if (not start-level)
4866 (progn
4867 nil) ;; does not even start with a heading
4868 (catch 'exit
4869 (while (setq start (string-match re kill (1+ start)))
4870 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4871 (throw 'exit nil)))
4872 t))))
4874 (defvar org-markers-to-move nil
4875 "Markers that should be moved with a cut-and-paste operation.
4876 Those markers are stored together with their positions relative to
4877 the start of the region.")
4879 (defun org-save-markers-in-region (beg end)
4880 "Check markers in region.
4881 If these markers are between BEG and END, record their position relative
4882 to BEG, so that after moving the block of text, we can put the markers back
4883 into place.
4884 This function gets called just before an entry or tree gets cut from the
4885 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4886 called immediately, to move the markers with the entries."
4887 (setq org-markers-to-move nil)
4888 (when (featurep 'org-clock)
4889 (org-clock-save-markers-for-cut-and-paste beg end))
4890 (when (featurep 'org-agenda)
4891 (org-agenda-save-markers-for-cut-and-paste beg end)))
4893 (defun org-check-and-save-marker (marker beg end)
4894 "Check if MARKER is between BEG and END.
4895 If yes, remember the marker and the distance to BEG."
4896 (when (and (marker-buffer marker)
4897 (equal (marker-buffer marker) (current-buffer)))
4898 (if (and (>= marker beg) (< marker end))
4899 (push (cons marker (- marker beg)) org-markers-to-move))))
4901 (defun org-reinstall-markers-in-region (beg)
4902 "Move all remembered markers to their position relative to BEG."
4903 (mapc (lambda (x)
4904 (move-marker (car x) (+ beg (cdr x))))
4905 org-markers-to-move)
4906 (setq org-markers-to-move nil))
4908 (defun org-narrow-to-subtree ()
4909 "Narrow buffer to the current subtree."
4910 (interactive)
4911 (save-excursion
4912 (save-match-data
4913 (narrow-to-region
4914 (progn (org-back-to-heading) (point))
4915 (progn (org-end-of-subtree t t) (point))))))
4918 ;;; Outline Sorting
4920 (defun org-sort (with-case)
4921 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4922 Optional argument WITH-CASE means sort case-sensitively."
4923 (interactive "P")
4924 (if (org-at-table-p)
4925 (org-call-with-arg 'org-table-sort-lines with-case)
4926 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4928 (defun org-sort-remove-invisible (s)
4929 (remove-text-properties 0 (length s) org-rm-props s)
4930 (while (string-match org-bracket-link-regexp s)
4931 (setq s (replace-match (if (match-end 2)
4932 (match-string 3 s)
4933 (match-string 1 s)) t t s)))
4936 (defvar org-priority-regexp) ; defined later in the file
4938 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4939 "Sort entries on a certain level of an outline tree.
4940 If there is an active region, the entries in the region are sorted.
4941 Else, if the cursor is before the first entry, sort the top-level items.
4942 Else, the children of the entry at point are sorted.
4944 Sorting can be alphabetically, numerically, and by date/time as given by
4945 the first time stamp in the entry. The command prompts for the sorting
4946 type unless it has been given to the function through the SORTING-TYPE
4947 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4948 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4949 called with point at the beginning of the record. It must return either
4950 a string or a number that should serve as the sorting key for that record.
4952 Comparing entries ignores case by default. However, with an optional argument
4953 WITH-CASE, the sorting considers case as well."
4954 (interactive "P")
4955 (let ((case-func (if with-case 'identity 'downcase))
4956 start beg end stars re re2
4957 txt what tmp plain-list-p)
4958 ;; Find beginning and end of region to sort
4959 (cond
4960 ((org-region-active-p)
4961 ;; we will sort the region
4962 (setq end (region-end)
4963 what "region")
4964 (goto-char (region-beginning))
4965 (if (not (org-on-heading-p)) (outline-next-heading))
4966 (setq start (point)))
4967 ((org-at-item-p)
4968 ;; we will sort this plain list
4969 (org-beginning-of-item-list) (setq start (point))
4970 (org-end-of-item-list) (setq end (point))
4971 (goto-char start)
4972 (setq plain-list-p t
4973 what "plain list"))
4974 ((or (org-on-heading-p)
4975 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4976 ;; we will sort the children of the current headline
4977 (org-back-to-heading)
4978 (setq start (point)
4979 end (progn (org-end-of-subtree t t)
4980 (org-back-over-empty-lines)
4981 (point))
4982 what "children")
4983 (goto-char start)
4984 (show-subtree)
4985 (outline-next-heading))
4987 ;; we will sort the top-level entries in this file
4988 (goto-char (point-min))
4989 (or (org-on-heading-p) (outline-next-heading))
4990 (setq start (point) end (point-max) what "top-level")
4991 (goto-char start)
4992 (show-all)))
4994 (setq beg (point))
4995 (if (>= beg end) (error "Nothing to sort"))
4997 (unless plain-list-p
4998 (looking-at "\\(\\*+\\)")
4999 (setq stars (match-string 1)
5000 re (concat "^" (regexp-quote stars) " +")
5001 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5002 txt (buffer-substring beg end))
5003 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5004 (if (and (not (equal stars "*")) (string-match re2 txt))
5005 (error "Region to sort contains a level above the first entry")))
5007 (unless sorting-type
5008 (message
5009 (if plain-list-p
5010 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5011 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5012 what)
5013 (setq sorting-type (read-char-exclusive))
5015 (and (= (downcase sorting-type) ?f)
5016 (setq getkey-func
5017 (completing-read "Sort using function: "
5018 obarray 'fboundp t nil nil))
5019 (setq getkey-func (intern getkey-func)))
5021 (and (= (downcase sorting-type) ?r)
5022 (setq property
5023 (completing-read "Property: "
5024 (mapcar 'list (org-buffer-property-keys t))
5025 nil t))))
5027 (message "Sorting entries...")
5029 (save-restriction
5030 (narrow-to-region start end)
5032 (let ((dcst (downcase sorting-type))
5033 (now (current-time)))
5034 (sort-subr
5035 (/= dcst sorting-type)
5036 ;; This function moves to the beginning character of the "record" to
5037 ;; be sorted.
5038 (if plain-list-p
5039 (lambda nil
5040 (if (org-at-item-p) t (goto-char (point-max))))
5041 (lambda nil
5042 (if (re-search-forward re nil t)
5043 (goto-char (match-beginning 0))
5044 (goto-char (point-max)))))
5045 ;; This function moves to the last character of the "record" being
5046 ;; sorted.
5047 (if plain-list-p
5048 'org-end-of-item
5049 (lambda nil
5050 (save-match-data
5051 (condition-case nil
5052 (outline-forward-same-level 1)
5053 (error
5054 (goto-char (point-max)))))))
5056 ;; This function returns the value that gets sorted against.
5057 (if plain-list-p
5058 (lambda nil
5059 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5060 (cond
5061 ((= dcst ?n)
5062 (string-to-number (buffer-substring (match-end 0)
5063 (point-at-eol))))
5064 ((= dcst ?a)
5065 (buffer-substring (match-end 0) (point-at-eol)))
5066 ((= dcst ?t)
5067 (if (re-search-forward org-ts-regexp
5068 (point-at-eol) t)
5069 (org-time-string-to-time (match-string 0))
5070 now))
5071 ((= dcst ?f)
5072 (if getkey-func
5073 (progn
5074 (setq tmp (funcall getkey-func))
5075 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5076 tmp)
5077 (error "Invalid key function `%s'" getkey-func)))
5078 (t (error "Invalid sorting type `%c'" sorting-type)))))
5079 (lambda nil
5080 (cond
5081 ((= dcst ?n)
5082 (if (looking-at outline-regexp)
5083 (string-to-number (buffer-substring (match-end 0)
5084 (point-at-eol)))
5085 nil))
5086 ((= dcst ?a)
5087 (funcall case-func (buffer-substring (point-at-bol)
5088 (point-at-eol))))
5089 ((= dcst ?t)
5090 (if (re-search-forward org-ts-regexp
5091 (save-excursion
5092 (forward-line 2)
5093 (point)) t)
5094 (org-time-string-to-time (match-string 0))
5095 now))
5096 ((= dcst ?p)
5097 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5098 (string-to-char (match-string 2))
5099 org-default-priority))
5100 ((= dcst ?r)
5101 (or (org-entry-get nil property) ""))
5102 ((= dcst ?o)
5103 (if (looking-at org-complex-heading-regexp)
5104 (- 9999 (length (member (match-string 2)
5105 org-todo-keywords-1)))))
5106 ((= dcst ?f)
5107 (if getkey-func
5108 (progn
5109 (setq tmp (funcall getkey-func))
5110 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5111 tmp)
5112 (error "Invalid key function `%s'" getkey-func)))
5113 (t (error "Invalid sorting type `%c'" sorting-type)))))
5115 (cond
5116 ((= dcst ?a) 'string<)
5117 ((= dcst ?t) 'time-less-p)
5118 (t nil)))))
5119 (message "Sorting entries...done")))
5121 (defun org-do-sort (table what &optional with-case sorting-type)
5122 "Sort TABLE of WHAT according to SORTING-TYPE.
5123 The user will be prompted for the SORTING-TYPE if the call to this
5124 function does not specify it. WHAT is only for the prompt, to indicate
5125 what is being sorted. The sorting key will be extracted from
5126 the car of the elements of the table.
5127 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5128 (unless sorting-type
5129 (message
5130 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5131 what)
5132 (setq sorting-type (read-char-exclusive)))
5133 (let ((dcst (downcase sorting-type))
5134 extractfun comparefun)
5135 ;; Define the appropriate functions
5136 (cond
5137 ((= dcst ?n)
5138 (setq extractfun 'string-to-number
5139 comparefun (if (= dcst sorting-type) '< '>)))
5140 ((= dcst ?a)
5141 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5142 (lambda(x) (downcase (org-sort-remove-invisible x))))
5143 comparefun (if (= dcst sorting-type)
5144 'string<
5145 (lambda (a b) (and (not (string< a b))
5146 (not (string= a b)))))))
5147 ((= dcst ?t)
5148 (setq extractfun
5149 (lambda (x)
5150 (if (string-match org-ts-regexp x)
5151 (time-to-seconds
5152 (org-time-string-to-time (match-string 0 x)))
5154 comparefun (if (= dcst sorting-type) '< '>)))
5155 (t (error "Invalid sorting type `%c'" sorting-type)))
5157 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5158 table)
5159 (lambda (a b) (funcall comparefun (car a) (car b))))))
5161 ;;;; Plain list items, including checkboxes
5163 ;;; Plain list items
5165 (defun org-at-item-p ()
5166 "Is point in a line starting a hand-formatted item?"
5167 (let ((llt org-plain-list-ordered-item-terminator))
5168 (save-excursion
5169 (goto-char (point-at-bol))
5170 (looking-at
5171 (cond
5172 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5173 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5174 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5175 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5177 (defun org-in-item-p ()
5178 "It the cursor inside a plain list item.
5179 Does not have to be the first line."
5180 (save-excursion
5181 (condition-case nil
5182 (progn
5183 (org-beginning-of-item)
5184 (org-at-item-p)
5186 (error nil))))
5188 (defun org-insert-item (&optional checkbox)
5189 "Insert a new item at the current level.
5190 Return t when things worked, nil when we are not in an item."
5191 (when (save-excursion
5192 (condition-case nil
5193 (progn
5194 (org-beginning-of-item)
5195 (org-at-item-p)
5196 (if (org-invisible-p) (error "Invisible item"))
5198 (error nil)))
5199 (let* ((bul (match-string 0))
5200 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5201 (match-end 0)))
5202 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5203 pos)
5204 (cond
5205 ((and (org-at-item-p) (<= (point) eow))
5206 ;; before the bullet
5207 (beginning-of-line 1)
5208 (open-line (if blank 2 1)))
5209 ((<= (point) eow)
5210 (beginning-of-line 1))
5212 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5213 (end-of-line 1)
5214 (delete-horizontal-space))
5215 (newline (if blank 2 1))))
5216 (insert bul (if checkbox "[ ]" ""))
5217 (just-one-space)
5218 (setq pos (point))
5219 (end-of-line 1)
5220 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5221 (org-maybe-renumber-ordered-list)
5222 (and checkbox (org-update-checkbox-count-maybe))
5225 ;;; Checkboxes
5227 (defun org-at-item-checkbox-p ()
5228 "Is point at a line starting a plain-list item with a checklet?"
5229 (and (org-at-item-p)
5230 (save-excursion
5231 (goto-char (match-end 0))
5232 (skip-chars-forward " \t")
5233 (looking-at "\\[[- X]\\]"))))
5235 (defun org-toggle-checkbox (&optional arg)
5236 "Toggle the checkbox in the current line."
5237 (interactive "P")
5238 (catch 'exit
5239 (let (beg end status (firstnew 'unknown))
5240 (cond
5241 ((org-region-active-p)
5242 (setq beg (region-beginning) end (region-end)))
5243 ((org-on-heading-p)
5244 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5245 ((org-at-item-checkbox-p)
5246 (let ((pos (point)))
5247 (replace-match
5248 (cond (arg "[-]")
5249 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5250 (t "[ ]"))
5251 t t)
5252 (goto-char pos))
5253 (throw 'exit t))
5254 (t (error "Not at a checkbox or heading, and no active region")))
5255 (save-excursion
5256 (goto-char beg)
5257 (while (< (point) end)
5258 (when (org-at-item-checkbox-p)
5259 (setq status (equal (match-string 0) "[X]"))
5260 (when (eq firstnew 'unknown)
5261 (setq firstnew (not status)))
5262 (replace-match
5263 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5264 (beginning-of-line 2)))))
5265 (org-update-checkbox-count-maybe))
5267 (defun org-update-checkbox-count-maybe ()
5268 "Update checkbox statistics unless turned off by user."
5269 (when org-provide-checkbox-statistics
5270 (org-update-checkbox-count)))
5272 (defun org-update-checkbox-count (&optional all)
5273 "Update the checkbox statistics in the current section.
5274 This will find all statistic cookies like [57%] and [6/12] and update them
5275 with the current numbers. With optional prefix argument ALL, do this for
5276 the whole buffer."
5277 (interactive "P")
5278 (save-excursion
5279 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5280 (beg (condition-case nil
5281 (progn (outline-back-to-heading) (point))
5282 (error (point-min))))
5283 (end (move-marker (make-marker)
5284 (progn (outline-next-heading) (point))))
5285 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5286 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5287 (re-find (concat re "\\|" re-box))
5288 beg-cookie end-cookie is-percent c-on c-off lim
5289 eline curr-ind next-ind continue-from startsearch
5290 (cstat 0)
5292 (when all
5293 (goto-char (point-min))
5294 (outline-next-heading)
5295 (setq beg (point) end (point-max)))
5296 (goto-char end)
5297 ;; find each statistic cookie
5298 (while (re-search-backward re-find beg t)
5299 (setq beg-cookie (match-beginning 1)
5300 end-cookie (match-end 1)
5301 cstat (+ cstat (if end-cookie 1 0))
5302 startsearch (point-at-eol)
5303 continue-from (point-at-bol)
5304 is-percent (match-beginning 2)
5305 lim (cond
5306 ((org-on-heading-p) (outline-next-heading) (point))
5307 ((org-at-item-p) (org-end-of-item) (point))
5308 (t nil))
5309 c-on 0
5310 c-off 0)
5311 (when lim
5312 ;; find first checkbox for this cookie and gather
5313 ;; statistics from all that are at this indentation level
5314 (goto-char startsearch)
5315 (if (re-search-forward re-box lim t)
5316 (progn
5317 (org-beginning-of-item)
5318 (setq curr-ind (org-get-indentation))
5319 (setq next-ind curr-ind)
5320 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5321 (save-excursion (end-of-line) (setq eline (point)))
5322 (if (re-search-forward re-box eline t)
5323 (if (member (match-string 2) '("[ ]" "[-]"))
5324 (setq c-off (1+ c-off))
5325 (setq c-on (1+ c-on))
5328 (org-end-of-item)
5329 (setq next-ind (org-get-indentation))
5331 (goto-char continue-from)
5332 ;; update cookie
5333 (when end-cookie
5334 (delete-region beg-cookie end-cookie)
5335 (goto-char beg-cookie)
5336 (insert
5337 (if is-percent
5338 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5339 (format "[%d/%d]" c-on (+ c-on c-off)))))
5340 ;; update items checkbox if it has one
5341 (when (org-at-item-p)
5342 (org-beginning-of-item)
5343 (when (and (> (+ c-on c-off) 0)
5344 (re-search-forward re-box (point-at-eol) t))
5345 (setq beg-cookie (match-beginning 2)
5346 end-cookie (match-end 2))
5347 (delete-region beg-cookie end-cookie)
5348 (goto-char beg-cookie)
5349 (cond ((= c-off 0) (insert "[X]"))
5350 ((= c-on 0) (insert "[ ]"))
5351 (t (insert "[-]")))
5353 (goto-char continue-from))
5354 (when (interactive-p)
5355 (message "Checkbox satistics updated %s (%d places)"
5356 (if all "in entire file" "in current outline entry") cstat)))))
5358 (defun org-get-checkbox-statistics-face ()
5359 "Select the face for checkbox statistics.
5360 The face will be `org-done' when all relevant boxes are checked. Otherwise
5361 it will be `org-todo'."
5362 (if (match-end 1)
5363 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5364 (if (and (> (match-end 2) (match-beginning 2))
5365 (equal (match-string 2) (match-string 3)))
5366 'org-done
5367 'org-todo)))
5369 (defun org-get-indentation (&optional line)
5370 "Get the indentation of the current line, interpreting tabs.
5371 When LINE is given, assume it represents a line and compute its indentation."
5372 (if line
5373 (if (string-match "^ *" (org-remove-tabs line))
5374 (match-end 0))
5375 (save-excursion
5376 (beginning-of-line 1)
5377 (skip-chars-forward " \t")
5378 (current-column))))
5380 (defun org-remove-tabs (s &optional width)
5381 "Replace tabulators in S with spaces.
5382 Assumes that s is a single line, starting in column 0."
5383 (setq width (or width tab-width))
5384 (while (string-match "\t" s)
5385 (setq s (replace-match
5386 (make-string
5387 (- (* width (/ (+ (match-beginning 0) width) width))
5388 (match-beginning 0)) ?\ )
5389 t t s)))
5392 (defun org-fix-indentation (line ind)
5393 "Fix indentation in LINE.
5394 IND is a cons cell with target and minimum indentation.
5395 If the current indenation in LINE is smaller than the minimum,
5396 leave it alone. If it is larger than ind, set it to the target."
5397 (let* ((l (org-remove-tabs line))
5398 (i (org-get-indentation l))
5399 (i1 (car ind)) (i2 (cdr ind)))
5400 (if (>= i i2) (setq l (substring line i2)))
5401 (if (> i1 0)
5402 (concat (make-string i1 ?\ ) l)
5403 l)))
5405 (defun org-beginning-of-item ()
5406 "Go to the beginning of the current hand-formatted item.
5407 If the cursor is not in an item, throw an error."
5408 (interactive)
5409 (let ((pos (point))
5410 (limit (save-excursion
5411 (condition-case nil
5412 (progn
5413 (org-back-to-heading)
5414 (beginning-of-line 2) (point))
5415 (error (point-min)))))
5416 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5417 ind ind1)
5418 (if (org-at-item-p)
5419 (beginning-of-line 1)
5420 (beginning-of-line 1)
5421 (skip-chars-forward " \t")
5422 (setq ind (current-column))
5423 (if (catch 'exit
5424 (while t
5425 (beginning-of-line 0)
5426 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5428 (if (looking-at "[ \t]*$")
5429 (setq ind1 ind-empty)
5430 (skip-chars-forward " \t")
5431 (setq ind1 (current-column)))
5432 (if (< ind1 ind)
5433 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5435 (goto-char pos)
5436 (error "Not in an item")))))
5438 (defun org-end-of-item ()
5439 "Go to the end of the current hand-formatted item.
5440 If the cursor is not in an item, throw an error."
5441 (interactive)
5442 (let* ((pos (point))
5443 ind1
5444 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5445 (limit (save-excursion (outline-next-heading) (point)))
5446 (ind (save-excursion
5447 (org-beginning-of-item)
5448 (skip-chars-forward " \t")
5449 (current-column)))
5450 (end (catch 'exit
5451 (while t
5452 (beginning-of-line 2)
5453 (if (eobp) (throw 'exit (point)))
5454 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5455 (if (looking-at "[ \t]*$")
5456 (setq ind1 ind-empty)
5457 (skip-chars-forward " \t")
5458 (setq ind1 (current-column)))
5459 (if (<= ind1 ind)
5460 (throw 'exit (point-at-bol)))))))
5461 (if end
5462 (goto-char end)
5463 (goto-char pos)
5464 (error "Not in an item"))))
5466 (defun org-next-item ()
5467 "Move to the beginning of the next item in the current plain list.
5468 Error if not at a plain list, or if this is the last item in the list."
5469 (interactive)
5470 (let (ind ind1 (pos (point)))
5471 (org-beginning-of-item)
5472 (setq ind (org-get-indentation))
5473 (org-end-of-item)
5474 (setq ind1 (org-get-indentation))
5475 (unless (and (org-at-item-p) (= ind ind1))
5476 (goto-char pos)
5477 (error "On last item"))))
5479 (defun org-previous-item ()
5480 "Move to the beginning of the previous item in the current plain list.
5481 Error if not at a plain list, or if this is the first item in the list."
5482 (interactive)
5483 (let (beg ind ind1 (pos (point)))
5484 (org-beginning-of-item)
5485 (setq beg (point))
5486 (setq ind (org-get-indentation))
5487 (goto-char beg)
5488 (catch 'exit
5489 (while t
5490 (beginning-of-line 0)
5491 (if (looking-at "[ \t]*$")
5493 (if (<= (setq ind1 (org-get-indentation)) ind)
5494 (throw 'exit t)))))
5495 (condition-case nil
5496 (if (or (not (org-at-item-p))
5497 (< ind1 (1- ind)))
5498 (error "")
5499 (org-beginning-of-item))
5500 (error (goto-char pos)
5501 (error "On first item")))))
5503 (defun org-first-list-item-p ()
5504 "Is this heading the item in a plain list?"
5505 (unless (org-at-item-p)
5506 (error "Not at a plain list item"))
5507 (org-beginning-of-item)
5508 (= (point) (save-excursion (org-beginning-of-item-list))))
5510 (defun org-move-item-down ()
5511 "Move the plain list item at point down, i.e. swap with following item.
5512 Subitems (items with larger indentation) are considered part of the item,
5513 so this really moves item trees."
5514 (interactive)
5515 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5516 (org-beginning-of-item)
5517 (setq beg0 (point))
5518 (save-excursion
5519 (setq ne-beg (org-back-over-empty-lines))
5520 (setq beg (point)))
5521 (goto-char beg0)
5522 (setq ind (org-get-indentation))
5523 (org-end-of-item)
5524 (setq end0 (point))
5525 (setq ind1 (org-get-indentation))
5526 (setq ne-end (org-back-over-empty-lines))
5527 (setq end (point))
5528 (goto-char beg0)
5529 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5530 ;; include less whitespace
5531 (save-excursion
5532 (goto-char beg)
5533 (forward-line (- ne-beg ne-end))
5534 (setq beg (point))))
5535 (goto-char end0)
5536 (if (and (org-at-item-p) (= ind ind1))
5537 (progn
5538 (org-end-of-item)
5539 (org-back-over-empty-lines)
5540 (setq txt (buffer-substring beg end))
5541 (save-excursion
5542 (delete-region beg end))
5543 (setq pos (point))
5544 (insert txt)
5545 (goto-char pos) (org-skip-whitespace)
5546 (org-maybe-renumber-ordered-list))
5547 (goto-char pos)
5548 (error "Cannot move this item further down"))))
5550 (defun org-move-item-up (arg)
5551 "Move the plain list item at point up, i.e. swap with previous item.
5552 Subitems (items with larger indentation) are considered part of the item,
5553 so this really moves item trees."
5554 (interactive "p")
5555 (let (beg beg0 end ind ind1 (pos (point)) txt
5556 ne-beg ne-ins ins-end)
5557 (org-beginning-of-item)
5558 (setq beg0 (point))
5559 (setq ind (org-get-indentation))
5560 (save-excursion
5561 (setq ne-beg (org-back-over-empty-lines))
5562 (setq beg (point)))
5563 (goto-char beg0)
5564 (org-end-of-item)
5565 (setq end (point))
5566 (goto-char beg0)
5567 (catch 'exit
5568 (while t
5569 (beginning-of-line 0)
5570 (if (looking-at "[ \t]*$")
5571 (if org-empty-line-terminates-plain-lists
5572 (progn
5573 (goto-char pos)
5574 (error "Cannot move this item further up"))
5575 nil)
5576 (if (<= (setq ind1 (org-get-indentation)) ind)
5577 (throw 'exit t)))))
5578 (condition-case nil
5579 (org-beginning-of-item)
5580 (error (goto-char beg)
5581 (error "Cannot move this item further up")))
5582 (setq ind1 (org-get-indentation))
5583 (if (and (org-at-item-p) (= ind ind1))
5584 (progn
5585 (setq ne-ins (org-back-over-empty-lines))
5586 (setq txt (buffer-substring beg end))
5587 (save-excursion
5588 (delete-region beg end))
5589 (setq pos (point))
5590 (insert txt)
5591 (setq ins-end (point))
5592 (goto-char pos) (org-skip-whitespace)
5594 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5595 ;; Move whitespace back to beginning
5596 (save-excursion
5597 (goto-char ins-end)
5598 (let ((kill-whole-line t))
5599 (kill-line (- ne-ins ne-beg)) (point)))
5600 (insert (make-string (- ne-ins ne-beg) ?\n)))
5602 (org-maybe-renumber-ordered-list))
5603 (goto-char pos)
5604 (error "Cannot move this item further up"))))
5606 (defun org-maybe-renumber-ordered-list ()
5607 "Renumber the ordered list at point if setup allows it.
5608 This tests the user option `org-auto-renumber-ordered-lists' before
5609 doing the renumbering."
5610 (interactive)
5611 (when (and org-auto-renumber-ordered-lists
5612 (org-at-item-p))
5613 (if (match-beginning 3)
5614 (org-renumber-ordered-list 1)
5615 (org-fix-bullet-type))))
5617 (defun org-maybe-renumber-ordered-list-safe ()
5618 (condition-case nil
5619 (save-excursion
5620 (org-maybe-renumber-ordered-list))
5621 (error nil)))
5623 (defun org-cycle-list-bullet (&optional which)
5624 "Cycle through the different itemize/enumerate bullets.
5625 This cycle the entire list level through the sequence:
5627 `-' -> `+' -> `*' -> `1.' -> `1)'
5629 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5630 0 meand `-', 1 means `+' etc."
5631 (interactive "P")
5632 (org-preserve-lc
5633 (org-beginning-of-item-list)
5634 (org-at-item-p)
5635 (beginning-of-line 1)
5636 (let ((current (match-string 0))
5637 (prevp (eq which 'previous))
5638 new)
5639 (setq new (cond
5640 ((and (numberp which)
5641 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5642 ((string-match "-" current) (if prevp "1)" "+"))
5643 ((string-match "\\+" current)
5644 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5645 ((string-match "\\*" current) (if prevp "+" "1."))
5646 ((string-match "\\." current) (if prevp "*" "1)"))
5647 ((string-match ")" current) (if prevp "1." "-"))
5648 (t (error "This should not happen"))))
5649 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5650 (org-fix-bullet-type)
5651 (org-maybe-renumber-ordered-list))))
5653 (defun org-get-string-indentation (s)
5654 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5655 (let ((n -1) (i 0) (w tab-width) c)
5656 (catch 'exit
5657 (while (< (setq n (1+ n)) (length s))
5658 (setq c (aref s n))
5659 (cond ((= c ?\ ) (setq i (1+ i)))
5660 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5661 (t (throw 'exit t)))))
5664 (defun org-renumber-ordered-list (arg)
5665 "Renumber an ordered plain list.
5666 Cursor needs to be in the first line of an item, the line that starts
5667 with something like \"1.\" or \"2)\"."
5668 (interactive "p")
5669 (unless (and (org-at-item-p)
5670 (match-beginning 3))
5671 (error "This is not an ordered list"))
5672 (let ((line (org-current-line))
5673 (col (current-column))
5674 (ind (org-get-string-indentation
5675 (buffer-substring (point-at-bol) (match-beginning 3))))
5676 ;; (term (substring (match-string 3) -1))
5677 ind1 (n (1- arg))
5678 fmt)
5679 ;; find where this list begins
5680 (org-beginning-of-item-list)
5681 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5682 (setq fmt (concat "%d" (match-string 1)))
5683 (beginning-of-line 0)
5684 ;; walk forward and replace these numbers
5685 (catch 'exit
5686 (while t
5687 (catch 'next
5688 (beginning-of-line 2)
5689 (if (eobp) (throw 'exit nil))
5690 (if (looking-at "[ \t]*$") (throw 'next nil))
5691 (skip-chars-forward " \t") (setq ind1 (current-column))
5692 (if (> ind1 ind) (throw 'next t))
5693 (if (< ind1 ind) (throw 'exit t))
5694 (if (not (org-at-item-p)) (throw 'exit nil))
5695 (delete-region (match-beginning 2) (match-end 2))
5696 (goto-char (match-beginning 2))
5697 (insert (format fmt (setq n (1+ n)))))))
5698 (goto-line line)
5699 (org-move-to-column col)))
5701 (defun org-fix-bullet-type ()
5702 "Make sure all items in this list have the same bullet as the firsst item."
5703 (interactive)
5704 (unless (org-at-item-p) (error "This is not a list"))
5705 (let ((line (org-current-line))
5706 (col (current-column))
5707 (ind (current-indentation))
5708 ind1 bullet)
5709 ;; find where this list begins
5710 (org-beginning-of-item-list)
5711 (beginning-of-line 1)
5712 ;; find out what the bullet type is
5713 (looking-at "[ \t]*\\(\\S-+\\)")
5714 (setq bullet (match-string 1))
5715 ;; walk forward and replace these numbers
5716 (beginning-of-line 0)
5717 (catch 'exit
5718 (while t
5719 (catch 'next
5720 (beginning-of-line 2)
5721 (if (eobp) (throw 'exit nil))
5722 (if (looking-at "[ \t]*$") (throw 'next nil))
5723 (skip-chars-forward " \t") (setq ind1 (current-column))
5724 (if (> ind1 ind) (throw 'next t))
5725 (if (< ind1 ind) (throw 'exit t))
5726 (if (not (org-at-item-p)) (throw 'exit nil))
5727 (skip-chars-forward " \t")
5728 (looking-at "\\S-+")
5729 (replace-match bullet))))
5730 (goto-line line)
5731 (org-move-to-column col)
5732 (if (string-match "[0-9]" bullet)
5733 (org-renumber-ordered-list 1))))
5735 (defun org-beginning-of-item-list ()
5736 "Go to the beginning of the current item list.
5737 I.e. to the first item in this list."
5738 (interactive)
5739 (org-beginning-of-item)
5740 (let ((pos (point-at-bol))
5741 (ind (org-get-indentation))
5742 ind1)
5743 ;; find where this list begins
5744 (catch 'exit
5745 (while t
5746 (catch 'next
5747 (beginning-of-line 0)
5748 (if (looking-at "[ \t]*$")
5749 (throw (if (bobp) 'exit 'next) t))
5750 (skip-chars-forward " \t") (setq ind1 (current-column))
5751 (if (or (< ind1 ind)
5752 (and (= ind1 ind)
5753 (not (org-at-item-p)))
5754 (bobp))
5755 (throw 'exit t)
5756 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5757 (goto-char pos)))
5760 (defun org-end-of-item-list ()
5761 "Go to the end of the current item list.
5762 I.e. to the text after the last item."
5763 (interactive)
5764 (org-beginning-of-item)
5765 (let ((pos (point-at-bol))
5766 (ind (org-get-indentation))
5767 ind1)
5768 ;; find where this list begins
5769 (catch 'exit
5770 (while t
5771 (catch 'next
5772 (beginning-of-line 2)
5773 (if (looking-at "[ \t]*$")
5774 (throw (if (eobp) 'exit 'next) t))
5775 (skip-chars-forward " \t") (setq ind1 (current-column))
5776 (if (or (< ind1 ind)
5777 (and (= ind1 ind)
5778 (not (org-at-item-p)))
5779 (eobp))
5780 (progn
5781 (setq pos (point-at-bol))
5782 (throw 'exit t))))))
5783 (goto-char pos)))
5786 (defvar org-last-indent-begin-marker (make-marker))
5787 (defvar org-last-indent-end-marker (make-marker))
5789 (defun org-outdent-item (arg)
5790 "Outdent a local list item."
5791 (interactive "p")
5792 (org-indent-item (- arg)))
5794 (defun org-indent-item (arg)
5795 "Indent a local list item."
5796 (interactive "p")
5797 (unless (org-at-item-p)
5798 (error "Not on an item"))
5799 (save-excursion
5800 (let (beg end ind ind1 tmp delta ind-down ind-up)
5801 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5802 (setq beg org-last-indent-begin-marker
5803 end org-last-indent-end-marker)
5804 (org-beginning-of-item)
5805 (setq beg (move-marker org-last-indent-begin-marker (point)))
5806 (org-end-of-item)
5807 (setq end (move-marker org-last-indent-end-marker (point))))
5808 (goto-char beg)
5809 (setq tmp (org-item-indent-positions)
5810 ind (car tmp)
5811 ind-down (nth 2 tmp)
5812 ind-up (nth 1 tmp)
5813 delta (if (> arg 0)
5814 (if ind-down (- ind-down ind) 2)
5815 (if ind-up (- ind-up ind) -2)))
5816 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5817 (while (< (point) end)
5818 (beginning-of-line 1)
5819 (skip-chars-forward " \t") (setq ind1 (current-column))
5820 (delete-region (point-at-bol) (point))
5821 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5822 (beginning-of-line 2))))
5823 (org-fix-bullet-type)
5824 (org-maybe-renumber-ordered-list-safe)
5825 (save-excursion
5826 (beginning-of-line 0)
5827 (condition-case nil (org-beginning-of-item) (error nil))
5828 (org-maybe-renumber-ordered-list-safe)))
5830 (defun org-item-indent-positions ()
5831 "Return indentation for plain list items.
5832 This returns a list with three values: The current indentation, the
5833 parent indentation and the indentation a child should habe.
5834 Assumes cursor in item line."
5835 (let* ((bolpos (point-at-bol))
5836 (ind (org-get-indentation))
5837 ind-down ind-up pos)
5838 (save-excursion
5839 (org-beginning-of-item-list)
5840 (skip-chars-backward "\n\r \t")
5841 (when (org-in-item-p)
5842 (org-beginning-of-item)
5843 (setq ind-up (org-get-indentation))))
5844 (setq pos (point))
5845 (save-excursion
5846 (cond
5847 ((and (condition-case nil (progn (org-previous-item) t)
5848 (error nil))
5849 (or (forward-char 1) t)
5850 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5851 (setq ind-down (org-get-indentation)))
5852 ((and (goto-char pos)
5853 (org-at-item-p))
5854 (goto-char (match-end 0))
5855 (skip-chars-forward " \t")
5856 (setq ind-down (current-column)))))
5857 (list ind ind-up ind-down)))
5859 ;;; The orgstruct minor mode
5861 ;; Define a minor mode which can be used in other modes in order to
5862 ;; integrate the org-mode structure editing commands.
5864 ;; This is really a hack, because the org-mode structure commands use
5865 ;; keys which normally belong to the major mode. Here is how it
5866 ;; works: The minor mode defines all the keys necessary to operate the
5867 ;; structure commands, but wraps the commands into a function which
5868 ;; tests if the cursor is currently at a headline or a plain list
5869 ;; item. If that is the case, the structure command is used,
5870 ;; temporarily setting many Org-mode variables like regular
5871 ;; expressions for filling etc. However, when any of those keys is
5872 ;; used at a different location, function uses `key-binding' to look
5873 ;; up if the key has an associated command in another currently active
5874 ;; keymap (minor modes, major mode, global), and executes that
5875 ;; command. There might be problems if any of the keys is otherwise
5876 ;; used as a prefix key.
5878 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5879 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5880 ;; addresses this by checking explicitly for both bindings.
5882 (defvar orgstruct-mode-map (make-sparse-keymap)
5883 "Keymap for the minor `orgstruct-mode'.")
5885 (defvar org-local-vars nil
5886 "List of local variables, for use by `orgstruct-mode'")
5888 ;;;###autoload
5889 (define-minor-mode orgstruct-mode
5890 "Toggle the minor more `orgstruct-mode'.
5891 This mode is for using Org-mode structure commands in other modes.
5892 The following key behave as if Org-mode was active, if the cursor
5893 is on a headline, or on a plain list item (both in the definition
5894 of Org-mode).
5896 M-up Move entry/item up
5897 M-down Move entry/item down
5898 M-left Promote
5899 M-right Demote
5900 M-S-up Move entry/item up
5901 M-S-down Move entry/item down
5902 M-S-left Promote subtree
5903 M-S-right Demote subtree
5904 M-q Fill paragraph and items like in Org-mode
5905 C-c ^ Sort entries
5906 C-c - Cycle list bullet
5907 TAB Cycle item visibility
5908 M-RET Insert new heading/item
5909 S-M-RET Insert new TODO heading / Chekbox item
5910 C-c C-c Set tags / toggle checkbox"
5911 nil " OrgStruct" nil
5912 (org-load-modules-maybe)
5913 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5915 ;;;###autoload
5916 (defun turn-on-orgstruct ()
5917 "Unconditionally turn on `orgstruct-mode'."
5918 (orgstruct-mode 1))
5920 ;;;###autoload
5921 (defun turn-on-orgstruct++ ()
5922 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5923 In addition to setting orgstruct-mode, this also exports all indentation and
5924 autofilling variables from org-mode into the buffer. Note that turning
5925 off orgstruct-mode will *not* remove these additional settings."
5926 (orgstruct-mode 1)
5927 (let (var val)
5928 (mapc
5929 (lambda (x)
5930 (when (string-match
5931 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5932 (symbol-name (car x)))
5933 (setq var (car x) val (nth 1 x))
5934 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5935 org-local-vars)))
5937 (defun orgstruct-error ()
5938 "Error when there is no default binding for a structure key."
5939 (interactive)
5940 (error "This key has no function outside structure elements"))
5942 (defun orgstruct-setup ()
5943 "Setup orgstruct keymaps."
5944 (let ((nfunc 0)
5945 (bindings
5946 (list
5947 '([(meta up)] org-metaup)
5948 '([(meta down)] org-metadown)
5949 '([(meta left)] org-metaleft)
5950 '([(meta right)] org-metaright)
5951 '([(meta shift up)] org-shiftmetaup)
5952 '([(meta shift down)] org-shiftmetadown)
5953 '([(meta shift left)] org-shiftmetaleft)
5954 '([(meta shift right)] org-shiftmetaright)
5955 '([(shift up)] org-shiftup)
5956 '([(shift down)] org-shiftdown)
5957 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5958 '("\M-q" fill-paragraph)
5959 '("\C-c^" org-sort)
5960 '("\C-c-" org-cycle-list-bullet)))
5961 elt key fun cmd)
5962 (while (setq elt (pop bindings))
5963 (setq nfunc (1+ nfunc))
5964 (setq key (org-key (car elt))
5965 fun (nth 1 elt)
5966 cmd (orgstruct-make-binding fun nfunc key))
5967 (org-defkey orgstruct-mode-map key cmd))
5969 ;; Special treatment needed for TAB and RET
5970 (org-defkey orgstruct-mode-map [(tab)]
5971 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5972 (org-defkey orgstruct-mode-map "\C-i"
5973 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5975 (org-defkey orgstruct-mode-map "\M-\C-m"
5976 (orgstruct-make-binding 'org-insert-heading 105
5977 "\M-\C-m" [(meta return)]))
5978 (org-defkey orgstruct-mode-map [(meta return)]
5979 (orgstruct-make-binding 'org-insert-heading 106
5980 [(meta return)] "\M-\C-m"))
5982 (org-defkey orgstruct-mode-map [(shift meta return)]
5983 (orgstruct-make-binding 'org-insert-todo-heading 107
5984 [(meta return)] "\M-\C-m"))
5986 (unless org-local-vars
5987 (setq org-local-vars (org-get-local-variables)))
5991 (defun orgstruct-make-binding (fun n &rest keys)
5992 "Create a function for binding in the structure minor mode.
5993 FUN is the command to call inside a table. N is used to create a unique
5994 command name. KEYS are keys that should be checked in for a command
5995 to execute outside of tables."
5996 (eval
5997 (list 'defun
5998 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5999 '(arg)
6000 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6001 "Outside of structure, run the binding of `"
6002 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6003 "'.")
6004 '(interactive "p")
6005 (list 'if
6006 '(org-context-p 'headline 'item)
6007 (list 'org-run-like-in-org-mode (list 'quote fun))
6008 (list 'let '(orgstruct-mode)
6009 (list 'call-interactively
6010 (append '(or)
6011 (mapcar (lambda (k)
6012 (list 'key-binding k))
6013 keys)
6014 '('orgstruct-error))))))))
6016 (defun org-context-p (&rest contexts)
6017 "Check if local context is and of CONTEXTS.
6018 Possible values in the list of contexts are `table', `headline', and `item'."
6019 (let ((pos (point)))
6020 (goto-char (point-at-bol))
6021 (prog1 (or (and (memq 'table contexts)
6022 (looking-at "[ \t]*|"))
6023 (and (memq 'headline contexts)
6024 (looking-at "\\*+"))
6025 (and (memq 'item contexts)
6026 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6027 (goto-char pos))))
6029 (defun org-get-local-variables ()
6030 "Return a list of all local variables in an org-mode buffer."
6031 (let (varlist)
6032 (with-current-buffer (get-buffer-create "*Org tmp*")
6033 (erase-buffer)
6034 (org-mode)
6035 (setq varlist (buffer-local-variables)))
6036 (kill-buffer "*Org tmp*")
6037 (delq nil
6038 (mapcar
6039 (lambda (x)
6040 (setq x
6041 (if (symbolp x)
6042 (list x)
6043 (list (car x) (list 'quote (cdr x)))))
6044 (if (string-match
6045 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6046 (symbol-name (car x)))
6047 x nil))
6048 varlist))))
6050 ;;;###autoload
6051 (defun org-run-like-in-org-mode (cmd)
6052 (org-load-modules-maybe)
6053 (unless org-local-vars
6054 (setq org-local-vars (org-get-local-variables)))
6055 (eval (list 'let org-local-vars
6056 (list 'call-interactively (list 'quote cmd)))))
6058 ;;;; Archiving
6060 (defun org-get-category (&optional pos)
6061 "Get the category applying to position POS."
6062 (get-text-property (or pos (point)) 'org-category))
6064 (defun org-refresh-category-properties ()
6065 "Refresh category text properties in the buffer."
6066 (let ((def-cat (cond
6067 ((null org-category)
6068 (if buffer-file-name
6069 (file-name-sans-extension
6070 (file-name-nondirectory buffer-file-name))
6071 "???"))
6072 ((symbolp org-category) (symbol-name org-category))
6073 (t org-category)))
6074 beg end cat pos optionp)
6075 (org-unmodified
6076 (save-excursion
6077 (save-restriction
6078 (widen)
6079 (goto-char (point-min))
6080 (put-text-property (point) (point-max) 'org-category def-cat)
6081 (while (re-search-forward
6082 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6083 (setq pos (match-end 0)
6084 optionp (equal (char-after (match-beginning 0)) ?#)
6085 cat (org-trim (match-string 2)))
6086 (if optionp
6087 (setq beg (point-at-bol) end (point-max))
6088 (org-back-to-heading t)
6089 (setq beg (point) end (org-end-of-subtree t t)))
6090 (put-text-property beg end 'org-category cat)
6091 (goto-char pos)))))))
6094 ;;;; Link Stuff
6096 ;;; Link abbreviations
6098 (defun org-link-expand-abbrev (link)
6099 "Apply replacements as defined in `org-link-abbrev-alist."
6100 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6101 (let* ((key (match-string 1 link))
6102 (as (or (assoc key org-link-abbrev-alist-local)
6103 (assoc key org-link-abbrev-alist)))
6104 (tag (and (match-end 2) (match-string 3 link)))
6105 rpl)
6106 (if (not as)
6107 link
6108 (setq rpl (cdr as))
6109 (cond
6110 ((symbolp rpl) (funcall rpl tag))
6111 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6112 (t (concat rpl tag)))))
6113 link))
6115 ;;; Storing and inserting links
6117 (defvar org-insert-link-history nil
6118 "Minibuffer history for links inserted with `org-insert-link'.")
6120 (defvar org-stored-links nil
6121 "Contains the links stored with `org-store-link'.")
6123 (defvar org-store-link-plist nil
6124 "Plist with info about the most recently link created with `org-store-link'.")
6126 (defvar org-link-protocols nil
6127 "Link protocols added to Org-mode using `org-add-link-type'.")
6129 (defvar org-store-link-functions nil
6130 "List of functions that are called to create and store a link.
6131 Each function will be called in turn until one returns a non-nil
6132 value. Each function should check if it is responsible for creating
6133 this link (for example by looking at the major mode).
6134 If not, it must exit and return nil.
6135 If yes, it should return a non-nil value after a calling
6136 `org-store-link-props' with a list of properties and values.
6137 Special properties are:
6139 :type The link prefix. like \"http\". This must be given.
6140 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6141 This is obligatory as well.
6142 :description Optional default description for the second pair
6143 of brackets in an Org-mode link. The user can still change
6144 this when inserting this link into an Org-mode buffer.
6146 In addition to these, any additional properties can be specified
6147 and then used in remember templates.")
6149 (defun org-add-link-type (type &optional follow export)
6150 "Add TYPE to the list of `org-link-types'.
6151 Re-compute all regular expressions depending on `org-link-types'
6153 FOLLOW and EXPORT are two functions.
6155 FOLLOW should take the link path as the single argument and do whatever
6156 is necessary to follow the link, for example find a file or display
6157 a mail message.
6159 EXPORT should format the link path for export to one of the export formats.
6160 It should be a function accepting three arguments:
6162 path the path of the link, the text after the prefix (like \"http:\")
6163 desc the description of the link, if any, nil if there was no descripton
6164 format the export format, a symbol like `html' or `latex'.
6166 The function may use the FORMAT information to return different values
6167 depending on the format. The return value will be put literally into
6168 the exported file.
6169 Org-mode has a built-in default for exporting links. If you are happy with
6170 this default, there is no need to define an export function for the link
6171 type. For a simple example of an export function, see `org-bbdb.el'."
6172 (add-to-list 'org-link-types type t)
6173 (org-make-link-regexps)
6174 (if (assoc type org-link-protocols)
6175 (setcdr (assoc type org-link-protocols) (list follow export))
6176 (push (list type follow export) org-link-protocols)))
6179 ;;;###autoload
6180 (defun org-store-link (arg)
6181 "\\<org-mode-map>Store an org-link to the current location.
6182 This link is added to `org-stored-links' and can later be inserted
6183 into an org-buffer with \\[org-insert-link].
6185 For some link types, a prefix arg is interpreted:
6186 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6187 For file links, arg negates `org-context-in-file-links'."
6188 (interactive "P")
6189 (org-load-modules-maybe)
6190 (setq org-store-link-plist nil) ; reset
6191 (let (link cpltxt desc description search txt)
6192 (cond
6194 ((run-hook-with-args-until-success 'org-store-link-functions)
6195 (setq link (plist-get org-store-link-plist :link)
6196 desc (or (plist-get org-store-link-plist :description) link)))
6198 ((eq major-mode 'calendar-mode)
6199 (let ((cd (calendar-cursor-to-date)))
6200 (setq link
6201 (format-time-string
6202 (car org-time-stamp-formats)
6203 (apply 'encode-time
6204 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6205 nil nil nil))))
6206 (org-store-link-props :type "calendar" :date cd)))
6208 ((eq major-mode 'w3-mode)
6209 (setq cpltxt (url-view-url t)
6210 link (org-make-link cpltxt))
6211 (org-store-link-props :type "w3" :url (url-view-url t)))
6213 ((eq major-mode 'w3m-mode)
6214 (setq cpltxt (or w3m-current-title w3m-current-url)
6215 link (org-make-link w3m-current-url))
6216 (org-store-link-props :type "w3m" :url (url-view-url t)))
6218 ((setq search (run-hook-with-args-until-success
6219 'org-create-file-search-functions))
6220 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6221 "::" search))
6222 (setq cpltxt (or description link)))
6224 ((eq major-mode 'image-mode)
6225 (setq cpltxt (concat "file:"
6226 (abbreviate-file-name buffer-file-name))
6227 link (org-make-link cpltxt))
6228 (org-store-link-props :type "image" :file buffer-file-name))
6230 ((eq major-mode 'dired-mode)
6231 ;; link to the file in the current line
6232 (setq cpltxt (concat "file:"
6233 (abbreviate-file-name
6234 (expand-file-name
6235 (dired-get-filename nil t))))
6236 link (org-make-link cpltxt)))
6238 ((and buffer-file-name (org-mode-p))
6239 ;; Just link to current headline
6240 (setq cpltxt (concat "file:"
6241 (abbreviate-file-name buffer-file-name)))
6242 ;; Add a context search string
6243 (when (org-xor org-context-in-file-links arg)
6244 ;; Check if we are on a target
6245 (if (org-in-regexp "<<\\(.*?\\)>>")
6246 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6247 (setq txt (cond
6248 ((org-on-heading-p) nil)
6249 ((org-region-active-p)
6250 (buffer-substring (region-beginning) (region-end)))
6251 (t nil)))
6252 (when (or (null txt) (string-match "\\S-" txt))
6253 (setq cpltxt
6254 (concat cpltxt "::"
6255 (condition-case nil
6256 (org-make-org-heading-search-string txt)
6257 (error "")))
6258 desc "NONE"))))
6259 (if (string-match "::\\'" cpltxt)
6260 (setq cpltxt (substring cpltxt 0 -2)))
6261 (setq link (org-make-link cpltxt)))
6263 ((buffer-file-name (buffer-base-buffer))
6264 ;; Just link to this file here.
6265 (setq cpltxt (concat "file:"
6266 (abbreviate-file-name
6267 (buffer-file-name (buffer-base-buffer)))))
6268 ;; Add a context string
6269 (when (org-xor org-context-in-file-links arg)
6270 (setq txt (if (org-region-active-p)
6271 (buffer-substring (region-beginning) (region-end))
6272 (buffer-substring (point-at-bol) (point-at-eol))))
6273 ;; Only use search option if there is some text.
6274 (when (string-match "\\S-" txt)
6275 (setq cpltxt
6276 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6277 desc "NONE")))
6278 (setq link (org-make-link cpltxt)))
6280 ((interactive-p)
6281 (error "Cannot link to a buffer which is not visiting a file"))
6283 (t (setq link nil)))
6285 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6286 (setq link (or link cpltxt)
6287 desc (or desc cpltxt))
6288 (if (equal desc "NONE") (setq desc nil))
6290 (if (and (interactive-p) link)
6291 (progn
6292 (setq org-stored-links
6293 (cons (list link desc) org-stored-links))
6294 (message "Stored: %s" (or desc link)))
6295 (and link (org-make-link-string link desc)))))
6297 (defun org-store-link-props (&rest plist)
6298 "Store link properties, extract names and addresses."
6299 (let (x adr)
6300 (when (setq x (plist-get plist :from))
6301 (setq adr (mail-extract-address-components x))
6302 (plist-put plist :fromname (car adr))
6303 (plist-put plist :fromaddress (nth 1 adr)))
6304 (when (setq x (plist-get plist :to))
6305 (setq adr (mail-extract-address-components x))
6306 (plist-put plist :toname (car adr))
6307 (plist-put plist :toaddress (nth 1 adr))))
6308 (let ((from (plist-get plist :from))
6309 (to (plist-get plist :to)))
6310 (when (and from to org-from-is-user-regexp)
6311 (plist-put plist :fromto
6312 (if (string-match org-from-is-user-regexp from)
6313 (concat "to %t")
6314 (concat "from %f")))))
6315 (setq org-store-link-plist plist))
6317 (defun org-add-link-props (&rest plist)
6318 "Add these properties to the link property list."
6319 (let (key value)
6320 (while plist
6321 (setq key (pop plist) value (pop plist))
6322 (setq org-store-link-plist
6323 (plist-put org-store-link-plist key value)))))
6325 (defun org-email-link-description (&optional fmt)
6326 "Return the description part of an email link.
6327 This takes information from `org-store-link-plist' and formats it
6328 according to FMT (default from `org-email-link-description-format')."
6329 (setq fmt (or fmt org-email-link-description-format))
6330 (let* ((p org-store-link-plist)
6331 (to (plist-get p :toaddress))
6332 (from (plist-get p :fromaddress))
6333 (table
6334 (list
6335 (cons "%c" (plist-get p :fromto))
6336 (cons "%F" (plist-get p :from))
6337 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6338 (cons "%T" (plist-get p :to))
6339 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6340 (cons "%s" (plist-get p :subject))
6341 (cons "%m" (plist-get p :message-id)))))
6342 (when (string-match "%c" fmt)
6343 ;; Check if the user wrote this message
6344 (if (and org-from-is-user-regexp from to
6345 (save-match-data (string-match org-from-is-user-regexp from)))
6346 (setq fmt (replace-match "to %t" t t fmt))
6347 (setq fmt (replace-match "from %f" t t fmt))))
6348 (org-replace-escapes fmt table)))
6350 (defun org-make-org-heading-search-string (&optional string heading)
6351 "Make search string for STRING or current headline."
6352 (interactive)
6353 (let ((s (or string (org-get-heading))))
6354 (unless (and string (not heading))
6355 ;; We are using a headline, clean up garbage in there.
6356 (if (string-match org-todo-regexp s)
6357 (setq s (replace-match "" t t s)))
6358 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6359 (setq s (replace-match "" t t s)))
6360 (setq s (org-trim s))
6361 (if (string-match (concat "^\\(" org-quote-string "\\|"
6362 org-comment-string "\\)") s)
6363 (setq s (replace-match "" t t s)))
6364 (while (string-match org-ts-regexp s)
6365 (setq s (replace-match "" t t s))))
6366 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6367 (setq s (replace-match " " t t s)))
6368 (or string (setq s (concat "*" s))) ; Add * for headlines
6369 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6371 (defun org-make-link (&rest strings)
6372 "Concatenate STRINGS."
6373 (apply 'concat strings))
6375 (defun org-make-link-string (link &optional description)
6376 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6377 (unless (string-match "\\S-" link)
6378 (error "Empty link"))
6379 (when (stringp description)
6380 ;; Remove brackets from the description, they are fatal.
6381 (while (string-match "\\[" description)
6382 (setq description (replace-match "{" t t description)))
6383 (while (string-match "\\]" description)
6384 (setq description (replace-match "}" t t description))))
6385 (when (equal (org-link-escape link) description)
6386 ;; No description needed, it is identical
6387 (setq description nil))
6388 (when (and (not description)
6389 (not (equal link (org-link-escape link))))
6390 (setq description link))
6391 (concat "[[" (org-link-escape link) "]"
6392 (if description (concat "[" description "]") "")
6393 "]"))
6395 (defconst org-link-escape-chars
6396 '((?\ . "%20")
6397 (?\[ . "%5B")
6398 (?\] . "%5D")
6399 (?\340 . "%E0") ; `a
6400 (?\342 . "%E2") ; ^a
6401 (?\347 . "%E7") ; ,c
6402 (?\350 . "%E8") ; `e
6403 (?\351 . "%E9") ; 'e
6404 (?\352 . "%EA") ; ^e
6405 (?\356 . "%EE") ; ^i
6406 (?\364 . "%F4") ; ^o
6407 (?\371 . "%F9") ; `u
6408 (?\373 . "%FB") ; ^u
6409 (?\; . "%3B")
6410 (?? . "%3F")
6411 (?= . "%3D")
6412 (?+ . "%2B")
6414 "Association list of escapes for some characters problematic in links.
6415 This is the list that is used for internal purposes.")
6417 (defconst org-link-escape-chars-browser
6418 '((?\ . "%20")) ; 32 for the SPC char
6419 "Association list of escapes for some characters problematic in links.
6420 This is the list that is used before handing over to the browser.")
6422 (defun org-link-escape (text &optional table)
6423 "Escape charaters in TEXT that are problematic for links."
6424 (setq table (or table org-link-escape-chars))
6425 (when text
6426 (let ((re (mapconcat (lambda (x) (regexp-quote
6427 (char-to-string (car x))))
6428 table "\\|")))
6429 (while (string-match re text)
6430 (setq text
6431 (replace-match
6432 (cdr (assoc (string-to-char (match-string 0 text))
6433 table))
6434 t t text)))
6435 text)))
6437 (defun org-link-unescape (text &optional table)
6438 "Reverse the action of `org-link-escape'."
6439 (setq table (or table org-link-escape-chars))
6440 (when text
6441 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6442 table "\\|")))
6443 (while (string-match re text)
6444 (setq text
6445 (replace-match
6446 (char-to-string (car (rassoc (match-string 0 text) table)))
6447 t t text)))
6448 text)))
6450 (defun org-xor (a b)
6451 "Exclusive or."
6452 (if a (not b) b))
6454 (defun org-get-header (header)
6455 "Find a header field in the current buffer."
6456 (save-excursion
6457 (goto-char (point-min))
6458 (let ((case-fold-search t) s)
6459 (cond
6460 ((eq header 'from)
6461 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6462 (setq s (match-string 1)))
6463 (while (string-match "\"" s)
6464 (setq s (replace-match "" t t s)))
6465 (if (string-match "[<(].*" s)
6466 (setq s (replace-match "" t t s))))
6467 ((eq header 'message-id)
6468 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6469 (setq s (match-string 1))))
6470 ((eq header 'subject)
6471 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6472 (setq s (match-string 1)))))
6473 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6474 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6475 s)))
6478 (defun org-fixup-message-id-for-http (s)
6479 "Replace special characters in a message id, so it can be used in an http query."
6480 (while (string-match "<" s)
6481 (setq s (replace-match "%3C" t t s)))
6482 (while (string-match ">" s)
6483 (setq s (replace-match "%3E" t t s)))
6484 (while (string-match "@" s)
6485 (setq s (replace-match "%40" t t s)))
6488 ;;;###autoload
6489 (defun org-insert-link-global ()
6490 "Insert a link like Org-mode does.
6491 This command can be called in any mode to insert a link in Org-mode syntax."
6492 (interactive)
6493 (org-load-modules-maybe)
6494 (org-run-like-in-org-mode 'org-insert-link))
6496 (defun org-insert-link (&optional complete-file link-location)
6497 "Insert a link. At the prompt, enter the link.
6499 Completion can be used to select a link previously stored with
6500 `org-store-link'. When the empty string is entered (i.e. if you just
6501 press RET at the prompt), the link defaults to the most recently
6502 stored link. As SPC triggers completion in the minibuffer, you need to
6503 use M-SPC or C-q SPC to force the insertion of a space character.
6505 You will also be prompted for a description, and if one is given, it will
6506 be displayed in the buffer instead of the link.
6508 If there is already a link at point, this command will allow you to edit link
6509 and description parts.
6511 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6512 be selected using completion. The path to the file will be relative to the
6513 current directory if the file is in the current directory or a subdirectory.
6514 Otherwise, the link will be the absolute path as completed in the minibuffer
6515 \(i.e. normally ~/path/to/file).
6517 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6518 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6519 of `org-keep-stored-link-after-insertion'.
6521 If `org-make-link-description-function' is non-nil, this function will be
6522 called with the link target, and the result will be the default
6523 link description.
6525 If the LINK-LOCATION parameter is non-nil, this value will be
6526 used as the link location instead of reading one interactively."
6527 (interactive "P")
6528 (let* ((wcf (current-window-configuration))
6529 (region (if (org-region-active-p)
6530 (buffer-substring (region-beginning) (region-end))))
6531 (remove (and region (list (region-beginning) (region-end))))
6532 (desc region)
6533 tmphist ; byte-compile incorrectly complains about this
6534 (link link-location)
6535 entry file)
6536 (cond
6537 (link-location) ; specified by arg, just use it.
6538 ((org-in-regexp org-bracket-link-regexp 1)
6539 ;; We do have a link at point, and we are going to edit it.
6540 (setq remove (list (match-beginning 0) (match-end 0)))
6541 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6542 (setq link (read-string "Link: "
6543 (org-link-unescape
6544 (org-match-string-no-properties 1)))))
6545 ((or (org-in-regexp org-angle-link-re)
6546 (org-in-regexp org-plain-link-re))
6547 ;; Convert to bracket link
6548 (setq remove (list (match-beginning 0) (match-end 0))
6549 link (read-string "Link: "
6550 (org-remove-angle-brackets (match-string 0)))))
6551 ((equal complete-file '(4))
6552 ;; Completing read for file names.
6553 (setq file (read-file-name "File: "))
6554 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6555 (pwd1 (file-name-as-directory (abbreviate-file-name
6556 (expand-file-name ".")))))
6557 (cond
6558 ((equal complete-file '(16))
6559 (setq link (org-make-link
6560 "file:"
6561 (abbreviate-file-name (expand-file-name file)))))
6562 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6563 (setq link (org-make-link "file:" (match-string 1 file))))
6564 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6565 (expand-file-name file))
6566 (setq link (org-make-link
6567 "file:" (match-string 1 (expand-file-name file)))))
6568 (t (setq link (org-make-link "file:" file))))))
6570 ;; Read link, with completion for stored links.
6571 (with-output-to-temp-buffer "*Org Links*"
6572 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6573 (when org-stored-links
6574 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6575 (princ (mapconcat
6576 (lambda (x)
6577 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6578 (reverse org-stored-links) "\n"))))
6579 (let ((cw (selected-window)))
6580 (select-window (get-buffer-window "*Org Links*"))
6581 (shrink-window-if-larger-than-buffer)
6582 (setq truncate-lines t)
6583 (select-window cw))
6584 ;; Fake a link history, containing the stored links.
6585 (setq tmphist (append (mapcar 'car org-stored-links)
6586 org-insert-link-history))
6587 (unwind-protect
6588 (setq link (org-completing-read
6589 "Link: "
6590 (append
6591 (mapcar (lambda (x) (list (concat (car x) ":")))
6592 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6593 (mapcar (lambda (x) (list (concat x ":")))
6594 org-link-types))
6595 nil nil nil
6596 'tmphist
6597 (or (car (car org-stored-links)))))
6598 (set-window-configuration wcf)
6599 (kill-buffer "*Org Links*"))
6600 (setq entry (assoc link org-stored-links))
6601 (or entry (push link org-insert-link-history))
6602 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6603 (not org-keep-stored-link-after-insertion))
6604 (setq org-stored-links (delq (assoc link org-stored-links)
6605 org-stored-links)))
6606 (setq desc (or desc (nth 1 entry)))))
6608 (if (string-match org-plain-link-re link)
6609 ;; URL-like link, normalize the use of angular brackets.
6610 (setq link (org-make-link (org-remove-angle-brackets link))))
6612 ;; Check if we are linking to the current file with a search option
6613 ;; If yes, simplify the link by using only the search option.
6614 (when (and buffer-file-name
6615 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6616 (let* ((path (match-string 1 link))
6617 (case-fold-search nil)
6618 (search (match-string 2 link)))
6619 (save-match-data
6620 (if (equal (file-truename buffer-file-name) (file-truename path))
6621 ;; We are linking to this same file, with a search option
6622 (setq link search)))))
6624 ;; Check if we can/should use a relative path. If yes, simplify the link
6625 (when (string-match "\\<file:\\(.*\\)" link)
6626 (let* ((path (match-string 1 link))
6627 (origpath path)
6628 (case-fold-search nil))
6629 (cond
6630 ((eq org-link-file-path-type 'absolute)
6631 (setq path (abbreviate-file-name (expand-file-name path))))
6632 ((eq org-link-file-path-type 'noabbrev)
6633 (setq path (expand-file-name path)))
6634 ((eq org-link-file-path-type 'relative)
6635 (setq path (file-relative-name path)))
6637 (save-match-data
6638 (if (string-match (concat "^" (regexp-quote
6639 (file-name-as-directory
6640 (expand-file-name "."))))
6641 (expand-file-name path))
6642 ;; We are linking a file with relative path name.
6643 (setq path (substring (expand-file-name path)
6644 (match-end 0)))))))
6645 (setq link (concat "file:" path))
6646 (if (equal desc origpath)
6647 (setq desc path))))
6649 (if org-make-link-description-function
6650 (setq desc (funcall org-make-link-description-function link desc)))
6652 (setq desc (read-string "Description: " desc))
6653 (unless (string-match "\\S-" desc) (setq desc nil))
6654 (if remove (apply 'delete-region remove))
6655 (insert (org-make-link-string link desc))))
6657 (defun org-completing-read (&rest args)
6658 (let ((minibuffer-local-completion-map
6659 (copy-keymap minibuffer-local-completion-map)))
6660 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6661 (apply 'completing-read args)))
6663 ;;; Opening/following a link
6665 (defvar org-link-search-failed nil)
6667 (defun org-next-link ()
6668 "Move forward to the next link.
6669 If the link is in hidden text, expose it."
6670 (interactive)
6671 (when (and org-link-search-failed (eq this-command last-command))
6672 (goto-char (point-min))
6673 (message "Link search wrapped back to beginning of buffer"))
6674 (setq org-link-search-failed nil)
6675 (let* ((pos (point))
6676 (ct (org-context))
6677 (a (assoc :link ct)))
6678 (if a (goto-char (nth 2 a)))
6679 (if (re-search-forward org-any-link-re nil t)
6680 (progn
6681 (goto-char (match-beginning 0))
6682 (if (org-invisible-p) (org-show-context)))
6683 (goto-char pos)
6684 (setq org-link-search-failed t)
6685 (error "No further link found"))))
6687 (defun org-previous-link ()
6688 "Move backward to the previous link.
6689 If the link is in hidden text, expose it."
6690 (interactive)
6691 (when (and org-link-search-failed (eq this-command last-command))
6692 (goto-char (point-max))
6693 (message "Link search wrapped back to end of buffer"))
6694 (setq org-link-search-failed nil)
6695 (let* ((pos (point))
6696 (ct (org-context))
6697 (a (assoc :link ct)))
6698 (if a (goto-char (nth 1 a)))
6699 (if (re-search-backward org-any-link-re nil t)
6700 (progn
6701 (goto-char (match-beginning 0))
6702 (if (org-invisible-p) (org-show-context)))
6703 (goto-char pos)
6704 (setq org-link-search-failed t)
6705 (error "No further link found"))))
6707 (defun org-find-file-at-mouse (ev)
6708 "Open file link or URL at mouse."
6709 (interactive "e")
6710 (mouse-set-point ev)
6711 (org-open-at-point 'in-emacs))
6713 (defun org-open-at-mouse (ev)
6714 "Open file link or URL at mouse."
6715 (interactive "e")
6716 (mouse-set-point ev)
6717 (org-open-at-point))
6719 (defvar org-window-config-before-follow-link nil
6720 "The window configuration before following a link.
6721 This is saved in case the need arises to restore it.")
6723 (defvar org-open-link-marker (make-marker)
6724 "Marker pointing to the location where `org-open-at-point; was called.")
6726 ;;;###autoload
6727 (defun org-open-at-point-global ()
6728 "Follow a link like Org-mode does.
6729 This command can be called in any mode to follow a link that has
6730 Org-mode syntax."
6731 (interactive)
6732 (org-run-like-in-org-mode 'org-open-at-point))
6734 ;;;###autoload
6735 (defun org-open-link-from-string (s &optional arg)
6736 "Open a link in the string S, as if it was in Org-mode."
6737 (interactive "sLink: \nP")
6738 (with-temp-buffer
6739 (let ((org-inhibit-startup t))
6740 (org-mode)
6741 (insert s)
6742 (goto-char (point-min))
6743 (org-open-at-point arg))))
6745 (defun org-open-at-point (&optional in-emacs)
6746 "Open link at or after point.
6747 If there is no link at point, this function will search forward up to
6748 the end of the current subtree.
6749 Normally, files will be opened by an appropriate application. If the
6750 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6751 (interactive "P")
6752 (org-load-modules-maybe)
6753 (move-marker org-open-link-marker (point))
6754 (setq org-window-config-before-follow-link (current-window-configuration))
6755 (org-remove-occur-highlights nil nil t)
6756 (if (org-at-timestamp-p t)
6757 (org-follow-timestamp-link)
6758 (let (type path link line search (pos (point)))
6759 (catch 'match
6760 (save-excursion
6761 (skip-chars-forward "^]\n\r")
6762 (when (org-in-regexp org-bracket-link-regexp)
6763 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6764 (while (string-match " *\n *" link)
6765 (setq link (replace-match " " t t link)))
6766 (setq link (org-link-expand-abbrev link))
6767 (if (string-match org-link-re-with-space2 link)
6768 (setq type (match-string 1 link) path (match-string 2 link))
6769 (setq type "thisfile" path link))
6770 (throw 'match t)))
6772 (when (get-text-property (point) 'org-linked-text)
6773 (setq type "thisfile"
6774 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6775 (1+ (point)) (point))
6776 path (buffer-substring
6777 (previous-single-property-change pos 'org-linked-text)
6778 (next-single-property-change pos 'org-linked-text)))
6779 (throw 'match t))
6781 (save-excursion
6782 (when (or (org-in-regexp org-angle-link-re)
6783 (org-in-regexp org-plain-link-re))
6784 (setq type (match-string 1) path (match-string 2))
6785 (throw 'match t)))
6786 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6787 (setq type "tree-match"
6788 path (match-string 1))
6789 (throw 'match t))
6790 (save-excursion
6791 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6792 (setq type "tags"
6793 path (match-string 1))
6794 (while (string-match ":" path)
6795 (setq path (replace-match "+" t t path)))
6796 (throw 'match t))))
6797 (unless path
6798 (error "No link found"))
6799 ;; Remove any trailing spaces in path
6800 (if (string-match " +\\'" path)
6801 (setq path (replace-match "" t t path)))
6803 (cond
6805 ((assoc type org-link-protocols)
6806 (funcall (nth 1 (assoc type org-link-protocols)) path))
6808 ((equal type "mailto")
6809 (let ((cmd (car org-link-mailto-program))
6810 (args (cdr org-link-mailto-program)) args1
6811 (address path) (subject "") a)
6812 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6813 (setq address (match-string 1 path)
6814 subject (org-link-escape (match-string 2 path))))
6815 (while args
6816 (cond
6817 ((not (stringp (car args))) (push (pop args) args1))
6818 (t (setq a (pop args))
6819 (if (string-match "%a" a)
6820 (setq a (replace-match address t t a)))
6821 (if (string-match "%s" a)
6822 (setq a (replace-match subject t t a)))
6823 (push a args1))))
6824 (apply cmd (nreverse args1))))
6826 ((member type '("http" "https" "ftp" "news"))
6827 (browse-url (concat type ":" (org-link-escape
6828 path org-link-escape-chars-browser))))
6830 ((member type '("message"))
6831 (browse-url (concat type ":" path)))
6833 ((string= type "tags")
6834 (org-tags-view in-emacs path))
6835 ((string= type "thisfile")
6836 (if in-emacs
6837 (switch-to-buffer-other-window
6838 (org-get-buffer-for-internal-link (current-buffer)))
6839 (org-mark-ring-push))
6840 (let ((cmd `(org-link-search
6841 ,path
6842 ,(cond ((equal in-emacs '(4)) 'occur)
6843 ((equal in-emacs '(16)) 'org-occur)
6844 (t nil))
6845 ,pos)))
6846 (condition-case nil (eval cmd)
6847 (error (progn (widen) (eval cmd))))))
6849 ((string= type "tree-match")
6850 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6852 ((string= type "file")
6853 (if (string-match "::\\([0-9]+\\)\\'" path)
6854 (setq line (string-to-number (match-string 1 path))
6855 path (substring path 0 (match-beginning 0)))
6856 (if (string-match "::\\(.+\\)\\'" path)
6857 (setq search (match-string 1 path)
6858 path (substring path 0 (match-beginning 0)))))
6859 (if (string-match "[*?{]" (file-name-nondirectory path))
6860 (dired path)
6861 (org-open-file path in-emacs line search)))
6863 ((string= type "news")
6864 (require 'org-gnus)
6865 (org-gnus-follow-link path))
6867 ((string= type "shell")
6868 (let ((cmd path))
6869 (if (or (not org-confirm-shell-link-function)
6870 (funcall org-confirm-shell-link-function
6871 (format "Execute \"%s\" in shell? "
6872 (org-add-props cmd nil
6873 'face 'org-warning))))
6874 (progn
6875 (message "Executing %s" cmd)
6876 (shell-command cmd))
6877 (error "Abort"))))
6879 ((string= type "elisp")
6880 (let ((cmd path))
6881 (if (or (not org-confirm-elisp-link-function)
6882 (funcall org-confirm-elisp-link-function
6883 (format "Execute \"%s\" as elisp? "
6884 (org-add-props cmd nil
6885 'face 'org-warning))))
6886 (message "%s => %s" cmd (eval (read cmd)))
6887 (error "Abort"))))
6890 (browse-url-at-point)))))
6891 (move-marker org-open-link-marker nil)
6892 (run-hook-with-args 'org-follow-link-hook))
6894 ;;;; Time estimates
6896 (defun org-get-effort (&optional pom)
6897 "Get the effort estimate for the current entry."
6898 (org-entry-get pom org-effort-property))
6900 ;;; File search
6902 (defvar org-create-file-search-functions nil
6903 "List of functions to construct the right search string for a file link.
6904 These functions are called in turn with point at the location to
6905 which the link should point.
6907 A function in the hook should first test if it would like to
6908 handle this file type, for example by checking the major-mode or
6909 the file extension. If it decides not to handle this file, it
6910 should just return nil to give other functions a chance. If it
6911 does handle the file, it must return the search string to be used
6912 when following the link. The search string will be part of the
6913 file link, given after a double colon, and `org-open-at-point'
6914 will automatically search for it. If special measures must be
6915 taken to make the search successful, another function should be
6916 added to the companion hook `org-execute-file-search-functions',
6917 which see.
6919 A function in this hook may also use `setq' to set the variable
6920 `description' to provide a suggestion for the descriptive text to
6921 be used for this link when it gets inserted into an Org-mode
6922 buffer with \\[org-insert-link].")
6924 (defvar org-execute-file-search-functions nil
6925 "List of functions to execute a file search triggered by a link.
6927 Functions added to this hook must accept a single argument, the
6928 search string that was part of the file link, the part after the
6929 double colon. The function must first check if it would like to
6930 handle this search, for example by checking the major-mode or the
6931 file extension. If it decides not to handle this search, it
6932 should just return nil to give other functions a chance. If it
6933 does handle the search, it must return a non-nil value to keep
6934 other functions from trying.
6936 Each function can access the current prefix argument through the
6937 variable `current-prefix-argument'. Note that a single prefix is
6938 used to force opening a link in Emacs, so it may be good to only
6939 use a numeric or double prefix to guide the search function.
6941 In case this is needed, a function in this hook can also restore
6942 the window configuration before `org-open-at-point' was called using:
6944 (set-window-configuration org-window-config-before-follow-link)")
6946 (defun org-link-search (s &optional type avoid-pos)
6947 "Search for a link search option.
6948 If S is surrounded by forward slashes, it is interpreted as a
6949 regular expression. In org-mode files, this will create an `org-occur'
6950 sparse tree. In ordinary files, `occur' will be used to list matches.
6951 If the current buffer is in `dired-mode', grep will be used to search
6952 in all files. If AVOID-POS is given, ignore matches near that position."
6953 (let ((case-fold-search t)
6954 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6955 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6956 (append '(("") (" ") ("\t") ("\n"))
6957 org-emphasis-alist)
6958 "\\|") "\\)"))
6959 (pos (point))
6960 (pre nil) (post nil)
6961 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6962 (cond
6963 ;; First check if there are any special
6964 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6965 ;; Now try the builtin stuff
6966 ((save-excursion
6967 (goto-char (point-min))
6968 (and
6969 (re-search-forward
6970 (concat "<<" (regexp-quote s0) ">>") nil t)
6971 (setq type 'dedicated
6972 pos (match-beginning 0))))
6973 ;; There is an exact target for this
6974 (goto-char pos))
6975 ((string-match "^/\\(.*\\)/$" s)
6976 ;; A regular expression
6977 (cond
6978 ((org-mode-p)
6979 (org-occur (match-string 1 s)))
6980 ;;((eq major-mode 'dired-mode)
6981 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6982 (t (org-do-occur (match-string 1 s)))))
6984 ;; A normal search strings
6985 (when (equal (string-to-char s) ?*)
6986 ;; Anchor on headlines, post may include tags.
6987 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6988 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6989 s (substring s 1)))
6990 (remove-text-properties
6991 0 (length s)
6992 '(face nil mouse-face nil keymap nil fontified nil) s)
6993 ;; Make a series of regular expressions to find a match
6994 (setq words (org-split-string s "[ \n\r\t]+")
6996 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6997 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6998 "\\)" markers)
6999 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7000 re2a (concat "[ \t\r\n]" re2a_)
7001 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7002 re4 (concat "[^a-zA-Z_]" re4_)
7004 re1 (concat pre re2 post)
7005 re3 (concat pre (if pre re4_ re4) post)
7006 re5 (concat pre ".*" re4)
7007 re2 (concat pre re2)
7008 re2a (concat pre (if pre re2a_ re2a))
7009 re4 (concat pre (if pre re4_ re4))
7010 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7011 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7012 re5 "\\)"
7014 (cond
7015 ((eq type 'org-occur) (org-occur reall))
7016 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7017 (t (goto-char (point-min))
7018 (setq type 'fuzzy)
7019 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7020 (org-search-not-self 1 re1 nil t)
7021 (org-search-not-self 1 re2 nil t)
7022 (org-search-not-self 1 re2a nil t)
7023 (org-search-not-self 1 re3 nil t)
7024 (org-search-not-self 1 re4 nil t)
7025 (org-search-not-self 1 re5 nil t)
7027 (goto-char (match-beginning 1))
7028 (goto-char pos)
7029 (error "No match")))))
7031 ;; Normal string-search
7032 (goto-char (point-min))
7033 (if (search-forward s nil t)
7034 (goto-char (match-beginning 0))
7035 (error "No match"))))
7036 (and (org-mode-p) (org-show-context 'link-search))
7037 type))
7039 (defun org-search-not-self (group &rest args)
7040 "Execute `re-search-forward', but only accept matches that do not
7041 enclose the position of `org-open-link-marker'."
7042 (let ((m org-open-link-marker))
7043 (catch 'exit
7044 (while (apply 're-search-forward args)
7045 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7046 (goto-char (match-end group))
7047 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7048 (> (match-beginning 0) (marker-position m))
7049 (< (match-end 0) (marker-position m)))
7050 (save-match-data
7051 (or (not (org-in-regexp
7052 org-bracket-link-analytic-regexp 1))
7053 (not (match-end 4)) ; no description
7054 (and (<= (match-beginning 4) (point))
7055 (>= (match-end 4) (point))))))
7056 (throw 'exit (point))))))))
7058 (defun org-get-buffer-for-internal-link (buffer)
7059 "Return a buffer to be used for displaying the link target of internal links."
7060 (cond
7061 ((not org-display-internal-link-with-indirect-buffer)
7062 buffer)
7063 ((string-match "(Clone)$" (buffer-name buffer))
7064 (message "Buffer is already a clone, not making another one")
7065 ;; we also do not modify visibility in this case
7066 buffer)
7067 (t ; make a new indirect buffer for displaying the link
7068 (let* ((bn (buffer-name buffer))
7069 (ibn (concat bn "(Clone)"))
7070 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7071 (with-current-buffer ib (org-overview))
7072 ib))))
7074 (defun org-do-occur (regexp &optional cleanup)
7075 "Call the Emacs command `occur'.
7076 If CLEANUP is non-nil, remove the printout of the regular expression
7077 in the *Occur* buffer. This is useful if the regex is long and not useful
7078 to read."
7079 (occur regexp)
7080 (when cleanup
7081 (let ((cwin (selected-window)) win beg end)
7082 (when (setq win (get-buffer-window "*Occur*"))
7083 (select-window win))
7084 (goto-char (point-min))
7085 (when (re-search-forward "match[a-z]+" nil t)
7086 (setq beg (match-end 0))
7087 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7088 (setq end (1- (match-beginning 0)))))
7089 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7090 (goto-char (point-min))
7091 (select-window cwin))))
7093 ;;; The mark ring for links jumps
7095 (defvar org-mark-ring nil
7096 "Mark ring for positions before jumps in Org-mode.")
7097 (defvar org-mark-ring-last-goto nil
7098 "Last position in the mark ring used to go back.")
7099 ;; Fill and close the ring
7100 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7101 (loop for i from 1 to org-mark-ring-length do
7102 (push (make-marker) org-mark-ring))
7103 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7104 org-mark-ring)
7106 (defun org-mark-ring-push (&optional pos buffer)
7107 "Put the current position or POS into the mark ring and rotate it."
7108 (interactive)
7109 (setq pos (or pos (point)))
7110 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7111 (move-marker (car org-mark-ring)
7112 (or pos (point))
7113 (or buffer (current-buffer)))
7114 (message "%s"
7115 (substitute-command-keys
7116 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7118 (defun org-mark-ring-goto (&optional n)
7119 "Jump to the previous position in the mark ring.
7120 With prefix arg N, jump back that many stored positions. When
7121 called several times in succession, walk through the entire ring.
7122 Org-mode commands jumping to a different position in the current file,
7123 or to another Org-mode file, automatically push the old position
7124 onto the ring."
7125 (interactive "p")
7126 (let (p m)
7127 (if (eq last-command this-command)
7128 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7129 (setq p org-mark-ring))
7130 (setq org-mark-ring-last-goto p)
7131 (setq m (car p))
7132 (switch-to-buffer (marker-buffer m))
7133 (goto-char m)
7134 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7136 (defun org-remove-angle-brackets (s)
7137 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7138 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7140 (defun org-add-angle-brackets (s)
7141 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7142 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7145 ;;; Following specific links
7147 (defun org-follow-timestamp-link ()
7148 (cond
7149 ((org-at-date-range-p t)
7150 (let ((org-agenda-start-on-weekday)
7151 (t1 (match-string 1))
7152 (t2 (match-string 2)))
7153 (setq t1 (time-to-days (org-time-string-to-time t1))
7154 t2 (time-to-days (org-time-string-to-time t2)))
7155 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7156 ((org-at-timestamp-p t)
7157 (org-agenda-list nil (time-to-days (org-time-string-to-time
7158 (substring (match-string 1) 0 10)))
7160 (t (error "This should not happen"))))
7163 ;;; Following file links
7164 (defvar org-wait nil)
7165 (defun org-open-file (path &optional in-emacs line search)
7166 "Open the file at PATH.
7167 First, this expands any special file name abbreviations. Then the
7168 configuration variable `org-file-apps' is checked if it contains an
7169 entry for this file type, and if yes, the corresponding command is launched.
7170 If no application is found, Emacs simply visits the file.
7171 With optional argument IN-EMACS, Emacs will visit the file.
7172 Optional LINE specifies a line to go to, optional SEARCH a string to
7173 search for. If LINE or SEARCH is given, the file will always be
7174 opened in Emacs.
7175 If the file does not exist, an error is thrown."
7176 (setq in-emacs (or in-emacs line search))
7177 (let* ((file (if (equal path "")
7178 buffer-file-name
7179 (substitute-in-file-name (expand-file-name path))))
7180 (apps (append org-file-apps (org-default-apps)))
7181 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7182 (dirp (if remp nil (file-directory-p file)))
7183 (dfile (downcase file))
7184 (old-buffer (current-buffer))
7185 (old-pos (point))
7186 (old-mode major-mode)
7187 ext cmd)
7188 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7189 (setq ext (match-string 1 dfile))
7190 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7191 (setq ext (match-string 1 dfile))))
7192 (if in-emacs
7193 (setq cmd 'emacs)
7194 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7195 (and dirp (cdr (assoc 'directory apps)))
7196 (cdr (assoc ext apps))
7197 (cdr (assoc t apps)))))
7198 (when (eq cmd 'mailcap)
7199 (require 'mailcap)
7200 (mailcap-parse-mailcaps)
7201 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7202 (command (mailcap-mime-info mime-type)))
7203 (if (stringp command)
7204 (setq cmd command)
7205 (setq cmd 'emacs))))
7206 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7207 (not (file-exists-p file))
7208 (not org-open-non-existing-files))
7209 (error "No such file: %s" file))
7210 (cond
7211 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7212 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7213 (while (string-match "['\"]%s['\"]" cmd)
7214 (setq cmd (replace-match "%s" t t cmd)))
7215 (while (string-match "%s" cmd)
7216 (setq cmd (replace-match
7217 (save-match-data (shell-quote-argument file))
7218 t t cmd)))
7219 (save-window-excursion
7220 (start-process-shell-command cmd nil cmd)
7221 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7223 ((or (stringp cmd)
7224 (eq cmd 'emacs))
7225 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7226 (widen)
7227 (if line (goto-line line)
7228 (if search (org-link-search search))))
7229 ((consp cmd)
7230 (eval cmd))
7231 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7232 (and (org-mode-p) (eq old-mode 'org-mode)
7233 (or (not (equal old-buffer (current-buffer)))
7234 (not (equal old-pos (point))))
7235 (org-mark-ring-push old-pos old-buffer))))
7237 (defun org-default-apps ()
7238 "Return the default applications for this operating system."
7239 (cond
7240 ((eq system-type 'darwin)
7241 org-file-apps-defaults-macosx)
7242 ((eq system-type 'windows-nt)
7243 org-file-apps-defaults-windowsnt)
7244 (t org-file-apps-defaults-gnu)))
7246 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7247 (defun org-file-remote-p (file)
7248 "Test whether FILE specifies a location on a remote system.
7249 Return non-nil if the location is indeed remote.
7251 For example, the filename \"/user@host:/foo\" specifies a location
7252 on the system \"/user@host:\"."
7253 (cond ((fboundp 'file-remote-p)
7254 (file-remote-p file))
7255 ((fboundp 'tramp-handle-file-remote-p)
7256 (tramp-handle-file-remote-p file))
7257 ((and (boundp 'ange-ftp-name-format)
7258 (string-match (car ange-ftp-name-format) file))
7260 (t nil)))
7263 ;;;; Refiling
7265 (defun org-get-org-file ()
7266 "Read a filename, with default directory `org-directory'."
7267 (let ((default (or org-default-notes-file remember-data-file)))
7268 (read-file-name (format "File name [%s]: " default)
7269 (file-name-as-directory org-directory)
7270 default)))
7272 (defun org-notes-order-reversed-p ()
7273 "Check if the current file should receive notes in reversed order."
7274 (cond
7275 ((not org-reverse-note-order) nil)
7276 ((eq t org-reverse-note-order) t)
7277 ((not (listp org-reverse-note-order)) nil)
7278 (t (catch 'exit
7279 (let ((all org-reverse-note-order)
7280 entry)
7281 (while (setq entry (pop all))
7282 (if (string-match (car entry) buffer-file-name)
7283 (throw 'exit (cdr entry))))
7284 nil)))))
7286 (defvar org-refile-target-table nil
7287 "The list of refile targets, created by `org-refile'.")
7289 (defvar org-agenda-new-buffers nil
7290 "Buffers created to visit agenda files.")
7292 (defun org-get-refile-targets (&optional default-buffer)
7293 "Produce a table with refile targets."
7294 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7295 targets txt re files f desc descre)
7296 (with-current-buffer (or default-buffer (current-buffer))
7297 (while (setq entry (pop entries))
7298 (setq files (car entry) desc (cdr entry))
7299 (cond
7300 ((null files) (setq files (list (current-buffer))))
7301 ((eq files 'org-agenda-files)
7302 (setq files (org-agenda-files 'unrestricted)))
7303 ((and (symbolp files) (fboundp files))
7304 (setq files (funcall files)))
7305 ((and (symbolp files) (boundp files))
7306 (setq files (symbol-value files))))
7307 (if (stringp files) (setq files (list files)))
7308 (cond
7309 ((eq (car desc) :tag)
7310 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7311 ((eq (car desc) :todo)
7312 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7313 ((eq (car desc) :regexp)
7314 (setq descre (cdr desc)))
7315 ((eq (car desc) :level)
7316 (setq descre (concat "^\\*\\{" (number-to-string
7317 (if org-odd-levels-only
7318 (1- (* 2 (cdr desc)))
7319 (cdr desc)))
7320 "\\}[ \t]")))
7321 ((eq (car desc) :maxlevel)
7322 (setq descre (concat "^\\*\\{1," (number-to-string
7323 (if org-odd-levels-only
7324 (1- (* 2 (cdr desc)))
7325 (cdr desc)))
7326 "\\}[ \t]")))
7327 (t (error "Bad refiling target description %s" desc)))
7328 (while (setq f (pop files))
7329 (save-excursion
7330 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7331 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7332 (save-excursion
7333 (save-restriction
7334 (widen)
7335 (goto-char (point-min))
7336 (while (re-search-forward descre nil t)
7337 (goto-char (point-at-bol))
7338 (when (looking-at org-complex-heading-regexp)
7339 (setq txt (match-string 4)
7340 re (concat "^" (regexp-quote
7341 (buffer-substring (match-beginning 1)
7342 (match-end 4)))))
7343 (if (match-end 5) (setq re (concat re "[ \t]+"
7344 (regexp-quote
7345 (match-string 5)))))
7346 (setq re (concat re "[ \t]*$"))
7347 (when org-refile-use-outline-path
7348 (setq txt (mapconcat 'identity
7349 (append
7350 (if (eq org-refile-use-outline-path 'file)
7351 (list (file-name-nondirectory
7352 (buffer-file-name (buffer-base-buffer))))
7353 (if (eq org-refile-use-outline-path 'full-file-path)
7354 (list (buffer-file-name (buffer-base-buffer)))))
7355 (org-get-outline-path)
7356 (list txt))
7357 "/")))
7358 (push (list txt f re (point)) targets))
7359 (goto-char (point-at-eol))))))))
7360 (nreverse targets))))
7362 (defun org-get-outline-path ()
7363 "Return the outline path to the current entry, as a list."
7364 (let (rtn)
7365 (save-excursion
7366 (while (org-up-heading-safe)
7367 (when (looking-at org-complex-heading-regexp)
7368 (push (org-match-string-no-properties 4) rtn)))
7369 rtn)))
7371 (defvar org-refile-history nil
7372 "History for refiling operations.")
7374 (defun org-refile (&optional goto default-buffer)
7375 "Move the entry at point to another heading.
7376 The list of target headings is compiled using the information in
7377 `org-refile-targets', which see. This list is created before each use
7378 and will therefore always be up-to-date.
7380 At the target location, the entry is filed as a subitem of the target heading.
7381 Depending on `org-reverse-note-order', the new subitem will either be the
7382 first of the last subitem.
7384 With prefix arg GOTO, the command will only visit the target location,
7385 not actually move anything.
7386 With a double prefix `C-c C-c', go to the location where the last refiling
7387 operation has put the subtree."
7388 (interactive "P")
7389 (let* ((cbuf (current-buffer))
7390 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7391 pos it nbuf file re level reversed)
7392 (if (equal goto '(16))
7393 (org-refile-goto-last-stored)
7394 (when (setq it (org-refile-get-location
7395 (if goto "Goto: " "Refile to: ") default-buffer))
7396 (setq file (nth 1 it)
7397 re (nth 2 it)
7398 pos (nth 3 it))
7399 (setq nbuf (or (find-buffer-visiting file)
7400 (find-file-noselect file)))
7401 (if goto
7402 (progn
7403 (switch-to-buffer nbuf)
7404 (goto-char pos)
7405 (org-show-context 'org-goto))
7406 (org-copy-subtree 1 nil t)
7407 (save-excursion
7408 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7409 (find-file-noselect file))))
7410 (setq reversed (org-notes-order-reversed-p))
7411 (save-excursion
7412 (save-restriction
7413 (widen)
7414 (goto-char pos)
7415 (looking-at outline-regexp)
7416 (setq level (org-get-valid-level (funcall outline-level) 1))
7417 (goto-char
7418 (if reversed
7419 (outline-next-heading)
7420 (or (save-excursion (outline-get-next-sibling))
7421 (org-end-of-subtree t t)
7422 (point-max))))
7423 (bookmark-set "org-refile-last-stored")
7424 (org-paste-subtree level))))
7425 (org-cut-subtree)
7426 (setq org-markers-to-move nil)
7427 (message "Entry refiled to \"%s\"" (car it)))))))
7429 (defun org-refile-goto-last-stored ()
7430 "Go to the location where the last refile was stored."
7431 (interactive)
7432 (bookmark-jump "org-refile-last-stored")
7433 (message "This is the location of the last refile"))
7435 (defun org-refile-get-location (&optional prompt default-buffer)
7436 "Prompt the user for a refile location, using PROMPT."
7437 (let ((org-refile-targets org-refile-targets)
7438 (org-refile-use-outline-path org-refile-use-outline-path))
7439 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7440 (unless org-refile-target-table
7441 (error "No refile targets"))
7442 (let* ((cbuf (current-buffer))
7443 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7444 (fname (and filename (file-truename filename)))
7445 (tbl (mapcar
7446 (lambda (x)
7447 (if (not (equal fname (file-truename (nth 1 x))))
7448 (cons (concat (car x) " (" (file-name-nondirectory
7449 (nth 1 x)) ")")
7450 (cdr x))
7452 org-refile-target-table))
7453 (completion-ignore-case t))
7454 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7455 tbl)))
7457 ;;;; Dynamic blocks
7459 (defun org-find-dblock (name)
7460 "Find the first dynamic block with name NAME in the buffer.
7461 If not found, stay at current position and return nil."
7462 (let (pos)
7463 (save-excursion
7464 (goto-char (point-min))
7465 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7466 nil t)
7467 (match-beginning 0))))
7468 (if pos (goto-char pos))
7469 pos))
7471 (defconst org-dblock-start-re
7472 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7473 "Matches the startline of a dynamic block, with parameters.")
7475 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7476 "Matches the end of a dyhamic block.")
7478 (defun org-create-dblock (plist)
7479 "Create a dynamic block section, with parameters taken from PLIST.
7480 PLIST must containe a :name entry which is used as name of the block."
7481 (unless (bolp) (newline))
7482 (let ((name (plist-get plist :name)))
7483 (insert "#+BEGIN: " name)
7484 (while plist
7485 (if (eq (car plist) :name)
7486 (setq plist (cddr plist))
7487 (insert " " (prin1-to-string (pop plist)))))
7488 (insert "\n\n#+END:\n")
7489 (beginning-of-line -2)))
7491 (defun org-prepare-dblock ()
7492 "Prepare dynamic block for refresh.
7493 This empties the block, puts the cursor at the insert position and returns
7494 the property list including an extra property :name with the block name."
7495 (unless (looking-at org-dblock-start-re)
7496 (error "Not at a dynamic block"))
7497 (let* ((begdel (1+ (match-end 0)))
7498 (name (org-no-properties (match-string 1)))
7499 (params (append (list :name name)
7500 (read (concat "(" (match-string 3) ")")))))
7501 (unless (re-search-forward org-dblock-end-re nil t)
7502 (error "Dynamic block not terminated"))
7503 (setq params
7504 (append params
7505 (list :content (buffer-substring
7506 begdel (match-beginning 0)))))
7507 (delete-region begdel (match-beginning 0))
7508 (goto-char begdel)
7509 (open-line 1)
7510 params))
7512 (defun org-map-dblocks (&optional command)
7513 "Apply COMMAND to all dynamic blocks in the current buffer.
7514 If COMMAND is not given, use `org-update-dblock'."
7515 (let ((cmd (or command 'org-update-dblock))
7516 pos)
7517 (save-excursion
7518 (goto-char (point-min))
7519 (while (re-search-forward org-dblock-start-re nil t)
7520 (goto-char (setq pos (match-beginning 0)))
7521 (condition-case nil
7522 (funcall cmd)
7523 (error (message "Error during update of dynamic block")))
7524 (goto-char pos)
7525 (unless (re-search-forward org-dblock-end-re nil t)
7526 (error "Dynamic block not terminated"))))))
7528 (defun org-dblock-update (&optional arg)
7529 "User command for updating dynamic blocks.
7530 Update the dynamic block at point. With prefix ARG, update all dynamic
7531 blocks in the buffer."
7532 (interactive "P")
7533 (if arg
7534 (org-update-all-dblocks)
7535 (or (looking-at org-dblock-start-re)
7536 (org-beginning-of-dblock))
7537 (org-update-dblock)))
7539 (defun org-update-dblock ()
7540 "Update the dynamic block at point
7541 This means to empty the block, parse for parameters and then call
7542 the correct writing function."
7543 (save-window-excursion
7544 (let* ((pos (point))
7545 (line (org-current-line))
7546 (params (org-prepare-dblock))
7547 (name (plist-get params :name))
7548 (cmd (intern (concat "org-dblock-write:" name))))
7549 (message "Updating dynamic block `%s' at line %d..." name line)
7550 (funcall cmd params)
7551 (message "Updating dynamic block `%s' at line %d...done" name line)
7552 (goto-char pos))))
7554 (defun org-beginning-of-dblock ()
7555 "Find the beginning of the dynamic block at point.
7556 Error if there is no scuh block at point."
7557 (let ((pos (point))
7558 beg)
7559 (end-of-line 1)
7560 (if (and (re-search-backward org-dblock-start-re nil t)
7561 (setq beg (match-beginning 0))
7562 (re-search-forward org-dblock-end-re nil t)
7563 (> (match-end 0) pos))
7564 (goto-char beg)
7565 (goto-char pos)
7566 (error "Not in a dynamic block"))))
7568 (defun org-update-all-dblocks ()
7569 "Update all dynamic blocks in the buffer.
7570 This function can be used in a hook."
7571 (when (org-mode-p)
7572 (org-map-dblocks 'org-update-dblock)))
7575 ;;;; Completion
7577 (defconst org-additional-option-like-keywords
7578 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7579 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7580 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7582 (defun org-complete (&optional arg)
7583 "Perform completion on word at point.
7584 At the beginning of a headline, this completes TODO keywords as given in
7585 `org-todo-keywords'.
7586 If the current word is preceded by a backslash, completes the TeX symbols
7587 that are supported for HTML support.
7588 If the current word is preceded by \"#+\", completes special words for
7589 setting file options.
7590 In the line after \"#+STARTUP:, complete valid keywords.\"
7591 At all other locations, this simply calls the value of
7592 `org-completion-fallback-command'."
7593 (interactive "P")
7594 (org-without-partial-completion
7595 (catch 'exit
7596 (let* ((end (point))
7597 (beg1 (save-excursion
7598 (skip-chars-backward (org-re "[:alnum:]_@"))
7599 (point)))
7600 (beg (save-excursion
7601 (skip-chars-backward "a-zA-Z0-9_:$")
7602 (point)))
7603 (confirm (lambda (x) (stringp (car x))))
7604 (searchhead (equal (char-before beg) ?*))
7605 (tag (and (equal (char-before beg1) ?:)
7606 (equal (char-after (point-at-bol)) ?*)))
7607 (prop (and (equal (char-before beg1) ?:)
7608 (not (equal (char-after (point-at-bol)) ?*))))
7609 (texp (equal (char-before beg) ?\\))
7610 (link (equal (char-before beg) ?\[))
7611 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7612 beg)
7613 "#+"))
7614 (startup (string-match "^#\\+STARTUP:.*"
7615 (buffer-substring (point-at-bol) (point))))
7616 (completion-ignore-case opt)
7617 (type nil)
7618 (tbl nil)
7619 (table (cond
7620 (opt
7621 (setq type :opt)
7622 (require 'org-exp)
7623 (append
7624 (mapcar
7625 (lambda (x)
7626 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7627 (cons (match-string 2 x) (match-string 1 x)))
7628 (org-split-string (org-get-current-options) "\n"))
7629 (mapcar 'list org-additional-option-like-keywords)))
7630 (startup
7631 (setq type :startup)
7632 org-startup-options)
7633 (link (append org-link-abbrev-alist-local
7634 org-link-abbrev-alist))
7635 (texp
7636 (setq type :tex)
7637 org-html-entities)
7638 ((string-match "\\`\\*+[ \t]+\\'"
7639 (buffer-substring (point-at-bol) beg))
7640 (setq type :todo)
7641 (mapcar 'list org-todo-keywords-1))
7642 (searchhead
7643 (setq type :searchhead)
7644 (save-excursion
7645 (goto-char (point-min))
7646 (while (re-search-forward org-todo-line-regexp nil t)
7647 (push (list
7648 (org-make-org-heading-search-string
7649 (match-string 3) t))
7650 tbl)))
7651 tbl)
7652 (tag (setq type :tag beg beg1)
7653 (or org-tag-alist (org-get-buffer-tags)))
7654 (prop (setq type :prop beg beg1)
7655 (mapcar 'list (org-buffer-property-keys nil t t)))
7656 (t (progn
7657 (call-interactively org-completion-fallback-command)
7658 (throw 'exit nil)))))
7659 (pattern (buffer-substring-no-properties beg end))
7660 (completion (try-completion pattern table confirm)))
7661 (cond ((eq completion t)
7662 (if (not (assoc (upcase pattern) table))
7663 (message "Already complete")
7664 (if (and (equal type :opt)
7665 (not (member (car (assoc (upcase pattern) table))
7666 org-additional-option-like-keywords)))
7667 (insert (substring (cdr (assoc (upcase pattern) table))
7668 (length pattern)))
7669 (if (memq type '(:tag :prop)) (insert ":")))))
7670 ((null completion)
7671 (message "Can't find completion for \"%s\"" pattern)
7672 (ding))
7673 ((not (string= pattern completion))
7674 (delete-region beg end)
7675 (if (string-match " +$" completion)
7676 (setq completion (replace-match "" t t completion)))
7677 (insert completion)
7678 (if (get-buffer-window "*Completions*")
7679 (delete-window (get-buffer-window "*Completions*")))
7680 (if (assoc completion table)
7681 (if (eq type :todo) (insert " ")
7682 (if (memq type '(:tag :prop)) (insert ":"))))
7683 (if (and (equal type :opt) (assoc completion table))
7684 (message "%s" (substitute-command-keys
7685 "Press \\[org-complete] again to insert example settings"))))
7687 (message "Making completion list...")
7688 (let ((list (sort (all-completions pattern table confirm)
7689 'string<)))
7690 (with-output-to-temp-buffer "*Completions*"
7691 (condition-case nil
7692 ;; Protection needed for XEmacs and emacs 21
7693 (display-completion-list list pattern)
7694 (error (display-completion-list list)))))
7695 (message "Making completion list...%s" "done")))))))
7697 ;;;; TODO, DEADLINE, Comments
7699 (defun org-toggle-comment ()
7700 "Change the COMMENT state of an entry."
7701 (interactive)
7702 (save-excursion
7703 (org-back-to-heading)
7704 (let (case-fold-search)
7705 (if (looking-at (concat outline-regexp
7706 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7707 (replace-match "" t t nil 1)
7708 (if (looking-at outline-regexp)
7709 (progn
7710 (goto-char (match-end 0))
7711 (insert org-comment-string " ")))))))
7713 (defvar org-last-todo-state-is-todo nil
7714 "This is non-nil when the last TODO state change led to a TODO state.
7715 If the last change removed the TODO tag or switched to DONE, then
7716 this is nil.")
7718 (defvar org-setting-tags nil) ; dynamically skiped
7720 (defun org-parse-local-options (string var)
7721 "Parse STRING for startup setting relevant for variable VAR."
7722 (let ((rtn (symbol-value var))
7723 e opts)
7724 (save-match-data
7725 (if (or (not string) (not (string-match "\\S-" string)))
7727 (setq opts (delq nil (mapcar (lambda (x)
7728 (setq e (assoc x org-startup-options))
7729 (if (eq (nth 1 e) var) e nil))
7730 (org-split-string string "[ \t]+"))))
7731 (if (not opts)
7733 (setq rtn nil)
7734 (while (setq e (pop opts))
7735 (if (not (nth 3 e))
7736 (setq rtn (nth 2 e))
7737 (if (not (listp rtn)) (setq rtn nil))
7738 (push (nth 2 e) rtn)))
7739 rtn)))))
7741 (defvar org-blocker-hook nil
7742 "Hook for functions that are allowed to block a state change.
7744 Each function gets as its single argument a property list, see
7745 `org-trigger-hook' for more information about this list.
7747 If any of the functions in this hook returns nil, the state change
7748 is blocked.")
7750 (defvar org-trigger-hook nil
7751 "Hook for functions that are triggered by a state change.
7753 Each function gets as its single argument a property list with at least
7754 the following elements:
7756 (:type type-of-change :position pos-at-entry-start
7757 :from old-state :to new-state)
7759 Depending on the type, more properties may be present.
7761 This mechanism is currently implemented for:
7763 TODO state changes
7764 ------------------
7765 :type todo-state-change
7766 :from previous state (keyword as a string), or nil
7767 :to new state (keyword as a string), or nil")
7770 (defun org-todo (&optional arg)
7771 "Change the TODO state of an item.
7772 The state of an item is given by a keyword at the start of the heading,
7773 like
7774 *** TODO Write paper
7775 *** DONE Call mom
7777 The different keywords are specified in the variable `org-todo-keywords'.
7778 By default the available states are \"TODO\" and \"DONE\".
7779 So for this example: when the item starts with TODO, it is changed to DONE.
7780 When it starts with DONE, the DONE is removed. And when neither TODO nor
7781 DONE are present, add TODO at the beginning of the heading.
7783 With C-u prefix arg, use completion to determine the new state.
7784 With numeric prefix arg, switch to that state.
7786 For calling through lisp, arg is also interpreted in the following way:
7787 'none -> empty state
7788 \"\"(empty string) -> switch to empty state
7789 'done -> switch to DONE
7790 'nextset -> switch to the next set of keywords
7791 'previousset -> switch to the previous set of keywords
7792 \"WAITING\" -> switch to the specified keyword, but only if it
7793 really is a member of `org-todo-keywords'."
7794 (interactive "P")
7795 (save-excursion
7796 (catch 'exit
7797 (org-back-to-heading)
7798 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7799 (or (looking-at (concat " +" org-todo-regexp " *"))
7800 (looking-at " *"))
7801 (let* ((match-data (match-data))
7802 (startpos (point-at-bol))
7803 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7804 (org-log-done org-log-done)
7805 (org-log-repeat org-log-repeat)
7806 (org-todo-log-states org-todo-log-states)
7807 (this (match-string 1))
7808 (hl-pos (match-beginning 0))
7809 (head (org-get-todo-sequence-head this))
7810 (ass (assoc head org-todo-kwd-alist))
7811 (interpret (nth 1 ass))
7812 (done-word (nth 3 ass))
7813 (final-done-word (nth 4 ass))
7814 (last-state (or this ""))
7815 (completion-ignore-case t)
7816 (member (member this org-todo-keywords-1))
7817 (tail (cdr member))
7818 (state (cond
7819 ((and org-todo-key-trigger
7820 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7821 (and (not arg) org-use-fast-todo-selection
7822 (not (eq org-use-fast-todo-selection 'prefix)))))
7823 ;; Use fast selection
7824 (org-fast-todo-selection))
7825 ((and (equal arg '(4))
7826 (or (not org-use-fast-todo-selection)
7827 (not org-todo-key-trigger)))
7828 ;; Read a state with completion
7829 (completing-read "State: " (mapcar (lambda(x) (list x))
7830 org-todo-keywords-1)
7831 nil t))
7832 ((eq arg 'right)
7833 (if this
7834 (if tail (car tail) nil)
7835 (car org-todo-keywords-1)))
7836 ((eq arg 'left)
7837 (if (equal member org-todo-keywords-1)
7839 (if this
7840 (nth (- (length org-todo-keywords-1) (length tail) 2)
7841 org-todo-keywords-1)
7842 (org-last org-todo-keywords-1))))
7843 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7844 (setq arg nil))) ; hack to fall back to cycling
7845 (arg
7846 ;; user or caller requests a specific state
7847 (cond
7848 ((equal arg "") nil)
7849 ((eq arg 'none) nil)
7850 ((eq arg 'done) (or done-word (car org-done-keywords)))
7851 ((eq arg 'nextset)
7852 (or (car (cdr (member head org-todo-heads)))
7853 (car org-todo-heads)))
7854 ((eq arg 'previousset)
7855 (let ((org-todo-heads (reverse org-todo-heads)))
7856 (or (car (cdr (member head org-todo-heads)))
7857 (car org-todo-heads))))
7858 ((car (member arg org-todo-keywords-1)))
7859 ((nth (1- (prefix-numeric-value arg))
7860 org-todo-keywords-1))))
7861 ((null member) (or head (car org-todo-keywords-1)))
7862 ((equal this final-done-word) nil) ;; -> make empty
7863 ((null tail) nil) ;; -> first entry
7864 ((eq interpret 'sequence)
7865 (car tail))
7866 ((memq interpret '(type priority))
7867 (if (eq this-command last-command)
7868 (car tail)
7869 (if (> (length tail) 0)
7870 (or done-word (car org-done-keywords))
7871 nil)))
7872 (t nil)))
7873 (next (if state (concat " " state " ") " "))
7874 (change-plist (list :type 'todo-state-change :from this :to state
7875 :position startpos))
7876 dolog now-done-p)
7877 (when org-blocker-hook
7878 (unless (save-excursion
7879 (save-match-data
7880 (run-hook-with-args-until-failure
7881 'org-blocker-hook change-plist)))
7882 (if (interactive-p)
7883 (error "TODO state change from %s to %s blocked" this state)
7884 ;; fail silently
7885 (message "TODO state change from %s to %s blocked" this state)
7886 (throw 'exit nil))))
7887 (store-match-data match-data)
7888 (replace-match next t t)
7889 (unless (pos-visible-in-window-p hl-pos)
7890 (message "TODO state changed to %s" (org-trim next)))
7891 (unless head
7892 (setq head (org-get-todo-sequence-head state)
7893 ass (assoc head org-todo-kwd-alist)
7894 interpret (nth 1 ass)
7895 done-word (nth 3 ass)
7896 final-done-word (nth 4 ass)))
7897 (when (memq arg '(nextset previousset))
7898 (message "Keyword-Set %d/%d: %s"
7899 (- (length org-todo-sets) -1
7900 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7901 (length org-todo-sets)
7902 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7903 (setq org-last-todo-state-is-todo
7904 (not (member state org-done-keywords)))
7905 (setq now-done-p (and (member state org-done-keywords)
7906 (not (member this org-done-keywords))))
7907 (and logging (org-local-logging logging))
7908 (when (and (or org-todo-log-states org-log-done)
7909 (not (memq arg '(nextset previousset))))
7910 ;; we need to look at recording a time and note
7911 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7912 (nth 2 (assoc this org-todo-log-states))))
7913 (when (and state
7914 (member state org-not-done-keywords)
7915 (not (member this org-not-done-keywords)))
7916 ;; This is now a todo state and was not one before
7917 ;; If there was a CLOSED time stamp, get rid of it.
7918 (org-add-planning-info nil nil 'closed))
7919 (when (and now-done-p org-log-done)
7920 ;; It is now done, and it was not done before
7921 (org-add-planning-info 'closed (org-current-time))
7922 (if (and (not dolog) (eq 'note org-log-done))
7923 (org-add-log-setup 'done state 'findpos 'note)))
7924 (when (and state dolog)
7925 ;; This is a non-nil state, and we need to log it
7926 (org-add-log-setup 'state state 'findpos dolog)))
7927 ;; Fixup tag positioning
7928 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7929 (run-hooks 'org-after-todo-state-change-hook)
7930 (if (and arg (not (member state org-done-keywords)))
7931 (setq head (org-get-todo-sequence-head state)))
7932 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7933 ;; Do we need to trigger a repeat?
7934 (when now-done-p (org-auto-repeat-maybe state))
7935 ;; Fixup cursor location if close to the keyword
7936 (if (and (outline-on-heading-p)
7937 (not (bolp))
7938 (save-excursion (beginning-of-line 1)
7939 (looking-at org-todo-line-regexp))
7940 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7941 (progn
7942 (goto-char (or (match-end 2) (match-end 1)))
7943 (just-one-space)))
7944 (when org-trigger-hook
7945 (save-excursion
7946 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7948 (defun org-local-logging (value)
7949 "Get logging settings from a property VALUE."
7950 (let* (words w a)
7951 ;; directly set the variables, they are already local.
7952 (setq org-log-done nil
7953 org-log-repeat nil
7954 org-todo-log-states nil)
7955 (setq words (org-split-string value))
7956 (while (setq w (pop words))
7957 (cond
7958 ((setq a (assoc w org-startup-options))
7959 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7960 (set (nth 1 a) (nth 2 a))))
7961 ((setq a (org-extract-log-state-settings w))
7962 (and (member (car a) org-todo-keywords-1)
7963 (push a org-todo-log-states)))))))
7965 (defun org-get-todo-sequence-head (kwd)
7966 "Return the head of the TODO sequence to which KWD belongs.
7967 If KWD is not set, check if there is a text property remembering the
7968 right sequence."
7969 (let (p)
7970 (cond
7971 ((not kwd)
7972 (or (get-text-property (point-at-bol) 'org-todo-head)
7973 (progn
7974 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7975 nil (point-at-eol)))
7976 (get-text-property p 'org-todo-head))))
7977 ((not (member kwd org-todo-keywords-1))
7978 (car org-todo-keywords-1))
7979 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7981 (defun org-fast-todo-selection ()
7982 "Fast TODO keyword selection with single keys.
7983 Returns the new TODO keyword, or nil if no state change should occur."
7984 (let* ((fulltable org-todo-key-alist)
7985 (done-keywords org-done-keywords) ;; needed for the faces.
7986 (maxlen (apply 'max (mapcar
7987 (lambda (x)
7988 (if (stringp (car x)) (string-width (car x)) 0))
7989 fulltable)))
7990 (expert nil)
7991 (fwidth (+ maxlen 3 1 3))
7992 (ncol (/ (- (window-width) 4) fwidth))
7993 tg cnt e c tbl
7994 groups ingroup)
7995 (save-window-excursion
7996 (if expert
7997 (set-buffer (get-buffer-create " *Org todo*"))
7998 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7999 (erase-buffer)
8000 (org-set-local 'org-done-keywords done-keywords)
8001 (setq tbl fulltable cnt 0)
8002 (while (setq e (pop tbl))
8003 (cond
8004 ((equal e '(:startgroup))
8005 (push '() groups) (setq ingroup t)
8006 (when (not (= cnt 0))
8007 (setq cnt 0)
8008 (insert "\n"))
8009 (insert "{ "))
8010 ((equal e '(:endgroup))
8011 (setq ingroup nil cnt 0)
8012 (insert "}\n"))
8014 (setq tg (car e) c (cdr e))
8015 (if ingroup (push tg (car groups)))
8016 (setq tg (org-add-props tg nil 'face
8017 (org-get-todo-face tg)))
8018 (if (and (= cnt 0) (not ingroup)) (insert " "))
8019 (insert "[" c "] " tg (make-string
8020 (- fwidth 4 (length tg)) ?\ ))
8021 (when (= (setq cnt (1+ cnt)) ncol)
8022 (insert "\n")
8023 (if ingroup (insert " "))
8024 (setq cnt 0)))))
8025 (insert "\n")
8026 (goto-char (point-min))
8027 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8028 (fit-window-to-buffer))
8029 (message "[a-z..]:Set [SPC]:clear")
8030 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8031 (cond
8032 ((or (= c ?\C-g)
8033 (and (= c ?q) (not (rassoc c fulltable))))
8034 (setq quit-flag t))
8035 ((= c ?\ ) nil)
8036 ((setq e (rassoc c fulltable) tg (car e))
8038 (t (setq quit-flag t))))))
8040 (defun org-entry-is-todo-p ()
8041 (member (org-get-todo-state) org-not-done-keywords))
8043 (defun org-entry-is-done-p ()
8044 (member (org-get-todo-state) org-done-keywords))
8046 (defun org-get-todo-state ()
8047 (save-excursion
8048 (org-back-to-heading t)
8049 (and (looking-at org-todo-line-regexp)
8050 (match-end 2)
8051 (match-string 2))))
8053 (defun org-at-date-range-p (&optional inactive-ok)
8054 "Is the cursor inside a date range?"
8055 (interactive)
8056 (save-excursion
8057 (catch 'exit
8058 (let ((pos (point)))
8059 (skip-chars-backward "^[<\r\n")
8060 (skip-chars-backward "<[")
8061 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8062 (>= (match-end 0) pos)
8063 (throw 'exit t))
8064 (skip-chars-backward "^<[\r\n")
8065 (skip-chars-backward "<[")
8066 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8067 (>= (match-end 0) pos)
8068 (throw 'exit t)))
8069 nil)))
8071 (defun org-get-repeat ()
8072 "Check if tere is a deadline/schedule with repeater in this entry."
8073 (save-match-data
8074 (save-excursion
8075 (org-back-to-heading t)
8076 (if (re-search-forward
8077 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8078 (match-string 1)))))
8080 (defvar org-last-changed-timestamp)
8081 (defvar org-log-post-message)
8082 (defvar org-log-note-purpose)
8083 (defvar org-log-note-how)
8084 (defun org-auto-repeat-maybe (done-word)
8085 "Check if the current headline contains a repeated deadline/schedule.
8086 If yes, set TODO state back to what it was and change the base date
8087 of repeating deadline/scheduled time stamps to new date.
8088 This function is run automatically after each state change to a DONE state."
8089 ;; last-state is dynamically scoped into this function
8090 (let* ((repeat (org-get-repeat))
8091 (aa (assoc last-state org-todo-kwd-alist))
8092 (interpret (nth 1 aa))
8093 (head (nth 2 aa))
8094 (whata '(("d" . day) ("m" . month) ("y" . year)))
8095 (msg "Entry repeats: ")
8096 (org-log-done nil)
8097 (org-todo-log-states nil)
8098 (nshiftmax 10) (nshift 0)
8099 re type n what ts mb0 time)
8100 (when repeat
8101 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8102 (org-todo (if (eq interpret 'type) last-state head))
8103 (when org-log-repeat
8104 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8105 (memq 'org-add-log-note post-command-hook))
8106 ;; OK, we are already setup for some record
8107 (if (eq org-log-repeat 'note)
8108 ;; make sure we take a note, not only a time stamp
8109 (setq org-log-note-how 'note))
8110 ;; Set up for taking a record
8111 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8112 'findpos org-log-repeat)))
8113 (org-back-to-heading t)
8114 (org-add-planning-info nil nil 'closed)
8115 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8116 org-deadline-time-regexp "\\)\\|\\("
8117 org-ts-regexp "\\)"))
8118 (while (re-search-forward
8119 re (save-excursion (outline-next-heading) (point)) t)
8120 (setq type (if (match-end 1) org-scheduled-string
8121 (if (match-end 3) org-deadline-string "Plain:"))
8122 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8123 mb0 (match-beginning 0))
8124 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8125 (setq n (string-to-number (match-string 2 ts))
8126 what (match-string 3 ts))
8127 (if (equal what "w") (setq n (* n 7) what "d"))
8128 ;; Preparation, see if we need to modify the start date for the change
8129 (when (match-end 1)
8130 (setq time (save-match-data (org-time-string-to-time ts)))
8131 (cond
8132 ((equal (match-string 1 ts) ".")
8133 ;; Shift starting date to today
8134 (org-timestamp-change
8135 (- (time-to-days (current-time)) (time-to-days time))
8136 'day))
8137 ((equal (match-string 1 ts) "+")
8138 (while (or (= nshift 0)
8139 (<= (time-to-days time) (time-to-days (current-time))))
8140 (when (= (incf nshift) nshiftmax)
8141 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8142 (error "Abort")))
8143 (org-timestamp-change n (cdr (assoc what whata)))
8144 (org-at-timestamp-p t)
8145 (setq ts (match-string 1))
8146 (setq time (save-match-data (org-time-string-to-time ts))))
8147 (org-timestamp-change (- n) (cdr (assoc what whata)))
8148 ;; rematch, so that we have everything in place for the real shift
8149 (org-at-timestamp-p t)
8150 (setq ts (match-string 1))
8151 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8152 (org-timestamp-change n (cdr (assoc what whata)))
8153 (setq msg (concat msg type org-last-changed-timestamp " "))))
8154 (setq org-log-post-message msg)
8155 (message "%s" msg))))
8157 (defun org-show-todo-tree (arg)
8158 "Make a compact tree which shows all headlines marked with TODO.
8159 The tree will show the lines where the regexp matches, and all higher
8160 headlines above the match.
8161 With a \\[universal-argument] prefix, also show the DONE entries.
8162 With a numeric prefix N, construct a sparse tree for the Nth element
8163 of `org-todo-keywords-1'."
8164 (interactive "P")
8165 (let ((case-fold-search nil)
8166 (kwd-re
8167 (cond ((null arg) org-not-done-regexp)
8168 ((equal arg '(4))
8169 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8170 (mapcar 'list org-todo-keywords-1))))
8171 (concat "\\("
8172 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8173 "\\)\\>")))
8174 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8175 (regexp-quote (nth (1- (prefix-numeric-value arg))
8176 org-todo-keywords-1)))
8177 (t (error "Invalid prefix argument: %s" arg)))))
8178 (message "%d TODO entries found"
8179 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8181 (defun org-deadline (&optional remove)
8182 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8183 With argument REMOVE, remove any deadline from the item."
8184 (interactive "P")
8185 (if remove
8186 (progn
8187 (org-remove-timestamp-with-keyword org-deadline-string)
8188 (message "Item no longer has a deadline."))
8189 (org-add-planning-info 'deadline nil 'closed)))
8191 (defun org-schedule (&optional remove)
8192 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8193 With argument REMOVE, remove any scheduling date from the item."
8194 (interactive "P")
8195 (if remove
8196 (progn
8197 (org-remove-timestamp-with-keyword org-scheduled-string)
8198 (message "Item is no longer scheduled."))
8199 (org-add-planning-info 'scheduled nil 'closed)))
8201 (defun org-remove-timestamp-with-keyword (keyword)
8202 "Remove all time stamps with KEYWORD in the current entry."
8203 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8204 beg)
8205 (save-excursion
8206 (org-back-to-heading t)
8207 (setq beg (point))
8208 (org-end-of-subtree t t)
8209 (while (re-search-backward re beg t)
8210 (replace-match "")
8211 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8212 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8214 (defun org-add-planning-info (what &optional time &rest remove)
8215 "Insert new timestamp with keyword in the line directly after the headline.
8216 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8217 If non is given, the user is prompted for a date.
8218 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8219 be removed."
8220 (interactive)
8221 (let (org-time-was-given org-end-time-was-given ts
8222 end default-time default-input)
8224 (when (and (not time) (memq what '(scheduled deadline)))
8225 ;; Try to get a default date/time from existing timestamp
8226 (save-excursion
8227 (org-back-to-heading t)
8228 (setq end (save-excursion (outline-next-heading) (point)))
8229 (when (re-search-forward (if (eq what 'scheduled)
8230 org-scheduled-time-regexp
8231 org-deadline-time-regexp)
8232 end t)
8233 (setq ts (match-string 1)
8234 default-time
8235 (apply 'encode-time (org-parse-time-string ts))
8236 default-input (and ts (org-get-compact-tod ts))))))
8237 (when what
8238 ;; If necessary, get the time from the user
8239 (setq time (or time (org-read-date nil 'to-time nil nil
8240 default-time default-input))))
8242 (when (and org-insert-labeled-timestamps-at-point
8243 (member what '(scheduled deadline)))
8244 (insert
8245 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8246 (org-insert-time-stamp time org-time-was-given
8247 nil nil nil (list org-end-time-was-given))
8248 (setq what nil))
8249 (save-excursion
8250 (save-restriction
8251 (let (col list elt ts buffer-invisibility-spec)
8252 (org-back-to-heading t)
8253 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8254 (goto-char (match-end 1))
8255 (setq col (current-column))
8256 (goto-char (match-end 0))
8257 (if (eobp) (insert "\n") (forward-char 1))
8258 (if (and (not (looking-at outline-regexp))
8259 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8260 "[^\r\n]*"))
8261 (not (equal (match-string 1) org-clock-string)))
8262 (narrow-to-region (match-beginning 0) (match-end 0))
8263 (insert-before-markers "\n")
8264 (backward-char 1)
8265 (narrow-to-region (point) (point))
8266 (org-indent-to-column col))
8267 ;; Check if we have to remove something.
8268 (setq list (cons what remove))
8269 (while list
8270 (setq elt (pop list))
8271 (goto-char (point-min))
8272 (when (or (and (eq elt 'scheduled)
8273 (re-search-forward org-scheduled-time-regexp nil t))
8274 (and (eq elt 'deadline)
8275 (re-search-forward org-deadline-time-regexp nil t))
8276 (and (eq elt 'closed)
8277 (re-search-forward org-closed-time-regexp nil t)))
8278 (replace-match "")
8279 (if (looking-at "--+<[^>]+>") (replace-match ""))
8280 (if (looking-at " +") (replace-match ""))))
8281 (goto-char (point-max))
8282 (when what
8283 (insert
8284 (if (not (equal (char-before) ?\ )) " " "")
8285 (cond ((eq what 'scheduled) org-scheduled-string)
8286 ((eq what 'deadline) org-deadline-string)
8287 ((eq what 'closed) org-closed-string))
8288 " ")
8289 (setq ts (org-insert-time-stamp
8290 time
8291 (or org-time-was-given
8292 (and (eq what 'closed) org-log-done-with-time))
8293 (eq what 'closed)
8294 nil nil (list org-end-time-was-given)))
8295 (end-of-line 1))
8296 (goto-char (point-min))
8297 (widen)
8298 (if (and (looking-at "[ \t]+\n")
8299 (equal (char-before) ?\n))
8300 (backward-delete-char 1))
8301 ts)))))
8303 (defvar org-log-note-marker (make-marker))
8304 (defvar org-log-note-purpose nil)
8305 (defvar org-log-note-state nil)
8306 (defvar org-log-note-how nil)
8307 (defvar org-log-note-window-configuration nil)
8308 (defvar org-log-note-return-to (make-marker))
8309 (defvar org-log-post-message nil
8310 "Message to be displayed after a log note has been stored.
8311 The auto-repeater uses this.")
8313 (defun org-add-note ()
8314 "Add a note to the current entry.
8315 This is done in the same way as adding a state change note."
8316 (interactive)
8317 (org-add-log-setup 'note nil t nil))
8319 (defun org-add-log-setup (&optional purpose state findpos how)
8320 "Set up the post command hook to take a note.
8321 If this is about to TODO state change, the new state is expected in STATE.
8322 When FINDPOS is non-nil, find the correct position for the note in
8323 the current entry. If not, assume that it can be inserted at point."
8324 (save-excursion
8325 (when findpos
8326 (org-back-to-heading t)
8327 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8328 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8329 "[^\r\n]*\\)?"))
8330 (goto-char (match-end 0))
8331 (unless org-log-states-order-reversed
8332 (and (= (char-after) ?\n) (forward-char 1))
8333 (org-skip-over-state-notes)
8334 (skip-chars-backward " \t\n\r")))
8335 (move-marker org-log-note-marker (point))
8336 (setq org-log-note-purpose purpose
8337 org-log-note-state state
8338 org-log-note-how how)
8339 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8341 (defun org-skip-over-state-notes ()
8342 "Skip past the list of State notes in an entry."
8343 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8344 (while (looking-at "[ \t]*- State")
8345 (condition-case nil
8346 (org-next-item)
8347 (error (org-end-of-item)))))
8349 (defun org-add-log-note (&optional purpose)
8350 "Pop up a window for taking a note, and add this note later at point."
8351 (remove-hook 'post-command-hook 'org-add-log-note)
8352 (setq org-log-note-window-configuration (current-window-configuration))
8353 (delete-other-windows)
8354 (move-marker org-log-note-return-to (point))
8355 (switch-to-buffer (marker-buffer org-log-note-marker))
8356 (goto-char org-log-note-marker)
8357 (org-switch-to-buffer-other-window "*Org Note*")
8358 (erase-buffer)
8359 (if (memq org-log-note-how '(time state))
8360 (org-store-log-note)
8361 (let ((org-inhibit-startup t)) (org-mode))
8362 (insert (format "# Insert note for %s.
8363 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8364 (cond
8365 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8366 ((eq org-log-note-purpose 'done) "closed todo item")
8367 ((eq org-log-note-purpose 'state)
8368 (format "state change to \"%s\"" org-log-note-state))
8369 ((eq org-log-note-purpose 'note)
8370 "this entry")
8371 (t (error "This should not happen")))))
8372 (org-set-local 'org-finish-function 'org-store-log-note)))
8374 (defvar org-note-abort nil) ; dynamically scoped
8375 (defun org-store-log-note ()
8376 "Finish taking a log note, and insert it to where it belongs."
8377 (let ((txt (buffer-string))
8378 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8379 lines ind)
8380 (kill-buffer (current-buffer))
8381 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8382 (setq txt (replace-match "" t t txt)))
8383 (if (string-match "\\s-+\\'" txt)
8384 (setq txt (replace-match "" t t txt)))
8385 (setq lines (org-split-string txt "\n"))
8386 (when (and note (string-match "\\S-" note))
8387 (setq note
8388 (org-replace-escapes
8389 note
8390 (list (cons "%u" (user-login-name))
8391 (cons "%U" user-full-name)
8392 (cons "%t" (format-time-string
8393 (org-time-stamp-format 'long 'inactive)
8394 (current-time)))
8395 (cons "%s" (if org-log-note-state
8396 (concat "\"" org-log-note-state "\"")
8397 "")))))
8398 (if lines (setq note (concat note " \\\\")))
8399 (push note lines))
8400 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8401 (when lines
8402 (save-excursion
8403 (set-buffer (marker-buffer org-log-note-marker))
8404 (save-excursion
8405 (goto-char org-log-note-marker)
8406 (move-marker org-log-note-marker nil)
8407 (end-of-line 1)
8408 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8409 (indent-relative nil)
8410 (insert "- " (pop lines))
8411 (org-indent-line-function)
8412 (beginning-of-line 1)
8413 (looking-at "[ \t]*")
8414 (setq ind (concat (match-string 0) " "))
8415 (end-of-line 1)
8416 (while lines (insert "\n" ind (pop lines)))))))
8417 (set-window-configuration org-log-note-window-configuration)
8418 (with-current-buffer (marker-buffer org-log-note-return-to)
8419 (goto-char org-log-note-return-to))
8420 (move-marker org-log-note-return-to nil)
8421 (and org-log-post-message (message "%s" org-log-post-message)))
8423 (defun org-sparse-tree (&optional arg)
8424 "Create a sparse tree, prompt for the details.
8425 This command can create sparse trees. You first need to select the type
8426 of match used to create the tree:
8428 t Show entries with a specific TODO keyword.
8429 T Show entries selected by a tags match.
8430 p Enter a property name and its value (both with completion on existing
8431 names/values) and show entries with that property.
8432 r Show entries matching a regular expression
8433 d Show deadlines due within `org-deadline-warning-days'."
8434 (interactive "P")
8435 (let (ans kwd value)
8436 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8437 (setq ans (read-char-exclusive))
8438 (cond
8439 ((equal ans ?d)
8440 (call-interactively 'org-check-deadlines))
8441 ((equal ans ?b)
8442 (call-interactively 'org-check-before-date))
8443 ((equal ans ?t)
8444 (org-show-todo-tree '(4)))
8445 ((equal ans ?T)
8446 (call-interactively 'org-tags-sparse-tree))
8447 ((member ans '(?p ?P))
8448 (setq kwd (completing-read "Property: "
8449 (mapcar 'list (org-buffer-property-keys))))
8450 (setq value (completing-read "Value: "
8451 (mapcar 'list (org-property-values kwd))))
8452 (unless (string-match "\\`{.*}\\'" value)
8453 (setq value (concat "\"" value "\"")))
8454 (org-tags-sparse-tree arg (concat kwd "=" value)))
8455 ((member ans '(?r ?R ?/))
8456 (call-interactively 'org-occur))
8457 (t (error "No such sparse tree command \"%c\"" ans)))))
8459 (defvar org-occur-highlights nil
8460 "List of overlays used for occur matches.")
8461 (make-variable-buffer-local 'org-occur-highlights)
8462 (defvar org-occur-parameters nil
8463 "Parameters of the active org-occur calls.
8464 This is a list, each call to org-occur pushes as cons cell,
8465 containing the regular expression and the callback, onto the list.
8466 The list can contain several entries if `org-occur' has been called
8467 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8468 will only contain one set of parameters. When the highlights are
8469 removed (for example with `C-c C-c', or with the next edit (depending
8470 on `org-remove-highlights-with-change'), this variable is emptied
8471 as well.")
8472 (make-variable-buffer-local 'org-occur-parameters)
8474 (defun org-occur (regexp &optional keep-previous callback)
8475 "Make a compact tree which shows all matches of REGEXP.
8476 The tree will show the lines where the regexp matches, and all higher
8477 headlines above the match. It will also show the heading after the match,
8478 to make sure editing the matching entry is easy.
8479 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8480 call to `org-occur' will be kept, to allow stacking of calls to this
8481 command.
8482 If CALLBACK is non-nil, it is a function which is called to confirm
8483 that the match should indeed be shown."
8484 (interactive "sRegexp: \nP")
8485 (unless keep-previous
8486 (org-remove-occur-highlights nil nil t))
8487 (push (cons regexp callback) org-occur-parameters)
8488 (let ((cnt 0))
8489 (save-excursion
8490 (goto-char (point-min))
8491 (if (or (not keep-previous) ; do not want to keep
8492 (not org-occur-highlights)) ; no previous matches
8493 ;; hide everything
8494 (org-overview))
8495 (while (re-search-forward regexp nil t)
8496 (when (or (not callback)
8497 (save-match-data (funcall callback)))
8498 (setq cnt (1+ cnt))
8499 (when org-highlight-sparse-tree-matches
8500 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8501 (org-show-context 'occur-tree))))
8502 (when org-remove-highlights-with-change
8503 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8504 nil 'local))
8505 (unless org-sparse-tree-open-archived-trees
8506 (org-hide-archived-subtrees (point-min) (point-max)))
8507 (run-hooks 'org-occur-hook)
8508 (if (interactive-p)
8509 (message "%d match(es) for regexp %s" cnt regexp))
8510 cnt))
8512 (defun org-show-context (&optional key)
8513 "Make sure point and context and visible.
8514 How much context is shown depends upon the variables
8515 `org-show-hierarchy-above', `org-show-following-heading'. and
8516 `org-show-siblings'."
8517 (let ((heading-p (org-on-heading-p t))
8518 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8519 (following-p (org-get-alist-option org-show-following-heading key))
8520 (entry-p (org-get-alist-option org-show-entry-below key))
8521 (siblings-p (org-get-alist-option org-show-siblings key)))
8522 (catch 'exit
8523 ;; Show heading or entry text
8524 (if (and heading-p (not entry-p))
8525 (org-flag-heading nil) ; only show the heading
8526 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8527 (org-show-hidden-entry))) ; show entire entry
8528 (when following-p
8529 ;; Show next sibling, or heading below text
8530 (save-excursion
8531 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8532 (org-flag-heading nil))))
8533 (when siblings-p (org-show-siblings))
8534 (when hierarchy-p
8535 ;; show all higher headings, possibly with siblings
8536 (save-excursion
8537 (while (and (condition-case nil
8538 (progn (org-up-heading-all 1) t)
8539 (error nil))
8540 (not (bobp)))
8541 (org-flag-heading nil)
8542 (when siblings-p (org-show-siblings))))))))
8544 (defun org-reveal (&optional siblings)
8545 "Show current entry, hierarchy above it, and the following headline.
8546 This can be used to show a consistent set of context around locations
8547 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8548 not t for the search context.
8550 With optional argument SIBLINGS, on each level of the hierarchy all
8551 siblings are shown. This repairs the tree structure to what it would
8552 look like when opened with hierarchical calls to `org-cycle'."
8553 (interactive "P")
8554 (let ((org-show-hierarchy-above t)
8555 (org-show-following-heading t)
8556 (org-show-siblings (if siblings t org-show-siblings)))
8557 (org-show-context nil)))
8559 (defun org-highlight-new-match (beg end)
8560 "Highlight from BEG to END and mark the highlight is an occur headline."
8561 (let ((ov (org-make-overlay beg end)))
8562 (org-overlay-put ov 'face 'secondary-selection)
8563 (push ov org-occur-highlights)))
8565 (defun org-remove-occur-highlights (&optional beg end noremove)
8566 "Remove the occur highlights from the buffer.
8567 BEG and END are ignored. If NOREMOVE is nil, remove this function
8568 from the `before-change-functions' in the current buffer."
8569 (interactive)
8570 (unless org-inhibit-highlight-removal
8571 (mapc 'org-delete-overlay org-occur-highlights)
8572 (setq org-occur-highlights nil)
8573 (setq org-occur-parameters nil)
8574 (unless noremove
8575 (remove-hook 'before-change-functions
8576 'org-remove-occur-highlights 'local))))
8578 ;;;; Priorities
8580 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8581 "Regular expression matching the priority indicator.")
8583 (defvar org-remove-priority-next-time nil)
8585 (defun org-priority-up ()
8586 "Increase the priority of the current item."
8587 (interactive)
8588 (org-priority 'up))
8590 (defun org-priority-down ()
8591 "Decrease the priority of the current item."
8592 (interactive)
8593 (org-priority 'down))
8595 (defun org-priority (&optional action)
8596 "Change the priority of an item by ARG.
8597 ACTION can be `set', `up', `down', or a character."
8598 (interactive)
8599 (setq action (or action 'set))
8600 (let (current new news have remove)
8601 (save-excursion
8602 (org-back-to-heading)
8603 (if (looking-at org-priority-regexp)
8604 (setq current (string-to-char (match-string 2))
8605 have t)
8606 (setq current org-default-priority))
8607 (cond
8608 ((or (eq action 'set)
8609 (if (featurep 'xemacs) (characterp action) (integerp action)))
8610 (if (not (eq action 'set))
8611 (setq new action)
8612 (message "Priority %c-%c, SPC to remove: "
8613 org-highest-priority org-lowest-priority)
8614 (setq new (read-char-exclusive)))
8615 (if (and (= (upcase org-highest-priority) org-highest-priority)
8616 (= (upcase org-lowest-priority) org-lowest-priority))
8617 (setq new (upcase new)))
8618 (cond ((equal new ?\ ) (setq remove t))
8619 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8620 (error "Priority must be between `%c' and `%c'"
8621 org-highest-priority org-lowest-priority))))
8622 ((eq action 'up)
8623 (if (and (not have) (eq last-command this-command))
8624 (setq new org-lowest-priority)
8625 (setq new (if (and org-priority-start-cycle-with-default (not have))
8626 org-default-priority (1- current)))))
8627 ((eq action 'down)
8628 (if (and (not have) (eq last-command this-command))
8629 (setq new org-highest-priority)
8630 (setq new (if (and org-priority-start-cycle-with-default (not have))
8631 org-default-priority (1+ current)))))
8632 (t (error "Invalid action")))
8633 (if (or (< (upcase new) org-highest-priority)
8634 (> (upcase new) org-lowest-priority))
8635 (setq remove t))
8636 (setq news (format "%c" new))
8637 (if have
8638 (if remove
8639 (replace-match "" t t nil 1)
8640 (replace-match news t t nil 2))
8641 (if remove
8642 (error "No priority cookie found in line")
8643 (looking-at org-todo-line-regexp)
8644 (if (match-end 2)
8645 (progn
8646 (goto-char (match-end 2))
8647 (insert " [#" news "]"))
8648 (goto-char (match-beginning 3))
8649 (insert "[#" news "] ")))))
8650 (org-preserve-lc (org-set-tags nil 'align))
8651 (if remove
8652 (message "Priority removed")
8653 (message "Priority of current item set to %s" news))))
8656 (defun org-get-priority (s)
8657 "Find priority cookie and return priority."
8658 (save-match-data
8659 (if (not (string-match org-priority-regexp s))
8660 (* 1000 (- org-lowest-priority org-default-priority))
8661 (* 1000 (- org-lowest-priority
8662 (string-to-char (match-string 2 s)))))))
8664 ;;;; Tags
8666 (defun org-scan-tags (action matcher &optional todo-only)
8667 "Scan headline tags with inheritance and produce output ACTION.
8668 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8669 evaluated, testing if a given set of tags qualifies a headline for
8670 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8671 are included in the output."
8672 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8673 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8674 (org-re
8675 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8676 (props (list 'face nil
8677 'done-face 'org-done
8678 'undone-face nil
8679 'mouse-face 'highlight
8680 'org-not-done-regexp org-not-done-regexp
8681 'org-todo-regexp org-todo-regexp
8682 'keymap org-agenda-keymap
8683 'help-echo
8684 (format "mouse-2 or RET jump to org file %s"
8685 (abbreviate-file-name
8686 (or (buffer-file-name (buffer-base-buffer))
8687 (buffer-name (buffer-base-buffer)))))))
8688 (case-fold-search nil)
8689 lspos
8690 tags tags-list tags-alist (llast 0) rtn level category i txt
8691 todo marker entry priority)
8692 (save-excursion
8693 (goto-char (point-min))
8694 (when (eq action 'sparse-tree)
8695 (org-overview)
8696 (org-remove-occur-highlights))
8697 (while (re-search-forward re nil t)
8698 (catch :skip
8699 (setq todo (if (match-end 1) (match-string 2))
8700 tags (if (match-end 4) (match-string 4)))
8701 (goto-char (setq lspos (1+ (match-beginning 0))))
8702 (setq level (org-reduced-level (funcall outline-level))
8703 category (org-get-category))
8704 (setq i llast llast level)
8705 ;; remove tag lists from same and sublevels
8706 (while (>= i level)
8707 (when (setq entry (assoc i tags-alist))
8708 (setq tags-alist (delete entry tags-alist)))
8709 (setq i (1- i)))
8710 ;; add the next tags
8711 (when tags
8712 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8713 tags-alist
8714 (cons (cons level tags) tags-alist)))
8715 ;; compile tags for current headline
8716 (setq tags-list
8717 (if org-use-tag-inheritance
8718 (apply 'append (mapcar 'cdr tags-alist))
8719 tags))
8720 (when (and tags org-use-tag-inheritance
8721 (not (eq t org-use-tag-inheritance)))
8722 ;; selective inheritance, remove uninherited ones
8723 (setcdr (car tags-alist)
8724 (org-remove-uniherited-tags (cdar tags-alist))))
8725 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8726 (eval matcher)
8727 (or (not org-agenda-skip-archived-trees)
8728 (not (member org-archive-tag tags-list))))
8729 (and (eq action 'agenda) (org-agenda-skip))
8730 ;; list this headline
8732 (if (eq action 'sparse-tree)
8733 (progn
8734 (and org-highlight-sparse-tree-matches
8735 (org-get-heading) (match-end 0)
8736 (org-highlight-new-match
8737 (match-beginning 0) (match-beginning 1)))
8738 (org-show-context 'tags-tree))
8739 (setq txt (org-format-agenda-item
8741 (concat
8742 (if org-tags-match-list-sublevels
8743 (make-string (1- level) ?.) "")
8744 (org-get-heading))
8745 category tags-list)
8746 priority (org-get-priority txt))
8747 (goto-char lspos)
8748 (setq marker (org-agenda-new-marker))
8749 (org-add-props txt props
8750 'org-marker marker 'org-hd-marker marker 'org-category category
8751 'priority priority 'type "tagsmatch")
8752 (push txt rtn))
8753 ;; if we are to skip sublevels, jump to end of subtree
8754 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8755 (when (and (eq action 'sparse-tree)
8756 (not org-sparse-tree-open-archived-trees))
8757 (org-hide-archived-subtrees (point-min) (point-max)))
8758 (nreverse rtn)))
8760 (defun org-remove-uniherited-tags (tags)
8761 "Remove all tags that are not inherited from the list TAGS."
8762 (cond
8763 ((eq org-use-tag-inheritance t) tags)
8764 ((not org-use-tag-inheritance) nil)
8765 ((stringp org-use-tag-inheritance)
8766 (delq nil (mapcar
8767 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8768 tags)))
8769 ((listp org-use-tag-inheritance)
8770 (org-delete-all org-use-tag-inheritance tags))))
8772 (defvar todo-only) ;; dynamically scoped
8774 (defun org-tags-sparse-tree (&optional todo-only match)
8775 "Create a sparse tree according to tags string MATCH.
8776 MATCH can contain positive and negative selection of tags, like
8777 \"+WORK+URGENT-WITHBOSS\".
8778 If optional argument TODO_ONLY is non-nil, only select lines that are
8779 also TODO lines."
8780 (interactive "P")
8781 (org-prepare-agenda-buffers (list (current-buffer)))
8782 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8784 (defvar org-cached-props nil)
8785 (defun org-cached-entry-get (pom property)
8786 (if (or (eq t org-use-property-inheritance)
8787 (and (stringp org-use-property-inheritance)
8788 (string-match org-use-property-inheritance property))
8789 (and (listp org-use-property-inheritance)
8790 (member property org-use-property-inheritance)))
8791 ;; Caching is not possible, check it directly
8792 (org-entry-get pom property 'inherit)
8793 ;; Get all properties, so that we can do complicated checks easily
8794 (cdr (assoc property (or org-cached-props
8795 (setq org-cached-props
8796 (org-entry-properties pom)))))))
8798 (defun org-global-tags-completion-table (&optional files)
8799 "Return the list of all tags in all agenda buffer/files."
8800 (save-excursion
8801 (org-uniquify
8802 (delq nil
8803 (apply 'append
8804 (mapcar
8805 (lambda (file)
8806 (set-buffer (find-file-noselect file))
8807 (append (org-get-buffer-tags)
8808 (mapcar (lambda (x) (if (stringp (car-safe x))
8809 (list (car-safe x)) nil))
8810 org-tag-alist)))
8811 (if (and files (car files))
8812 files
8813 (org-agenda-files))))))))
8815 (defun org-make-tags-matcher (match)
8816 "Create the TAGS//TODO matcher form for the selection string MATCH."
8817 ;; todo-only is scoped dynamically into this function, and the function
8818 ;; may change it it the matcher asksk for it.
8819 (unless match
8820 ;; Get a new match request, with completion
8821 (let ((org-last-tags-completion-table
8822 (org-global-tags-completion-table)))
8823 (setq match (completing-read
8824 "Match: " 'org-tags-completion-function nil nil nil
8825 'org-tags-history))))
8827 ;; Parse the string and create a lisp form
8828 (let ((match0 match)
8829 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8830 minus tag mm
8831 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8832 orterms term orlist re-p str-p level-p level-op
8833 prop-p pn pv po cat-p gv)
8834 (if (string-match "/+" match)
8835 ;; match contains also a todo-matching request
8836 (progn
8837 (setq tagsmatch (substring match 0 (match-beginning 0))
8838 todomatch (substring match (match-end 0)))
8839 (if (string-match "^!" todomatch)
8840 (setq todo-only t todomatch (substring todomatch 1)))
8841 (if (string-match "^\\s-*$" todomatch)
8842 (setq todomatch nil)))
8843 ;; only matching tags
8844 (setq tagsmatch match todomatch nil))
8846 ;; Make the tags matcher
8847 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8848 (setq tagsmatcher t)
8849 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8850 (while (setq term (pop orterms))
8851 (while (and (equal (substring term -1) "\\") orterms)
8852 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8853 (while (string-match re term)
8854 (setq minus (and (match-end 1)
8855 (equal (match-string 1 term) "-"))
8856 tag (match-string 2 term)
8857 re-p (equal (string-to-char tag) ?{)
8858 level-p (match-end 4)
8859 prop-p (match-end 5)
8860 mm (cond
8861 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8862 (level-p
8863 (setq level-op (org-op-to-function (match-string 3 term)))
8864 `(,level-op level ,(string-to-number
8865 (match-string 4 term))))
8866 (prop-p
8867 (setq pn (match-string 5 term)
8868 po (match-string 6 term)
8869 pv (match-string 7 term)
8870 cat-p (equal pn "CATEGORY")
8871 re-p (equal (string-to-char pv) ?{)
8872 str-p (equal (string-to-char pv) ?\")
8873 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8874 (setq po (org-op-to-function po str-p))
8875 (if (equal pn "CATEGORY")
8876 (setq gv '(get-text-property (point) 'org-category))
8877 (setq gv `(org-cached-entry-get nil ,pn)))
8878 (if re-p
8879 (if (eq po 'org<>)
8880 `(not (string-match ,pv (or ,gv "")))
8881 `(string-match ,pv (or ,gv "")))
8882 (if str-p
8883 `(,po (or ,gv "") ,pv)
8884 `(,po (string-to-number (or ,gv ""))
8885 ,(string-to-number pv) ))))
8886 (t `(member ,(downcase tag) tags-list)))
8887 mm (if minus (list 'not mm) mm)
8888 term (substring term (match-end 0)))
8889 (push mm tagsmatcher))
8890 (push (if (> (length tagsmatcher) 1)
8891 (cons 'and tagsmatcher)
8892 (car tagsmatcher))
8893 orlist)
8894 (setq tagsmatcher nil))
8895 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8896 (setq tagsmatcher
8897 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8898 ;; Make the todo matcher
8899 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8900 (setq todomatcher t)
8901 (setq orterms (org-split-string todomatch "|") orlist nil)
8902 (while (setq term (pop orterms))
8903 (while (string-match re term)
8904 (setq minus (and (match-end 1)
8905 (equal (match-string 1 term) "-"))
8906 kwd (match-string 2 term)
8907 re-p (equal (string-to-char kwd) ?{)
8908 term (substring term (match-end 0))
8909 mm (if re-p
8910 `(string-match ,(substring kwd 1 -1) todo)
8911 (list 'equal 'todo kwd))
8912 mm (if minus (list 'not mm) mm))
8913 (push mm todomatcher))
8914 (push (if (> (length todomatcher) 1)
8915 (cons 'and todomatcher)
8916 (car todomatcher))
8917 orlist)
8918 (setq todomatcher nil))
8919 (setq todomatcher (if (> (length orlist) 1)
8920 (cons 'or orlist) (car orlist))))
8922 ;; Return the string and lisp forms of the matcher
8923 (setq matcher (if todomatcher
8924 (list 'and tagsmatcher todomatcher)
8925 tagsmatcher))
8926 (cons match0 matcher)))
8928 (defun org-op-to-function (op &optional stringp)
8929 (setq op
8930 (cond
8931 ((equal op "<" ) '(< string< ))
8932 ((equal op ">" ) '(> org-string> ))
8933 ((member op '("<=" "=<")) '(<= org-string<= ))
8934 ((member op '(">=" "=>")) '(>= org-string>= ))
8935 ((member op '("=" "==")) '(= string= ))
8936 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8937 (nth (if stringp 1 0) op))
8939 (defun org<> (a b) (not (= a b)))
8940 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8941 (defun org-string>= (a b) (not (string< a b)))
8942 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8943 (defun org-string<> (a b) (not (string= a b)))
8945 (defun org-match-any-p (re list)
8946 "Does re match any element of list?"
8947 (setq list (mapcar (lambda (x) (string-match re x)) list))
8948 (delq nil list))
8950 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8951 (defvar org-tags-overlay (org-make-overlay 1 1))
8952 (org-detach-overlay org-tags-overlay)
8954 (defun org-get-tags-at (&optional pos)
8955 "Get a list of all headline tags applicable at POS.
8956 POS defaults to point. If tags are inherited, the list contains
8957 the targets in the same sequence as the headlines appear, i.e.
8958 sthe tags of the current headline come last."
8959 (interactive)
8960 (let (tags ltags lastpos parent)
8961 (save-excursion
8962 (save-restriction
8963 (widen)
8964 (goto-char (or pos (point)))
8965 (save-match-data
8966 (condition-case nil
8967 (progn
8968 (org-back-to-heading t)
8969 (while (not (equal lastpos (point)))
8970 (setq lastpos (point))
8971 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8972 (setq ltags (org-split-string
8973 (org-match-string-no-properties 1) ":"))
8974 (setq tags (append (org-remove-uniherited-tags ltags)
8975 tags)))
8976 (or org-use-tag-inheritance (error ""))
8977 (org-up-heading-all 1)
8978 (setq parent t)))
8979 (error nil))))
8980 tags)))
8982 (defun org-toggle-tag (tag &optional onoff)
8983 "Toggle the tag TAG for the current line.
8984 If ONOFF is `on' or `off', don't toggle but set to this state."
8985 (unless (org-on-heading-p t) (error "Not on headling"))
8986 (let (res current)
8987 (save-excursion
8988 (beginning-of-line)
8989 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8990 (point-at-eol) t)
8991 (progn
8992 (setq current (match-string 1))
8993 (replace-match ""))
8994 (setq current ""))
8995 (setq current (nreverse (org-split-string current ":")))
8996 (cond
8997 ((eq onoff 'on)
8998 (setq res t)
8999 (or (member tag current) (push tag current)))
9000 ((eq onoff 'off)
9001 (or (not (member tag current)) (setq current (delete tag current))))
9002 (t (if (member tag current)
9003 (setq current (delete tag current))
9004 (setq res t)
9005 (push tag current))))
9006 (end-of-line 1)
9007 (if current
9008 (progn
9009 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9010 (org-set-tags nil t))
9011 (delete-horizontal-space))
9012 (run-hooks 'org-after-tags-change-hook))
9013 res))
9015 (defun org-align-tags-here (to-col)
9016 ;; Assumes that this is a headline
9017 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9018 (beginning-of-line 1)
9019 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9020 (< pos (match-beginning 2)))
9021 (progn
9022 (setq tags-l (- (match-end 2) (match-beginning 2)))
9023 (goto-char (match-beginning 1))
9024 (insert " ")
9025 (delete-region (point) (1+ (match-beginning 2)))
9026 (setq ncol (max (1+ (current-column))
9027 (1+ col)
9028 (if (> to-col 0)
9029 to-col
9030 (- (abs to-col) tags-l))))
9031 (setq p (point))
9032 (insert (make-string (- ncol (current-column)) ?\ ))
9033 (setq ncol (current-column))
9034 (tabify p (point-at-eol))
9035 (org-move-to-column (min ncol col) t))
9036 (goto-char pos))))
9038 (defun org-set-tags (&optional arg just-align)
9039 "Set the tags for the current headline.
9040 With prefix ARG, realign all tags in headings in the current buffer."
9041 (interactive "P")
9042 (let* ((re (concat "^" outline-regexp))
9043 (current (org-get-tags-string))
9044 (col (current-column))
9045 (org-setting-tags t)
9046 table current-tags inherited-tags ; computed below when needed
9047 tags p0 c0 c1 rpl)
9048 (if arg
9049 (save-excursion
9050 (goto-char (point-min))
9051 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9052 (while (re-search-forward re nil t)
9053 (org-set-tags nil t)
9054 (end-of-line 1)))
9055 (message "All tags realigned to column %d" org-tags-column))
9056 (if just-align
9057 (setq tags current)
9058 ;; Get a new set of tags from the user
9059 (save-excursion
9060 (setq table (or org-tag-alist (org-get-buffer-tags))
9061 org-last-tags-completion-table table
9062 current-tags (org-split-string current ":")
9063 inherited-tags (nreverse
9064 (nthcdr (length current-tags)
9065 (nreverse (org-get-tags-at))))
9066 tags
9067 (if (or (eq t org-use-fast-tag-selection)
9068 (and org-use-fast-tag-selection
9069 (delq nil (mapcar 'cdr table))))
9070 (org-fast-tag-selection
9071 current-tags inherited-tags table
9072 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9073 (let ((org-add-colon-after-tag-completion t))
9074 (org-trim
9075 (org-without-partial-completion
9076 (completing-read "Tags: " 'org-tags-completion-function
9077 nil nil current 'org-tags-history)))))))
9078 (while (string-match "[-+&]+" tags)
9079 ;; No boolean logic, just a list
9080 (setq tags (replace-match ":" t t tags))))
9082 (if (string-match "\\`[\t ]*\\'" tags)
9083 (setq tags "")
9084 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9085 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9087 ;; Insert new tags at the correct column
9088 (beginning-of-line 1)
9089 (cond
9090 ((and (equal current "") (equal tags "")))
9091 ((re-search-forward
9092 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9093 (point-at-eol) t)
9094 (if (equal tags "")
9095 (setq rpl "")
9096 (goto-char (match-beginning 0))
9097 (setq c0 (current-column) p0 (point)
9098 c1 (max (1+ c0) (if (> org-tags-column 0)
9099 org-tags-column
9100 (- (- org-tags-column) (length tags))))
9101 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9102 (replace-match rpl t t)
9103 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9104 tags)
9105 (t (error "Tags alignment failed")))
9106 (org-move-to-column col)
9107 (unless just-align
9108 (run-hooks 'org-after-tags-change-hook)))))
9110 (defun org-change-tag-in-region (beg end tag off)
9111 "Add or remove TAG for each entry in the region.
9112 This works in the agenda, and also in an org-mode buffer."
9113 (interactive
9114 (list (region-beginning) (region-end)
9115 (let ((org-last-tags-completion-table
9116 (if (org-mode-p)
9117 (org-get-buffer-tags)
9118 (org-global-tags-completion-table))))
9119 (completing-read
9120 "Tag: " 'org-tags-completion-function nil nil nil
9121 'org-tags-history))
9122 (progn
9123 (message "[s]et or [r]emove? ")
9124 (equal (read-char-exclusive) ?r))))
9125 (if (fboundp 'deactivate-mark) (deactivate-mark))
9126 (let ((agendap (equal major-mode 'org-agenda-mode))
9127 l1 l2 m buf pos newhead (cnt 0))
9128 (goto-char end)
9129 (setq l2 (1- (org-current-line)))
9130 (goto-char beg)
9131 (setq l1 (org-current-line))
9132 (loop for l from l1 to l2 do
9133 (goto-line l)
9134 (setq m (get-text-property (point) 'org-hd-marker))
9135 (when (or (and (org-mode-p) (org-on-heading-p))
9136 (and agendap m))
9137 (setq buf (if agendap (marker-buffer m) (current-buffer))
9138 pos (if agendap m (point)))
9139 (with-current-buffer buf
9140 (save-excursion
9141 (save-restriction
9142 (goto-char pos)
9143 (setq cnt (1+ cnt))
9144 (org-toggle-tag tag (if off 'off 'on))
9145 (setq newhead (org-get-heading)))))
9146 (and agendap (org-agenda-change-all-lines newhead m))))
9147 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9149 (defun org-tags-completion-function (string predicate &optional flag)
9150 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9151 (confirm (lambda (x) (stringp (car x)))))
9152 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9153 (setq s1 (match-string 1 string)
9154 s2 (match-string 2 string))
9155 (setq s1 "" s2 string))
9156 (cond
9157 ((eq flag nil)
9158 ;; try completion
9159 (setq rtn (try-completion s2 ctable confirm))
9160 (if (stringp rtn)
9161 (setq rtn
9162 (concat s1 s2 (substring rtn (length s2))
9163 (if (and org-add-colon-after-tag-completion
9164 (assoc rtn ctable))
9165 ":" ""))))
9166 rtn)
9167 ((eq flag t)
9168 ;; all-completions
9169 (all-completions s2 ctable confirm)
9171 ((eq flag 'lambda)
9172 ;; exact match?
9173 (assoc s2 ctable)))
9176 (defun org-fast-tag-insert (kwd tags face &optional end)
9177 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9178 (insert (format "%-12s" (concat kwd ":"))
9179 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9180 (or end "")))
9182 (defun org-fast-tag-show-exit (flag)
9183 (save-excursion
9184 (goto-line 3)
9185 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9186 (replace-match ""))
9187 (when flag
9188 (end-of-line 1)
9189 (org-move-to-column (- (window-width) 19) t)
9190 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9192 (defun org-set-current-tags-overlay (current prefix)
9193 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9194 (if (featurep 'xemacs)
9195 (org-overlay-display org-tags-overlay (concat prefix s)
9196 'secondary-selection)
9197 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9198 (org-overlay-display org-tags-overlay (concat prefix s)))))
9200 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9201 "Fast tag selection with single keys.
9202 CURRENT is the current list of tags in the headline, INHERITED is the
9203 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9204 possibly with grouping information. TODO-TABLE is a similar table with
9205 TODO keywords, should these have keys assigned to them.
9206 If the keys are nil, a-z are automatically assigned.
9207 Returns the new tags string, or nil to not change the current settings."
9208 (let* ((fulltable (append table todo-table))
9209 (maxlen (apply 'max (mapcar
9210 (lambda (x)
9211 (if (stringp (car x)) (string-width (car x)) 0))
9212 fulltable)))
9213 (buf (current-buffer))
9214 (expert (eq org-fast-tag-selection-single-key 'expert))
9215 (buffer-tags nil)
9216 (fwidth (+ maxlen 3 1 3))
9217 (ncol (/ (- (window-width) 4) fwidth))
9218 (i-face 'org-done)
9219 (c-face 'org-todo)
9220 tg cnt e c char c1 c2 ntable tbl rtn
9221 ov-start ov-end ov-prefix
9222 (exit-after-next org-fast-tag-selection-single-key)
9223 (done-keywords org-done-keywords)
9224 groups ingroup)
9225 (save-excursion
9226 (beginning-of-line 1)
9227 (if (looking-at
9228 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9229 (setq ov-start (match-beginning 1)
9230 ov-end (match-end 1)
9231 ov-prefix "")
9232 (setq ov-start (1- (point-at-eol))
9233 ov-end (1+ ov-start))
9234 (skip-chars-forward "^\n\r")
9235 (setq ov-prefix
9236 (concat
9237 (buffer-substring (1- (point)) (point))
9238 (if (> (current-column) org-tags-column)
9240 (make-string (- org-tags-column (current-column)) ?\ ))))))
9241 (org-move-overlay org-tags-overlay ov-start ov-end)
9242 (save-window-excursion
9243 (if expert
9244 (set-buffer (get-buffer-create " *Org tags*"))
9245 (delete-other-windows)
9246 (split-window-vertically)
9247 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9248 (erase-buffer)
9249 (org-set-local 'org-done-keywords done-keywords)
9250 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9251 (org-fast-tag-insert "Current" current c-face "\n\n")
9252 (org-fast-tag-show-exit exit-after-next)
9253 (org-set-current-tags-overlay current ov-prefix)
9254 (setq tbl fulltable char ?a cnt 0)
9255 (while (setq e (pop tbl))
9256 (cond
9257 ((equal e '(:startgroup))
9258 (push '() groups) (setq ingroup t)
9259 (when (not (= cnt 0))
9260 (setq cnt 0)
9261 (insert "\n"))
9262 (insert "{ "))
9263 ((equal e '(:endgroup))
9264 (setq ingroup nil cnt 0)
9265 (insert "}\n"))
9267 (setq tg (car e) c2 nil)
9268 (if (cdr e)
9269 (setq c (cdr e))
9270 ;; automatically assign a character.
9271 (setq c1 (string-to-char
9272 (downcase (substring
9273 tg (if (= (string-to-char tg) ?@) 1 0)))))
9274 (if (or (rassoc c1 ntable) (rassoc c1 table))
9275 (while (or (rassoc char ntable) (rassoc char table))
9276 (setq char (1+ char)))
9277 (setq c2 c1))
9278 (setq c (or c2 char)))
9279 (if ingroup (push tg (car groups)))
9280 (setq tg (org-add-props tg nil 'face
9281 (cond
9282 ((not (assoc tg table))
9283 (org-get-todo-face tg))
9284 ((member tg current) c-face)
9285 ((member tg inherited) i-face)
9286 (t nil))))
9287 (if (and (= cnt 0) (not ingroup)) (insert " "))
9288 (insert "[" c "] " tg (make-string
9289 (- fwidth 4 (length tg)) ?\ ))
9290 (push (cons tg c) ntable)
9291 (when (= (setq cnt (1+ cnt)) ncol)
9292 (insert "\n")
9293 (if ingroup (insert " "))
9294 (setq cnt 0)))))
9295 (setq ntable (nreverse ntable))
9296 (insert "\n")
9297 (goto-char (point-min))
9298 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9299 (fit-window-to-buffer))
9300 (setq rtn
9301 (catch 'exit
9302 (while t
9303 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9304 (if groups " [!] no groups" " [!]groups")
9305 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9306 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9307 (cond
9308 ((= c ?\r) (throw 'exit t))
9309 ((= c ?!)
9310 (setq groups (not groups))
9311 (goto-char (point-min))
9312 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9313 ((= c ?\C-c)
9314 (if (not expert)
9315 (org-fast-tag-show-exit
9316 (setq exit-after-next (not exit-after-next)))
9317 (setq expert nil)
9318 (delete-other-windows)
9319 (split-window-vertically)
9320 (org-switch-to-buffer-other-window " *Org tags*")
9321 (and (fboundp 'fit-window-to-buffer)
9322 (fit-window-to-buffer))))
9323 ((or (= c ?\C-g)
9324 (and (= c ?q) (not (rassoc c ntable))))
9325 (org-detach-overlay org-tags-overlay)
9326 (setq quit-flag t))
9327 ((= c ?\ )
9328 (setq current nil)
9329 (if exit-after-next (setq exit-after-next 'now)))
9330 ((= c ?\t)
9331 (condition-case nil
9332 (setq tg (completing-read
9333 "Tag: "
9334 (or buffer-tags
9335 (with-current-buffer buf
9336 (org-get-buffer-tags)))))
9337 (quit (setq tg "")))
9338 (when (string-match "\\S-" tg)
9339 (add-to-list 'buffer-tags (list tg))
9340 (if (member tg current)
9341 (setq current (delete tg current))
9342 (push tg current)))
9343 (if exit-after-next (setq exit-after-next 'now)))
9344 ((setq e (rassoc c todo-table) tg (car e))
9345 (with-current-buffer buf
9346 (save-excursion (org-todo tg)))
9347 (if exit-after-next (setq exit-after-next 'now)))
9348 ((setq e (rassoc c ntable) tg (car e))
9349 (if (member tg current)
9350 (setq current (delete tg current))
9351 (loop for g in groups do
9352 (if (member tg g)
9353 (mapc (lambda (x)
9354 (setq current (delete x current)))
9355 g)))
9356 (push tg current))
9357 (if exit-after-next (setq exit-after-next 'now))))
9359 ;; Create a sorted list
9360 (setq current
9361 (sort current
9362 (lambda (a b)
9363 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9364 (if (eq exit-after-next 'now) (throw 'exit t))
9365 (goto-char (point-min))
9366 (beginning-of-line 2)
9367 (delete-region (point) (point-at-eol))
9368 (org-fast-tag-insert "Current" current c-face)
9369 (org-set-current-tags-overlay current ov-prefix)
9370 (while (re-search-forward
9371 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9372 (setq tg (match-string 1))
9373 (add-text-properties
9374 (match-beginning 1) (match-end 1)
9375 (list 'face
9376 (cond
9377 ((member tg current) c-face)
9378 ((member tg inherited) i-face)
9379 (t (get-text-property (match-beginning 1) 'face))))))
9380 (goto-char (point-min)))))
9381 (org-detach-overlay org-tags-overlay)
9382 (if rtn
9383 (mapconcat 'identity current ":")
9384 nil))))
9386 (defun org-get-tags-string ()
9387 "Get the TAGS string in the current headline."
9388 (unless (org-on-heading-p t)
9389 (error "Not on a heading"))
9390 (save-excursion
9391 (beginning-of-line 1)
9392 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9393 (org-match-string-no-properties 1)
9394 "")))
9396 (defun org-get-tags ()
9397 "Get the list of tags specified in the current headline."
9398 (org-split-string (org-get-tags-string) ":"))
9400 (defun org-get-buffer-tags ()
9401 "Get a table of all tags used in the buffer, for completion."
9402 (let (tags)
9403 (save-excursion
9404 (goto-char (point-min))
9405 (while (re-search-forward
9406 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9407 (when (equal (char-after (point-at-bol 0)) ?*)
9408 (mapc (lambda (x) (add-to-list 'tags x))
9409 (org-split-string (org-match-string-no-properties 1) ":")))))
9410 (mapcar 'list tags)))
9413 ;;;; Properties
9415 ;;; Setting and retrieving properties
9417 (defconst org-special-properties
9418 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9419 "TIMESTAMP" "TIMESTAMP_IA")
9420 "The special properties valid in Org-mode.
9422 These are properties that are not defined in the property drawer,
9423 but in some other way.")
9425 (defconst org-default-properties
9426 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9427 "LOCATION" "LOGGING" "COLUMNS")
9428 "Some properties that are used by Org-mode for various purposes.
9429 Being in this list makes sure that they are offered for completion.")
9431 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9432 "Regular expression matching the first line of a property drawer.")
9434 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9435 "Regular expression matching the first line of a property drawer.")
9437 (defun org-property-action ()
9438 "Do an action on properties."
9439 (interactive)
9440 (let (c)
9441 (org-at-property-p)
9442 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9443 (setq c (read-char-exclusive))
9444 (cond
9445 ((equal c ?s)
9446 (call-interactively 'org-set-property))
9447 ((equal c ?d)
9448 (call-interactively 'org-delete-property))
9449 ((equal c ?D)
9450 (call-interactively 'org-delete-property-globally))
9451 ((equal c ?c)
9452 (call-interactively 'org-compute-property-at-point))
9453 (t (error "No such property action %c" c)))))
9455 (defun org-at-property-p ()
9456 "Is the cursor in a property line?"
9457 ;; FIXME: Does not check if we are actually in the drawer.
9458 ;; FIXME: also returns true on any drawers.....
9459 ;; This is used by C-c C-c for property action.
9460 (save-excursion
9461 (beginning-of-line 1)
9462 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9464 (defun org-get-property-block (&optional beg end force)
9465 "Return the (beg . end) range of the body of the property drawer.
9466 BEG and END can be beginning and end of subtree, if not given
9467 they will be found.
9468 If the drawer does not exist and FORCE is non-nil, create the drawer."
9469 (catch 'exit
9470 (save-excursion
9471 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9472 (end (or end (progn (outline-next-heading) (point)))))
9473 (goto-char beg)
9474 (if (re-search-forward org-property-start-re end t)
9475 (setq beg (1+ (match-end 0)))
9476 (if force
9477 (save-excursion
9478 (org-insert-property-drawer)
9479 (setq end (progn (outline-next-heading) (point))))
9480 (throw 'exit nil))
9481 (goto-char beg)
9482 (if (re-search-forward org-property-start-re end t)
9483 (setq beg (1+ (match-end 0)))))
9484 (if (re-search-forward org-property-end-re end t)
9485 (setq end (match-beginning 0))
9486 (or force (throw 'exit nil))
9487 (goto-char beg)
9488 (setq end beg)
9489 (org-indent-line-function)
9490 (insert ":END:\n"))
9491 (cons beg end)))))
9493 (defun org-entry-properties (&optional pom which)
9494 "Get all properties of the entry at point-or-marker POM.
9495 This includes the TODO keyword, the tags, time strings for deadline,
9496 scheduled, and clocking, and any additional properties defined in the
9497 entry. The return value is an alist, keys may occur multiple times
9498 if the property key was used several times.
9499 POM may also be nil, in which case the current entry is used.
9500 If WHICH is nil or `all', get all properties. If WHICH is
9501 `special' or `standard', only get that subclass."
9502 (setq which (or which 'all))
9503 (org-with-point-at pom
9504 (let ((clockstr (substring org-clock-string 0 -1))
9505 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9506 beg end range props sum-props key value string clocksum)
9507 (save-excursion
9508 (when (condition-case nil (org-back-to-heading t) (error nil))
9509 (setq beg (point))
9510 (setq sum-props (get-text-property (point) 'org-summaries))
9511 (setq clocksum (get-text-property (point) :org-clock-minutes))
9512 (outline-next-heading)
9513 (setq end (point))
9514 (when (memq which '(all special))
9515 ;; Get the special properties, like TODO and tags
9516 (goto-char beg)
9517 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9518 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9519 (when (looking-at org-priority-regexp)
9520 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9521 (when (and (setq value (org-get-tags-string))
9522 (string-match "\\S-" value))
9523 (push (cons "TAGS" value) props))
9524 (when (setq value (org-get-tags-at))
9525 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9526 props))
9527 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9528 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9529 string (if (equal key clockstr)
9530 (org-no-properties
9531 (org-trim
9532 (buffer-substring
9533 (match-beginning 3) (goto-char (point-at-eol)))))
9534 (substring (org-match-string-no-properties 3) 1 -1)))
9535 (unless key
9536 (if (= (char-after (match-beginning 3)) ?\[)
9537 (setq key "TIMESTAMP_IA")
9538 (setq key "TIMESTAMP")))
9539 (when (or (equal key clockstr) (not (assoc key props)))
9540 (push (cons key string) props)))
9544 (when (memq which '(all standard))
9545 ;; Get the standard properties, like :PORP: ...
9546 (setq range (org-get-property-block beg end))
9547 (when range
9548 (goto-char (car range))
9549 (while (re-search-forward
9550 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9551 (cdr range) t)
9552 (setq key (org-match-string-no-properties 1)
9553 value (org-trim (or (org-match-string-no-properties 2) "")))
9554 (unless (member key excluded)
9555 (push (cons key (or value "")) props)))))
9556 (if clocksum
9557 (push (cons "CLOCKSUM"
9558 (org-columns-number-to-string (/ (float clocksum) 60.)
9559 'add_times))
9560 props))
9561 (append sum-props (nreverse props)))))))
9563 (defun org-entry-get (pom property &optional inherit)
9564 "Get value of PROPERTY for entry at point-or-marker POM.
9565 If INHERIT is non-nil and the entry does not have the property,
9566 then also check higher levels of the hierarchy.
9567 If INHERIT is the symbol `selective', use inheritance only if the setting
9568 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9569 If the property is present but empty, the return value is the empty string.
9570 If the property is not present at all, nil is returned."
9571 (org-with-point-at pom
9572 (if (and inherit (if (eq inherit 'selective)
9573 (org-property-inherit-p property)
9575 (org-entry-get-with-inheritance property)
9576 (if (member property org-special-properties)
9577 ;; We need a special property. Use brute force, get all properties.
9578 (cdr (assoc property (org-entry-properties nil 'special)))
9579 (let ((range (org-get-property-block)))
9580 (if (and range
9581 (goto-char (car range))
9582 (re-search-forward
9583 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9584 (cdr range) t))
9585 ;; Found the property, return it.
9586 (if (match-end 1)
9587 (org-match-string-no-properties 1)
9588 "")))))))
9590 (defun org-property-or-variable-value (var &optional inherit)
9591 "Check if there is a property fixing the value of VAR.
9592 If yes, return this value. If not, return the current value of the variable."
9593 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9594 (if (and prop (stringp prop) (string-match "\\S-" prop))
9595 (read prop)
9596 (symbol-value var))))
9598 (defun org-entry-delete (pom property)
9599 "Delete the property PROPERTY from entry at point-or-marker POM."
9600 (org-with-point-at pom
9601 (if (member property org-special-properties)
9602 nil ; cannot delete these properties.
9603 (let ((range (org-get-property-block)))
9604 (if (and range
9605 (goto-char (car range))
9606 (re-search-forward
9607 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9608 (cdr range) t))
9609 (progn
9610 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9612 nil)))))
9614 ;; Multi-values properties are properties that contain multiple values
9615 ;; These values are assumed to be single words, separated by whitespace.
9616 (defun org-entry-add-to-multivalued-property (pom property value)
9617 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9618 (let* ((old (org-entry-get pom property))
9619 (values (and old (org-split-string old "[ \t]"))))
9620 (unless (member value values)
9621 (setq values (cons value values))
9622 (org-entry-put pom property
9623 (mapconcat 'identity values " ")))))
9625 (defun org-entry-remove-from-multivalued-property (pom property value)
9626 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9627 (let* ((old (org-entry-get pom property))
9628 (values (and old (org-split-string old "[ \t]"))))
9629 (when (member value values)
9630 (setq values (delete value values))
9631 (org-entry-put pom property
9632 (mapconcat 'identity values " ")))))
9634 (defun org-entry-member-in-multivalued-property (pom property value)
9635 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9636 (let* ((old (org-entry-get pom property))
9637 (values (and old (org-split-string old "[ \t]"))))
9638 (member value values)))
9640 (defvar org-entry-property-inherited-from (make-marker))
9642 (defun org-entry-get-with-inheritance (property)
9643 "Get entry property, and search higher levels if not present."
9644 (let (tmp)
9645 (save-excursion
9646 (save-restriction
9647 (widen)
9648 (catch 'ex
9649 (while t
9650 (when (setq tmp (org-entry-get nil property))
9651 (org-back-to-heading t)
9652 (move-marker org-entry-property-inherited-from (point))
9653 (throw 'ex tmp))
9654 (or (org-up-heading-safe) (throw 'ex nil)))))
9655 (or tmp (cdr (assoc property org-local-properties))
9656 (cdr (assoc property org-global-properties))))))
9658 (defun org-entry-put (pom property value)
9659 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9660 (org-with-point-at pom
9661 (org-back-to-heading t)
9662 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9663 range)
9664 (cond
9665 ((equal property "TODO")
9666 (when (and (stringp value) (string-match "\\S-" value)
9667 (not (member value org-todo-keywords-1)))
9668 (error "\"%s\" is not a valid TODO state" value))
9669 (if (or (not value)
9670 (not (string-match "\\S-" value)))
9671 (setq value 'none))
9672 (org-todo value)
9673 (org-set-tags nil 'align))
9674 ((equal property "PRIORITY")
9675 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9676 (string-to-char value) ?\ ))
9677 (org-set-tags nil 'align))
9678 ((equal property "SCHEDULED")
9679 (if (re-search-forward org-scheduled-time-regexp end t)
9680 (cond
9681 ((eq value 'earlier) (org-timestamp-change -1 'day))
9682 ((eq value 'later) (org-timestamp-change 1 'day))
9683 (t (call-interactively 'org-schedule)))
9684 (call-interactively 'org-schedule)))
9685 ((equal property "DEADLINE")
9686 (if (re-search-forward org-deadline-time-regexp end t)
9687 (cond
9688 ((eq value 'earlier) (org-timestamp-change -1 'day))
9689 ((eq value 'later) (org-timestamp-change 1 'day))
9690 (t (call-interactively 'org-deadline)))
9691 (call-interactively 'org-deadline)))
9692 ((member property org-special-properties)
9693 (error "The %s property can not yet be set with `org-entry-put'"
9694 property))
9695 (t ; a non-special property
9696 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9697 (setq range (org-get-property-block beg end 'force))
9698 (goto-char (car range))
9699 (if (re-search-forward
9700 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9701 (progn
9702 (delete-region (match-beginning 1) (match-end 1))
9703 (goto-char (match-beginning 1)))
9704 (goto-char (cdr range))
9705 (insert "\n")
9706 (backward-char 1)
9707 (org-indent-line-function)
9708 (insert ":" property ":"))
9709 (and value (insert " " value))
9710 (org-indent-line-function)))))))
9712 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9713 "Get all property keys in the current buffer.
9714 With INCLUDE-SPECIALS, also list the special properties that relect things
9715 like tags and TODO state.
9716 With INCLUDE-DEFAULTS, also include properties that has special meaning
9717 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9718 With INCLUDE-COLUMNS, also include property names given in COLUMN
9719 formats in the current buffer."
9720 (let (rtn range cfmt cols s p)
9721 (save-excursion
9722 (save-restriction
9723 (widen)
9724 (goto-char (point-min))
9725 (while (re-search-forward org-property-start-re nil t)
9726 (setq range (org-get-property-block))
9727 (goto-char (car range))
9728 (while (re-search-forward
9729 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9730 (cdr range) t)
9731 (add-to-list 'rtn (org-match-string-no-properties 1)))
9732 (outline-next-heading))))
9734 (when include-specials
9735 (setq rtn (append org-special-properties rtn)))
9737 (when include-defaults
9738 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9740 (when include-columns
9741 (save-excursion
9742 (save-restriction
9743 (widen)
9744 (goto-char (point-min))
9745 (while (re-search-forward
9746 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9747 nil t)
9748 (setq cfmt (match-string 2) s 0)
9749 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9750 cfmt s)
9751 (setq s (match-end 0)
9752 p (match-string 1 cfmt))
9753 (unless (or (equal p "ITEM")
9754 (member p org-special-properties))
9755 (add-to-list 'rtn (match-string 1 cfmt))))))))
9757 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9759 (defun org-property-values (key)
9760 "Return a list of all values of property KEY."
9761 (save-excursion
9762 (save-restriction
9763 (widen)
9764 (goto-char (point-min))
9765 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9766 values)
9767 (while (re-search-forward re nil t)
9768 (add-to-list 'values (org-trim (match-string 1))))
9769 (delete "" values)))))
9771 (defun org-insert-property-drawer ()
9772 "Insert a property drawer into the current entry."
9773 (interactive)
9774 (org-back-to-heading t)
9775 (looking-at outline-regexp)
9776 (let ((indent (- (match-end 0)(match-beginning 0)))
9777 (beg (point))
9778 (re (concat "^[ \t]*" org-keyword-time-regexp))
9779 end hiddenp)
9780 (outline-next-heading)
9781 (setq end (point))
9782 (goto-char beg)
9783 (while (re-search-forward re end t))
9784 (setq hiddenp (org-invisible-p))
9785 (end-of-line 1)
9786 (and (equal (char-after) ?\n) (forward-char 1))
9787 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9788 (beginning-of-line 2))
9789 (org-skip-over-state-notes)
9790 (skip-chars-backward " \t\n\r")
9791 (if (eq (char-before) ?*) (forward-char 1))
9792 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9793 (beginning-of-line 0)
9794 (org-indent-to-column indent)
9795 (beginning-of-line 2)
9796 (org-indent-to-column indent)
9797 (beginning-of-line 0)
9798 (if hiddenp
9799 (save-excursion
9800 (org-back-to-heading t)
9801 (hide-entry))
9802 (org-flag-drawer t))))
9804 (defun org-set-property (property value)
9805 "In the current entry, set PROPERTY to VALUE.
9806 When called interactively, this will prompt for a property name, offering
9807 completion on existing and default properties. And then it will prompt
9808 for a value, offering competion either on allowed values (via an inherited
9809 xxx_ALL property) or on existing values in other instances of this property
9810 in the current file."
9811 (interactive
9812 (let* ((prop (completing-read
9813 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9814 (cur (org-entry-get nil prop))
9815 (allowed (org-property-get-allowed-values nil prop 'table))
9816 (existing (mapcar 'list (org-property-values prop)))
9817 (val (if allowed
9818 (completing-read "Value: " allowed nil 'req-match)
9819 (completing-read
9820 (concat "Value" (if (and cur (string-match "\\S-" cur))
9821 (concat "[" cur "]") "")
9822 ": ")
9823 existing nil nil "" nil cur))))
9824 (list prop (if (equal val "") cur val))))
9825 (unless (equal (org-entry-get nil property) value)
9826 (org-entry-put nil property value)))
9828 (defun org-delete-property (property)
9829 "In the current entry, delete PROPERTY."
9830 (interactive
9831 (let* ((prop (completing-read
9832 "Property: " (org-entry-properties nil 'standard))))
9833 (list prop)))
9834 (message "Property %s %s" property
9835 (if (org-entry-delete nil property)
9836 "deleted"
9837 "was not present in the entry")))
9839 (defun org-delete-property-globally (property)
9840 "Remove PROPERTY globally, from all entries."
9841 (interactive
9842 (let* ((prop (completing-read
9843 "Globally remove property: "
9844 (mapcar 'list (org-buffer-property-keys)))))
9845 (list prop)))
9846 (save-excursion
9847 (save-restriction
9848 (widen)
9849 (goto-char (point-min))
9850 (let ((cnt 0))
9851 (while (re-search-forward
9852 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9853 nil t)
9854 (setq cnt (1+ cnt))
9855 (replace-match ""))
9856 (message "Property \"%s\" removed from %d entries" property cnt)))))
9858 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9860 (defun org-compute-property-at-point ()
9861 "Compute the property at point.
9862 This looks for an enclosing column format, extracts the operator and
9863 then applies it to the proerty in the column format's scope."
9864 (interactive)
9865 (unless (org-at-property-p)
9866 (error "Not at a property"))
9867 (let ((prop (org-match-string-no-properties 2)))
9868 (org-columns-get-format-and-top-level)
9869 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9870 (error "No operator defined for property %s" prop))
9871 (org-columns-compute prop)))
9873 (defun org-property-get-allowed-values (pom property &optional table)
9874 "Get allowed values for the property PROPERTY.
9875 When TABLE is non-nil, return an alist that can directly be used for
9876 completion."
9877 (let (vals)
9878 (cond
9879 ((equal property "TODO")
9880 (setq vals (org-with-point-at pom
9881 (append org-todo-keywords-1 '("")))))
9882 ((equal property "PRIORITY")
9883 (let ((n org-lowest-priority))
9884 (while (>= n org-highest-priority)
9885 (push (char-to-string n) vals)
9886 (setq n (1- n)))))
9887 ((member property org-special-properties))
9889 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9891 (when (and vals (string-match "\\S-" vals))
9892 (setq vals (car (read-from-string (concat "(" vals ")"))))
9893 (setq vals (mapcar (lambda (x)
9894 (cond ((stringp x) x)
9895 ((numberp x) (number-to-string x))
9896 ((symbolp x) (symbol-name x))
9897 (t "???")))
9898 vals)))))
9899 (if table (mapcar 'list vals) vals)))
9901 (defun org-property-previous-allowed-value (&optional previous)
9902 "Switch to the next allowed value for this property."
9903 (interactive)
9904 (org-property-next-allowed-value t))
9906 (defun org-property-next-allowed-value (&optional previous)
9907 "Switch to the next allowed value for this property."
9908 (interactive)
9909 (unless (org-at-property-p)
9910 (error "Not at a property"))
9911 (let* ((key (match-string 2))
9912 (value (match-string 3))
9913 (allowed (or (org-property-get-allowed-values (point) key)
9914 (and (member value '("[ ]" "[-]" "[X]"))
9915 '("[ ]" "[X]"))))
9916 nval)
9917 (unless allowed
9918 (error "Allowed values for this property have not been defined"))
9919 (if previous (setq allowed (reverse allowed)))
9920 (if (member value allowed)
9921 (setq nval (car (cdr (member value allowed)))))
9922 (setq nval (or nval (car allowed)))
9923 (if (equal nval value)
9924 (error "Only one allowed value for this property"))
9925 (org-at-property-p)
9926 (replace-match (concat " :" key ": " nval) t t)
9927 (org-indent-line-function)
9928 (beginning-of-line 1)
9929 (skip-chars-forward " \t")))
9931 (defun org-find-entry-with-id (ident)
9932 "Locate the entry that contains the ID property with exact value IDENT.
9933 IDENT can be a string, a symbol or a number, this function will search for
9934 the string representation of it.
9935 Return the position where this entry starts, or nil if there is no such entry."
9936 (let ((id (cond
9937 ((stringp ident) ident)
9938 ((symbol-name ident) (symbol-name ident))
9939 ((numberp ident) (number-to-string ident))
9940 (t (error "IDENT %s must be a string, symbol or number" ident))))
9941 (case-fold-search nil))
9942 (save-excursion
9943 (save-restriction
9944 (widen)
9945 (goto-char (point-min))
9946 (when (re-search-forward
9947 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9948 nil t)
9949 (org-back-to-heading)
9950 (point))))))
9952 ;;;; Timestamps
9954 (defvar org-last-changed-timestamp nil)
9955 (defvar org-time-was-given) ; dynamically scoped parameter
9956 (defvar org-end-time-was-given) ; dynamically scoped parameter
9957 (defvar org-ts-what) ; dynamically scoped parameter
9959 (defun org-time-stamp (arg)
9960 "Prompt for a date/time and insert a time stamp.
9961 If the user specifies a time like HH:MM, or if this command is called
9962 with a prefix argument, the time stamp will contain date and time.
9963 Otherwise, only the date will be included. All parts of a date not
9964 specified by the user will be filled in from the current date/time.
9965 So if you press just return without typing anything, the time stamp
9966 will represent the current date/time. If there is already a timestamp
9967 at the cursor, it will be modified."
9968 (interactive "P")
9969 (let* ((ts nil)
9970 (default-time
9971 ;; Default time is either today, or, when entering a range,
9972 ;; the range start.
9973 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9974 (save-excursion
9975 (re-search-backward
9976 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9977 (- (point) 20) t)))
9978 (apply 'encode-time (org-parse-time-string (match-string 1)))
9979 (current-time)))
9980 (default-input (and ts (org-get-compact-tod ts)))
9981 org-time-was-given org-end-time-was-given time)
9982 (cond
9983 ((and (org-at-timestamp-p)
9984 (eq last-command 'org-time-stamp)
9985 (eq this-command 'org-time-stamp))
9986 (insert "--")
9987 (setq time (let ((this-command this-command))
9988 (org-read-date arg 'totime nil nil default-time default-input)))
9989 (org-insert-time-stamp time (or org-time-was-given arg)))
9990 ((org-at-timestamp-p)
9991 (setq time (let ((this-command this-command))
9992 (org-read-date arg 'totime nil nil default-time default-input)))
9993 (when (org-at-timestamp-p) ; just to get the match data
9994 (replace-match "")
9995 (setq org-last-changed-timestamp
9996 (org-insert-time-stamp
9997 time (or org-time-was-given arg)
9998 nil nil nil (list org-end-time-was-given))))
9999 (message "Timestamp updated"))
10001 (setq time (let ((this-command this-command))
10002 (org-read-date arg 'totime nil nil default-time default-input)))
10003 (org-insert-time-stamp time (or org-time-was-given arg)
10004 nil nil nil (list org-end-time-was-given))))))
10006 ;; FIXME: can we use this for something else, like computing time differences?
10007 (defun org-get-compact-tod (s)
10008 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10009 (let* ((t1 (match-string 1 s))
10010 (h1 (string-to-number (match-string 2 s)))
10011 (m1 (string-to-number (match-string 3 s)))
10012 (t2 (and (match-end 4) (match-string 5 s)))
10013 (h2 (and t2 (string-to-number (match-string 6 s))))
10014 (m2 (and t2 (string-to-number (match-string 7 s))))
10015 dh dm)
10016 (if (not t2)
10018 (setq dh (- h2 h1) dm (- m2 m1))
10019 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10020 (concat t1 "+" (number-to-string dh)
10021 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10023 (defun org-time-stamp-inactive (&optional arg)
10024 "Insert an inactive time stamp.
10025 An inactive time stamp is enclosed in square brackets instead of angle
10026 brackets. It is inactive in the sense that it does not trigger agenda entries,
10027 does not link to the calendar and cannot be changed with the S-cursor keys.
10028 So these are more for recording a certain time/date."
10029 (interactive "P")
10030 (let (org-time-was-given org-end-time-was-given time)
10031 (setq time (org-read-date arg 'totime))
10032 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10033 nil nil (list org-end-time-was-given))))
10035 (defvar org-date-ovl (org-make-overlay 1 1))
10036 (org-overlay-put org-date-ovl 'face 'org-warning)
10037 (org-detach-overlay org-date-ovl)
10039 (defvar org-ans1) ; dynamically scoped parameter
10040 (defvar org-ans2) ; dynamically scoped parameter
10042 (defvar org-plain-time-of-day-regexp) ; defined below
10044 (defvar org-read-date-overlay nil)
10045 (defvar org-dcst nil) ; dynamically scoped
10047 (defun org-read-date (&optional with-time to-time from-string prompt
10048 default-time default-input)
10049 "Read a date, possibly a time, and make things smooth for the user.
10050 The prompt will suggest to enter an ISO date, but you can also enter anything
10051 which will at least partially be understood by `parse-time-string'.
10052 Unrecognized parts of the date will default to the current day, month, year,
10053 hour and minute. If this command is called to replace a timestamp at point,
10054 of to enter the second timestamp of a range, the default time is taken from the
10055 existing stamp. For example,
10056 3-2-5 --> 2003-02-05
10057 feb 15 --> currentyear-02-15
10058 sep 12 9 --> 2009-09-12
10059 12:45 --> today 12:45
10060 22 sept 0:34 --> currentyear-09-22 0:34
10061 12 --> currentyear-currentmonth-12
10062 Fri --> nearest Friday (today or later)
10063 etc.
10065 Furthermore you can specify a relative date by giving, as the *first* thing
10066 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10067 change in days weeks, months, years.
10068 With a single plus or minus, the date is relative to today. With a double
10069 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10070 +4d --> four days from today
10071 +4 --> same as above
10072 +2w --> two weeks from today
10073 ++5 --> five days from default date
10075 The function understands only English month and weekday abbreviations,
10076 but this can be configured with the variables `parse-time-months' and
10077 `parse-time-weekdays'.
10079 While prompting, a calendar is popped up - you can also select the
10080 date with the mouse (button 1). The calendar shows a period of three
10081 months. To scroll it to other months, use the keys `>' and `<'.
10082 If you don't like the calendar, turn it off with
10083 \(setq org-read-date-popup-calendar nil)
10085 With optional argument TO-TIME, the date will immediately be converted
10086 to an internal time.
10087 With an optional argument WITH-TIME, the prompt will suggest to also
10088 insert a time. Note that when WITH-TIME is not set, you can still
10089 enter a time, and this function will inform the calling routine about
10090 this change. The calling routine may then choose to change the format
10091 used to insert the time stamp into the buffer to include the time.
10092 With optional argument FROM-STRING, read from this string instead from
10093 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10094 the time/date that is used for everything that is not specified by the
10095 user."
10096 (require 'parse-time)
10097 (let* ((org-time-stamp-rounding-minutes
10098 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10099 (org-dcst org-display-custom-times)
10100 (ct (org-current-time))
10101 (def (or default-time ct))
10102 (defdecode (decode-time def))
10103 (dummy (progn
10104 (when (< (nth 2 defdecode) org-extend-today-until)
10105 (setcar (nthcdr 2 defdecode) -1)
10106 (setcar (nthcdr 1 defdecode) 59)
10107 (setq def (apply 'encode-time defdecode)
10108 defdecode (decode-time def)))))
10109 (calendar-move-hook nil)
10110 (calendar-view-diary-initially-flag nil)
10111 (view-diary-entries-initially nil)
10112 (calendar-view-holidays-initially-flag nil)
10113 (view-calendar-holidays-initially nil)
10114 (timestr (format-time-string
10115 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10116 (prompt (concat (if prompt (concat prompt " ") "")
10117 (format "Date+time [%s]: " timestr)))
10118 ans (org-ans0 "") org-ans1 org-ans2 final)
10120 (cond
10121 (from-string (setq ans from-string))
10122 (org-read-date-popup-calendar
10123 (save-excursion
10124 (save-window-excursion
10125 (calendar)
10126 (calendar-forward-day (- (time-to-days def)
10127 (calendar-absolute-from-gregorian
10128 (calendar-current-date))))
10129 (org-eval-in-calendar nil t)
10130 (let* ((old-map (current-local-map))
10131 (map (copy-keymap calendar-mode-map))
10132 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10133 (org-defkey map (kbd "RET") 'org-calendar-select)
10134 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10135 'org-calendar-select-mouse)
10136 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10137 'org-calendar-select-mouse)
10138 (org-defkey minibuffer-local-map [(meta shift left)]
10139 (lambda () (interactive)
10140 (org-eval-in-calendar '(calendar-backward-month 1))))
10141 (org-defkey minibuffer-local-map [(meta shift right)]
10142 (lambda () (interactive)
10143 (org-eval-in-calendar '(calendar-forward-month 1))))
10144 (org-defkey minibuffer-local-map [(meta shift up)]
10145 (lambda () (interactive)
10146 (org-eval-in-calendar '(calendar-backward-year 1))))
10147 (org-defkey minibuffer-local-map [(meta shift down)]
10148 (lambda () (interactive)
10149 (org-eval-in-calendar '(calendar-forward-year 1))))
10150 (org-defkey minibuffer-local-map [(shift up)]
10151 (lambda () (interactive)
10152 (org-eval-in-calendar '(calendar-backward-week 1))))
10153 (org-defkey minibuffer-local-map [(shift down)]
10154 (lambda () (interactive)
10155 (org-eval-in-calendar '(calendar-forward-week 1))))
10156 (org-defkey minibuffer-local-map [(shift left)]
10157 (lambda () (interactive)
10158 (org-eval-in-calendar '(calendar-backward-day 1))))
10159 (org-defkey minibuffer-local-map [(shift right)]
10160 (lambda () (interactive)
10161 (org-eval-in-calendar '(calendar-forward-day 1))))
10162 (org-defkey minibuffer-local-map ">"
10163 (lambda () (interactive)
10164 (org-eval-in-calendar '(scroll-calendar-left 1))))
10165 (org-defkey minibuffer-local-map "<"
10166 (lambda () (interactive)
10167 (org-eval-in-calendar '(scroll-calendar-right 1))))
10168 (unwind-protect
10169 (progn
10170 (use-local-map map)
10171 (add-hook 'post-command-hook 'org-read-date-display)
10172 (setq org-ans0 (read-string prompt default-input nil nil))
10173 ;; org-ans0: from prompt
10174 ;; org-ans1: from mouse click
10175 ;; org-ans2: from calendar motion
10176 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10177 (remove-hook 'post-command-hook 'org-read-date-display)
10178 (use-local-map old-map)
10179 (when org-read-date-overlay
10180 (org-delete-overlay org-read-date-overlay)
10181 (setq org-read-date-overlay nil)))))))
10183 (t ; Naked prompt only
10184 (unwind-protect
10185 (setq ans (read-string prompt default-input nil timestr))
10186 (when org-read-date-overlay
10187 (org-delete-overlay org-read-date-overlay)
10188 (setq org-read-date-overlay nil)))))
10190 (setq final (org-read-date-analyze ans def defdecode))
10192 (if to-time
10193 (apply 'encode-time final)
10194 (if (and (boundp 'org-time-was-given) org-time-was-given)
10195 (format "%04d-%02d-%02d %02d:%02d"
10196 (nth 5 final) (nth 4 final) (nth 3 final)
10197 (nth 2 final) (nth 1 final))
10198 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10199 (defvar def)
10200 (defvar defdecode)
10201 (defvar with-time)
10202 (defun org-read-date-display ()
10203 "Display the currrent date prompt interpretation in the minibuffer."
10204 (when org-read-date-display-live
10205 (when org-read-date-overlay
10206 (org-delete-overlay org-read-date-overlay))
10207 (let ((p (point)))
10208 (end-of-line 1)
10209 (while (not (equal (buffer-substring
10210 (max (point-min) (- (point) 4)) (point))
10211 " "))
10212 (insert " "))
10213 (goto-char p))
10214 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10215 " " (or org-ans1 org-ans2)))
10216 (org-end-time-was-given nil)
10217 (f (org-read-date-analyze ans def defdecode))
10218 (fmts (if org-dcst
10219 org-time-stamp-custom-formats
10220 org-time-stamp-formats))
10221 (fmt (if (or with-time
10222 (and (boundp 'org-time-was-given) org-time-was-given))
10223 (cdr fmts)
10224 (car fmts)))
10225 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10226 (when (and org-end-time-was-given
10227 (string-match org-plain-time-of-day-regexp txt))
10228 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10229 org-end-time-was-given
10230 (substring txt (match-end 0)))))
10231 (setq org-read-date-overlay
10232 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10233 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10235 (defun org-read-date-analyze (ans def defdecode)
10236 "Analyze the combined answer of the date prompt."
10237 ;; FIXME: cleanup and comment
10238 (let (delta deltan deltaw deltadef year month day
10239 hour minute second wday pm h2 m2 tl wday1
10240 iso-year iso-weekday iso-week iso-year iso-date)
10242 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10243 (setq ans "+0"))
10245 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10246 (setq ans (replace-match "" t t ans)
10247 deltan (car delta)
10248 deltaw (nth 1 delta)
10249 deltadef (nth 2 delta)))
10251 ;; Check if there is an iso week date in there
10252 ;; If yes, sore the info and ostpone interpreting it until the rest
10253 ;; of the parsing is done
10254 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10255 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10256 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10257 iso-week (string-to-number (match-string 2 ans)))
10258 (setq ans (replace-match "" t t ans)))
10260 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10261 (when (string-match
10262 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10263 (setq year (if (match-end 2)
10264 (string-to-number (match-string 2 ans))
10265 (string-to-number (format-time-string "%Y")))
10266 month (string-to-number (match-string 3 ans))
10267 day (string-to-number (match-string 4 ans)))
10268 (if (< year 100) (setq year (+ 2000 year)))
10269 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10270 t nil ans)))
10271 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10272 ;; If there is a time with am/pm, and *no* time without it, we convert
10273 ;; so that matching will be successful.
10274 (loop for i from 1 to 2 do ; twice, for end time as well
10275 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10276 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10277 (setq hour (string-to-number (match-string 1 ans))
10278 minute (if (match-end 3)
10279 (string-to-number (match-string 3 ans))
10281 pm (equal ?p
10282 (string-to-char (downcase (match-string 4 ans)))))
10283 (if (and (= hour 12) (not pm))
10284 (setq hour 0)
10285 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10286 (setq ans (replace-match (format "%02d:%02d" hour minute)
10287 t t ans))))
10289 ;; Check if a time range is given as a duration
10290 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10291 (setq hour (string-to-number (match-string 1 ans))
10292 h2 (+ hour (string-to-number (match-string 3 ans)))
10293 minute (string-to-number (match-string 2 ans))
10294 m2 (+ minute (if (match-end 5) (string-to-number
10295 (match-string 5 ans))0)))
10296 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10297 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10298 t t ans)))
10300 ;; Check if there is a time range
10301 (when (boundp 'org-end-time-was-given)
10302 (setq org-time-was-given nil)
10303 (when (and (string-match org-plain-time-of-day-regexp ans)
10304 (match-end 8))
10305 (setq org-end-time-was-given (match-string 8 ans))
10306 (setq ans (concat (substring ans 0 (match-beginning 7))
10307 (substring ans (match-end 7))))))
10309 (setq tl (parse-time-string ans)
10310 day (or (nth 3 tl) (nth 3 defdecode))
10311 month (or (nth 4 tl)
10312 (if (and org-read-date-prefer-future
10313 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10314 (1+ (nth 4 defdecode))
10315 (nth 4 defdecode)))
10316 year (or (nth 5 tl)
10317 (if (and org-read-date-prefer-future
10318 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10319 (1+ (nth 5 defdecode))
10320 (nth 5 defdecode)))
10321 hour (or (nth 2 tl) (nth 2 defdecode))
10322 minute (or (nth 1 tl) (nth 1 defdecode))
10323 second (or (nth 0 tl) 0)
10324 wday (nth 6 tl))
10326 ;; Special date definitions below
10327 (cond
10328 (iso-week
10329 ;; There was an iso week
10330 (setq year (or iso-year year)
10331 day (or iso-weekday wday 1)
10332 wday nil ; to make sure that the trigger below does not match
10333 iso-date (calendar-gregorian-from-absolute
10334 (calendar-absolute-from-iso
10335 (list iso-week day year))))
10336 ; FIXME: Should we also push ISO weeks into the future?
10337 ; (when (and org-read-date-prefer-future
10338 ; (not iso-year)
10339 ; (< (calendar-absolute-from-gregorian iso-date)
10340 ; (time-to-days (current-time))))
10341 ; (setq year (1+ year)
10342 ; iso-date (calendar-gregorian-from-absolute
10343 ; (calendar-absolute-from-iso
10344 ; (list iso-week day year)))))
10345 (setq month (car iso-date)
10346 year (nth 2 iso-date)
10347 day (nth 1 iso-date)))
10348 (deltan
10349 (unless deltadef
10350 (let ((now (decode-time (current-time))))
10351 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10352 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10353 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10354 ((equal deltaw "m") (setq month (+ month deltan)))
10355 ((equal deltaw "y") (setq year (+ year deltan)))))
10356 ((and wday (not (nth 3 tl)))
10357 ;; Weekday was given, but no day, so pick that day in the week
10358 ;; on or after the derived date.
10359 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10360 (unless (equal wday wday1)
10361 (setq day (+ day (% (- wday wday1 -7) 7))))))
10362 (if (and (boundp 'org-time-was-given)
10363 (nth 2 tl))
10364 (setq org-time-was-given t))
10365 (if (< year 100) (setq year (+ 2000 year)))
10366 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10367 (list second minute hour day month year)))
10369 (defvar parse-time-weekdays)
10371 (defun org-read-date-get-relative (s today default)
10372 "Check string S for special relative date string.
10373 TODAY and DEFAULT are internal times, for today and for a default.
10374 Return shift list (N what def-flag)
10375 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10376 N is the number of WHATs to shift.
10377 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10378 the DEFAULT date rather than TODAY."
10379 (when (string-match
10380 (concat
10381 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10382 "\\([0-9]+\\)?"
10383 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10384 "\\([ \t]\\|$\\)") s)
10385 (let* ((dir (if (match-end 1)
10386 (string-to-char (substring (match-string 1 s) -1))
10387 ?+))
10388 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10389 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10390 (what (if (match-end 3) (match-string 3 s) "d"))
10391 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10392 (date (if rel default today))
10393 (wday (nth 6 (decode-time date)))
10394 delta)
10395 (if wday1
10396 (progn
10397 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10398 (if (= dir ?-) (setq delta (- delta 7)))
10399 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10400 (list delta "d" rel))
10401 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10403 (defun org-eval-in-calendar (form &optional keepdate)
10404 "Eval FORM in the calendar window and return to current window.
10405 Also, store the cursor date in variable org-ans2."
10406 (let ((sw (selected-window)))
10407 (select-window (get-buffer-window "*Calendar*"))
10408 (eval form)
10409 (when (and (not keepdate) (calendar-cursor-to-date))
10410 (let* ((date (calendar-cursor-to-date))
10411 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10412 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10413 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10414 (select-window sw)))
10416 ; ;; Update the prompt to show new default date
10417 ; (save-excursion
10418 ; (goto-char (point-min))
10419 ; (when (and org-ans2
10420 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10421 ; (get-text-property (match-end 0) 'field))
10422 ; (let ((inhibit-read-only t))
10423 ; (replace-match (concat "[" org-ans2 "]") t t)
10424 ; (add-text-properties (point-min) (1+ (match-end 0))
10425 ; (text-properties-at (1+ (point-min)))))))))
10427 (defun org-calendar-select ()
10428 "Return to `org-read-date' with the date currently selected.
10429 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10430 (interactive)
10431 (when (calendar-cursor-to-date)
10432 (let* ((date (calendar-cursor-to-date))
10433 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10434 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10435 (if (active-minibuffer-window) (exit-minibuffer))))
10437 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10438 "Insert a date stamp for the date given by the internal TIME.
10439 WITH-HM means, use the stamp format that includes the time of the day.
10440 INACTIVE means use square brackets instead of angular ones, so that the
10441 stamp will not contribute to the agenda.
10442 PRE and POST are optional strings to be inserted before and after the
10443 stamp.
10444 The command returns the inserted time stamp."
10445 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10446 stamp)
10447 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10448 (insert-before-markers (or pre ""))
10449 (insert-before-markers (setq stamp (format-time-string fmt time)))
10450 (when (listp extra)
10451 (setq extra (car extra))
10452 (if (and (stringp extra)
10453 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10454 (setq extra (format "-%02d:%02d"
10455 (string-to-number (match-string 1 extra))
10456 (string-to-number (match-string 2 extra))))
10457 (setq extra nil)))
10458 (when extra
10459 (backward-char 1)
10460 (insert-before-markers extra)
10461 (forward-char 1))
10462 (insert-before-markers (or post ""))
10463 stamp))
10465 (defun org-toggle-time-stamp-overlays ()
10466 "Toggle the use of custom time stamp formats."
10467 (interactive)
10468 (setq org-display-custom-times (not org-display-custom-times))
10469 (unless org-display-custom-times
10470 (let ((p (point-min)) (bmp (buffer-modified-p)))
10471 (while (setq p (next-single-property-change p 'display))
10472 (if (and (get-text-property p 'display)
10473 (eq (get-text-property p 'face) 'org-date))
10474 (remove-text-properties
10475 p (setq p (next-single-property-change p 'display))
10476 '(display t))))
10477 (set-buffer-modified-p bmp)))
10478 (if (featurep 'xemacs)
10479 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10480 (org-restart-font-lock)
10481 (setq org-table-may-need-update t)
10482 (if org-display-custom-times
10483 (message "Time stamps are overlayed with custom format")
10484 (message "Time stamp overlays removed")))
10486 (defun org-display-custom-time (beg end)
10487 "Overlay modified time stamp format over timestamp between BEG and END."
10488 (let* ((ts (buffer-substring beg end))
10489 t1 w1 with-hm tf time str w2 (off 0))
10490 (save-match-data
10491 (setq t1 (org-parse-time-string ts t))
10492 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10493 (setq off (- (match-end 0) (match-beginning 0)))))
10494 (setq end (- end off))
10495 (setq w1 (- end beg)
10496 with-hm (and (nth 1 t1) (nth 2 t1))
10497 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10498 time (org-fix-decoded-time t1)
10499 str (org-add-props
10500 (format-time-string
10501 (substring tf 1 -1) (apply 'encode-time time))
10502 nil 'mouse-face 'highlight)
10503 w2 (length str))
10504 (if (not (= w2 w1))
10505 (add-text-properties (1+ beg) (+ 2 beg)
10506 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10507 (if (featurep 'xemacs)
10508 (progn
10509 (put-text-property beg end 'invisible t)
10510 (put-text-property beg end 'end-glyph (make-glyph str)))
10511 (put-text-property beg end 'display str))))
10513 (defun org-translate-time (string)
10514 "Translate all timestamps in STRING to custom format.
10515 But do this only if the variable `org-display-custom-times' is set."
10516 (when org-display-custom-times
10517 (save-match-data
10518 (let* ((start 0)
10519 (re org-ts-regexp-both)
10520 t1 with-hm inactive tf time str beg end)
10521 (while (setq start (string-match re string start))
10522 (setq beg (match-beginning 0)
10523 end (match-end 0)
10524 t1 (save-match-data
10525 (org-parse-time-string (substring string beg end) t))
10526 with-hm (and (nth 1 t1) (nth 2 t1))
10527 inactive (equal (substring string beg (1+ beg)) "[")
10528 tf (funcall (if with-hm 'cdr 'car)
10529 org-time-stamp-custom-formats)
10530 time (org-fix-decoded-time t1)
10531 str (format-time-string
10532 (concat
10533 (if inactive "[" "<") (substring tf 1 -1)
10534 (if inactive "]" ">"))
10535 (apply 'encode-time time))
10536 string (replace-match str t t string)
10537 start (+ start (length str)))))))
10538 string)
10540 (defun org-fix-decoded-time (time)
10541 "Set 0 instead of nil for the first 6 elements of time.
10542 Don't touch the rest."
10543 (let ((n 0))
10544 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10546 (defun org-days-to-time (timestamp-string)
10547 "Difference between TIMESTAMP-STRING and now in days."
10548 (- (time-to-days (org-time-string-to-time timestamp-string))
10549 (time-to-days (current-time))))
10551 (defun org-deadline-close (timestamp-string &optional ndays)
10552 "Is the time in TIMESTAMP-STRING close to the current date?"
10553 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10554 (and (< (org-days-to-time timestamp-string) ndays)
10555 (not (org-entry-is-done-p))))
10557 (defun org-get-wdays (ts)
10558 "Get the deadline lead time appropriate for timestring TS."
10559 (cond
10560 ((<= org-deadline-warning-days 0)
10561 ;; 0 or negative, enforce this value no matter what
10562 (- org-deadline-warning-days))
10563 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10564 ;; lead time is specified.
10565 (floor (* (string-to-number (match-string 1 ts))
10566 (cdr (assoc (match-string 2 ts)
10567 '(("d" . 1) ("w" . 7)
10568 ("m" . 30.4) ("y" . 365.25)))))))
10569 ;; go for the default.
10570 (t org-deadline-warning-days)))
10572 (defun org-calendar-select-mouse (ev)
10573 "Return to `org-read-date' with the date currently selected.
10574 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10575 (interactive "e")
10576 (mouse-set-point ev)
10577 (when (calendar-cursor-to-date)
10578 (let* ((date (calendar-cursor-to-date))
10579 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10580 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10581 (if (active-minibuffer-window) (exit-minibuffer))))
10583 (defun org-check-deadlines (ndays)
10584 "Check if there are any deadlines due or past due.
10585 A deadline is considered due if it happens within `org-deadline-warning-days'
10586 days from today's date. If the deadline appears in an entry marked DONE,
10587 it is not shown. The prefix arg NDAYS can be used to test that many
10588 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10589 (interactive "P")
10590 (let* ((org-warn-days
10591 (cond
10592 ((equal ndays '(4)) 100000)
10593 (ndays (prefix-numeric-value ndays))
10594 (t (abs org-deadline-warning-days))))
10595 (case-fold-search nil)
10596 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10597 (callback
10598 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10600 (message "%d deadlines past-due or due within %d days"
10601 (org-occur regexp nil callback)
10602 org-warn-days)))
10604 (defun org-check-before-date (date)
10605 "Check if there are deadlines or scheduled entries before DATE."
10606 (interactive (list (org-read-date)))
10607 (let ((case-fold-search nil)
10608 (regexp (concat "\\<\\(" org-deadline-string
10609 "\\|" org-scheduled-string
10610 "\\) *<\\([^>]+\\)>"))
10611 (callback
10612 (lambda () (time-less-p
10613 (org-time-string-to-time (match-string 2))
10614 (org-time-string-to-time date)))))
10615 (message "%d entries before %s"
10616 (org-occur regexp nil callback) date)))
10618 (defun org-evaluate-time-range (&optional to-buffer)
10619 "Evaluate a time range by computing the difference between start and end.
10620 Normally the result is just printed in the echo area, but with prefix arg
10621 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10622 If the time range is actually in a table, the result is inserted into the
10623 next column.
10624 For time difference computation, a year is assumed to be exactly 365
10625 days in order to avoid rounding problems."
10626 (interactive "P")
10628 (org-clock-update-time-maybe)
10629 (save-excursion
10630 (unless (org-at-date-range-p t)
10631 (goto-char (point-at-bol))
10632 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10633 (if (not (org-at-date-range-p t))
10634 (error "Not at a time-stamp range, and none found in current line")))
10635 (let* ((ts1 (match-string 1))
10636 (ts2 (match-string 2))
10637 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10638 (match-end (match-end 0))
10639 (time1 (org-time-string-to-time ts1))
10640 (time2 (org-time-string-to-time ts2))
10641 (t1 (time-to-seconds time1))
10642 (t2 (time-to-seconds time2))
10643 (diff (abs (- t2 t1)))
10644 (negative (< (- t2 t1) 0))
10645 ;; (ys (floor (* 365 24 60 60)))
10646 (ds (* 24 60 60))
10647 (hs (* 60 60))
10648 (fy "%dy %dd %02d:%02d")
10649 (fy1 "%dy %dd")
10650 (fd "%dd %02d:%02d")
10651 (fd1 "%dd")
10652 (fh "%02d:%02d")
10653 y d h m align)
10654 (if havetime
10655 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10657 d (floor (/ diff ds)) diff (mod diff ds)
10658 h (floor (/ diff hs)) diff (mod diff hs)
10659 m (floor (/ diff 60)))
10660 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10662 d (floor (+ (/ diff ds) 0.5))
10663 h 0 m 0))
10664 (if (not to-buffer)
10665 (message "%s" (org-make-tdiff-string y d h m))
10666 (if (org-at-table-p)
10667 (progn
10668 (goto-char match-end)
10669 (setq align t)
10670 (and (looking-at " *|") (goto-char (match-end 0))))
10671 (goto-char match-end))
10672 (if (looking-at
10673 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10674 (replace-match ""))
10675 (if negative (insert " -"))
10676 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10677 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10678 (insert " " (format fh h m))))
10679 (if align (org-table-align))
10680 (message "Time difference inserted")))))
10682 (defun org-make-tdiff-string (y d h m)
10683 (let ((fmt "")
10684 (l nil))
10685 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10686 l (push y l)))
10687 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10688 l (push d l)))
10689 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10690 l (push h l)))
10691 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10692 l (push m l)))
10693 (apply 'format fmt (nreverse l))))
10695 (defun org-time-string-to-time (s)
10696 (apply 'encode-time (org-parse-time-string s)))
10698 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10699 "Convert a time stamp to an absolute day number.
10700 If there is a specifyer for a cyclic time stamp, get the closest date to
10701 DAYNR.
10702 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10703 (cond
10704 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10705 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10706 daynr
10707 (+ daynr 1000)))
10708 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10709 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10710 (time-to-days (current-time))) (match-string 0 s)
10711 prefer show-all))
10712 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10714 (defun org-days-to-iso-week (days)
10715 "Return the iso week number."
10716 (require 'cal-iso)
10717 (car (calendar-iso-from-absolute days)))
10719 (defun org-small-year-to-year (year)
10720 "Convert 2-digit years into 4-digit years.
10721 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10722 The year 2000 cannot be abbreviated. Any year lager than 99
10723 is retrned unchanged."
10724 (if (< year 38)
10725 (setq year (+ 2000 year))
10726 (if (< year 100)
10727 (setq year (+ 1900 year))))
10728 year)
10730 (defun org-time-from-absolute (d)
10731 "Return the time corresponding to date D.
10732 D may be an absolute day number, or a calendar-type list (month day year)."
10733 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10734 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10736 (defun org-calendar-holiday ()
10737 "List of holidays, for Diary display in Org-mode."
10738 (require 'holidays)
10739 (let ((hl (funcall
10740 (if (fboundp 'calendar-check-holidays)
10741 'calendar-check-holidays 'check-calendar-holidays) date)))
10742 (if hl (mapconcat 'identity hl "; "))))
10744 (defun org-diary-sexp-entry (sexp entry date)
10745 "Process a SEXP diary ENTRY for DATE."
10746 (require 'diary-lib)
10747 (let ((result (if calendar-debug-sexp
10748 (let ((stack-trace-on-error t))
10749 (eval (car (read-from-string sexp))))
10750 (condition-case nil
10751 (eval (car (read-from-string sexp)))
10752 (error
10753 (beep)
10754 (message "Bad sexp at line %d in %s: %s"
10755 (org-current-line)
10756 (buffer-file-name) sexp)
10757 (sleep-for 2))))))
10758 (cond ((stringp result) result)
10759 ((and (consp result)
10760 (stringp (cdr result))) (cdr result))
10761 (result entry)
10762 (t nil))))
10764 (defun org-diary-to-ical-string (frombuf)
10765 "Get iCalendar entries from diary entries in buffer FROMBUF.
10766 This uses the icalendar.el library."
10767 (let* ((tmpdir (if (featurep 'xemacs)
10768 (temp-directory)
10769 temporary-file-directory))
10770 (tmpfile (make-temp-name
10771 (expand-file-name "orgics" tmpdir)))
10772 buf rtn b e)
10773 (save-excursion
10774 (set-buffer frombuf)
10775 (icalendar-export-region (point-min) (point-max) tmpfile)
10776 (setq buf (find-buffer-visiting tmpfile))
10777 (set-buffer buf)
10778 (goto-char (point-min))
10779 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10780 (setq b (match-beginning 0)))
10781 (goto-char (point-max))
10782 (if (re-search-backward "^END:VEVENT" nil t)
10783 (setq e (match-end 0)))
10784 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10785 (kill-buffer buf)
10786 (kill-buffer frombuf)
10787 (delete-file tmpfile)
10788 rtn))
10790 (defun org-closest-date (start current change prefer show-all)
10791 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10792 When PREFER is `past' return a date that is either CURRENT or past.
10793 When PREFER is `future', return a date that is either CURRENT or future.
10794 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10795 ;; Make the proper lists from the dates
10796 (catch 'exit
10797 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10798 dn dw sday cday n1 n2
10799 d m y y1 y2 date1 date2 nmonths nm ny m2)
10801 (setq start (org-date-to-gregorian start)
10802 current (org-date-to-gregorian
10803 (if show-all
10804 current
10805 (time-to-days (current-time))))
10806 sday (calendar-absolute-from-gregorian start)
10807 cday (calendar-absolute-from-gregorian current))
10809 (if (<= cday sday) (throw 'exit sday))
10811 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10812 (setq dn (string-to-number (match-string 1 change))
10813 dw (cdr (assoc (match-string 2 change) a1)))
10814 (error "Invalid change specifyer: %s" change))
10815 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10816 (cond
10817 ((eq dw 'day)
10818 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10819 n2 (+ n1 dn)))
10820 ((eq dw 'year)
10821 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10822 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10823 (setq date1 (list m d y1)
10824 n1 (calendar-absolute-from-gregorian date1)
10825 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10826 n2 (calendar-absolute-from-gregorian date2)))
10827 ((eq dw 'month)
10828 ;; approx number of month between the tow dates
10829 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10830 ;; How often does dn fit in there?
10831 (setq d (nth 1 start) m (car start) y (nth 2 start)
10832 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10833 m (+ m nm)
10834 ny (floor (/ m 12))
10835 y (+ y ny)
10836 m (- m (* ny 12)))
10837 (while (> m 12) (setq m (- m 12) y (1+ y)))
10838 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10839 (setq m2 (+ m dn) y2 y)
10840 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10841 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10842 (while (< n2 cday)
10843 (setq n1 n2 m m2 y y2)
10844 (setq m2 (+ m dn) y2 y)
10845 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10846 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10848 (if show-all
10849 (cond
10850 ((eq prefer 'past) n1)
10851 ((eq prefer 'future) (if (= cday n1) n1 n2))
10852 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10853 (cond
10854 ((eq prefer 'past) n1)
10855 ((eq prefer 'future) (if (= cday n1) n1 n2))
10856 (t (if (= cday n1) n1 n2)))))))
10858 (defun org-date-to-gregorian (date)
10859 "Turn any specification of DATE into a gregorian date for the calendar."
10860 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10861 ((and (listp date) (= (length date) 3)) date)
10862 ((stringp date)
10863 (setq date (org-parse-time-string date))
10864 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10865 ((listp date)
10866 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10868 (defun org-parse-time-string (s &optional nodefault)
10869 "Parse the standard Org-mode time string.
10870 This should be a lot faster than the normal `parse-time-string'.
10871 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10872 hour and minute fields will be nil if not given."
10873 (if (string-match org-ts-regexp0 s)
10874 (list 0
10875 (if (or (match-beginning 8) (not nodefault))
10876 (string-to-number (or (match-string 8 s) "0")))
10877 (if (or (match-beginning 7) (not nodefault))
10878 (string-to-number (or (match-string 7 s) "0")))
10879 (string-to-number (match-string 4 s))
10880 (string-to-number (match-string 3 s))
10881 (string-to-number (match-string 2 s))
10882 nil nil nil)
10883 (make-list 9 0)))
10885 (defun org-timestamp-up (&optional arg)
10886 "Increase the date item at the cursor by one.
10887 If the cursor is on the year, change the year. If it is on the month or
10888 the day, change that.
10889 With prefix ARG, change by that many units."
10890 (interactive "p")
10891 (org-timestamp-change (prefix-numeric-value arg)))
10893 (defun org-timestamp-down (&optional arg)
10894 "Decrease the date item at the cursor by one.
10895 If the cursor is on the year, change the year. If it is on the month or
10896 the day, change that.
10897 With prefix ARG, change by that many units."
10898 (interactive "p")
10899 (org-timestamp-change (- (prefix-numeric-value arg))))
10901 (defun org-timestamp-up-day (&optional arg)
10902 "Increase the date in the time stamp by one day.
10903 With prefix ARG, change that many days."
10904 (interactive "p")
10905 (if (and (not (org-at-timestamp-p t))
10906 (org-on-heading-p))
10907 (org-todo 'up)
10908 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10910 (defun org-timestamp-down-day (&optional arg)
10911 "Decrease the date in the time stamp by one day.
10912 With prefix ARG, change that many days."
10913 (interactive "p")
10914 (if (and (not (org-at-timestamp-p t))
10915 (org-on-heading-p))
10916 (org-todo 'down)
10917 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10919 (defun org-at-timestamp-p (&optional inactive-ok)
10920 "Determine if the cursor is in or at a timestamp."
10921 (interactive)
10922 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10923 (pos (point))
10924 (ans (or (looking-at tsr)
10925 (save-excursion
10926 (skip-chars-backward "^[<\n\r\t")
10927 (if (> (point) (point-min)) (backward-char 1))
10928 (and (looking-at tsr)
10929 (> (- (match-end 0) pos) -1))))))
10930 (and ans
10931 (boundp 'org-ts-what)
10932 (setq org-ts-what
10933 (cond
10934 ((= pos (match-beginning 0)) 'bracket)
10935 ((= pos (1- (match-end 0))) 'bracket)
10936 ((org-pos-in-match-range pos 2) 'year)
10937 ((org-pos-in-match-range pos 3) 'month)
10938 ((org-pos-in-match-range pos 7) 'hour)
10939 ((org-pos-in-match-range pos 8) 'minute)
10940 ((or (org-pos-in-match-range pos 4)
10941 (org-pos-in-match-range pos 5)) 'day)
10942 ((and (> pos (or (match-end 8) (match-end 5)))
10943 (< pos (match-end 0)))
10944 (- pos (or (match-end 8) (match-end 5))))
10945 (t 'day))))
10946 ans))
10948 (defun org-toggle-timestamp-type ()
10949 "Toggle the type (<active> or [inactive]) of a time stamp."
10950 (interactive)
10951 (when (org-at-timestamp-p t)
10952 (save-excursion
10953 (goto-char (match-beginning 0))
10954 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10955 (goto-char (1- (match-end 0)))
10956 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10957 (message "Timestamp is now %sactive"
10958 (if (equal (char-before) ?>) "in" ""))))
10960 (defun org-timestamp-change (n &optional what)
10961 "Change the date in the time stamp at point.
10962 The date will be changed by N times WHAT. WHAT can be `day', `month',
10963 `year', `minute', `second'. If WHAT is not given, the cursor position
10964 in the timestamp determines what will be changed."
10965 (let ((pos (point))
10966 with-hm inactive
10967 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10968 org-ts-what
10969 extra rem
10970 ts time time0)
10971 (if (not (org-at-timestamp-p t))
10972 (error "Not at a timestamp"))
10973 (if (and (not what) (eq org-ts-what 'bracket))
10974 (org-toggle-timestamp-type)
10975 (if (and (not what) (not (eq org-ts-what 'day))
10976 org-display-custom-times
10977 (get-text-property (point) 'display)
10978 (not (get-text-property (1- (point)) 'display)))
10979 (setq org-ts-what 'day))
10980 (setq org-ts-what (or what org-ts-what)
10981 inactive (= (char-after (match-beginning 0)) ?\[)
10982 ts (match-string 0))
10983 (replace-match "")
10984 (if (string-match
10985 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10987 (setq extra (match-string 1 ts)))
10988 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10989 (setq with-hm t))
10990 (setq time0 (org-parse-time-string ts))
10991 (when (and (eq org-ts-what 'minute)
10992 (eq current-prefix-arg nil))
10993 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10994 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10995 (setcar (cdr time0) (+ (nth 1 time0)
10996 (if (> n 0) (- rem) (- dm rem))))))
10997 (setq time
10998 (encode-time (or (car time0) 0)
10999 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11000 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11001 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11002 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11003 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11004 (nthcdr 6 time0)))
11005 (when (integerp org-ts-what)
11006 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11007 (if (eq what 'calendar)
11008 (let ((cal-date (org-get-date-from-calendar)))
11009 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11010 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11011 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11012 (setcar time0 (or (car time0) 0))
11013 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11014 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11015 (setq time (apply 'encode-time time0))))
11016 (setq org-last-changed-timestamp
11017 (org-insert-time-stamp time with-hm inactive nil nil extra))
11018 (org-clock-update-time-maybe)
11019 (goto-char pos)
11020 ;; Try to recenter the calendar window, if any
11021 (if (and org-calendar-follow-timestamp-change
11022 (get-buffer-window "*Calendar*" t)
11023 (memq org-ts-what '(day month year)))
11024 (org-recenter-calendar (time-to-days time))))))
11026 (defun org-modify-ts-extra (s pos n dm)
11027 "Change the different parts of the lead-time and repeat fields in timestamp."
11028 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11029 ng h m new rem)
11030 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11031 (cond
11032 ((or (org-pos-in-match-range pos 2)
11033 (org-pos-in-match-range pos 3))
11034 (setq m (string-to-number (match-string 3 s))
11035 h (string-to-number (match-string 2 s)))
11036 (if (org-pos-in-match-range pos 2)
11037 (setq h (+ h n))
11038 (setq n (* dm (org-no-warnings (signum n))))
11039 (when (not (= 0 (setq rem (% m dm))))
11040 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11041 (setq m (+ m n)))
11042 (if (< m 0) (setq m (+ m 60) h (1- h)))
11043 (if (> m 59) (setq m (- m 60) h (1+ h)))
11044 (setq h (min 24 (max 0 h)))
11045 (setq ng 1 new (format "-%02d:%02d" h m)))
11046 ((org-pos-in-match-range pos 6)
11047 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11048 ((org-pos-in-match-range pos 5)
11049 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11051 ((org-pos-in-match-range pos 9)
11052 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11053 ((org-pos-in-match-range pos 8)
11054 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11056 (when ng
11057 (setq s (concat
11058 (substring s 0 (match-beginning ng))
11060 (substring s (match-end ng))))))
11063 (defun org-recenter-calendar (date)
11064 "If the calendar is visible, recenter it to DATE."
11065 (let* ((win (selected-window))
11066 (cwin (get-buffer-window "*Calendar*" t))
11067 (calendar-move-hook nil))
11068 (when cwin
11069 (select-window cwin)
11070 (calendar-goto-date (if (listp date) date
11071 (calendar-gregorian-from-absolute date)))
11072 (select-window win))))
11074 (defun org-goto-calendar (&optional arg)
11075 "Go to the Emacs calendar at the current date.
11076 If there is a time stamp in the current line, go to that date.
11077 A prefix ARG can be used to force the current date."
11078 (interactive "P")
11079 (let ((tsr org-ts-regexp) diff
11080 (calendar-move-hook nil)
11081 (calendar-view-holidays-initially-flag nil)
11082 (view-calendar-holidays-initially nil)
11083 (calendar-view-diary-initially-flag nil)
11084 (view-diary-entries-initially nil))
11085 (if (or (org-at-timestamp-p)
11086 (save-excursion
11087 (beginning-of-line 1)
11088 (looking-at (concat ".*" tsr))))
11089 (let ((d1 (time-to-days (current-time)))
11090 (d2 (time-to-days
11091 (org-time-string-to-time (match-string 1)))))
11092 (setq diff (- d2 d1))))
11093 (calendar)
11094 (calendar-goto-today)
11095 (if (and diff (not arg)) (calendar-forward-day diff))))
11097 (defun org-get-date-from-calendar ()
11098 "Return a list (month day year) of date at point in calendar."
11099 (with-current-buffer "*Calendar*"
11100 (save-match-data
11101 (calendar-cursor-to-date))))
11103 (defun org-date-from-calendar ()
11104 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11105 If there is already a time stamp at the cursor position, update it."
11106 (interactive)
11107 (if (org-at-timestamp-p t)
11108 (org-timestamp-change 0 'calendar)
11109 (let ((cal-date (org-get-date-from-calendar)))
11110 (org-insert-time-stamp
11111 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11113 (defun org-minutes-to-hh:mm-string (m)
11114 "Compute H:MM from a number of minutes."
11115 (let ((h (/ m 60)))
11116 (setq m (- m (* 60 h)))
11117 (format "%d:%02d" h m)))
11119 (defun org-hh:mm-string-to-minutes (s)
11120 "Convert a string H:MM to a number of minutes."
11121 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11122 (+ (* (string-to-number (match-string 1 s)) 60)
11123 (string-to-number (match-string 2 s)))
11126 ;;;; Agenda files
11128 ;;;###autoload
11129 (defun org-iswitchb (&optional arg)
11130 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11131 With a prefix argument, restrict available to files.
11132 With two prefix arguments, restrict available buffers to agenda files.
11134 Due to some yet unresolved reason, global function
11135 `iswitchb-mode' needs to be active for this function to work."
11136 (interactive "P")
11137 (require 'iswitchb)
11138 (let ((enabled iswitchb-mode) blist)
11139 (or enabled (iswitchb-mode 1))
11140 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11141 ((equal arg '(16)) (org-buffer-list 'agenda))
11142 (t (org-buffer-list))))
11143 (unwind-protect
11144 (let ((iswitchb-make-buflist-hook
11145 (lambda ()
11146 (setq iswitchb-temp-buflist
11147 (mapcar 'buffer-name blist)))))
11148 (switch-to-buffer
11149 (iswitchb-read-buffer
11150 "Switch-to: " nil t))
11151 (or enabled (iswitchb-mode -1))))))
11153 (defun org-buffer-list (&optional predicate tmp)
11154 "Return a list of Org buffers.
11155 PREDICATE can be either 'export, 'files or 'agenda.
11157 'export restrict the list to Export buffers.
11158 'files restrict the list to buffers visiting Org files.
11159 'agenda restrict the list to buffers visiting agenda files.
11161 If TMP is non-nil, don't include temporary buffers."
11162 (let (filter blist)
11163 (setq filter
11164 (cond ((eq predicate 'files) "\.org$")
11165 ((eq predicate 'export) "\*Org .*Export")
11166 (t "\*Org \\|\.org$")))
11167 (setq blist
11168 (mapcar
11169 (lambda(b)
11170 (let ((bname (buffer-name b))
11171 (bfile (buffer-file-name b)))
11172 (if (and (string-match filter bname)
11173 (if (eq predicate 'agenda)
11174 (member bfile
11175 (mapcar (lambda(f) (file-truename f))
11176 org-agenda-files)) t)
11177 (if tmp (not (string-match "tmp" bname)) t)) b)))
11178 (buffer-list)))
11179 (delete nil blist)))
11181 (defun org-agenda-files (&optional unrestricted ext)
11182 "Get the list of agenda files.
11183 Optional UNRESTRICTED means return the full list even if a restriction
11184 is currently in place.
11185 When EXT is non-nil, try to add all files that are created by adding EXT
11186 to the file nemes. Basically, this is a way to add the archive files
11187 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11188 a string, \"_archive\" will be used."
11189 (let ((files
11190 (cond
11191 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11192 ((stringp org-agenda-files) (org-read-agenda-file-list))
11193 ((listp org-agenda-files) org-agenda-files)
11194 (t (error "Invalid value of `org-agenda-files'")))))
11195 (setq files (apply 'append
11196 (mapcar (lambda (f)
11197 (if (file-directory-p f)
11198 (directory-files
11199 f t org-agenda-file-regexp)
11200 (list f)))
11201 files)))
11202 (when org-agenda-skip-unavailable-files
11203 (setq files (delq nil
11204 (mapcar (function
11205 (lambda (file)
11206 (and (file-readable-p file) file)))
11207 files))))
11208 (when ext
11209 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11210 ext "_archive"))
11211 (setq files (apply 'append
11212 (mapcar
11213 (lambda (f)
11214 (if (file-exists-p (concat f ext))
11215 (list f (concat f ext))
11216 (list f)))
11217 files))))
11218 files))
11220 (defun org-edit-agenda-file-list ()
11221 "Edit the list of agenda files.
11222 Depending on setup, this either uses customize to edit the variable
11223 `org-agenda-files', or it visits the file that is holding the list. In the
11224 latter case, the buffer is set up in a way that saving it automatically kills
11225 the buffer and restores the previous window configuration."
11226 (interactive)
11227 (if (stringp org-agenda-files)
11228 (let ((cw (current-window-configuration)))
11229 (find-file org-agenda-files)
11230 (org-set-local 'org-window-configuration cw)
11231 (org-add-hook 'after-save-hook
11232 (lambda ()
11233 (set-window-configuration
11234 (prog1 org-window-configuration
11235 (kill-buffer (current-buffer))))
11236 (org-install-agenda-files-menu)
11237 (message "New agenda file list installed"))
11238 nil 'local)
11239 (message "%s" (substitute-command-keys
11240 "Edit list and finish with \\[save-buffer]")))
11241 (customize-variable 'org-agenda-files)))
11243 (defun org-store-new-agenda-file-list (list)
11244 "Set new value for the agenda file list and save it correcly."
11245 (if (stringp org-agenda-files)
11246 (let ((f org-agenda-files) b)
11247 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11248 (with-temp-file f
11249 (insert (mapconcat 'identity list "\n") "\n")))
11250 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11251 (setq org-agenda-files list)
11252 (customize-save-variable 'org-agenda-files org-agenda-files))))
11254 (defun org-read-agenda-file-list ()
11255 "Read the list of agenda files from a file."
11256 (when (file-directory-p org-agenda-files)
11257 (error "`org-agenda-files' cannot be a single directory"))
11258 (when (stringp org-agenda-files)
11259 (with-temp-buffer
11260 (insert-file-contents org-agenda-files)
11261 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11264 ;;;###autoload
11265 (defun org-cycle-agenda-files ()
11266 "Cycle through the files in `org-agenda-files'.
11267 If the current buffer visits an agenda file, find the next one in the list.
11268 If the current buffer does not, find the first agenda file."
11269 (interactive)
11270 (let* ((fs (org-agenda-files t))
11271 (files (append fs (list (car fs))))
11272 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11273 file)
11274 (unless files (error "No agenda files"))
11275 (catch 'exit
11276 (while (setq file (pop files))
11277 (if (equal (file-truename file) tcf)
11278 (when (car files)
11279 (find-file (car files))
11280 (throw 'exit t))))
11281 (find-file (car fs)))
11282 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11284 (defun org-agenda-file-to-front (&optional to-end)
11285 "Move/add the current file to the top of the agenda file list.
11286 If the file is not present in the list, it is added to the front. If it is
11287 present, it is moved there. With optional argument TO-END, add/move to the
11288 end of the list."
11289 (interactive "P")
11290 (let ((org-agenda-skip-unavailable-files nil)
11291 (file-alist (mapcar (lambda (x)
11292 (cons (file-truename x) x))
11293 (org-agenda-files t)))
11294 (ctf (file-truename buffer-file-name))
11295 x had)
11296 (setq x (assoc ctf file-alist) had x)
11298 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11299 (if to-end
11300 (setq file-alist (append (delq x file-alist) (list x)))
11301 (setq file-alist (cons x (delq x file-alist))))
11302 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11303 (org-install-agenda-files-menu)
11304 (message "File %s to %s of agenda file list"
11305 (if had "moved" "added") (if to-end "end" "front"))))
11307 (defun org-remove-file (&optional file)
11308 "Remove current file from the list of files in variable `org-agenda-files'.
11309 These are the files which are being checked for agenda entries.
11310 Optional argument FILE means, use this file instead of the current."
11311 (interactive)
11312 (let* ((org-agenda-skip-unavailable-files nil)
11313 (file (or file buffer-file-name))
11314 (true-file (file-truename file))
11315 (afile (abbreviate-file-name file))
11316 (files (delq nil (mapcar
11317 (lambda (x)
11318 (if (equal true-file
11319 (file-truename x))
11320 nil x))
11321 (org-agenda-files t)))))
11322 (if (not (= (length files) (length (org-agenda-files t))))
11323 (progn
11324 (org-store-new-agenda-file-list files)
11325 (org-install-agenda-files-menu)
11326 (message "Removed file: %s" afile))
11327 (message "File was not in list: %s (not removed)" afile))))
11329 (defun org-file-menu-entry (file)
11330 (vector file (list 'find-file file) t))
11332 (defun org-check-agenda-file (file)
11333 "Make sure FILE exists. If not, ask user what to do."
11334 (when (not (file-exists-p file))
11335 (message "non-existent file %s. [R]emove from list or [A]bort?"
11336 (abbreviate-file-name file))
11337 (let ((r (downcase (read-char-exclusive))))
11338 (cond
11339 ((equal r ?r)
11340 (org-remove-file file)
11341 (throw 'nextfile t))
11342 (t (error "Abort"))))))
11344 (defun org-get-agenda-file-buffer (file)
11345 "Get a buffer visiting FILE. If the buffer needs to be created, add
11346 it to the list of buffers which might be released later."
11347 (let ((buf (org-find-base-buffer-visiting file)))
11348 (if buf
11349 buf ; just return it
11350 ;; Make a new buffer and remember it
11351 (setq buf (find-file-noselect file))
11352 (if buf (push buf org-agenda-new-buffers))
11353 buf)))
11355 (defun org-release-buffers (blist)
11356 "Release all buffers in list, asking the user for confirmation when needed.
11357 When a buffer is unmodified, it is just killed. When modified, it is saved
11358 \(if the user agrees) and then killed."
11359 (let (buf file)
11360 (while (setq buf (pop blist))
11361 (setq file (buffer-file-name buf))
11362 (when (and (buffer-modified-p buf)
11363 file
11364 (y-or-n-p (format "Save file %s? " file)))
11365 (with-current-buffer buf (save-buffer)))
11366 (kill-buffer buf))))
11368 (defun org-prepare-agenda-buffers (files)
11369 "Create buffers for all agenda files, protect archived trees and comments."
11370 (interactive)
11371 (let ((pa '(:org-archived t))
11372 (pc '(:org-comment t))
11373 (pall '(:org-archived t :org-comment t))
11374 (inhibit-read-only t)
11375 (rea (concat ":" org-archive-tag ":"))
11376 bmp file re)
11377 (save-excursion
11378 (save-restriction
11379 (while (setq file (pop files))
11380 (if (bufferp file)
11381 (set-buffer file)
11382 (org-check-agenda-file file)
11383 (set-buffer (org-get-agenda-file-buffer file)))
11384 (widen)
11385 (setq bmp (buffer-modified-p))
11386 (org-refresh-category-properties)
11387 (setq org-todo-keywords-for-agenda
11388 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11389 (setq org-done-keywords-for-agenda
11390 (append org-done-keywords-for-agenda org-done-keywords))
11391 (save-excursion
11392 (remove-text-properties (point-min) (point-max) pall)
11393 (when org-agenda-skip-archived-trees
11394 (goto-char (point-min))
11395 (while (re-search-forward rea nil t)
11396 (if (org-on-heading-p t)
11397 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11398 (goto-char (point-min))
11399 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11400 (while (re-search-forward re nil t)
11401 (add-text-properties
11402 (match-beginning 0) (org-end-of-subtree t) pc)))
11403 (set-buffer-modified-p bmp))))))
11405 ;;;; Embedded LaTeX
11407 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11408 "Keymap for the minor `org-cdlatex-mode'.")
11410 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11411 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11412 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11413 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11414 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11416 (defvar org-cdlatex-texmathp-advice-is-done nil
11417 "Flag remembering if we have applied the advice to texmathp already.")
11419 (define-minor-mode org-cdlatex-mode
11420 "Toggle the minor `org-cdlatex-mode'.
11421 This mode supports entering LaTeX environment and math in LaTeX fragments
11422 in Org-mode.
11423 \\{org-cdlatex-mode-map}"
11424 nil " OCDL" nil
11425 (when org-cdlatex-mode (require 'cdlatex))
11426 (unless org-cdlatex-texmathp-advice-is-done
11427 (setq org-cdlatex-texmathp-advice-is-done t)
11428 (defadvice texmathp (around org-math-always-on activate)
11429 "Always return t in org-mode buffers.
11430 This is because we want to insert math symbols without dollars even outside
11431 the LaTeX math segments. If Orgmode thinks that point is actually inside
11432 en embedded LaTeX fragement, let texmathp do its job.
11433 \\[org-cdlatex-mode-map]"
11434 (interactive)
11435 (let (p)
11436 (cond
11437 ((not (org-mode-p)) ad-do-it)
11438 ((eq this-command 'cdlatex-math-symbol)
11439 (setq ad-return-value t
11440 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11442 (let ((p (org-inside-LaTeX-fragment-p)))
11443 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11444 (setq ad-return-value t
11445 texmathp-why '("Org-mode embedded math" . 0))
11446 (if p ad-do-it)))))))))
11448 (defun turn-on-org-cdlatex ()
11449 "Unconditionally turn on `org-cdlatex-mode'."
11450 (org-cdlatex-mode 1))
11452 (defun org-inside-LaTeX-fragment-p ()
11453 "Test if point is inside a LaTeX fragment.
11454 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11455 sequence appearing also before point.
11456 Even though the matchers for math are configurable, this function assumes
11457 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11458 delimiters are skipped when they have been removed by customization.
11459 The return value is nil, or a cons cell with the delimiter and
11460 and the position of this delimiter.
11462 This function does a reasonably good job, but can locally be fooled by
11463 for example currency specifications. For example it will assume being in
11464 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11465 fragments that are properly closed, but during editing, we have to live
11466 with the uncertainty caused by missing closing delimiters. This function
11467 looks only before point, not after."
11468 (catch 'exit
11469 (let ((pos (point))
11470 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11471 (lim (progn
11472 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11473 (point)))
11474 dd-on str (start 0) m re)
11475 (goto-char pos)
11476 (when dodollar
11477 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11478 re (nth 1 (assoc "$" org-latex-regexps)))
11479 (while (string-match re str start)
11480 (cond
11481 ((= (match-end 0) (length str))
11482 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11483 ((= (match-end 0) (- (length str) 5))
11484 (throw 'exit nil))
11485 (t (setq start (match-end 0))))))
11486 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11487 (goto-char pos)
11488 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11489 (and (match-beginning 2) (throw 'exit nil))
11490 ;; count $$
11491 (while (re-search-backward "\\$\\$" lim t)
11492 (setq dd-on (not dd-on)))
11493 (goto-char pos)
11494 (if dd-on (cons "$$" m))))))
11497 (defun org-try-cdlatex-tab ()
11498 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11499 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11500 - inside a LaTeX fragment, or
11501 - after the first word in a line, where an abbreviation expansion could
11502 insert a LaTeX environment."
11503 (when org-cdlatex-mode
11504 (cond
11505 ((save-excursion
11506 (skip-chars-backward "a-zA-Z0-9*")
11507 (skip-chars-backward " \t")
11508 (bolp))
11509 (cdlatex-tab) t)
11510 ((org-inside-LaTeX-fragment-p)
11511 (cdlatex-tab) t)
11512 (t nil))))
11514 (defun org-cdlatex-underscore-caret (&optional arg)
11515 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11516 Revert to the normal definition outside of these fragments."
11517 (interactive "P")
11518 (if (org-inside-LaTeX-fragment-p)
11519 (call-interactively 'cdlatex-sub-superscript)
11520 (let (org-cdlatex-mode)
11521 (call-interactively (key-binding (vector last-input-event))))))
11523 (defun org-cdlatex-math-modify (&optional arg)
11524 "Execute `cdlatex-math-modify' in LaTeX fragments.
11525 Revert to the normal definition outside of these fragments."
11526 (interactive "P")
11527 (if (org-inside-LaTeX-fragment-p)
11528 (call-interactively 'cdlatex-math-modify)
11529 (let (org-cdlatex-mode)
11530 (call-interactively (key-binding (vector last-input-event))))))
11532 (defvar org-latex-fragment-image-overlays nil
11533 "List of overlays carrying the images of latex fragments.")
11534 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11536 (defun org-remove-latex-fragment-image-overlays ()
11537 "Remove all overlays with LaTeX fragment images in current buffer."
11538 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11539 (setq org-latex-fragment-image-overlays nil))
11541 (defun org-preview-latex-fragment (&optional subtree)
11542 "Preview the LaTeX fragment at point, or all locally or globally.
11543 If the cursor is in a LaTeX fragment, create the image and overlay
11544 it over the source code. If there is no fragment at point, display
11545 all fragments in the current text, from one headline to the next. With
11546 prefix SUBTREE, display all fragments in the current subtree. With a
11547 double prefix `C-u C-u', or when the cursor is before the first headline,
11548 display all fragments in the buffer.
11549 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11550 (interactive "P")
11551 (org-remove-latex-fragment-image-overlays)
11552 (save-excursion
11553 (save-restriction
11554 (let (beg end at msg)
11555 (cond
11556 ((or (equal subtree '(16))
11557 (not (save-excursion
11558 (re-search-backward (concat "^" outline-regexp) nil t))))
11559 (setq beg (point-min) end (point-max)
11560 msg "Creating images for buffer...%s"))
11561 ((equal subtree '(4))
11562 (org-back-to-heading)
11563 (setq beg (point) end (org-end-of-subtree t)
11564 msg "Creating images for subtree...%s"))
11566 (if (setq at (org-inside-LaTeX-fragment-p))
11567 (goto-char (max (point-min) (- (cdr at) 2)))
11568 (org-back-to-heading))
11569 (setq beg (point) end (progn (outline-next-heading) (point))
11570 msg (if at "Creating image...%s"
11571 "Creating images for entry...%s"))))
11572 (message msg "")
11573 (narrow-to-region beg end)
11574 (goto-char beg)
11575 (org-format-latex
11576 (concat "ltxpng/" (file-name-sans-extension
11577 (file-name-nondirectory
11578 buffer-file-name)))
11579 default-directory 'overlays msg at 'forbuffer)
11580 (message msg "done. Use `C-c C-c' to remove images.")))))
11582 (defvar org-latex-regexps
11583 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11584 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11585 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11586 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11587 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11588 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11589 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11590 "Regular expressions for matching embedded LaTeX.")
11592 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11593 "Replace LaTeX fragments with links to an image, and produce images."
11594 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11595 (let* ((prefixnodir (file-name-nondirectory prefix))
11596 (absprefix (expand-file-name prefix dir))
11597 (todir (file-name-directory absprefix))
11598 (opt org-format-latex-options)
11599 (matchers (plist-get opt :matchers))
11600 (re-list org-latex-regexps)
11601 (cnt 0) txt link beg end re e checkdir
11602 m n block linkfile movefile ov)
11603 ;; Check if there are old images files with this prefix, and remove them
11604 (when (file-directory-p todir)
11605 (mapc 'delete-file
11606 (directory-files
11607 todir 'full
11608 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11609 ;; Check the different regular expressions
11610 (while (setq e (pop re-list))
11611 (setq m (car e) re (nth 1 e) n (nth 2 e)
11612 block (if (nth 3 e) "\n\n" ""))
11613 (when (member m matchers)
11614 (goto-char (point-min))
11615 (while (re-search-forward re nil t)
11616 (when (or (not at) (equal (cdr at) (match-beginning n)))
11617 (setq txt (match-string n)
11618 beg (match-beginning n) end (match-end n)
11619 cnt (1+ cnt)
11620 linkfile (format "%s_%04d.png" prefix cnt)
11621 movefile (format "%s_%04d.png" absprefix cnt)
11622 link (concat block "[[file:" linkfile "]]" block))
11623 (if msg (message msg cnt))
11624 (goto-char beg)
11625 (unless checkdir ; make sure the directory exists
11626 (setq checkdir t)
11627 (or (file-directory-p todir) (make-directory todir)))
11628 (org-create-formula-image
11629 txt movefile opt forbuffer)
11630 (if overlays
11631 (progn
11632 (setq ov (org-make-overlay beg end))
11633 (if (featurep 'xemacs)
11634 (progn
11635 (org-overlay-put ov 'invisible t)
11636 (org-overlay-put
11637 ov 'end-glyph
11638 (make-glyph (vector 'png :file movefile))))
11639 (org-overlay-put
11640 ov 'display
11641 (list 'image :type 'png :file movefile :ascent 'center)))
11642 (push ov org-latex-fragment-image-overlays)
11643 (goto-char end))
11644 (delete-region beg end)
11645 (insert link))))))))
11647 ;; This function borrows from Ganesh Swami's latex2png.el
11648 (defun org-create-formula-image (string tofile options buffer)
11649 (let* ((tmpdir (if (featurep 'xemacs)
11650 (temp-directory)
11651 temporary-file-directory))
11652 (texfilebase (make-temp-name
11653 (expand-file-name "orgtex" tmpdir)))
11654 (texfile (concat texfilebase ".tex"))
11655 (dvifile (concat texfilebase ".dvi"))
11656 (pngfile (concat texfilebase ".png"))
11657 (fnh (if (featurep 'xemacs)
11658 (font-height (get-face-font 'default))
11659 (face-attribute 'default :height nil)))
11660 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11661 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11662 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11663 "Black"))
11664 (bg (or (plist-get options (if buffer :background :html-background))
11665 "Transparent")))
11666 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11667 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11668 (with-temp-file texfile
11669 (insert org-format-latex-header
11670 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11671 (let ((dir default-directory))
11672 (condition-case nil
11673 (progn
11674 (cd tmpdir)
11675 (call-process "latex" nil nil nil texfile))
11676 (error nil))
11677 (cd dir))
11678 (if (not (file-exists-p dvifile))
11679 (progn (message "Failed to create dvi file from %s" texfile) nil)
11680 (call-process "dvipng" nil nil nil
11681 "-E" "-fg" fg "-bg" bg
11682 "-D" dpi
11683 ;;"-x" scale "-y" scale
11684 "-T" "tight"
11685 "-o" pngfile
11686 dvifile)
11687 (if (not (file-exists-p pngfile))
11688 (progn (message "Failed to create png file from %s" texfile) nil)
11689 ;; Use the requested file name and clean up
11690 (copy-file pngfile tofile 'replace)
11691 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11692 (delete-file (concat texfilebase e)))
11693 pngfile))))
11695 (defun org-dvipng-color (attr)
11696 "Return an rgb color specification for dvipng."
11697 (apply 'format "rgb %s %s %s"
11698 (mapcar 'org-normalize-color
11699 (color-values (face-attribute 'default attr nil)))))
11701 (defun org-normalize-color (value)
11702 "Return string to be used as color value for an RGB component."
11703 (format "%g" (/ value 65535.0)))
11706 ;;;; Key bindings
11708 ;; Make `C-c C-x' a prefix key
11709 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11711 ;; TAB key with modifiers
11712 (org-defkey org-mode-map "\C-i" 'org-cycle)
11713 (org-defkey org-mode-map [(tab)] 'org-cycle)
11714 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11715 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11716 (org-defkey org-mode-map "\M-\t" 'org-complete)
11717 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11718 ;; The following line is necessary under Suse GNU/Linux
11719 (unless (featurep 'xemacs)
11720 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11721 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11722 (define-key org-mode-map [backtab] 'org-shifttab)
11724 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11725 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11726 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11728 ;; Cursor keys with modifiers
11729 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11730 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11731 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11732 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11734 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11735 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11736 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11737 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11739 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11740 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11741 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11742 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11744 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11745 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11747 ;;; Extra keys for tty access.
11748 ;; We only set them when really needed because otherwise the
11749 ;; menus don't show the simple keys
11751 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11752 (not window-system))
11753 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11754 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11755 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11756 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11757 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11758 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11759 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11760 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11761 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11762 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11763 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11764 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11765 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11766 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11767 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11768 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11769 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11770 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11771 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11772 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11773 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11774 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11776 ;; All the other keys
11778 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11779 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11780 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11781 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11782 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11783 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11784 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11785 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11786 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11787 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11788 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11789 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11790 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11791 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11792 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11793 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11794 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11795 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11796 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11797 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11798 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11799 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11800 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11801 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11802 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11803 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11804 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11805 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11806 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11807 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11808 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11809 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11810 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11811 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11812 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11813 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11814 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11815 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11816 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11817 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11818 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11819 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11820 (org-defkey org-mode-map "\C-c^" 'org-sort)
11821 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11822 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11823 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11824 (org-defkey org-mode-map "\C-m" 'org-return)
11825 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11826 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11827 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11828 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11829 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11830 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11831 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11832 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11833 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11834 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11835 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11836 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11837 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11838 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11839 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11840 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11842 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11843 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11844 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11845 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11847 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11848 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11849 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11850 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11851 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11852 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11853 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11854 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11855 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11856 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11857 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11858 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11860 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11862 (when (featurep 'xemacs)
11863 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11865 (defvar org-table-auto-blank-field) ; defined in org-table.el
11866 (defun org-self-insert-command (N)
11867 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11868 If the cursor is in a table looking at whitespace, the whitespace is
11869 overwritten, and the table is not marked as requiring realignment."
11870 (interactive "p")
11871 (if (and (org-table-p)
11872 (progn
11873 ;; check if we blank the field, and if that triggers align
11874 (and (featurep 'org-table) org-table-auto-blank-field
11875 (member last-command
11876 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11877 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11878 ;; got extra space, this field does not determine column width
11879 (let (org-table-may-need-update) (org-table-blank-field))
11880 ;; no extra space, this field may determine column width
11881 (org-table-blank-field)))
11883 (eq N 1)
11884 (looking-at "[^|\n]* |"))
11885 (let (org-table-may-need-update)
11886 (goto-char (1- (match-end 0)))
11887 (delete-backward-char 1)
11888 (goto-char (match-beginning 0))
11889 (self-insert-command N))
11890 (setq org-table-may-need-update t)
11891 (self-insert-command N)
11892 (org-fix-tags-on-the-fly)))
11894 (defun org-fix-tags-on-the-fly ()
11895 (when (and (equal (char-after (point-at-bol)) ?*)
11896 (org-on-heading-p))
11897 (org-align-tags-here org-tags-column)))
11899 (defun org-delete-backward-char (N)
11900 "Like `delete-backward-char', insert whitespace at field end in tables.
11901 When deleting backwards, in tables this function will insert whitespace in
11902 front of the next \"|\" separator, to keep the table aligned. The table will
11903 still be marked for re-alignment if the field did fill the entire column,
11904 because, in this case the deletion might narrow the column."
11905 (interactive "p")
11906 (if (and (org-table-p)
11907 (eq N 1)
11908 (string-match "|" (buffer-substring (point-at-bol) (point)))
11909 (looking-at ".*?|"))
11910 (let ((pos (point))
11911 (noalign (looking-at "[^|\n\r]* |"))
11912 (c org-table-may-need-update))
11913 (backward-delete-char N)
11914 (skip-chars-forward "^|")
11915 (insert " ")
11916 (goto-char (1- pos))
11917 ;; noalign: if there were two spaces at the end, this field
11918 ;; does not determine the width of the column.
11919 (if noalign (setq org-table-may-need-update c)))
11920 (backward-delete-char N)
11921 (org-fix-tags-on-the-fly)))
11923 (defun org-delete-char (N)
11924 "Like `delete-char', but insert whitespace at field end in tables.
11925 When deleting characters, in tables this function will insert whitespace in
11926 front of the next \"|\" separator, to keep the table aligned. The table will
11927 still be marked for re-alignment if the field did fill the entire column,
11928 because, in this case the deletion might narrow the column."
11929 (interactive "p")
11930 (if (and (org-table-p)
11931 (not (bolp))
11932 (not (= (char-after) ?|))
11933 (eq N 1))
11934 (if (looking-at ".*?|")
11935 (let ((pos (point))
11936 (noalign (looking-at "[^|\n\r]* |"))
11937 (c org-table-may-need-update))
11938 (replace-match (concat
11939 (substring (match-string 0) 1 -1)
11940 " |"))
11941 (goto-char pos)
11942 ;; noalign: if there were two spaces at the end, this field
11943 ;; does not determine the width of the column.
11944 (if noalign (setq org-table-may-need-update c)))
11945 (delete-char N))
11946 (delete-char N)
11947 (org-fix-tags-on-the-fly)))
11949 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11950 (put 'org-self-insert-command 'delete-selection t)
11951 (put 'orgtbl-self-insert-command 'delete-selection t)
11952 (put 'org-delete-char 'delete-selection 'supersede)
11953 (put 'org-delete-backward-char 'delete-selection 'supersede)
11955 ;; Make `flyspell-mode' delay after some commands
11956 (put 'org-self-insert-command 'flyspell-delayed t)
11957 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11958 (put 'org-delete-char 'flyspell-delayed t)
11959 (put 'org-delete-backward-char 'flyspell-delayed t)
11961 ;; Make pabbrev-mode expand after org-mode commands
11962 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11963 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11965 ;; How to do this: Measure non-white length of current string
11966 ;; If equal to column width, we should realign.
11968 (defun org-remap (map &rest commands)
11969 "In MAP, remap the functions given in COMMANDS.
11970 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11971 (let (new old)
11972 (while commands
11973 (setq old (pop commands) new (pop commands))
11974 (if (fboundp 'command-remapping)
11975 (org-defkey map (vector 'remap old) new)
11976 (substitute-key-definition old new map global-map)))))
11978 (when (eq org-enable-table-editor 'optimized)
11979 ;; If the user wants maximum table support, we need to hijack
11980 ;; some standard editing functions
11981 (org-remap org-mode-map
11982 'self-insert-command 'org-self-insert-command
11983 'delete-char 'org-delete-char
11984 'delete-backward-char 'org-delete-backward-char)
11985 (org-defkey org-mode-map "|" 'org-force-self-insert))
11987 (defun org-shiftcursor-error ()
11988 "Throw an error because Shift-Cursor command was applied in wrong context."
11989 (error "This command is active in special context like tables, headlines or timestamps"))
11991 (defun org-shifttab (&optional arg)
11992 "Global visibility cycling or move to previous table field.
11993 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11994 on context.
11995 See the individual commands for more information."
11996 (interactive "P")
11997 (cond
11998 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11999 (arg (message "Content view to level: ")
12000 (org-content (prefix-numeric-value arg))
12001 (setq org-cycle-global-status 'overview))
12002 (t (call-interactively 'org-global-cycle))))
12004 (defun org-shiftmetaleft ()
12005 "Promote subtree or delete table column.
12006 Calls `org-promote-subtree', `org-outdent-item',
12007 or `org-table-delete-column', depending on context.
12008 See the individual commands for more information."
12009 (interactive)
12010 (cond
12011 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12012 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12013 ((org-at-item-p) (call-interactively 'org-outdent-item))
12014 (t (org-shiftcursor-error))))
12016 (defun org-shiftmetaright ()
12017 "Demote subtree or insert table column.
12018 Calls `org-demote-subtree', `org-indent-item',
12019 or `org-table-insert-column', depending on context.
12020 See the individual commands for more information."
12021 (interactive)
12022 (cond
12023 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12024 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12025 ((org-at-item-p) (call-interactively 'org-indent-item))
12026 (t (org-shiftcursor-error))))
12028 (defun org-shiftmetaup (&optional arg)
12029 "Move subtree up or kill table row.
12030 Calls `org-move-subtree-up' or `org-table-kill-row' or
12031 `org-move-item-up' depending on context. See the individual commands
12032 for more information."
12033 (interactive "P")
12034 (cond
12035 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12036 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12037 ((org-at-item-p) (call-interactively 'org-move-item-up))
12038 (t (org-shiftcursor-error))))
12039 (defun org-shiftmetadown (&optional arg)
12040 "Move subtree down or insert table row.
12041 Calls `org-move-subtree-down' or `org-table-insert-row' or
12042 `org-move-item-down', depending on context. See the individual
12043 commands for more information."
12044 (interactive "P")
12045 (cond
12046 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12047 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12048 ((org-at-item-p) (call-interactively 'org-move-item-down))
12049 (t (org-shiftcursor-error))))
12051 (defun org-metaleft (&optional arg)
12052 "Promote heading or move table column to left.
12053 Calls `org-do-promote' or `org-table-move-column', depending on context.
12054 With no specific context, calls the Emacs default `backward-word'.
12055 See the individual commands for more information."
12056 (interactive "P")
12057 (cond
12058 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12059 ((or (org-on-heading-p) (org-region-active-p))
12060 (call-interactively 'org-do-promote))
12061 ((org-at-item-p) (call-interactively 'org-outdent-item))
12062 (t (call-interactively 'backward-word))))
12064 (defun org-metaright (&optional arg)
12065 "Demote subtree or move table column to right.
12066 Calls `org-do-demote' or `org-table-move-column', depending on context.
12067 With no specific context, calls the Emacs default `forward-word'.
12068 See the individual commands for more information."
12069 (interactive "P")
12070 (cond
12071 ((org-at-table-p) (call-interactively 'org-table-move-column))
12072 ((or (org-on-heading-p) (org-region-active-p))
12073 (call-interactively 'org-do-demote))
12074 ((org-at-item-p) (call-interactively 'org-indent-item))
12075 (t (call-interactively 'forward-word))))
12077 (defun org-metaup (&optional arg)
12078 "Move subtree up or move table row up.
12079 Calls `org-move-subtree-up' or `org-table-move-row' or
12080 `org-move-item-up', depending on context. See the individual commands
12081 for more information."
12082 (interactive "P")
12083 (cond
12084 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12085 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12086 ((org-at-item-p) (call-interactively 'org-move-item-up))
12087 (t (transpose-lines 1) (beginning-of-line -1))))
12089 (defun org-metadown (&optional arg)
12090 "Move subtree down or move table row down.
12091 Calls `org-move-subtree-down' or `org-table-move-row' or
12092 `org-move-item-down', depending on context. See the individual
12093 commands for more information."
12094 (interactive "P")
12095 (cond
12096 ((org-at-table-p) (call-interactively 'org-table-move-row))
12097 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12098 ((org-at-item-p) (call-interactively 'org-move-item-down))
12099 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12101 (defun org-shiftup (&optional arg)
12102 "Increase item in timestamp or increase priority of current headline.
12103 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12104 depending on context. See the individual commands for more information."
12105 (interactive "P")
12106 (cond
12107 ((org-at-timestamp-p t)
12108 (call-interactively (if org-edit-timestamp-down-means-later
12109 'org-timestamp-down 'org-timestamp-up)))
12110 ((org-on-heading-p) (call-interactively 'org-priority-up))
12111 ((org-at-item-p) (call-interactively 'org-previous-item))
12112 ((org-clocktable-try-shift 'up arg))
12113 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12115 (defun org-shiftdown (&optional arg)
12116 "Decrease item in timestamp or decrease priority of current headline.
12117 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12118 depending on context. See the individual commands for more information."
12119 (interactive "P")
12120 (cond
12121 ((org-at-timestamp-p t)
12122 (call-interactively (if org-edit-timestamp-down-means-later
12123 'org-timestamp-up 'org-timestamp-down)))
12124 ((org-on-heading-p) (call-interactively 'org-priority-down))
12125 ((org-clocktable-try-shift 'down arg))
12126 (t (call-interactively 'org-next-item))))
12128 (defun org-shiftright (&optional arg)
12129 "Next TODO keyword or timestamp one day later, depending on context."
12130 (interactive "P")
12131 (cond
12132 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12133 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12134 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12135 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12136 ((org-clocktable-try-shift 'right arg))
12137 (t (org-shiftcursor-error))))
12139 (defun org-shiftleft (&optional arg)
12140 "Previous TODO keyword or timestamp one day earlier, depending on context."
12141 (interactive "P")
12142 (cond
12143 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12144 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12145 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12146 ((org-at-property-p)
12147 (call-interactively 'org-property-previous-allowed-value))
12148 ((org-clocktable-try-shift 'left arg))
12149 (t (org-shiftcursor-error))))
12151 (defun org-shiftcontrolright ()
12152 "Switch to next TODO set."
12153 (interactive)
12154 (cond
12155 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12156 (t (org-shiftcursor-error))))
12158 (defun org-shiftcontrolleft ()
12159 "Switch to previous TODO set."
12160 (interactive)
12161 (cond
12162 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12163 (t (org-shiftcursor-error))))
12165 (defun org-ctrl-c-ret ()
12166 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12167 (interactive)
12168 (cond
12169 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12170 (t (call-interactively 'org-insert-heading))))
12172 (defun org-copy-special ()
12173 "Copy region in table or copy current subtree.
12174 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12175 See the individual commands for more information."
12176 (interactive)
12177 (call-interactively
12178 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12180 (defun org-cut-special ()
12181 "Cut region in table or cut current subtree.
12182 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12183 See the individual commands for more information."
12184 (interactive)
12185 (call-interactively
12186 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12188 (defun org-paste-special (arg)
12189 "Paste rectangular region into table, or past subtree relative to level.
12190 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12191 See the individual commands for more information."
12192 (interactive "P")
12193 (if (org-at-table-p)
12194 (org-table-paste-rectangle)
12195 (org-paste-subtree arg)))
12197 (defun org-ctrl-c-ctrl-c (&optional arg)
12198 "Set tags in headline, or update according to changed information at point.
12200 This command does many different things, depending on context:
12202 - If the cursor is in a headline, prompt for tags and insert them
12203 into the current line, aligned to `org-tags-column'. When called
12204 with prefix arg, realign all tags in the current buffer.
12206 - If the cursor is in one of the special #+KEYWORD lines, this
12207 triggers scanning the buffer for these lines and updating the
12208 information.
12210 - If the cursor is inside a table, realign the table. This command
12211 works even if the automatic table editor has been turned off.
12213 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12214 the entire table.
12216 - If the cursor is a the beginning of a dynamic block, update it.
12218 - If the cursor is inside a table created by the table.el package,
12219 activate that table.
12221 - If the current buffer is a remember buffer, close note and file it.
12222 with a prefix argument, file it without further interaction to the default
12223 location.
12225 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12226 links in this buffer.
12228 - If the cursor is on a numbered item in a plain list, renumber the
12229 ordered list.
12231 - If the cursor is on a checkbox, toggle it."
12232 (interactive "P")
12233 (let ((org-enable-table-editor t))
12234 (cond
12235 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12236 org-occur-highlights
12237 org-latex-fragment-image-overlays)
12238 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12239 (org-remove-occur-highlights)
12240 (org-remove-latex-fragment-image-overlays)
12241 (message "Temporary highlights/overlays removed from current buffer"))
12242 ((and (local-variable-p 'org-finish-function (current-buffer))
12243 (fboundp org-finish-function))
12244 (funcall org-finish-function))
12245 ((org-at-property-p)
12246 (call-interactively 'org-property-action))
12247 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12248 ((org-on-heading-p) (call-interactively 'org-set-tags))
12249 ((org-at-table.el-p)
12250 (require 'table)
12251 (beginning-of-line 1)
12252 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12253 (call-interactively 'table-recognize-table))
12254 ((org-at-table-p)
12255 (org-table-maybe-eval-formula)
12256 (if arg
12257 (call-interactively 'org-table-recalculate)
12258 (org-table-maybe-recalculate-line))
12259 (call-interactively 'org-table-align))
12260 ((org-at-item-checkbox-p)
12261 (call-interactively 'org-toggle-checkbox))
12262 ((org-at-item-p)
12263 (call-interactively 'org-maybe-renumber-ordered-list))
12264 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12265 ;; Dynamic block
12266 (beginning-of-line 1)
12267 (org-update-dblock))
12268 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12269 (cond
12270 ((equal (match-string 1) "TBLFM")
12271 ;; Recalculate the table before this line
12272 (save-excursion
12273 (beginning-of-line 1)
12274 (skip-chars-backward " \r\n\t")
12275 (if (org-at-table-p)
12276 (org-call-with-arg 'org-table-recalculate t))))
12278 (call-interactively 'org-mode-restart))))
12279 (t (error "C-c C-c can do nothing useful at this location.")))))
12281 (defun org-mode-restart ()
12282 "Restart Org-mode, to scan again for special lines.
12283 Also updates the keyword regular expressions."
12284 (interactive)
12285 (let ((org-inhibit-startup t)) (org-mode))
12286 (message "Org-mode restarted to refresh keyword and special line setup"))
12288 (defun org-kill-note-or-show-branches ()
12289 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12290 (interactive)
12291 (if (not org-finish-function)
12292 (call-interactively 'show-branches)
12293 (let ((org-note-abort t))
12294 (funcall org-finish-function))))
12296 (defun org-return (&optional indent)
12297 "Goto next table row or insert a newline.
12298 Calls `org-table-next-row' or `newline', depending on context.
12299 See the individual commands for more information."
12300 (interactive)
12301 (cond
12302 ((bobp) (if indent (newline-and-indent) (newline)))
12303 ((and (org-at-heading-p)
12304 (looking-at
12305 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12306 (org-show-entry)
12307 (end-of-line 1)
12308 (newline))
12309 ((org-at-table-p)
12310 (org-table-justify-field-maybe)
12311 (call-interactively 'org-table-next-row))
12312 (t (if indent (newline-and-indent) (newline)))))
12314 (defun org-return-indent ()
12315 "Goto next table row or insert a newline and indent.
12316 Calls `org-table-next-row' or `newline-and-indent', depending on
12317 context. See the individual commands for more information."
12318 (interactive)
12319 (org-return t))
12321 (defun org-ctrl-c-star ()
12322 "Compute table, or change heading status of lines.
12323 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12324 depending on context. This will also turn a plain list item or a normal
12325 line into a subheading."
12326 (interactive)
12327 (cond
12328 ((org-at-table-p)
12329 (call-interactively 'org-table-recalculate))
12330 ((org-region-active-p)
12331 ;; Convert all lines in region to list items
12332 (call-interactively 'org-toggle-region-headings))
12333 ((org-on-heading-p)
12334 (org-toggle-region-headings (point-at-bol)
12335 (min (1+ (point-at-eol)) (point-max))))
12336 ((org-at-item-p)
12337 ;; Convert to heading
12338 (let ((level (save-match-data
12339 (save-excursion
12340 (condition-case nil
12341 (progn
12342 (org-back-to-heading t)
12343 (funcall outline-level))
12344 (error 0))))))
12345 (replace-match
12346 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12347 (t (org-toggle-region-headings (point-at-bol)
12348 (min (1+ (point-at-eol)) (point-max))))))
12350 (defun org-ctrl-c-minus ()
12351 "Insert separator line in table or modify bullet status of line.
12352 Also turns a plain line or a region of lines into list items.
12353 Calls `org-table-insert-hline', `org-toggle-region-items', or
12354 `org-cycle-list-bullet', depending on context."
12355 (interactive)
12356 (cond
12357 ((org-at-table-p)
12358 (call-interactively 'org-table-insert-hline))
12359 ((org-on-heading-p)
12360 ;; Convert to item
12361 (save-excursion
12362 (beginning-of-line 1)
12363 (if (looking-at "\\*+ ")
12364 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12365 ((org-region-active-p)
12366 ;; Convert all lines in region to list items
12367 (call-interactively 'org-toggle-region-items))
12368 ((org-in-item-p)
12369 (call-interactively 'org-cycle-list-bullet))
12370 (t (org-toggle-region-items (point-at-bol)
12371 (min (1+ (point-at-eol)) (point-max))))))
12373 (defun org-toggle-region-items (beg end)
12374 "Convert all lines in region to list items.
12375 If the first line is already an item, convert all list items in the region
12376 to normal lines."
12377 (interactive "r")
12378 (let (l2 l)
12379 (save-excursion
12380 (goto-char end)
12381 (setq l2 (org-current-line))
12382 (goto-char beg)
12383 (beginning-of-line 1)
12384 (setq l (1- (org-current-line)))
12385 (if (org-at-item-p)
12386 ;; We already have items, de-itemize
12387 (while (< (setq l (1+ l)) l2)
12388 (when (org-at-item-p)
12389 (goto-char (match-beginning 2))
12390 (delete-region (match-beginning 2) (match-end 2))
12391 (and (looking-at "[ \t]+") (replace-match "")))
12392 (beginning-of-line 2))
12393 (while (< (setq l (1+ l)) l2)
12394 (unless (org-at-item-p)
12395 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12396 (replace-match "\\1- \\2")))
12397 (beginning-of-line 2))))))
12399 (defun org-toggle-region-headings (beg end)
12400 "Convert all lines in region to list items.
12401 If the first line is already an item, convert all list items in the region
12402 to normal lines."
12403 (interactive "r")
12404 (let (l2 l)
12405 (save-excursion
12406 (goto-char end)
12407 (setq l2 (org-current-line))
12408 (goto-char beg)
12409 (beginning-of-line 1)
12410 (setq l (1- (org-current-line)))
12411 (if (org-on-heading-p)
12412 ;; We already have headlines, de-star them
12413 (while (< (setq l (1+ l)) l2)
12414 (when (org-on-heading-p t)
12415 (and (looking-at outline-regexp) (replace-match "")))
12416 (beginning-of-line 2))
12417 (let* ((stars (save-excursion
12418 (re-search-backward org-complex-heading-regexp nil t)
12419 (or (match-string 1) "*")))
12420 (add-stars (if org-odd-levels-only "**" "*"))
12421 (rpl (concat stars add-stars " \\2")))
12422 (while (< (setq l (1+ l)) l2)
12423 (unless (org-on-heading-p)
12424 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12425 (replace-match rpl)))
12426 (beginning-of-line 2)))))))
12428 (defun org-meta-return (&optional arg)
12429 "Insert a new heading or wrap a region in a table.
12430 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12431 See the individual commands for more information."
12432 (interactive "P")
12433 (cond
12434 ((org-at-table-p)
12435 (call-interactively 'org-table-wrap-region))
12436 (t (call-interactively 'org-insert-heading))))
12438 ;;; Menu entries
12440 ;; Define the Org-mode menus
12441 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12442 '("Tbl"
12443 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12444 ["Next Field" org-cycle (org-at-table-p)]
12445 ["Previous Field" org-shifttab (org-at-table-p)]
12446 ["Next Row" org-return (org-at-table-p)]
12447 "--"
12448 ["Blank Field" org-table-blank-field (org-at-table-p)]
12449 ["Edit Field" org-table-edit-field (org-at-table-p)]
12450 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12451 "--"
12452 ("Column"
12453 ["Move Column Left" org-metaleft (org-at-table-p)]
12454 ["Move Column Right" org-metaright (org-at-table-p)]
12455 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12456 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12457 ("Row"
12458 ["Move Row Up" org-metaup (org-at-table-p)]
12459 ["Move Row Down" org-metadown (org-at-table-p)]
12460 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12461 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12462 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12463 "--"
12464 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12465 ("Rectangle"
12466 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12467 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12468 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12469 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12470 "--"
12471 ("Calculate"
12472 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12473 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12474 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12475 "--"
12476 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12477 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12478 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12479 "--"
12480 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12481 "--"
12482 ["Sum Column/Rectangle" org-table-sum
12483 (or (org-at-table-p) (org-region-active-p))]
12484 ["Which Column?" org-table-current-column (org-at-table-p)])
12485 ["Debug Formulas"
12486 org-table-toggle-formula-debugger
12487 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12488 ["Show Col/Row Numbers"
12489 org-table-toggle-coordinate-overlays
12490 :style toggle
12491 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12492 "--"
12493 ["Create" org-table-create (and (not (org-at-table-p))
12494 org-enable-table-editor)]
12495 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12496 ["Import from File" org-table-import (not (org-at-table-p))]
12497 ["Export to File" org-table-export (org-at-table-p)]
12498 "--"
12499 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12501 (easy-menu-define org-org-menu org-mode-map "Org menu"
12502 '("Org"
12503 ("Show/Hide"
12504 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12505 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12506 ["Sparse Tree..." org-sparse-tree t]
12507 ["Reveal Context" org-reveal t]
12508 ["Show All" show-all t]
12509 "--"
12510 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12511 "--"
12512 ["New Heading" org-insert-heading t]
12513 ("Navigate Headings"
12514 ["Up" outline-up-heading t]
12515 ["Next" outline-next-visible-heading t]
12516 ["Previous" outline-previous-visible-heading t]
12517 ["Next Same Level" outline-forward-same-level t]
12518 ["Previous Same Level" outline-backward-same-level t]
12519 "--"
12520 ["Jump" org-goto t])
12521 ("Edit Structure"
12522 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12523 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12524 "--"
12525 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12526 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12527 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12528 "--"
12529 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12530 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12531 ["Demote Heading" org-metaright (not (org-at-table-p))]
12532 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12533 "--"
12534 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12535 "--"
12536 ["Convert to odd levels" org-convert-to-odd-levels t]
12537 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12538 ("Editing"
12539 ["Emphasis..." org-emphasize t])
12540 ("Archive"
12541 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12542 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12543 ; :active t :keys "C-u C-c C-x C-a"]
12544 ["Sparse trees open ARCHIVE trees"
12545 (setq org-sparse-tree-open-archived-trees
12546 (not org-sparse-tree-open-archived-trees))
12547 :style toggle :selected org-sparse-tree-open-archived-trees]
12548 ["Cycling opens ARCHIVE trees"
12549 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12550 :style toggle :selected org-cycle-open-archived-trees]
12551 ["Agenda includes ARCHIVE trees"
12552 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12553 :style toggle :selected (not org-agenda-skip-archived-trees)]
12554 "--"
12555 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12556 ; ["Check and Move Children" (org-archive-subtree '(4))
12557 ; :active t :keys "C-u C-c C-x C-s"]
12559 "--"
12560 ("TODO Lists"
12561 ["TODO/DONE/-" org-todo t]
12562 ("Select keyword"
12563 ["Next keyword" org-shiftright (org-on-heading-p)]
12564 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12565 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12566 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12567 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12568 ["Show TODO Tree" org-show-todo-tree t]
12569 ["Global TODO list" org-todo-list t]
12570 "--"
12571 ["Set Priority" org-priority t]
12572 ["Priority Up" org-shiftup t]
12573 ["Priority Down" org-shiftdown t])
12574 ("TAGS and Properties"
12575 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12576 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12577 "--"
12578 ["Set property" 'org-set-property t]
12579 ["Column view of properties" org-columns t]
12580 ["Insert Column View DBlock" org-insert-columns-dblock t])
12581 ("Dates and Scheduling"
12582 ["Timestamp" org-time-stamp t]
12583 ["Timestamp (inactive)" org-time-stamp-inactive t]
12584 ("Change Date"
12585 ["1 Day Later" org-shiftright t]
12586 ["1 Day Earlier" org-shiftleft t]
12587 ["1 ... Later" org-shiftup t]
12588 ["1 ... Earlier" org-shiftdown t])
12589 ["Compute Time Range" org-evaluate-time-range t]
12590 ["Schedule Item" org-schedule t]
12591 ["Deadline" org-deadline t]
12592 "--"
12593 ["Custom time format" org-toggle-time-stamp-overlays
12594 :style radio :selected org-display-custom-times]
12595 "--"
12596 ["Goto Calendar" org-goto-calendar t]
12597 ["Date from Calendar" org-date-from-calendar t])
12598 ("Logging work"
12599 ["Clock in" org-clock-in t]
12600 ["Clock out" org-clock-out t]
12601 ["Clock cancel" org-clock-cancel t]
12602 ["Goto running clock" org-clock-goto t]
12603 ["Display times" org-clock-display t]
12604 ["Create clock table" org-clock-report t]
12605 "--"
12606 ["Record DONE time"
12607 (progn (setq org-log-done (not org-log-done))
12608 (message "Switching to %s will %s record a timestamp"
12609 (car org-done-keywords)
12610 (if org-log-done "automatically" "not")))
12611 :style toggle :selected org-log-done])
12612 "--"
12613 ["Agenda Command..." org-agenda t]
12614 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12615 ("File List for Agenda")
12616 ("Special views current file"
12617 ["TODO Tree" org-show-todo-tree t]
12618 ["Check Deadlines" org-check-deadlines t]
12619 ["Timeline" org-timeline t]
12620 ["Tags Tree" org-tags-sparse-tree t])
12621 "--"
12622 ("Hyperlinks"
12623 ["Store Link (Global)" org-store-link t]
12624 ["Insert Link" org-insert-link t]
12625 ["Follow Link" org-open-at-point t]
12626 "--"
12627 ["Next link" org-next-link t]
12628 ["Previous link" org-previous-link t]
12629 "--"
12630 ["Descriptive Links"
12631 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12632 :style radio
12633 :selected (member '(org-link) buffer-invisibility-spec)]
12634 ["Literal Links"
12635 (progn
12636 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12637 :style radio
12638 :selected (not (member '(org-link) buffer-invisibility-spec))])
12639 "--"
12640 ["Export/Publish..." org-export t]
12641 ("LaTeX"
12642 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12643 :selected org-cdlatex-mode]
12644 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12645 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12646 ["Modify math symbol" org-cdlatex-math-modify
12647 (org-inside-LaTeX-fragment-p)]
12648 ["Export LaTeX fragments as images"
12649 (if (featurep 'org-exp)
12650 (setq org-export-with-LaTeX-fragments
12651 (not org-export-with-LaTeX-fragments))
12652 (require 'org-exp))
12653 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12654 org-export-with-LaTeX-fragments)])
12655 "--"
12656 ("Documentation"
12657 ["Show Version" org-version t]
12658 ["Info Documentation" org-info t])
12659 ("Customize"
12660 ["Browse Org Group" org-customize t]
12661 "--"
12662 ["Expand This Menu" org-create-customize-menu
12663 (fboundp 'customize-menu-create)])
12664 "--"
12665 ["Refresh setup" org-mode-restart t]
12668 (defun org-info (&optional node)
12669 "Read documentation for Org-mode in the info system.
12670 With optional NODE, go directly to that node."
12671 (interactive)
12672 (info (format "(org)%s" (or node ""))))
12674 (defun org-install-agenda-files-menu ()
12675 (let ((bl (buffer-list)))
12676 (save-excursion
12677 (while bl
12678 (set-buffer (pop bl))
12679 (if (org-mode-p) (setq bl nil)))
12680 (when (org-mode-p)
12681 (easy-menu-change
12682 '("Org") "File List for Agenda"
12683 (append
12684 (list
12685 ["Edit File List" (org-edit-agenda-file-list) t]
12686 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12687 ["Remove Current File from List" org-remove-file t]
12688 ["Cycle through agenda files" org-cycle-agenda-files t]
12689 ["Occur in all agenda files" org-occur-in-agenda-files t]
12690 "--")
12691 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12693 ;;;; Documentation
12695 (defun org-require-autoloaded-modules ()
12696 (interactive)
12697 (mapc 'require
12698 '(org-agenda org-archive org-clock org-colview
12699 org-exp org-export-latex org-publish
12700 org-remember org-table)))
12702 (defun org-customize ()
12703 "Call the customize function with org as argument."
12704 (interactive)
12705 (org-load-modules-maybe)
12706 (org-require-autoloaded-modules)
12707 (customize-browse 'org))
12709 (defun org-create-customize-menu ()
12710 "Create a full customization menu for Org-mode, insert it into the menu."
12711 (interactive)
12712 (org-load-modules-maybe)
12713 (org-require-autoloaded-modules)
12714 (if (fboundp 'customize-menu-create)
12715 (progn
12716 (easy-menu-change
12717 '("Org") "Customize"
12718 `(["Browse Org group" org-customize t]
12719 "--"
12720 ,(customize-menu-create 'org)
12721 ["Set" Custom-set t]
12722 ["Save" Custom-save t]
12723 ["Reset to Current" Custom-reset-current t]
12724 ["Reset to Saved" Custom-reset-saved t]
12725 ["Reset to Standard Settings" Custom-reset-standard t]))
12726 (message "\"Org\"-menu now contains full customization menu"))
12727 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12729 ;;;; Miscellaneous stuff
12731 ;;; Generally useful functions
12733 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12734 "Display the given MESSAGE as a warning."
12735 (if (fboundp 'display-warning)
12736 (display-warning 'org message
12737 (if (featurep 'xemacs)
12738 'warning
12739 :warning))
12740 (let ((buf (get-buffer-create "*Org warnings*")))
12741 (with-current-buffer buf
12742 (goto-char (point-max))
12743 (insert "Warning (Org): " message)
12744 (unless (bolp)
12745 (newline)))
12746 (display-buffer buf)
12747 (sit-for 0))))
12749 (defun org-plist-delete (plist property)
12750 "Delete PROPERTY from PLIST.
12751 This is in contrast to merely setting it to 0."
12752 (let (p)
12753 (while plist
12754 (if (not (eq property (car plist)))
12755 (setq p (plist-put p (car plist) (nth 1 plist))))
12756 (setq plist (cddr plist)))
12759 (defun org-force-self-insert (N)
12760 "Needed to enforce self-insert under remapping."
12761 (interactive "p")
12762 (self-insert-command N))
12764 (defun org-string-width (s)
12765 "Compute width of string, ignoring invisible characters.
12766 This ignores character with invisibility property `org-link', and also
12767 characters with property `org-cwidth', because these will become invisible
12768 upon the next fontification round."
12769 (let (b l)
12770 (when (or (eq t buffer-invisibility-spec)
12771 (assq 'org-link buffer-invisibility-spec))
12772 (while (setq b (text-property-any 0 (length s)
12773 'invisible 'org-link s))
12774 (setq s (concat (substring s 0 b)
12775 (substring s (or (next-single-property-change
12776 b 'invisible s) (length s)))))))
12777 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12778 (setq s (concat (substring s 0 b)
12779 (substring s (or (next-single-property-change
12780 b 'org-cwidth s) (length s))))))
12781 (setq l (string-width s) b -1)
12782 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12783 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12786 (defun org-base-buffer (buffer)
12787 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12788 (if (not buffer)
12789 buffer
12790 (or (buffer-base-buffer buffer)
12791 buffer)))
12793 (defun org-trim (s)
12794 "Remove whitespace at beginning and end of string."
12795 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12796 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12799 (defun org-wrap (string &optional width lines)
12800 "Wrap string to either a number of lines, or a width in characters.
12801 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12802 that costs. If there is a word longer than WIDTH, the text is actually
12803 wrapped to the length of that word.
12804 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12805 many lines, whatever width that takes.
12806 The return value is a list of lines, without newlines at the end."
12807 (let* ((words (org-split-string string "[ \t\n]+"))
12808 (maxword (apply 'max (mapcar 'org-string-width words)))
12809 w ll)
12810 (cond (width
12811 (org-do-wrap words (max maxword width)))
12812 (lines
12813 (setq w maxword)
12814 (setq ll (org-do-wrap words maxword))
12815 (if (<= (length ll) lines)
12817 (setq ll words)
12818 (while (> (length ll) lines)
12819 (setq w (1+ w))
12820 (setq ll (org-do-wrap words w)))
12821 ll))
12822 (t (error "Cannot wrap this")))))
12824 (defun org-do-wrap (words width)
12825 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12826 (let (lines line)
12827 (while words
12828 (setq line (pop words))
12829 (while (and words (< (+ (length line) (length (car words))) width))
12830 (setq line (concat line " " (pop words))))
12831 (setq lines (push line lines)))
12832 (nreverse lines)))
12834 (defun org-split-string (string &optional separators)
12835 "Splits STRING into substrings at SEPARATORS.
12836 No empty strings are returned if there are matches at the beginning
12837 and end of string."
12838 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12839 (start 0)
12840 notfirst
12841 (list nil))
12842 (while (and (string-match rexp string
12843 (if (and notfirst
12844 (= start (match-beginning 0))
12845 (< start (length string)))
12846 (1+ start) start))
12847 (< (match-beginning 0) (length string)))
12848 (setq notfirst t)
12849 (or (eq (match-beginning 0) 0)
12850 (and (eq (match-beginning 0) (match-end 0))
12851 (eq (match-beginning 0) start))
12852 (setq list
12853 (cons (substring string start (match-beginning 0))
12854 list)))
12855 (setq start (match-end 0)))
12856 (or (eq start (length string))
12857 (setq list
12858 (cons (substring string start)
12859 list)))
12860 (nreverse list)))
12862 (defun org-context ()
12863 "Return a list of contexts of the current cursor position.
12864 If several contexts apply, all are returned.
12865 Each context entry is a list with a symbol naming the context, and
12866 two positions indicating start and end of the context. Possible
12867 contexts are:
12869 :headline anywhere in a headline
12870 :headline-stars on the leading stars in a headline
12871 :todo-keyword on a TODO keyword (including DONE) in a headline
12872 :tags on the TAGS in a headline
12873 :priority on the priority cookie in a headline
12874 :item on the first line of a plain list item
12875 :item-bullet on the bullet/number of a plain list item
12876 :checkbox on the checkbox in a plain list item
12877 :table in an org-mode table
12878 :table-special on a special filed in a table
12879 :table-table in a table.el table
12880 :link on a hyperlink
12881 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12882 :target on a <<target>>
12883 :radio-target on a <<<radio-target>>>
12884 :latex-fragment on a LaTeX fragment
12885 :latex-preview on a LaTeX fragment with overlayed preview image
12887 This function expects the position to be visible because it uses font-lock
12888 faces as a help to recognize the following contexts: :table-special, :link,
12889 and :keyword."
12890 (let* ((f (get-text-property (point) 'face))
12891 (faces (if (listp f) f (list f)))
12892 (p (point)) clist o)
12893 ;; First the large context
12894 (cond
12895 ((org-on-heading-p t)
12896 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12897 (when (progn
12898 (beginning-of-line 1)
12899 (looking-at org-todo-line-tags-regexp))
12900 (push (org-point-in-group p 1 :headline-stars) clist)
12901 (push (org-point-in-group p 2 :todo-keyword) clist)
12902 (push (org-point-in-group p 4 :tags) clist))
12903 (goto-char p)
12904 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12905 (if (looking-at "\\[#[A-Z0-9]\\]")
12906 (push (org-point-in-group p 0 :priority) clist)))
12908 ((org-at-item-p)
12909 (push (org-point-in-group p 2 :item-bullet) clist)
12910 (push (list :item (point-at-bol)
12911 (save-excursion (org-end-of-item) (point)))
12912 clist)
12913 (and (org-at-item-checkbox-p)
12914 (push (org-point-in-group p 0 :checkbox) clist)))
12916 ((org-at-table-p)
12917 (push (list :table (org-table-begin) (org-table-end)) clist)
12918 (if (memq 'org-formula faces)
12919 (push (list :table-special
12920 (previous-single-property-change p 'face)
12921 (next-single-property-change p 'face)) clist)))
12922 ((org-at-table-p 'any)
12923 (push (list :table-table) clist)))
12924 (goto-char p)
12926 ;; Now the small context
12927 (cond
12928 ((org-at-timestamp-p)
12929 (push (org-point-in-group p 0 :timestamp) clist))
12930 ((memq 'org-link faces)
12931 (push (list :link
12932 (previous-single-property-change p 'face)
12933 (next-single-property-change p 'face)) clist))
12934 ((memq 'org-special-keyword faces)
12935 (push (list :keyword
12936 (previous-single-property-change p 'face)
12937 (next-single-property-change p 'face)) clist))
12938 ((org-on-target-p)
12939 (push (org-point-in-group p 0 :target) clist)
12940 (goto-char (1- (match-beginning 0)))
12941 (if (looking-at org-radio-target-regexp)
12942 (push (org-point-in-group p 0 :radio-target) clist))
12943 (goto-char p))
12944 ((setq o (car (delq nil
12945 (mapcar
12946 (lambda (x)
12947 (if (memq x org-latex-fragment-image-overlays) x))
12948 (org-overlays-at (point))))))
12949 (push (list :latex-fragment
12950 (org-overlay-start o) (org-overlay-end o)) clist)
12951 (push (list :latex-preview
12952 (org-overlay-start o) (org-overlay-end o)) clist))
12953 ((org-inside-LaTeX-fragment-p)
12954 ;; FIXME: positions wrong.
12955 (push (list :latex-fragment (point) (point)) clist)))
12957 (setq clist (nreverse (delq nil clist)))
12958 clist))
12960 ;; FIXME: Compare with at-regexp-p Do we need both?
12961 (defun org-in-regexp (re &optional nlines visually)
12962 "Check if point is inside a match of regexp.
12963 Normally only the current line is checked, but you can include NLINES extra
12964 lines both before and after point into the search.
12965 If VISUALLY is set, require that the cursor is not after the match but
12966 really on, so that the block visually is on the match."
12967 (catch 'exit
12968 (let ((pos (point))
12969 (eol (point-at-eol (+ 1 (or nlines 0))))
12970 (inc (if visually 1 0)))
12971 (save-excursion
12972 (beginning-of-line (- 1 (or nlines 0)))
12973 (while (re-search-forward re eol t)
12974 (if (and (<= (match-beginning 0) pos)
12975 (>= (+ inc (match-end 0)) pos))
12976 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12978 (defun org-at-regexp-p (regexp)
12979 "Is point inside a match of REGEXP in the current line?"
12980 (catch 'exit
12981 (save-excursion
12982 (let ((pos (point)) (end (point-at-eol)))
12983 (beginning-of-line 1)
12984 (while (re-search-forward regexp end t)
12985 (if (and (<= (match-beginning 0) pos)
12986 (>= (match-end 0) pos))
12987 (throw 'exit t)))
12988 nil))))
12990 (defun org-occur-in-agenda-files (regexp &optional nlines)
12991 "Call `multi-occur' with buffers for all agenda files."
12992 (interactive "sOrg-files matching: \np")
12993 (let* ((files (org-agenda-files))
12994 (tnames (mapcar 'file-truename files))
12995 (extra org-agenda-text-search-extra-files)
12997 (when (eq (car extra) 'agenda-archives)
12998 (setq extra (cdr extra))
12999 (setq files (org-add-archive-files files)))
13000 (while (setq f (pop extra))
13001 (unless (member (file-truename f) tnames)
13002 (add-to-list 'files f 'append)
13003 (add-to-list 'tnames (file-truename f) 'append)))
13004 (multi-occur
13005 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13006 regexp)))
13008 (if (boundp 'occur-mode-find-occurrence-hook)
13009 ;; Emacs 23
13010 (add-hook 'occur-mode-find-occurrence-hook
13011 (lambda ()
13012 (when (org-mode-p)
13013 (org-reveal))))
13014 ;; Emacs 22
13015 (defadvice occur-mode-goto-occurrence
13016 (after org-occur-reveal activate)
13017 (and (org-mode-p) (org-reveal)))
13018 (defadvice occur-mode-goto-occurrence-other-window
13019 (after org-occur-reveal activate)
13020 (and (org-mode-p) (org-reveal)))
13021 (defadvice occur-mode-display-occurrence
13022 (after org-occur-reveal activate)
13023 (when (org-mode-p)
13024 (let ((pos (occur-mode-find-occurrence)))
13025 (with-current-buffer (marker-buffer pos)
13026 (save-excursion
13027 (goto-char pos)
13028 (org-reveal)))))))
13030 (defun org-uniquify (list)
13031 "Remove duplicate elements from LIST."
13032 (let (res)
13033 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13034 res))
13036 (defun org-delete-all (elts list)
13037 "Remove all elements in ELTS from LIST."
13038 (while elts
13039 (setq list (delete (pop elts) list)))
13040 list)
13042 (defun org-back-over-empty-lines ()
13043 "Move backwards over witespace, to the beginning of the first empty line.
13044 Returns the number of empty lines passed."
13045 (let ((pos (point)))
13046 (skip-chars-backward " \t\n\r")
13047 (beginning-of-line 2)
13048 (goto-char (min (point) pos))
13049 (count-lines (point) pos)))
13051 (defun org-skip-whitespace ()
13052 (skip-chars-forward " \t\n\r"))
13054 (defun org-point-in-group (point group &optional context)
13055 "Check if POINT is in match-group GROUP.
13056 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13057 match. If the match group does ot exist or point is not inside it,
13058 return nil."
13059 (and (match-beginning group)
13060 (>= point (match-beginning group))
13061 (<= point (match-end group))
13062 (if context
13063 (list context (match-beginning group) (match-end group))
13064 t)))
13066 (defun org-switch-to-buffer-other-window (&rest args)
13067 "Switch to buffer in a second window on the current frame.
13068 In particular, do not allow pop-up frames."
13069 (let (pop-up-frames special-display-buffer-names special-display-regexps
13070 special-display-function)
13071 (apply 'switch-to-buffer-other-window args)))
13073 (defun org-combine-plists (&rest plists)
13074 "Create a single property list from all plists in PLISTS.
13075 The process starts by copying the first list, and then setting properties
13076 from the other lists. Settings in the last list are the most significant
13077 ones and overrule settings in the other lists."
13078 (let ((rtn (copy-sequence (pop plists)))
13079 p v ls)
13080 (while plists
13081 (setq ls (pop plists))
13082 (while ls
13083 (setq p (pop ls) v (pop ls))
13084 (setq rtn (plist-put rtn p v))))
13085 rtn))
13087 (defun org-move-line-down (arg)
13088 "Move the current line down. With prefix argument, move it past ARG lines."
13089 (interactive "p")
13090 (let ((col (current-column))
13091 beg end pos)
13092 (beginning-of-line 1) (setq beg (point))
13093 (beginning-of-line 2) (setq end (point))
13094 (beginning-of-line (+ 1 arg))
13095 (setq pos (move-marker (make-marker) (point)))
13096 (insert (delete-and-extract-region beg end))
13097 (goto-char pos)
13098 (org-move-to-column col)))
13100 (defun org-move-line-up (arg)
13101 "Move the current line up. With prefix argument, move it past ARG lines."
13102 (interactive "p")
13103 (let ((col (current-column))
13104 beg end pos)
13105 (beginning-of-line 1) (setq beg (point))
13106 (beginning-of-line 2) (setq end (point))
13107 (beginning-of-line (- arg))
13108 (setq pos (move-marker (make-marker) (point)))
13109 (insert (delete-and-extract-region beg end))
13110 (goto-char pos)
13111 (org-move-to-column col)))
13113 (defun org-replace-escapes (string table)
13114 "Replace %-escapes in STRING with values in TABLE.
13115 TABLE is an association list with keys like \"%a\" and string values.
13116 The sequences in STRING may contain normal field width and padding information,
13117 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13118 so values can contain further %-escapes if they are define later in TABLE."
13119 (let ((case-fold-search nil)
13120 e re rpl)
13121 (while (setq e (pop table))
13122 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13123 (while (string-match re string)
13124 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13125 (cdr e)))
13126 (setq string (replace-match rpl t t string))))
13127 string))
13130 (defun org-sublist (list start end)
13131 "Return a section of LIST, from START to END.
13132 Counting starts at 1."
13133 (let (rtn (c start))
13134 (setq list (nthcdr (1- start) list))
13135 (while (and list (<= c end))
13136 (push (pop list) rtn)
13137 (setq c (1+ c)))
13138 (nreverse rtn)))
13140 (defun org-find-base-buffer-visiting (file)
13141 "Like `find-buffer-visiting' but alway return the base buffer and
13142 not an indirect buffer."
13143 (let ((buf (find-buffer-visiting file)))
13144 (if buf
13145 (or (buffer-base-buffer buf) buf)
13146 nil)))
13148 (defun org-image-file-name-regexp ()
13149 "Return regexp matching the file names of images."
13150 (if (fboundp 'image-file-name-regexp)
13151 (image-file-name-regexp)
13152 (let ((image-file-name-extensions
13153 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13154 "xbm" "xpm" "pbm" "pgm" "ppm")))
13155 (concat "\\."
13156 (regexp-opt (nconc (mapcar 'upcase
13157 image-file-name-extensions)
13158 image-file-name-extensions)
13160 "\\'"))))
13162 (defun org-file-image-p (file)
13163 "Return non-nil if FILE is an image."
13164 (save-match-data
13165 (string-match (org-image-file-name-regexp) file)))
13167 ;;; Paragraph filling stuff.
13168 ;; We want this to be just right, so use the full arsenal.
13170 (defun org-indent-line-function ()
13171 "Indent line like previous, but further if previous was headline or item."
13172 (interactive)
13173 (let* ((pos (point))
13174 (itemp (org-at-item-p))
13175 column bpos bcol tpos tcol bullet btype bullet-type)
13176 ;; Find the previous relevant line
13177 (beginning-of-line 1)
13178 (cond
13179 ((looking-at "#") (setq column 0))
13180 ((looking-at "\\*+ ") (setq column 0))
13182 (beginning-of-line 0)
13183 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13184 (beginning-of-line 0))
13185 (cond
13186 ((looking-at "\\*+[ \t]+")
13187 (goto-char (match-end 0))
13188 (setq column (current-column)))
13189 ((org-in-item-p)
13190 (org-beginning-of-item)
13191 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13192 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13193 (setq bpos (match-beginning 1) tpos (match-end 0)
13194 bcol (progn (goto-char bpos) (current-column))
13195 tcol (progn (goto-char tpos) (current-column))
13196 bullet (match-string 1)
13197 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13198 (if (not itemp)
13199 (setq column tcol)
13200 (goto-char pos)
13201 (beginning-of-line 1)
13202 (if (looking-at "\\S-")
13203 (progn
13204 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13205 (setq bullet (match-string 1)
13206 btype (if (string-match "[0-9]" bullet) "n" bullet))
13207 (setq column (if (equal btype bullet-type) bcol tcol)))
13208 (setq column (org-get-indentation)))))
13209 (t (setq column (org-get-indentation))))))
13210 (goto-char pos)
13211 (if (<= (current-column) (current-indentation))
13212 (org-indent-line-to column)
13213 (save-excursion (org-indent-line-to column)))
13214 (setq column (current-column))
13215 (beginning-of-line 1)
13216 (if (looking-at
13217 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13218 (replace-match (concat "\\1" (format org-property-format
13219 (match-string 2) (match-string 3)))
13220 t nil))
13221 (org-move-to-column column)))
13223 (defun org-set-autofill-regexps ()
13224 (interactive)
13225 ;; In the paragraph separator we include headlines, because filling
13226 ;; text in a line directly attached to a headline would otherwise
13227 ;; fill the headline as well.
13228 (org-set-local 'comment-start-skip "^#+[ \t]*")
13229 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13230 ;; The paragraph starter includes hand-formatted lists.
13231 (org-set-local 'paragraph-start
13232 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13233 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13234 ;; But only if the user has not turned off tables or fixed-width regions
13235 (org-set-local
13236 'auto-fill-inhibit-regexp
13237 (concat "\\*+ \\|#\\+"
13238 "\\|[ \t]*" org-keyword-time-regexp
13239 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13240 (concat
13241 "\\|[ \t]*["
13242 (if org-enable-table-editor "|" "")
13243 (if org-enable-fixed-width-editor ":" "")
13244 "]"))))
13245 ;; We use our own fill-paragraph function, to make sure that tables
13246 ;; and fixed-width regions are not wrapped. That function will pass
13247 ;; through to `fill-paragraph' when appropriate.
13248 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13249 ; Adaptive filling: To get full control, first make sure that
13250 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13251 (org-set-local 'adaptive-fill-regexp "\000")
13252 (org-set-local 'adaptive-fill-function
13253 'org-adaptive-fill-function)
13254 (org-set-local
13255 'align-mode-rules-list
13256 '((org-in-buffer-settings
13257 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13258 (modes . '(org-mode))))))
13260 (defun org-fill-paragraph (&optional justify)
13261 "Re-align a table, pass through to fill-paragraph if no table."
13262 (let ((table-p (org-at-table-p))
13263 (table.el-p (org-at-table.el-p)))
13264 (cond ((and (equal (char-after (point-at-bol)) ?*)
13265 (save-excursion (goto-char (point-at-bol))
13266 (looking-at outline-regexp)))
13267 t) ; skip headlines
13268 (table.el-p t) ; skip table.el tables
13269 (table-p (org-table-align) t) ; align org-mode tables
13270 (t nil)))) ; call paragraph-fill
13272 ;; For reference, this is the default value of adaptive-fill-regexp
13273 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13275 (defun org-adaptive-fill-function ()
13276 "Return a fill prefix for org-mode files.
13277 In particular, this makes sure hanging paragraphs for hand-formatted lists
13278 work correctly."
13279 (cond ((looking-at "#[ \t]+")
13280 (match-string 0))
13281 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13282 (save-excursion
13283 (goto-char (match-end 0))
13284 (make-string (current-column) ?\ )))
13285 (t nil)))
13287 ;;; Other stuff.
13289 (defun org-toggle-fixed-width-section (arg)
13290 "Toggle the fixed-width export.
13291 If there is no active region, the QUOTE keyword at the current headline is
13292 inserted or removed. When present, it causes the text between this headline
13293 and the next to be exported as fixed-width text, and unmodified.
13294 If there is an active region, this command adds or removes a colon as the
13295 first character of this line. If the first character of a line is a colon,
13296 this line is also exported in fixed-width font."
13297 (interactive "P")
13298 (let* ((cc 0)
13299 (regionp (org-region-active-p))
13300 (beg (if regionp (region-beginning) (point)))
13301 (end (if regionp (region-end)))
13302 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13303 (case-fold-search nil)
13304 (re "[ \t]*\\(:\\)")
13305 off)
13306 (if regionp
13307 (save-excursion
13308 (goto-char beg)
13309 (setq cc (current-column))
13310 (beginning-of-line 1)
13311 (setq off (looking-at re))
13312 (while (> nlines 0)
13313 (setq nlines (1- nlines))
13314 (beginning-of-line 1)
13315 (cond
13316 (arg
13317 (org-move-to-column cc t)
13318 (insert ":\n")
13319 (forward-line -1))
13320 ((and off (looking-at re))
13321 (replace-match "" t t nil 1))
13322 ((not off) (org-move-to-column cc t) (insert ":")))
13323 (forward-line 1)))
13324 (save-excursion
13325 (org-back-to-heading)
13326 (if (looking-at (concat outline-regexp
13327 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13328 (replace-match "" t t nil 1)
13329 (if (looking-at outline-regexp)
13330 (progn
13331 (goto-char (match-end 0))
13332 (insert org-quote-string " "))))))))
13334 ;;;; Functions extending outline functionality
13336 (defun org-beginning-of-line (&optional arg)
13337 "Go to the beginning of the current line. If that is invisible, continue
13338 to a visible line beginning. This makes the function of C-a more intuitive.
13339 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13340 first attempt, and only move to after the tags when the cursor is already
13341 beyond the end of the headline."
13342 (interactive "P")
13343 (let ((pos (point)))
13344 (beginning-of-line 1)
13345 (if (bobp)
13347 (backward-char 1)
13348 (if (org-invisible-p)
13349 (while (and (not (bobp)) (org-invisible-p))
13350 (backward-char 1)
13351 (beginning-of-line 1))
13352 (forward-char 1)))
13353 (when org-special-ctrl-a/e
13354 (cond
13355 ((and (looking-at org-todo-line-regexp)
13356 (= (char-after (match-end 1)) ?\ ))
13357 (goto-char
13358 (if (eq org-special-ctrl-a/e t)
13359 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13360 ((= pos (point)) (match-beginning 3))
13361 (t (point)))
13362 (cond ((> pos (point)) (point))
13363 ((not (eq last-command this-command)) (point))
13364 (t (match-beginning 3))))))
13365 ((org-at-item-p)
13366 (goto-char
13367 (if (eq org-special-ctrl-a/e t)
13368 (cond ((> pos (match-end 4)) (match-end 4))
13369 ((= pos (point)) (match-end 4))
13370 (t (point)))
13371 (cond ((> pos (point)) (point))
13372 ((not (eq last-command this-command)) (point))
13373 (t (match-end 4))))))))))
13375 (defun org-end-of-line (&optional arg)
13376 "Go to the end of the line.
13377 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13378 first attempt, and only move to after the tags when the cursor is already
13379 beyond the end of the headline."
13380 (interactive "P")
13381 (if (or (not org-special-ctrl-a/e)
13382 (not (org-on-heading-p)))
13383 (end-of-line arg)
13384 (let ((pos (point)))
13385 (beginning-of-line 1)
13386 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13387 (if (eq org-special-ctrl-a/e t)
13388 (if (or (< pos (match-beginning 1))
13389 (= pos (match-end 0)))
13390 (goto-char (match-beginning 1))
13391 (goto-char (match-end 0)))
13392 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13393 (goto-char (match-end 0))
13394 (goto-char (match-beginning 1))))
13395 (end-of-line arg)))))
13397 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13398 (define-key org-mode-map "\C-e" 'org-end-of-line)
13400 (defun org-kill-line (&optional arg)
13401 "Kill line, to tags or end of line."
13402 (interactive "P")
13403 (cond
13404 ((or (not org-special-ctrl-k)
13405 (bolp)
13406 (not (org-on-heading-p)))
13407 (call-interactively 'kill-line))
13408 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13409 (kill-region (point) (match-beginning 1))
13410 (org-set-tags nil t))
13411 (t (kill-region (point) (point-at-eol)))))
13413 (define-key org-mode-map "\C-k" 'org-kill-line)
13415 (defun org-invisible-p ()
13416 "Check if point is at a character currently not visible."
13417 ;; Early versions of noutline don't have `outline-invisible-p'.
13418 (if (fboundp 'outline-invisible-p)
13419 (outline-invisible-p)
13420 (get-char-property (point) 'invisible)))
13422 (defun org-invisible-p2 ()
13423 "Check if point is at a character currently not visible."
13424 (save-excursion
13425 (if (and (eolp) (not (bobp))) (backward-char 1))
13426 ;; Early versions of noutline don't have `outline-invisible-p'.
13427 (if (fboundp 'outline-invisible-p)
13428 (outline-invisible-p)
13429 (get-char-property (point) 'invisible))))
13431 (defalias 'org-back-to-heading 'outline-back-to-heading)
13432 (defalias 'org-on-heading-p 'outline-on-heading-p)
13433 (defalias 'org-at-heading-p 'outline-on-heading-p)
13434 (defun org-at-heading-or-item-p ()
13435 (or (org-on-heading-p) (org-at-item-p)))
13437 (defun org-on-target-p ()
13438 (or (org-in-regexp org-radio-target-regexp)
13439 (org-in-regexp org-target-regexp)))
13441 (defun org-up-heading-all (arg)
13442 "Move to the heading line of which the present line is a subheading.
13443 This function considers both visible and invisible heading lines.
13444 With argument, move up ARG levels."
13445 (if (fboundp 'outline-up-heading-all)
13446 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13447 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13449 (defun org-up-heading-safe ()
13450 "Move to the heading line of which the present line is a subheading.
13451 This version will not throw an error. It will return the level of the
13452 headline found, or nil if no higher level is found."
13453 (let ((pos (point)) start-level level
13454 (re (concat "^" outline-regexp)))
13455 (catch 'exit
13456 (outline-back-to-heading t)
13457 (setq start-level (funcall outline-level))
13458 (if (equal start-level 1) (throw 'exit nil))
13459 (while (re-search-backward re nil t)
13460 (setq level (funcall outline-level))
13461 (if (< level start-level) (throw 'exit level)))
13462 nil)))
13464 (defun org-first-sibling-p ()
13465 "Is this heading the first child of its parents?"
13466 (interactive)
13467 (let ((re (concat "^" outline-regexp))
13468 level l)
13469 (unless (org-at-heading-p t)
13470 (error "Not at a heading"))
13471 (setq level (funcall outline-level))
13472 (save-excursion
13473 (if (not (re-search-backward re nil t))
13475 (setq l (funcall outline-level))
13476 (< l level)))))
13478 (defun org-goto-sibling (&optional previous)
13479 "Goto the next sibling, even if it is invisible.
13480 When PREVIOUS is set, go to the previous sibling instead. Returns t
13481 when a sibling was found. When none is found, return nil and don't
13482 move point."
13483 (let ((fun (if previous 're-search-backward 're-search-forward))
13484 (pos (point))
13485 (re (concat "^" outline-regexp))
13486 level l)
13487 (when (condition-case nil (org-back-to-heading t) (error nil))
13488 (setq level (funcall outline-level))
13489 (catch 'exit
13490 (or previous (forward-char 1))
13491 (while (funcall fun re nil t)
13492 (setq l (funcall outline-level))
13493 (when (< l level) (goto-char pos) (throw 'exit nil))
13494 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13495 (goto-char pos)
13496 nil))))
13498 (defun org-show-siblings ()
13499 "Show all siblings of the current headline."
13500 (save-excursion
13501 (while (org-goto-sibling) (org-flag-heading nil)))
13502 (save-excursion
13503 (while (org-goto-sibling 'previous)
13504 (org-flag-heading nil))))
13506 (defun org-show-hidden-entry ()
13507 "Show an entry where even the heading is hidden."
13508 (save-excursion
13509 (org-show-entry)))
13511 (defun org-flag-heading (flag &optional entry)
13512 "Flag the current heading. FLAG non-nil means make invisible.
13513 When ENTRY is non-nil, show the entire entry."
13514 (save-excursion
13515 (org-back-to-heading t)
13516 ;; Check if we should show the entire entry
13517 (if entry
13518 (progn
13519 (org-show-entry)
13520 (save-excursion
13521 (and (outline-next-heading)
13522 (org-flag-heading nil))))
13523 (outline-flag-region (max (point-min) (1- (point)))
13524 (save-excursion (outline-end-of-heading) (point))
13525 flag))))
13527 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13528 ;; This is an exact copy of the original function, but it uses
13529 ;; `org-back-to-heading', to make it work also in invisible
13530 ;; trees. And is uses an invisible-OK argument.
13531 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13532 (org-back-to-heading invisible-OK)
13533 (let ((first t)
13534 (level (funcall outline-level)))
13535 (while (and (not (eobp))
13536 (or first (> (funcall outline-level) level)))
13537 (setq first nil)
13538 (outline-next-heading))
13539 (unless to-heading
13540 (if (memq (preceding-char) '(?\n ?\^M))
13541 (progn
13542 ;; Go to end of line before heading
13543 (forward-char -1)
13544 (if (memq (preceding-char) '(?\n ?\^M))
13545 ;; leave blank line before heading
13546 (forward-char -1))))))
13547 (point))
13549 (defun org-show-subtree ()
13550 "Show everything after this heading at deeper levels."
13551 (outline-flag-region
13552 (point)
13553 (save-excursion
13554 (outline-end-of-subtree) (outline-next-heading) (point))
13555 nil))
13557 (defun org-show-entry ()
13558 "Show the body directly following this heading.
13559 Show the heading too, if it is currently invisible."
13560 (interactive)
13561 (save-excursion
13562 (condition-case nil
13563 (progn
13564 (org-back-to-heading t)
13565 (outline-flag-region
13566 (max (point-min) (1- (point)))
13567 (save-excursion
13568 (re-search-forward
13569 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13570 (or (match-beginning 1) (point-max)))
13571 nil))
13572 (error nil))))
13574 (defun org-make-options-regexp (kwds)
13575 "Make a regular expression for keyword lines."
13576 (concat
13578 "#?[ \t]*\\+\\("
13579 (mapconcat 'regexp-quote kwds "\\|")
13580 "\\):[ \t]*"
13581 "\\(.+\\)"))
13583 ;; Make isearch reveal the necessary context
13584 (defun org-isearch-end ()
13585 "Reveal context after isearch exits."
13586 (when isearch-success ; only if search was successful
13587 (if (featurep 'xemacs)
13588 ;; Under XEmacs, the hook is run in the correct place,
13589 ;; we directly show the context.
13590 (org-show-context 'isearch)
13591 ;; In Emacs the hook runs *before* restoring the overlays.
13592 ;; So we have to use a one-time post-command-hook to do this.
13593 ;; (Emacs 22 has a special variable, see function `org-mode')
13594 (unless (and (boundp 'isearch-mode-end-hook-quit)
13595 isearch-mode-end-hook-quit)
13596 ;; Only when the isearch was not quitted.
13597 (org-add-hook 'post-command-hook 'org-isearch-post-command
13598 'append 'local)))))
13600 (defun org-isearch-post-command ()
13601 "Remove self from hook, and show context."
13602 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13603 (org-show-context 'isearch))
13606 ;;;; Integration with and fixes for other packages
13608 ;;; Imenu support
13610 (defvar org-imenu-markers nil
13611 "All markers currently used by Imenu.")
13612 (make-variable-buffer-local 'org-imenu-markers)
13614 (defun org-imenu-new-marker (&optional pos)
13615 "Return a new marker for use by Imenu, and remember the marker."
13616 (let ((m (make-marker)))
13617 (move-marker m (or pos (point)))
13618 (push m org-imenu-markers)
13621 (defun org-imenu-get-tree ()
13622 "Produce the index for Imenu."
13623 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13624 (setq org-imenu-markers nil)
13625 (let* ((n org-imenu-depth)
13626 (re (concat "^" outline-regexp))
13627 (subs (make-vector (1+ n) nil))
13628 (last-level 0)
13629 m tree level head)
13630 (save-excursion
13631 (save-restriction
13632 (widen)
13633 (goto-char (point-max))
13634 (while (re-search-backward re nil t)
13635 (setq level (org-reduced-level (funcall outline-level)))
13636 (when (<= level n)
13637 (looking-at org-complex-heading-regexp)
13638 (setq head (org-match-string-no-properties 4)
13639 m (org-imenu-new-marker))
13640 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13641 (if (>= level last-level)
13642 (push (cons head m) (aref subs level))
13643 (push (cons head (aref subs (1+ level))) (aref subs level))
13644 (loop for i from (1+ level) to n do (aset subs i nil)))
13645 (setq last-level level)))))
13646 (aref subs 1)))
13648 (eval-after-load "imenu"
13649 '(progn
13650 (add-hook 'imenu-after-jump-hook
13651 (lambda () (org-show-context 'org-goto)))))
13653 ;; Speedbar support
13655 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13656 "Overlay marking the agenda restriction line in speedbar.")
13657 (org-overlay-put org-speedbar-restriction-lock-overlay
13658 'face 'org-agenda-restriction-lock)
13659 (org-overlay-put org-speedbar-restriction-lock-overlay
13660 'help-echo "Agendas are currently limited to this item.")
13661 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13663 (defun org-speedbar-set-agenda-restriction ()
13664 "Restrict future agenda commands to the location at point in speedbar.
13665 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13666 (interactive)
13667 (require 'org-agenda)
13668 (let (p m tp np dir txt w)
13669 (cond
13670 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13671 'org-imenu t))
13672 (setq m (get-text-property p 'org-imenu-marker))
13673 (save-excursion
13674 (save-restriction
13675 (set-buffer (marker-buffer m))
13676 (goto-char m)
13677 (org-agenda-set-restriction-lock 'subtree))))
13678 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13679 'speedbar-function 'speedbar-find-file))
13680 (setq tp (previous-single-property-change
13681 (1+ p) 'speedbar-function)
13682 np (next-single-property-change
13683 tp 'speedbar-function)
13684 dir (speedbar-line-directory)
13685 txt (buffer-substring-no-properties (or tp (point-min))
13686 (or np (point-max))))
13687 (save-excursion
13688 (save-restriction
13689 (set-buffer (find-file-noselect
13690 (let ((default-directory dir))
13691 (expand-file-name txt))))
13692 (unless (org-mode-p)
13693 (error "Cannot restrict to non-Org-mode file"))
13694 (org-agenda-set-restriction-lock 'file))))
13695 (t (error "Don't know how to restrict Org-mode's agenda")))
13696 (org-move-overlay org-speedbar-restriction-lock-overlay
13697 (point-at-bol) (point-at-eol))
13698 (setq current-prefix-arg nil)
13699 (org-agenda-maybe-redo)))
13701 (eval-after-load "speedbar"
13702 '(progn
13703 (speedbar-add-supported-extension ".org")
13704 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13705 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13706 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13707 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13708 (add-hook 'speedbar-visiting-tag-hook
13709 (lambda () (org-show-context 'org-goto)))))
13712 ;;; Fixes and Hacks for problems with other packages
13714 ;; Make flyspell not check words in links, to not mess up our keymap
13715 (defun org-mode-flyspell-verify ()
13716 "Don't let flyspell put overlays at active buttons."
13717 (not (get-text-property (point) 'keymap)))
13719 ;; Make `bookmark-jump' show the jump location if it was hidden.
13720 (eval-after-load "bookmark"
13721 '(if (boundp 'bookmark-after-jump-hook)
13722 ;; We can use the hook
13723 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13724 ;; Hook not available, use advice
13725 (defadvice bookmark-jump (after org-make-visible activate)
13726 "Make the position visible."
13727 (org-bookmark-jump-unhide))))
13729 (defun org-bookmark-jump-unhide ()
13730 "Unhide the current position, to show the bookmark location."
13731 (and (org-mode-p)
13732 (or (org-invisible-p)
13733 (save-excursion (goto-char (max (point-min) (1- (point))))
13734 (org-invisible-p)))
13735 (org-show-context 'bookmark-jump)))
13737 ;; Make session.el ignore our circular variable
13738 (eval-after-load "session"
13739 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13741 ;;;; Experimental code
13743 (defun org-closed-in-range ()
13744 "Sparse tree of items closed in a certain time range.
13745 Still experimental, may disappear in the future."
13746 (interactive)
13747 ;; Get the time interval from the user.
13748 (let* ((time1 (time-to-seconds
13749 (org-read-date nil 'to-time nil "Starting date: ")))
13750 (time2 (time-to-seconds
13751 (org-read-date nil 'to-time nil "End date:")))
13752 ;; callback function
13753 (callback (lambda ()
13754 (let ((time
13755 (time-to-seconds
13756 (apply 'encode-time
13757 (org-parse-time-string
13758 (match-string 1))))))
13759 ;; check if time in interval
13760 (and (>= time time1) (<= time time2))))))
13761 ;; make tree, check each match with the callback
13762 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13765 ;;;; Finish up
13767 (provide 'org)
13769 (run-hooks 'org-load-hook)
13771 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13773 ;;; org.el ends here