initial steps
[org-mode/org-tableheadings.git] / lisp / org.el
blob80288dbf8223ca4dde569c2df7f4687659d8e9fe
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.03pre01
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.03pre01"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " info: Links to Info nodes" org-info)
165 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
166 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
167 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
168 (const :tag " mew Links to Mew folders/messages" org-mew)
169 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
170 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
171 (const :tag " vm: Links to VM folders/messages" org-vm)
172 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
173 (const :tag " mouse: Additional mouse support" org-mouse)
175 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
176 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
177 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
178 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
179 (const :tag "C eval: Include command output as text" org-eval)
180 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
181 (const :tag "C id: Global id's for identifying entries" org-id)
182 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
183 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
184 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
185 (const :tag "C mtags: Support for muse-like tags" org-mtags)
186 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
187 (const :tag "C registry: A registry for Org links" org-registry)
188 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
189 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
190 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
191 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
192 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
195 (defgroup org-startup nil
196 "Options concerning startup of Org-mode."
197 :tag "Org Startup"
198 :group 'org)
200 (defcustom org-startup-folded t
201 "Non-nil means, entering Org-mode will switch to OVERVIEW.
202 This can also be configured on a per-file basis by adding one of
203 the following lines anywhere in the buffer:
205 #+STARTUP: fold
206 #+STARTUP: nofold
207 #+STARTUP: content"
208 :group 'org-startup
209 :type '(choice
210 (const :tag "nofold: show all" nil)
211 (const :tag "fold: overview" t)
212 (const :tag "content: all headlines" content)))
214 (defcustom org-startup-truncated t
215 "Non-nil means, entering Org-mode will set `truncate-lines'.
216 This is useful since some lines containing links can be very long and
217 uninteresting. Also tables look terrible when wrapped."
218 :group 'org-startup
219 :type 'boolean)
221 (defcustom org-startup-align-all-tables nil
222 "Non-nil means, align all tables when visiting a file.
223 This is useful when the column width in tables is forced with <N> cookies
224 in table fields. Such tables will look correct only after the first re-align.
225 This can also be configured on a per-file basis by adding one of
226 the following lines anywhere in the buffer:
227 #+STARTUP: align
228 #+STARTUP: noalign"
229 :group 'org-startup
230 :type 'boolean)
232 (defcustom org-insert-mode-line-in-empty-file nil
233 "Non-nil means insert the first line setting Org-mode in empty files.
234 When the function `org-mode' is called interactively in an empty file, this
235 normally means that the file name does not automatically trigger Org-mode.
236 To ensure that the file will always be in Org-mode in the future, a
237 line enforcing Org-mode will be inserted into the buffer, if this option
238 has been set."
239 :group 'org-startup
240 :type 'boolean)
242 (defcustom org-replace-disputed-keys nil
243 "Non-nil means use alternative key bindings for some keys.
244 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
245 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
246 If you want to use Org-mode together with one of these other modes,
247 or more generally if you would like to move some Org-mode commands to
248 other keys, set this variable and configure the keys with the variable
249 `org-disputed-keys'.
251 This option is only relevant at load-time of Org-mode, and must be set
252 *before* org.el is loaded. Changing it requires a restart of Emacs to
253 become effective."
254 :group 'org-startup
255 :type 'boolean)
257 (if (fboundp 'defvaralias)
258 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
260 (defcustom org-disputed-keys
261 '(([(shift up)] . [(meta p)])
262 ([(shift down)] . [(meta n)])
263 ([(shift left)] . [(meta -)])
264 ([(shift right)] . [(meta +)])
265 ([(control shift right)] . [(meta shift +)])
266 ([(control shift left)] . [(meta shift -)]))
267 "Keys for which Org-mode and other modes compete.
268 This is an alist, cars are the default keys, second element specifies
269 the alternative to use when `org-replace-disputed-keys' is t.
271 Keys can be specified in any syntax supported by `define-key'.
272 The value of this option takes effect only at Org-mode's startup,
273 therefore you'll have to restart Emacs to apply it after changing."
274 :group 'org-startup
275 :type 'alist)
277 (defun org-key (key)
278 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
279 Or return the original if not disputed."
280 (if org-replace-disputed-keys
281 (let* ((nkey (key-description key))
282 (x (org-find-if (lambda (x)
283 (equal (key-description (car x)) nkey))
284 org-disputed-keys)))
285 (if x (cdr x) key))
286 key))
288 (defun org-find-if (predicate seq)
289 (catch 'exit
290 (while seq
291 (if (funcall predicate (car seq))
292 (throw 'exit (car seq))
293 (pop seq)))))
295 (defun org-defkey (keymap key def)
296 "Define a key, possibly translated, as returned by `org-key'."
297 (define-key keymap (org-key key) def))
299 (defcustom org-ellipsis nil
300 "The ellipsis to use in the Org-mode outline.
301 When nil, just use the standard three dots. When a string, use that instead,
302 When a face, use the standart 3 dots, but with the specified face.
303 The change affects only Org-mode (which will then use its own display table).
304 Changing this requires executing `M-x org-mode' in a buffer to become
305 effective."
306 :group 'org-startup
307 :type '(choice (const :tag "Default" nil)
308 (face :tag "Face" :value org-warning)
309 (string :tag "String" :value "...#")))
311 (defvar org-display-table nil
312 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
314 (defgroup org-keywords nil
315 "Keywords in Org-mode."
316 :tag "Org Keywords"
317 :group 'org)
319 (defcustom org-deadline-string "DEADLINE:"
320 "String to mark deadline entries.
321 A deadline is this string, followed by a time stamp. Should be a word,
322 terminated by a colon. You can insert a schedule keyword and
323 a timestamp with \\[org-deadline].
324 Changes become only effective after restarting Emacs."
325 :group 'org-keywords
326 :type 'string)
328 (defcustom org-scheduled-string "SCHEDULED:"
329 "String to mark scheduled TODO entries.
330 A schedule is this string, followed by a time stamp. Should be a word,
331 terminated by a colon. You can insert a schedule keyword and
332 a timestamp with \\[org-schedule].
333 Changes become only effective after restarting Emacs."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-closed-string "CLOSED:"
338 "String used as the prefix for timestamps logging closing a TODO entry."
339 :group 'org-keywords
340 :type 'string)
342 (defcustom org-clock-string "CLOCK:"
343 "String used as prefix for timestamps clocking work hours on an item."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-comment-string "COMMENT"
348 "Entries starting with this keyword will never be exported.
349 An entry can be toggled between COMMENT and normal with
350 \\[org-toggle-comment].
351 Changes become only effective after restarting Emacs."
352 :group 'org-keywords
353 :type 'string)
355 (defcustom org-quote-string "QUOTE"
356 "Entries starting with this keyword will be exported in fixed-width font.
357 Quoting applies only to the text in the entry following the headline, and does
358 not extend beyond the next headline, even if that is lower level.
359 An entry can be toggled between QUOTE and normal with
360 \\[org-toggle-fixed-width-section]."
361 :group 'org-keywords
362 :type 'string)
364 (defconst org-repeat-re
365 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
366 "Regular expression for specifying repeated events.
367 After a match, group 1 contains the repeat expression.")
369 (defgroup org-structure nil
370 "Options concerning the general structure of Org-mode files."
371 :tag "Org Structure"
372 :group 'org)
374 (defgroup org-reveal-location nil
375 "Options about how to make context of a location visible."
376 :tag "Org Reveal Location"
377 :group 'org-structure)
379 (defconst org-context-choice
380 '(choice
381 (const :tag "Always" t)
382 (const :tag "Never" nil)
383 (repeat :greedy t :tag "Individual contexts"
384 (cons
385 (choice :tag "Context"
386 (const agenda)
387 (const org-goto)
388 (const occur-tree)
389 (const tags-tree)
390 (const link-search)
391 (const mark-goto)
392 (const bookmark-jump)
393 (const isearch)
394 (const default))
395 (boolean))))
396 "Contexts for the reveal options.")
398 (defcustom org-show-hierarchy-above '((default . t))
399 "Non-nil means, show full hierarchy when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the hierarchy of headings
402 above the exposed location is shown.
403 Turning this off for example for sparse trees makes them very compact.
404 Instead of t, this can also be an alist specifying this option for different
405 contexts. Valid contexts are
406 agenda when exposing an entry from the agenda
407 org-goto when using the command `org-goto' on key C-c C-j
408 occur-tree when using the command `org-occur' on key C-c /
409 tags-tree when constructing a sparse tree based on tags matches
410 link-search when exposing search matches associated with a link
411 mark-goto when exposing the jump goal of a mark
412 bookmark-jump when exposing a bookmark location
413 isearch when exiting from an incremental search
414 default default for all contexts not set explicitly"
415 :group 'org-reveal-location
416 :type org-context-choice)
418 (defcustom org-show-following-heading '((default . nil))
419 "Non-nil means, show following heading when revealing a location.
420 Org-mode often shows locations in an org-mode file which might have
421 been invisible before. When this is set, the heading following the
422 match is shown.
423 Turning this off for example for sparse trees makes them very compact,
424 but makes it harder to edit the location of the match. In such a case,
425 use the command \\[org-reveal] to show more context.
426 Instead of t, this can also be an alist specifying this option for different
427 contexts. See `org-show-hierarchy-above' for valid contexts."
428 :group 'org-reveal-location
429 :type org-context-choice)
431 (defcustom org-show-siblings '((default . nil) (isearch t))
432 "Non-nil means, show all sibling heading when revealing a location.
433 Org-mode often shows locations in an org-mode file which might have
434 been invisible before. When this is set, the sibling of the current entry
435 heading are all made visible. If `org-show-hierarchy-above' is t,
436 the same happens on each level of the hierarchy above the current entry.
438 By default this is on for the isearch context, off for all other contexts.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-entry-below '((default . nil))
448 "Non-nil means, show the entry below a headline when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the text below the headline that is
451 exposed is also shown.
453 By default this is off for all contexts.
454 Instead of t, this can also be an alist specifying this option for different
455 contexts. See `org-show-hierarchy-above' for valid contexts."
456 :group 'org-reveal-location
457 :type org-context-choice)
459 (defcustom org-indirect-buffer-display 'other-window
460 "How should indirect tree buffers be displayed?
461 This applies to indirect buffers created with the commands
462 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
463 Valid values are:
464 current-window Display in the current window
465 other-window Just display in another window.
466 dedicated-frame Create one new frame, and re-use it each time.
467 new-frame Make a new frame each time. Note that in this case
468 previously-made indirect buffers are kept, and you need to
469 kill these buffers yourself."
470 :group 'org-structure
471 :group 'org-agenda-windows
472 :type '(choice
473 (const :tag "In current window" current-window)
474 (const :tag "In current frame, other window" other-window)
475 (const :tag "Each time a new frame" new-frame)
476 (const :tag "One dedicated frame" dedicated-frame)))
478 (defgroup org-cycle nil
479 "Options concerning visibility cycling in Org-mode."
480 :tag "Org Cycle"
481 :group 'org-structure)
483 (defcustom org-drawers '("PROPERTIES" "CLOCK")
484 "Names of drawers. Drawers are not opened by cycling on the headline above.
485 Drawers only open with a TAB on the drawer line itself. A drawer looks like
486 this:
487 :DRAWERNAME:
488 .....
489 :END:
490 The drawer \"PROPERTIES\" is special for capturing properties through
491 the property API.
493 Drawers can be defined on the per-file basis with a line like:
495 #+DRAWERS: HIDDEN STATE PROPERTIES"
496 :group 'org-structure
497 :type '(repeat (string :tag "Drawer Name")))
499 (defcustom org-cycle-global-at-bob nil
500 "Cycle globally if cursor is at beginning of buffer and not at a headline.
501 This makes it possible to do global cycling without having to use S-TAB or
502 C-u TAB. For this special case to work, the first line of the buffer
503 must not be a headline - it may be empty ot some other text. When used in
504 this way, `org-cycle-hook' is disables temporarily, to make sure the
505 cursor stays at the beginning of the buffer.
506 When this option is nil, don't do anything special at the beginning
507 of the buffer."
508 :group 'org-cycle
509 :type 'boolean)
511 (defcustom org-cycle-emulate-tab t
512 "Where should `org-cycle' emulate TAB.
513 nil Never
514 white Only in completely white lines
515 whitestart Only at the beginning of lines, before the first non-white char
516 t Everywhere except in headlines
517 exc-hl-bol Everywhere except at the start of a headline
518 If TAB is used in a place where it does not emulate TAB, the current subtree
519 visibility is cycled."
520 :group 'org-cycle
521 :type '(choice (const :tag "Never" nil)
522 (const :tag "Only in completely white lines" white)
523 (const :tag "Before first char in a line" whitestart)
524 (const :tag "Everywhere except in headlines" t)
525 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
528 (defcustom org-cycle-separator-lines 2
529 "Number of empty lines needed to keep an empty line between collapsed trees.
530 If you leave an empty line between the end of a subtree and the following
531 headline, this empty line is hidden when the subtree is folded.
532 Org-mode will leave (exactly) one empty line visible if the number of
533 empty lines is equal or larger to the number given in this variable.
534 So the default 2 means, at least 2 empty lines after the end of a subtree
535 are needed to produce free space between a collapsed subtree and the
536 following headline.
538 Special case: when 0, never leave empty lines in collapsed view."
539 :group 'org-cycle
540 :type 'integer)
542 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
543 org-cycle-hide-drawers
544 org-cycle-show-empty-lines
545 org-optimize-window-after-visibility-change)
546 "Hook that is run after `org-cycle' has changed the buffer visibility.
547 The function(s) in this hook must accept a single argument which indicates
548 the new state that was set by the most recent `org-cycle' command. The
549 argument is a symbol. After a global state change, it can have the values
550 `overview', `content', or `all'. After a local state change, it can have
551 the values `folded', `children', or `subtree'."
552 :group 'org-cycle
553 :type 'hook)
555 (defgroup org-edit-structure nil
556 "Options concerning structure editing in Org-mode."
557 :tag "Org Edit Structure"
558 :group 'org-structure)
560 (defcustom org-odd-levels-only nil
561 "Non-nil means, skip even levels and only use odd levels for the outline.
562 This has the effect that two stars are being added/taken away in
563 promotion/demotion commands. It also influences how levels are
564 handled by the exporters.
565 Changing it requires restart of `font-lock-mode' to become effective
566 for fontification also in regions already fontified.
567 You may also set this on a per-file basis by adding one of the following
568 lines to the buffer:
570 #+STARTUP: odd
571 #+STARTUP: oddeven"
572 :group 'org-edit-structure
573 :group 'org-font-lock
574 :type 'boolean)
576 (defcustom org-adapt-indentation t
577 "Non-nil means, adapt indentation when promoting and demoting.
578 When this is set and the *entire* text in an entry is indented, the
579 indentation is increased by one space in a demotion command, and
580 decreased by one in a promotion command. If any line in the entry
581 body starts at column 0, indentation is not changed at all."
582 :group 'org-edit-structure
583 :type 'boolean)
585 (defcustom org-special-ctrl-a/e nil
586 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
587 When t, `C-a' will bring back the cursor to the beginning of the
588 headline text, i.e. after the stars and after a possible TODO keyword.
589 In an item, this will be the position after the bullet.
590 When the cursor is already at that position, another `C-a' will bring
591 it to the beginning of the line.
592 `C-e' will jump to the end of the headline, ignoring the presence of tags
593 in the headline. A second `C-e' will then jump to the true end of the
594 line, after any tags.
595 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
596 and only a directly following, identical keypress will bring the cursor
597 to the special positions."
598 :group 'org-edit-structure
599 :type '(choice
600 (const :tag "off" nil)
601 (const :tag "after bullet first" t)
602 (const :tag "border first" reversed)))
604 (if (fboundp 'defvaralias)
605 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
607 (defcustom org-special-ctrl-k nil
608 "Non-nil means `C-k' will behave specially in headlines.
609 When nil, `C-k' will call the default `kill-line' command.
610 When t, the following will happen while the cursor is in the headline:
612 - When the cursor is at the beginning of a headline, kill the entire
613 line and possible the folded subtree below the line.
614 - When in the middle of the headline text, kill the headline up to the tags.
615 - When after the headline text, kill the tags."
616 :group 'org-edit-structure
617 :type 'boolean)
619 (defcustom org-M-RET-may-split-line '((default . t))
620 "Non-nil means, M-RET will split the line at the cursor position.
621 When nil, it will go to the end of the line before making a
622 new line.
623 You may also set this option in a different way for different
624 contexts. Valid contexts are:
626 headline when creating a new headline
627 item when creating a new item
628 table in a table field
629 default the value to be used for all contexts not explicitly
630 customized"
631 :group 'org-structure
632 :group 'org-table
633 :type '(choice
634 (const :tag "Always" t)
635 (const :tag "Never" nil)
636 (repeat :greedy t :tag "Individual contexts"
637 (cons
638 (choice :tag "Context"
639 (const headline)
640 (const item)
641 (const table)
642 (const default))
643 (boolean)))))
646 (defcustom org-blank-before-new-entry '((heading . nil)
647 (plain-list-item . nil))
648 "Should `org-insert-heading' leave a blank line before new heading/item?
649 The value is an alist, with `heading' and `plain-list-item' as car,
650 and a boolean flag as cdr."
651 :group 'org-edit-structure
652 :type '(list
653 (cons (const heading) (boolean))
654 (cons (const plain-list-item) (boolean))))
656 (defcustom org-insert-heading-hook nil
657 "Hook being run after inserting a new heading."
658 :group 'org-edit-structure
659 :type 'hook)
661 (defcustom org-enable-fixed-width-editor t
662 "Non-nil means, lines starting with \":\" are treated as fixed-width.
663 This currently only means, they are never auto-wrapped.
664 When nil, such lines will be treated like ordinary lines.
665 See also the QUOTE keyword."
666 :group 'org-edit-structure
667 :type 'boolean)
669 (defcustom org-goto-auto-isearch t
670 "Non-nil means, typing characters in org-goto starts incremental search."
671 :group 'org-edit-structure
672 :type 'boolean)
674 (defgroup org-sparse-trees nil
675 "Options concerning sparse trees in Org-mode."
676 :tag "Org Sparse Trees"
677 :group 'org-structure)
679 (defcustom org-highlight-sparse-tree-matches t
680 "Non-nil means, highlight all matches that define a sparse tree.
681 The highlights will automatically disappear the next time the buffer is
682 changed by an edit command."
683 :group 'org-sparse-trees
684 :type 'boolean)
686 (defcustom org-remove-highlights-with-change t
687 "Non-nil means, any change to the buffer will remove temporary highlights.
688 Such highlights are created by `org-occur' and `org-clock-display'.
689 When nil, `C-c C-c needs to be used to get rid of the highlights.
690 The highlights created by `org-preview-latex-fragment' always need
691 `C-c C-c' to be removed."
692 :group 'org-sparse-trees
693 :group 'org-time
694 :type 'boolean)
697 (defcustom org-occur-hook '(org-first-headline-recenter)
698 "Hook that is run after `org-occur' has constructed a sparse tree.
699 This can be used to recenter the window to show as much of the structure
700 as possible."
701 :group 'org-sparse-trees
702 :type 'hook)
704 (defgroup org-plain-lists nil
705 "Options concerning plain lists in Org-mode."
706 :tag "Org Plain lists"
707 :group 'org-structure)
709 (defcustom org-cycle-include-plain-lists nil
710 "Non-nil means, include plain lists into visibility cycling.
711 This means that during cycling, plain list items will *temporarily* be
712 interpreted as outline headlines with a level given by 1000+i where i is the
713 indentation of the bullet. In all other operations, plain list items are
714 not seen as headlines. For example, you cannot assign a TODO keyword to
715 such an item."
716 :group 'org-plain-lists
717 :type 'boolean)
719 (defcustom org-plain-list-ordered-item-terminator t
720 "The character that makes a line with leading number an ordered list item.
721 Valid values are ?. and ?\). To get both terminators, use t. While
722 ?. may look nicer, it creates the danger that a line with leading
723 number may be incorrectly interpreted as an item. ?\) therefore is
724 the safe choice."
725 :group 'org-plain-lists
726 :type '(choice (const :tag "dot like in \"2.\"" ?.)
727 (const :tag "paren like in \"2)\"" ?\))
728 (const :tab "both" t)))
730 (defcustom org-empty-line-terminates-plain-lists nil
731 "Non-nil means, an empty line ends all plain list levels.
732 When nil, empty lines are part of the preceeding item."
733 :group 'org-plain-lists
734 :type 'boolean)
736 (defcustom org-auto-renumber-ordered-lists t
737 "Non-nil means, automatically renumber ordered plain lists.
738 Renumbering happens when the sequence have been changed with
739 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
740 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
741 :group 'org-plain-lists
742 :type 'boolean)
744 (defcustom org-provide-checkbox-statistics t
745 "Non-nil means, update checkbox statistics after insert and toggle.
746 When this is set, checkbox statistics is updated each time you either insert
747 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
748 with \\[org-ctrl-c-ctrl-c\\]."
749 :group 'org-plain-lists
750 :type 'boolean)
753 (defgroup org-imenu-and-speedbar nil
754 "Options concerning imenu and speedbar in Org-mode."
755 :tag "Org Imenu and Speedbar"
756 :group 'org-structure)
758 (defcustom org-imenu-depth 2
759 "The maximum level for Imenu access to Org-mode headlines.
760 This also applied for speedbar access."
761 :group 'org-imenu-and-speedbar
762 :type 'number)
764 (defgroup org-table nil
765 "Options concerning tables in Org-mode."
766 :tag "Org Table"
767 :group 'org)
769 (defcustom org-enable-table-editor 'optimized
770 "Non-nil means, lines starting with \"|\" are handled by the table editor.
771 When nil, such lines will be treated like ordinary lines.
773 When equal to the symbol `optimized', the table editor will be optimized to
774 do the following:
775 - Automatic overwrite mode in front of whitespace in table fields.
776 This makes the structure of the table stay in tact as long as the edited
777 field does not exceed the column width.
778 - Minimize the number of realigns. Normally, the table is aligned each time
779 TAB or RET are pressed to move to another field. With optimization this
780 happens only if changes to a field might have changed the column width.
781 Optimization requires replacing the functions `self-insert-command',
782 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
783 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
784 very good at guessing when a re-align will be necessary, but you can always
785 force one with \\[org-ctrl-c-ctrl-c].
787 If you would like to use the optimized version in Org-mode, but the
788 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
790 This variable can be used to turn on and off the table editor during a session,
791 but in order to toggle optimization, a restart is required.
793 See also the variable `org-table-auto-blank-field'."
794 :group 'org-table
795 :type '(choice
796 (const :tag "off" nil)
797 (const :tag "on" t)
798 (const :tag "on, optimized" optimized)))
800 (defcustom org-table-tab-recognizes-table.el t
801 "Non-nil means, TAB will automatically notice a table.el table.
802 When it sees such a table, it moves point into it and - if necessary -
803 calls `table-recognize-table'."
804 :group 'org-table-editing
805 :type 'boolean)
807 (defgroup org-link nil
808 "Options concerning links in Org-mode."
809 :tag "Org Link"
810 :group 'org)
812 (defvar org-link-abbrev-alist-local nil
813 "Buffer-local version of `org-link-abbrev-alist', which see.
814 The value of this is taken from the #+LINK lines.")
815 (make-variable-buffer-local 'org-link-abbrev-alist-local)
817 (defcustom org-link-abbrev-alist nil
818 "Alist of link abbreviations.
819 The car of each element is a string, to be replaced at the start of a link.
820 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
821 links in Org-mode buffers can have an optional tag after a double colon, e.g.
823 [[linkkey:tag][description]]
825 If REPLACE is a string, the tag will simply be appended to create the link.
826 If the string contains \"%s\", the tag will be inserted there.
828 REPLACE may also be a function that will be called with the tag as the
829 only argument to create the link, which should be returned as a string.
831 See the manual for examples."
832 :group 'org-link
833 :type 'alist)
835 (defcustom org-descriptive-links t
836 "Non-nil means, hide link part and only show description of bracket links.
837 Bracket links are like [[link][descritpion]]. This variable sets the initial
838 state in new org-mode buffers. The setting can then be toggled on a
839 per-buffer basis from the Org->Hyperlinks menu."
840 :group 'org-link
841 :type 'boolean)
843 (defcustom org-link-file-path-type 'adaptive
844 "How the path name in file links should be stored.
845 Valid values are:
847 relative Relative to the current directory, i.e. the directory of the file
848 into which the link is being inserted.
849 absolute Absolute path, if possible with ~ for home directory.
850 noabbrev Absolute path, no abbreviation of home directory.
851 adaptive Use relative path for files in the current directory and sub-
852 directories of it. For other files, use an absolute path."
853 :group 'org-link
854 :type '(choice
855 (const relative)
856 (const absolute)
857 (const noabbrev)
858 (const adaptive)))
860 (defcustom org-activate-links '(bracket angle plain radio tag date)
861 "Types of links that should be activated in Org-mode files.
862 This is a list of symbols, each leading to the activation of a certain link
863 type. In principle, it does not hurt to turn on most link types - there may
864 be a small gain when turning off unused link types. The types are:
866 bracket The recommended [[link][description]] or [[link]] links with hiding.
867 angular Links in angular brackes that may contain whitespace like
868 <bbdb:Carsten Dominik>.
869 plain Plain links in normal text, no whitespace, like http://google.com.
870 radio Text that is matched by a radio target, see manual for details.
871 tag Tag settings in a headline (link to tag search).
872 date Time stamps (link to calendar).
874 Changing this variable requires a restart of Emacs to become effective."
875 :group 'org-link
876 :type '(set (const :tag "Double bracket links (new style)" bracket)
877 (const :tag "Angular bracket links (old style)" angular)
878 (const :tag "Plain text links" plain)
879 (const :tag "Radio target matches" radio)
880 (const :tag "Tags" tag)
881 (const :tag "Timestamps" date)))
883 (defcustom org-make-link-description-function nil
884 "Function to use to generate link descriptions from links. If
885 nil the link location will be used. This function must take two
886 parameters; the first is the link and the second the description
887 org-insert-link has generated, and should return the description
888 to use."
889 :group 'org-link
890 :type 'function)
892 (defgroup org-link-store nil
893 "Options concerning storing links in Org-mode."
894 :tag "Org Store Link"
895 :group 'org-link)
897 (defcustom org-email-link-description-format "Email %c: %.30s"
898 "Format of the description part of a link to an email or usenet message.
899 The following %-excapes will be replaced by corresponding information:
901 %F full \"From\" field
902 %f name, taken from \"From\" field, address if no name
903 %T full \"To\" field
904 %t first name in \"To\" field, address if no name
905 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
906 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
907 %s subject
908 %m message-id.
910 You may use normal field width specification between the % and the letter.
911 This is for example useful to limit the length of the subject.
913 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
914 :group 'org-link-store
915 :type 'string)
917 (defcustom org-from-is-user-regexp
918 (let (r1 r2)
919 (when (and user-mail-address (not (string= user-mail-address "")))
920 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
921 (when (and user-full-name (not (string= user-full-name "")))
922 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
923 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
924 "Regexp mached against the \"From:\" header of an email or usenet message.
925 It should match if the message is from the user him/herself."
926 :group 'org-link-store
927 :type 'regexp)
929 (defcustom org-context-in-file-links t
930 "Non-nil means, file links from `org-store-link' contain context.
931 A search string will be added to the file name with :: as separator and
932 used to find the context when the link is activated by the command
933 `org-open-at-point'.
934 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
935 negates this setting for the duration of the command."
936 :group 'org-link-store
937 :type 'boolean)
939 (defcustom org-keep-stored-link-after-insertion nil
940 "Non-nil means, keep link in list for entire session.
942 The command `org-store-link' adds a link pointing to the current
943 location to an internal list. These links accumulate during a session.
944 The command `org-insert-link' can be used to insert links into any
945 Org-mode file (offering completion for all stored links). When this
946 option is nil, every link which has been inserted once using \\[org-insert-link]
947 will be removed from the list, to make completing the unused links
948 more efficient."
949 :group 'org-link-store
950 :type 'boolean)
952 (defgroup org-link-follow nil
953 "Options concerning following links in Org-mode."
954 :tag "Org Follow Link"
955 :group 'org-link)
957 (defcustom org-follow-link-hook nil
958 "Hook that is run after a link has been followed."
959 :group 'org-link-follow
960 :type 'hook)
962 (defcustom org-tab-follows-link nil
963 "Non-nil means, on links TAB will follow the link.
964 Needs to be set before org.el is loaded."
965 :group 'org-link-follow
966 :type 'boolean)
968 (defcustom org-return-follows-link nil
969 "Non-nil means, on links RET will follow the link.
970 Needs to be set before org.el is loaded."
971 :group 'org-link-follow
972 :type 'boolean)
974 (defcustom org-mouse-1-follows-link
975 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
976 "Non-nil means, mouse-1 on a link will follow the link.
977 A longer mouse click will still set point. Does not work on XEmacs.
978 Needs to be set before org.el is loaded."
979 :group 'org-link-follow
980 :type 'boolean)
982 (defcustom org-mark-ring-length 4
983 "Number of different positions to be recorded in the ring
984 Changing this requires a restart of Emacs to work correctly."
985 :group 'org-link-follow
986 :type 'interger)
988 (defcustom org-link-frame-setup
989 '((vm . vm-visit-folder-other-frame)
990 (gnus . gnus-other-frame)
991 (file . find-file-other-window))
992 "Setup the frame configuration for following links.
993 When following a link with Emacs, it may often be useful to display
994 this link in another window or frame. This variable can be used to
995 set this up for the different types of links.
996 For VM, use any of
997 `vm-visit-folder'
998 `vm-visit-folder-other-frame'
999 For Gnus, use any of
1000 `gnus'
1001 `gnus-other-frame'
1002 For FILE, use any of
1003 `find-file'
1004 `find-file-other-window'
1005 `find-file-other-frame'
1006 For the calendar, use the variable `calendar-setup'.
1007 For BBDB, it is currently only possible to display the matches in
1008 another window."
1009 :group 'org-link-follow
1010 :type '(list
1011 (cons (const vm)
1012 (choice
1013 (const vm-visit-folder)
1014 (const vm-visit-folder-other-window)
1015 (const vm-visit-folder-other-frame)))
1016 (cons (const gnus)
1017 (choice
1018 (const gnus)
1019 (const gnus-other-frame)))
1020 (cons (const file)
1021 (choice
1022 (const find-file)
1023 (const find-file-other-window)
1024 (const find-file-other-frame)))))
1026 (defcustom org-display-internal-link-with-indirect-buffer nil
1027 "Non-nil means, use indirect buffer to display infile links.
1028 Activating internal links (from one location in a file to another location
1029 in the same file) normally just jumps to the location. When the link is
1030 activated with a C-u prefix (or with mouse-3), the link is displayed in
1031 another window. When this option is set, the other window actually displays
1032 an indirect buffer clone of the current buffer, to avoid any visibility
1033 changes to the current buffer."
1034 :group 'org-link-follow
1035 :type 'boolean)
1037 (defcustom org-open-non-existing-files nil
1038 "Non-nil means, `org-open-file' will open non-existing files.
1039 When nil, an error will be generated."
1040 :group 'org-link-follow
1041 :type 'boolean)
1043 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1044 "Function and arguments to call for following mailto links.
1045 This is a list with the first element being a lisp function, and the
1046 remaining elements being arguments to the function. In string arguments,
1047 %a will be replaced by the address, and %s will be replaced by the subject
1048 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1049 :group 'org-link-follow
1050 :type '(choice
1051 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1052 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1053 (const :tag "message-mail" (message-mail "%a" "%s"))
1054 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1056 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1057 "Non-nil means, ask for confirmation before executing shell links.
1058 Shell links can be dangerous: just think about a link
1060 [[shell:rm -rf ~/*][Google Search]]
1062 This link would show up in your Org-mode document as \"Google Search\",
1063 but really it would remove your entire home directory.
1064 Therefore we advise against setting this variable to nil.
1065 Just change it to `y-or-n-p' of you want to confirm with a
1066 single keystroke rather than having to type \"yes\"."
1067 :group 'org-link-follow
1068 :type '(choice
1069 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1070 (const :tag "with y-or-n (faster)" y-or-n-p)
1071 (const :tag "no confirmation (dangerous)" nil)))
1073 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1074 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1075 Elisp links can be dangerous: just think about a link
1077 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1079 This link would show up in your Org-mode document as \"Google Search\",
1080 but really it would remove your entire home directory.
1081 Therefore we advise against setting this variable to nil.
1082 Just change it to `y-or-n-p' of you want to confirm with a
1083 single keystroke rather than having to type \"yes\"."
1084 :group 'org-link-follow
1085 :type '(choice
1086 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1087 (const :tag "with y-or-n (faster)" y-or-n-p)
1088 (const :tag "no confirmation (dangerous)" nil)))
1090 (defconst org-file-apps-defaults-gnu
1091 '((remote . emacs)
1092 (t . mailcap))
1093 "Default file applications on a UNIX or GNU/Linux system.
1094 See `org-file-apps'.")
1096 (defconst org-file-apps-defaults-macosx
1097 '((remote . emacs)
1098 (t . "open %s")
1099 ("ps" . "gv %s")
1100 ("ps.gz" . "gv %s")
1101 ("eps" . "gv %s")
1102 ("eps.gz" . "gv %s")
1103 ("dvi" . "xdvi %s")
1104 ("fig" . "xfig %s"))
1105 "Default file applications on a MacOS X system.
1106 The system \"open\" is known as a default, but we use X11 applications
1107 for some files for which the OS does not have a good default.
1108 See `org-file-apps'.")
1110 (defconst org-file-apps-defaults-windowsnt
1111 (list
1112 '(remote . emacs)
1113 (cons t
1114 (list (if (featurep 'xemacs)
1115 'mswindows-shell-execute
1116 'w32-shell-execute)
1117 "open" 'file)))
1118 "Default file applications on a Windows NT system.
1119 The system \"open\" is used for most files.
1120 See `org-file-apps'.")
1122 (defcustom org-file-apps
1124 ("txt" . emacs)
1125 ("tex" . emacs)
1126 ("ltx" . emacs)
1127 ("org" . emacs)
1128 ("el" . emacs)
1129 ("bib" . emacs)
1131 "External applications for opening `file:path' items in a document.
1132 Org-mode uses system defaults for different file types, but
1133 you can use this variable to set the application for a given file
1134 extension. The entries in this list are cons cells where the car identifies
1135 files and the cdr the corresponding command. Possible values for the
1136 file identifier are
1137 \"ext\" A string identifying an extension
1138 `directory' Matches a directory
1139 `remote' Matches a remote file, accessible through tramp or efs.
1140 Remote files most likely should be visited through Emacs
1141 because external applications cannot handle such paths.
1142 t Default for all remaining files
1144 Possible values for the command are:
1145 `emacs' The file will be visited by the current Emacs process.
1146 `default' Use the default application for this file type.
1147 string A command to be executed by a shell; %s will be replaced
1148 by the path to the file.
1149 sexp A Lisp form which will be evaluated. The file path will
1150 be available in the Lisp variable `file'.
1151 For more examples, see the system specific constants
1152 `org-file-apps-defaults-macosx'
1153 `org-file-apps-defaults-windowsnt'
1154 `org-file-apps-defaults-gnu'."
1155 :group 'org-link-follow
1156 :type '(repeat
1157 (cons (choice :value ""
1158 (string :tag "Extension")
1159 (const :tag "Default for unrecognized files" t)
1160 (const :tag "Remote file" remote)
1161 (const :tag "Links to a directory" directory))
1162 (choice :value ""
1163 (const :tag "Visit with Emacs" emacs)
1164 (const :tag "Use system default" default)
1165 (string :tag "Command")
1166 (sexp :tag "Lisp form")))))
1168 (defgroup org-refile nil
1169 "Options concerning refiling entries in Org-mode."
1170 :tag "Org Remember"
1171 :group 'org)
1173 (defcustom org-directory "~/org"
1174 "Directory with org files.
1175 This directory will be used as default to prompt for org files.
1176 Used by the hooks for remember.el."
1177 :group 'org-refile
1178 :group 'org-remember
1179 :type 'directory)
1181 (defcustom org-default-notes-file "~/.notes"
1182 "Default target for storing notes.
1183 Used by the hooks for remember.el. This can be a string, or nil to mean
1184 the value of `remember-data-file'.
1185 You can set this on a per-template basis with the variable
1186 `org-remember-templates'."
1187 :group 'org-refile
1188 :group 'org-remember
1189 :type '(choice
1190 (const :tag "Default from remember-data-file" nil)
1191 file))
1193 (defcustom org-goto-interface 'outline
1194 "The default interface to be used for `org-goto'.
1195 Allowed vaues are:
1196 outline The interface shows an outline of the relevant file
1197 and the correct heading is found by moving through
1198 the outline or by searching with incremental search.
1199 outline-path-completion Headlines in the current buffer are offered via
1200 completion."
1201 :group 'org-refile
1202 :type '(choice
1203 (const :tag "Outline" outline)
1204 (const :tag "Outline-path-completion" outline-path-completion)))
1206 (defcustom org-reverse-note-order nil
1207 "Non-nil means, store new notes at the beginning of a file or entry.
1208 When nil, new notes will be filed to the end of a file or entry.
1209 This can also be a list with cons cells of regular expressions that
1210 are matched against file names, and values."
1211 :group 'org-remember
1212 :type '(choice
1213 (const :tag "Reverse always" t)
1214 (const :tag "Reverse never" nil)
1215 (repeat :tag "By file name regexp"
1216 (cons regexp boolean))))
1218 (defcustom org-refile-targets nil
1219 "Targets for refiling entries with \\[org-refile].
1220 This is list of cons cells. Each cell contains:
1221 - a specification of the files to be considered, either a list of files,
1222 or a symbol whose function or variable value will be used to retrieve
1223 a file name or a list of file names. Nil means, refile to a different
1224 heading in the current buffer.
1225 - A specification of how to find candidate refile targets. This may be
1226 any of
1227 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1228 This tag has to be present in all target headlines, inheritance will
1229 not be considered.
1230 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1231 todo keyword.
1232 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1233 headlines that are refiling targets.
1234 - a cons cell (:level . N). Any headline of level N is considered a target.
1235 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1236 :group 'org-remember
1237 :type '(repeat
1238 (cons
1239 (choice :value org-agenda-files
1240 (const :tag "All agenda files" org-agenda-files)
1241 (const :tag "Current buffer" nil)
1242 (function) (variable) (file))
1243 (choice :tag "Identify target headline by"
1244 (cons :tag "Specific tag" (const :tag) (string))
1245 (cons :tag "TODO keyword" (const :todo) (string))
1246 (cons :tag "Regular expression" (const :regexp) (regexp))
1247 (cons :tag "Level number" (const :level) (integer))
1248 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1250 (defcustom org-refile-use-outline-path nil
1251 "Non-nil means, provide refile targets as paths.
1252 So a level 3 headline will be available as level1/level2/level3.
1253 When the value is `file', also include the file name (without directory)
1254 into the path. When `full-file-path', include the full file path."
1255 :group 'org-remember
1256 :type '(choice
1257 (const :tag "Not" nil)
1258 (const :tag "Yes" t)
1259 (const :tag "Start with file name" file)
1260 (const :tag "Start with full file path" full-file-path)))
1262 (defgroup org-todo nil
1263 "Options concerning TODO items in Org-mode."
1264 :tag "Org TODO"
1265 :group 'org)
1267 (defgroup org-progress nil
1268 "Options concerning Progress logging in Org-mode."
1269 :tag "Org Progress"
1270 :group 'org-time)
1272 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1273 "List of TODO entry keyword sequences and their interpretation.
1274 \\<org-mode-map>This is a list of sequences.
1276 Each sequence starts with a symbol, either `sequence' or `type',
1277 indicating if the keywords should be interpreted as a sequence of
1278 action steps, or as different types of TODO items. The first
1279 keywords are states requiring action - these states will select a headline
1280 for inclusion into the global TODO list Org-mode produces. If one of
1281 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1282 signify that no further action is necessary. If \"|\" is not found,
1283 the last keyword is treated as the only DONE state of the sequence.
1285 The command \\[org-todo] cycles an entry through these states, and one
1286 additional state where no keyword is present. For details about this
1287 cycling, see the manual.
1289 TODO keywords and interpretation can also be set on a per-file basis with
1290 the special #+SEQ_TODO and #+TYP_TODO lines.
1292 Each keyword can optionally specify a character for fast state selection
1293 \(in combination with the variable `org-use-fast-todo-selection')
1294 and specifiers for state change logging, using the same syntax
1295 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1296 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1297 indicates to record a time stamp each time this state is selected.
1299 Each keyword may also specify if a timestamp or a note should be
1300 recorded when entering or leaving the state, by adding additional
1301 characters in the parenthesis after the keyword. This looks like this:
1302 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1303 record only the time of the state change. With X and Y being either
1304 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1305 Y when leaving the state if and only if the *target* state does not
1306 define X. You may omit any of the fast-selection key or X or /Y,
1307 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1309 For backward compatibility, this variable may also be just a list
1310 of keywords - in this case the interptetation (sequence or type) will be
1311 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1312 :group 'org-todo
1313 :group 'org-keywords
1314 :type '(choice
1315 (repeat :tag "Old syntax, just keywords"
1316 (string :tag "Keyword"))
1317 (repeat :tag "New syntax"
1318 (cons
1319 (choice
1320 :tag "Interpretation"
1321 (const :tag "Sequence (cycling hits every state)" sequence)
1322 (const :tag "Type (cycling directly to DONE)" type))
1323 (repeat
1324 (string :tag "Keyword"))))))
1326 (defvar org-todo-keywords-1 nil
1327 "All TODO and DONE keywords active in a buffer.")
1328 (make-variable-buffer-local 'org-todo-keywords-1)
1329 (defvar org-todo-keywords-for-agenda nil)
1330 (defvar org-done-keywords-for-agenda nil)
1331 (defvar org-agenda-contributing-files nil)
1332 (defvar org-not-done-keywords nil)
1333 (make-variable-buffer-local 'org-not-done-keywords)
1334 (defvar org-done-keywords nil)
1335 (make-variable-buffer-local 'org-done-keywords)
1336 (defvar org-todo-heads nil)
1337 (make-variable-buffer-local 'org-todo-heads)
1338 (defvar org-todo-sets nil)
1339 (make-variable-buffer-local 'org-todo-sets)
1340 (defvar org-todo-log-states nil)
1341 (make-variable-buffer-local 'org-todo-log-states)
1342 (defvar org-todo-kwd-alist nil)
1343 (make-variable-buffer-local 'org-todo-kwd-alist)
1344 (defvar org-todo-key-alist nil)
1345 (make-variable-buffer-local 'org-todo-key-alist)
1346 (defvar org-todo-key-trigger nil)
1347 (make-variable-buffer-local 'org-todo-key-trigger)
1349 (defcustom org-todo-interpretation 'sequence
1350 "Controls how TODO keywords are interpreted.
1351 This variable is in principle obsolete and is only used for
1352 backward compatibility, if the interpretation of todo keywords is
1353 not given already in `org-todo-keywords'. See that variable for
1354 more information."
1355 :group 'org-todo
1356 :group 'org-keywords
1357 :type '(choice (const sequence)
1358 (const type)))
1360 (defcustom org-use-fast-todo-selection 'prefix
1361 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1362 This variable describes if and under what circumstances the cycling
1363 mechanism for TODO keywords will be replaced by a single-key, direct
1364 selection scheme.
1366 When nil, fast selection is never used.
1368 When the symbol `prefix', it will be used when `org-todo' is called with
1369 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1370 in an agenda buffer.
1372 When t, fast selection is used by default. In this case, the prefix
1373 argument forces cycling instead.
1375 In all cases, the special interface is only used if access keys have actually
1376 been assigned by the user, i.e. if keywords in the configuration are followed
1377 by a letter in parenthesis, like TODO(t)."
1378 :group 'org-todo
1379 :type '(choice
1380 (const :tag "Never" nil)
1381 (const :tag "By default" t)
1382 (const :tag "Only with C-u C-c C-t" prefix)))
1384 (defcustom org-after-todo-state-change-hook nil
1385 "Hook which is run after the state of a TODO item was changed.
1386 The new state (a string with a TODO keyword, or nil) is available in the
1387 Lisp variable `state'."
1388 :group 'org-todo
1389 :type 'hook)
1391 (defcustom org-log-done nil
1392 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1393 When equal to the list (done), also prompt for a closing note.
1394 This can also be configured on a per-file basis by adding one of
1395 the following lines anywhere in the buffer:
1397 #+STARTUP: logdone
1398 #+STARTUP: lognotedone
1399 #+STARTUP: nologdone"
1400 :group 'org-todo
1401 :group 'org-progress
1402 :type '(choice
1403 (const :tag "No logging" nil)
1404 (const :tag "Record CLOSED timestamp" time)
1405 (const :tag "Record CLOSED timestamp with closing note." note)))
1407 ;; Normalize old uses of org-log-done.
1408 (cond
1409 ((eq org-log-done t) (setq org-log-done 'time))
1410 ((and (listp org-log-done) (memq 'done org-log-done))
1411 (setq org-log-done 'note)))
1413 (defcustom org-log-note-clock-out nil
1414 "Non-nil means, recored a note when clocking out of an item.
1415 This can also be configured on a per-file basis by adding one of
1416 the following lines anywhere in the buffer:
1418 #+STARTUP: lognoteclock-out
1419 #+STARTUP: nolognoteclock-out"
1420 :group 'org-todo
1421 :group 'org-progress
1422 :type 'boolean)
1424 (defcustom org-log-done-with-time t
1425 "Non-nil means, the CLOSED time stamp will contain date and time.
1426 When nil, only the date will be recorded."
1427 :group 'org-progress
1428 :type 'boolean)
1430 (defcustom org-log-note-headings
1431 '((done . "CLOSING NOTE %t")
1432 (state . "State %-12s %t")
1433 (note . "Note taken on %t")
1434 (clock-out . ""))
1435 "Headings for notes added to entries.
1436 The value is an alist, with the car being a symbol indicating the note
1437 context, and the cdr is the heading to be used. The heading may also be the
1438 empty string.
1439 %t in the heading will be replaced by a time stamp.
1440 %s will be replaced by the new TODO state, in double quotes.
1441 %u will be replaced by the user name.
1442 %U will be replaced by the full user name."
1443 :group 'org-todo
1444 :group 'org-progress
1445 :type '(list :greedy t
1446 (cons (const :tag "Heading when closing an item" done) string)
1447 (cons (const :tag
1448 "Heading when changing todo state (todo sequence only)"
1449 state) string)
1450 (cons (const :tag "Heading when just taking a note" note) string)
1451 (cons (const :tag "Heading when clocking out" clock-out) string)))
1453 (unless (assq 'note org-log-note-headings)
1454 (push '(note . "%t") org-log-note-headings))
1456 (defcustom org-log-states-order-reversed t
1457 "Non-nil means, the latest state change note will be directly after heading.
1458 When nil, the notes will be orderer according to time."
1459 :group 'org-todo
1460 :group 'org-progress
1461 :type 'boolean)
1463 (defcustom org-log-repeat 'time
1464 "Non-nil means, record moving through the DONE state when triggering repeat.
1465 An auto-repeating tasks is immediately switched back to TODO when marked
1466 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1467 the TODO keyword definition, or recording a closing note by setting
1468 `org-log-done', there will be no record of the task moving through DONE.
1469 This variable forces taking a note anyway. Possible values are:
1471 nil Don't force a record
1472 time Record a time stamp
1473 note Record a note
1475 This option can also be set with on a per-file-basis with
1477 #+STARTUP: logrepeat
1478 #+STARTUP: lognoterepeat
1479 #+STARTUP: nologrepeat
1481 You can have local logging settings for a subtree by setting the LOGGING
1482 property to one or more of these keywords."
1483 :group 'org-todo
1484 :group 'org-progress
1485 :type '(choice
1486 (const :tag "Don't force a record" nil)
1487 (const :tag "Force recording the DONE state" time)
1488 (const :tag "Force recording a note with the DONE state" note)))
1491 (defgroup org-priorities nil
1492 "Priorities in Org-mode."
1493 :tag "Org Priorities"
1494 :group 'org-todo)
1496 (defcustom org-highest-priority ?A
1497 "The highest priority of TODO items. A character like ?A, ?B etc.
1498 Must have a smaller ASCII number than `org-lowest-priority'."
1499 :group 'org-priorities
1500 :type 'character)
1502 (defcustom org-lowest-priority ?C
1503 "The lowest priority of TODO items. A character like ?A, ?B etc.
1504 Must have a larger ASCII number than `org-highest-priority'."
1505 :group 'org-priorities
1506 :type 'character)
1508 (defcustom org-default-priority ?B
1509 "The default priority of TODO items.
1510 This is the priority an item get if no explicit priority is given."
1511 :group 'org-priorities
1512 :type 'character)
1514 (defcustom org-priority-start-cycle-with-default t
1515 "Non-nil means, start with default priority when starting to cycle.
1516 When this is nil, the first step in the cycle will be (depending on the
1517 command used) one higher or lower that the default priority."
1518 :group 'org-priorities
1519 :type 'boolean)
1521 (defgroup org-time nil
1522 "Options concerning time stamps and deadlines in Org-mode."
1523 :tag "Org Time"
1524 :group 'org)
1526 (defcustom org-insert-labeled-timestamps-at-point nil
1527 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1528 When nil, these labeled time stamps are forces into the second line of an
1529 entry, just after the headline. When scheduling from the global TODO list,
1530 the time stamp will always be forced into the second line."
1531 :group 'org-time
1532 :type 'boolean)
1534 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1535 "Formats for `format-time-string' which are used for time stamps.
1536 It is not recommended to change this constant.")
1538 (defcustom org-time-stamp-rounding-minutes '(0 5)
1539 "Number of minutes to round time stamps to.
1540 These are two values, the first applies when first creating a time stamp.
1541 The second applies when changing it with the commands `S-up' and `S-down'.
1542 When changing the time stamp, this means that it will change in steps
1543 of N minutes, as given by the second value.
1545 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1546 numbers should be factors of 60, so for example 5, 10, 15.
1548 When this is larger than 1, you can still force an exact time-stamp by using
1549 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1550 and by using a prefix arg to `S-up/down' to specify the exact number
1551 of minutes to shift."
1552 :group 'org-time
1553 :get '(lambda (var) ; Make sure all entries have 5 elements
1554 (if (integerp (default-value var))
1555 (list (default-value var) 5)
1556 (default-value var)))
1557 :type '(list
1558 (integer :tag "when inserting times")
1559 (integer :tag "when modifying times")))
1561 ;; Normalize old customizations of this variable.
1562 (when (integerp org-time-stamp-rounding-minutes)
1563 (setq org-time-stamp-rounding-minutes
1564 (list org-time-stamp-rounding-minutes
1565 org-time-stamp-rounding-minutes)))
1567 (defcustom org-display-custom-times nil
1568 "Non-nil means, overlay custom formats over all time stamps.
1569 The formats are defined through the variable `org-time-stamp-custom-formats'.
1570 To turn this on on a per-file basis, insert anywhere in the file:
1571 #+STARTUP: customtime"
1572 :group 'org-time
1573 :set 'set-default
1574 :type 'sexp)
1575 (make-variable-buffer-local 'org-display-custom-times)
1577 (defcustom org-time-stamp-custom-formats
1578 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1579 "Custom formats for time stamps. See `format-time-string' for the syntax.
1580 These are overlayed over the default ISO format if the variable
1581 `org-display-custom-times' is set. Time like %H:%M should be at the
1582 end of the second format."
1583 :group 'org-time
1584 :type 'sexp)
1586 (defun org-time-stamp-format (&optional long inactive)
1587 "Get the right format for a time string."
1588 (let ((f (if long (cdr org-time-stamp-formats)
1589 (car org-time-stamp-formats))))
1590 (if inactive
1591 (concat "[" (substring f 1 -1) "]")
1592 f)))
1594 (defcustom org-deadline-warning-days 14
1595 "No. of days before expiration during which a deadline becomes active.
1596 This variable governs the display in sparse trees and in the agenda.
1597 When 0 or negative, it means use this number (the absolute value of it)
1598 even if a deadline has a different individual lead time specified."
1599 :group 'org-time
1600 :group 'org-agenda-daily/weekly
1601 :type 'number)
1603 (defcustom org-read-date-prefer-future t
1604 "Non-nil means, assume future for incomplete date input from user.
1605 This affects the following situations:
1606 1. The user gives a day, but no month.
1607 For example, if today is the 15th, and you enter \"3\", Org-mode will
1608 read this as the third of *next* month. However, if you enter \"17\",
1609 it will be considered as *this* month.
1610 2. The user gives a month but not a year.
1611 For example, if it is april and you enter \"feb 2\", this will be read
1612 as feb 2, *next* year. \"May 5\", however, will be this year.
1614 Currently this does not work for ISO week specifications.
1616 When this option is nil, the current month and year will always be used
1617 as defaults."
1618 :group 'org-time
1619 :type 'boolean)
1621 (defcustom org-read-date-display-live t
1622 "Non-nil means, display current interpretation of date prompt live.
1623 This display will be in an overlay, in the minibuffer."
1624 :group 'org-time
1625 :type 'boolean)
1627 (defcustom org-read-date-popup-calendar t
1628 "Non-nil means, pop up a calendar when prompting for a date.
1629 In the calendar, the date can be selected with mouse-1. However, the
1630 minibuffer will also be active, and you can simply enter the date as well.
1631 When nil, only the minibuffer will be available."
1632 :group 'org-time
1633 :type 'boolean)
1634 (if (fboundp 'defvaralias)
1635 (defvaralias 'org-popup-calendar-for-date-prompt
1636 'org-read-date-popup-calendar))
1638 (defcustom org-extend-today-until 0
1639 "The hour when your day really ends.
1640 This has influence for the following applications:
1641 - When switching the agenda to \"today\". It it is still earlier than
1642 the time given here, the day recognized as TODAY is actually yesterday.
1643 - When a date is read from the user and it is still before the time given
1644 here, the current date and time will be assumed to be yesterday, 23:59.
1646 FIXME:
1647 IMPORTANT: This is still a very experimental feature, it may disappear
1648 again or it may be extended to mean more things."
1649 :group 'org-time
1650 :type 'number)
1652 (defcustom org-edit-timestamp-down-means-later nil
1653 "Non-nil means, S-down will increase the time in a time stamp.
1654 When nil, S-up will increase."
1655 :group 'org-time
1656 :type 'boolean)
1658 (defcustom org-calendar-follow-timestamp-change t
1659 "Non-nil means, make the calendar window follow timestamp changes.
1660 When a timestamp is modified and the calendar window is visible, it will be
1661 moved to the new date."
1662 :group 'org-time
1663 :type 'boolean)
1665 (defgroup org-tags nil
1666 "Options concerning tags in Org-mode."
1667 :tag "Org Tags"
1668 :group 'org)
1670 (defcustom org-tag-alist nil
1671 "List of tags allowed in Org-mode files.
1672 When this list is nil, Org-mode will base TAG input on what is already in the
1673 buffer.
1674 The value of this variable is an alist, the car of each entry must be a
1675 keyword as a string, the cdr may be a character that is used to select
1676 that tag through the fast-tag-selection interface.
1677 See the manual for details."
1678 :group 'org-tags
1679 :type '(repeat
1680 (choice
1681 (cons (string :tag "Tag name")
1682 (character :tag "Access char"))
1683 (const :tag "Start radio group" (:startgroup))
1684 (const :tag "End radio group" (:endgroup)))))
1686 (defcustom org-use-fast-tag-selection 'auto
1687 "Non-nil means, use fast tag selection scheme.
1688 This is a special interface to select and deselect tags with single keys.
1689 When nil, fast selection is never used.
1690 When the symbol `auto', fast selection is used if and only if selection
1691 characters for tags have been configured, either through the variable
1692 `org-tag-alist' or through a #+TAGS line in the buffer.
1693 When t, fast selection is always used and selection keys are assigned
1694 automatically if necessary."
1695 :group 'org-tags
1696 :type '(choice
1697 (const :tag "Always" t)
1698 (const :tag "Never" nil)
1699 (const :tag "When selection characters are configured" 'auto)))
1701 (defcustom org-fast-tag-selection-single-key nil
1702 "Non-nil means, fast tag selection exits after first change.
1703 When nil, you have to press RET to exit it.
1704 During fast tag selection, you can toggle this flag with `C-c'.
1705 This variable can also have the value `expert'. In this case, the window
1706 displaying the tags menu is not even shown, until you press C-c again."
1707 :group 'org-tags
1708 :type '(choice
1709 (const :tag "No" nil)
1710 (const :tag "Yes" t)
1711 (const :tag "Expert" expert)))
1713 (defvar org-fast-tag-selection-include-todo nil
1714 "Non-nil means, fast tags selection interface will also offer TODO states.
1715 This is an undocumented feature, you should not rely on it.")
1717 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1718 "The column to which tags should be indented in a headline.
1719 If this number is positive, it specifies the column. If it is negative,
1720 it means that the tags should be flushright to that column. For example,
1721 -80 works well for a normal 80 character screen."
1722 :group 'org-tags
1723 :type 'integer)
1725 (defcustom org-auto-align-tags t
1726 "Non-nil means, realign tags after pro/demotion of TODO state change.
1727 These operations change the length of a headline and therefore shift
1728 the tags around. With this options turned on, after each such operation
1729 the tags are again aligned to `org-tags-column'."
1730 :group 'org-tags
1731 :type 'boolean)
1733 (defcustom org-use-tag-inheritance t
1734 "Non-nil means, tags in levels apply also for sublevels.
1735 When nil, only the tags directly given in a specific line apply there.
1736 If you turn off this option, you very likely want to turn on the
1737 companion option `org-tags-match-list-sublevels'.
1739 This may also be a list of tags that should be inherited, or a regexp that
1740 matches tags that should be inherited."
1741 :group 'org-tags
1742 :type '(choice
1743 (const :tag "Not" nil)
1744 (const :tag "Always" t)
1745 (repeat :tag "Specific tags" (string :tag "Tag"))
1746 (regexp :tag "Tags matched by regexp")))
1748 (defun org-tag-inherit-p (tag)
1749 "Check if TAG is one that should be inherited."
1750 (cond
1751 ((eq org-use-tag-inheritance t) t)
1752 ((not org-use-tag-inheritance) nil)
1753 ((stringp org-use-tag-inheritance)
1754 (string-match org-use-tag-inheritance tag))
1755 ((listp org-use-tag-inheritance)
1756 (member tag org-use-tag-inheritance))
1757 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1759 (defcustom org-tags-match-list-sublevels nil
1760 "Non-nil means list also sublevels of headlines matching tag search.
1761 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1762 the sublevels of a headline matching a tag search often also match
1763 the same search. Listing all of them can create very long lists.
1764 Setting this variable to nil causes subtrees of a match to be skipped.
1765 This option is off by default, because inheritance in on. If you turn
1766 inheritance off, you very likely want to turn this option on.
1768 As a special case, if the tag search is restricted to TODO items, the
1769 value of this variable is ignored and sublevels are always checked, to
1770 make sure all corresponding TODO items find their way into the list."
1771 :group 'org-tags
1772 :type 'boolean)
1774 (defvar org-tags-history nil
1775 "History of minibuffer reads for tags.")
1776 (defvar org-last-tags-completion-table nil
1777 "The last used completion table for tags.")
1778 (defvar org-after-tags-change-hook nil
1779 "Hook that is run after the tags in a line have changed.")
1781 (defgroup org-properties nil
1782 "Options concerning properties in Org-mode."
1783 :tag "Org Properties"
1784 :group 'org)
1786 (defcustom org-property-format "%-10s %s"
1787 "How property key/value pairs should be formatted by `indent-line'.
1788 When `indent-line' hits a property definition, it will format the line
1789 according to this format, mainly to make sure that the values are
1790 lined-up with respect to each other."
1791 :group 'org-properties
1792 :type 'string)
1794 (defcustom org-use-property-inheritance nil
1795 "Non-nil means, properties apply also for sublevels.
1797 This setting is chiefly used during property searches. Turning it on can
1798 cause significant overhead when doing a search, which is why it is not
1799 on by default.
1801 When nil, only the properties directly given in the current entry count.
1802 When t, every property is inherited. The value may also be a list of
1803 properties that should have inheritance, or a regular expression matching
1804 properties that should be inherited.
1806 However, note that some special properties use inheritance under special
1807 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1808 and the properties ending in \"_ALL\" when they are used as descriptor
1809 for valid values of a property.
1811 Note for programmers:
1812 When querying an entry with `org-entry-get', you can control if inheritance
1813 should be used. By default, `org-entry-get' looks only at the local
1814 properties. You can request inheritance by setting the inherit argument
1815 to t (to force inheritance) or to `selective' (to respect the setting
1816 in this variable)."
1817 :group 'org-properties
1818 :type '(choice
1819 (const :tag "Not" nil)
1820 (const :tag "Always" t)
1821 (repeat :tag "Specific properties" (string :tag "Property"))
1822 (regexp :tag "Properties matched by regexp")))
1824 (defun org-property-inherit-p (property)
1825 "Check if PROPERTY is one that should be inherited."
1826 (cond
1827 ((eq org-use-property-inheritance t) t)
1828 ((not org-use-property-inheritance) nil)
1829 ((stringp org-use-property-inheritance)
1830 (string-match org-use-property-inheritance property))
1831 ((listp org-use-property-inheritance)
1832 (member property org-use-property-inheritance))
1833 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1835 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1836 "The default column format, if no other format has been defined.
1837 This variable can be set on the per-file basis by inserting a line
1839 #+COLUMNS: %25ITEM ....."
1840 :group 'org-properties
1841 :type 'string)
1843 (defcustom org-effort-property "Effort"
1844 "The property that is being used to keep track of effort estimates.
1845 Effort estimates given in this property need to have the format H:MM."
1846 :group 'org-properties
1847 :group 'org-progress
1848 :type '(string :tag "Property"))
1850 (defconst org-global-properties-fixed
1851 '(("VISIBILITY_ALL" . "folded children content all"))
1852 "List of property/value pairs that can be inherited by any entry.
1853 These are fixed values, for the preset properties.")
1856 (defcustom org-global-properties nil
1857 "List of property/value pairs that can be inherited by any entry.
1858 You can set buffer-local values for this by adding lines like
1860 #+PROPERTY: NAME VALUE"
1861 :group 'org-properties
1862 :type '(repeat
1863 (cons (string :tag "Property")
1864 (string :tag "Value"))))
1866 (defvar org-local-properties nil
1867 "List of property/value pairs that can be inherited by any entry.
1868 Valid for the current buffer.
1869 This variable is populated from #+PROPERTY lines.")
1871 (defgroup org-agenda nil
1872 "Options concerning agenda views in Org-mode."
1873 :tag "Org Agenda"
1874 :group 'org)
1876 (defvar org-category nil
1877 "Variable used by org files to set a category for agenda display.
1878 Such files should use a file variable to set it, for example
1880 # -*- mode: org; org-category: \"ELisp\"
1882 or contain a special line
1884 #+CATEGORY: ELisp
1886 If the file does not specify a category, then file's base name
1887 is used instead.")
1888 (make-variable-buffer-local 'org-category)
1890 (defcustom org-agenda-files nil
1891 "The files to be used for agenda display.
1892 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1893 \\[org-remove-file]. You can also use customize to edit the list.
1895 If an entry is a directory, all files in that directory that are matched by
1896 `org-agenda-file-regexp' will be part of the file list.
1898 If the value of the variable is not a list but a single file name, then
1899 the list of agenda files is actually stored and maintained in that file, one
1900 agenda file per line."
1901 :group 'org-agenda
1902 :type '(choice
1903 (repeat :tag "List of files and directories" file)
1904 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1906 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1907 "Regular expression to match files for `org-agenda-files'.
1908 If any element in the list in that variable contains a directory instead
1909 of a normal file, all files in that directory that are matched by this
1910 regular expression will be included."
1911 :group 'org-agenda
1912 :type 'regexp)
1914 (defcustom org-agenda-text-search-extra-files nil
1915 "List of extra files to be searched by text search commands.
1916 These files will be search in addition to the agenda files by the
1917 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1918 Note that these files will only be searched for text search commands,
1919 not for the other agenda views like todo lists, tag searches or the weekly
1920 agenda. This variable is intended to list notes and possibly archive files
1921 that should also be searched by these two commands.
1922 In fact, if the first element in the list is the symbol `agenda-archives',
1923 than all archive files of all agenda files will be added to the search
1924 scope."
1925 :group 'org-agenda
1926 :type '(set :greedy t
1927 (const :tag "Agenda Archives" agenda-archives)
1928 (repeat :inline t (file))))
1930 (if (fboundp 'defvaralias)
1931 (defvaralias 'org-agenda-multi-occur-extra-files
1932 'org-agenda-text-search-extra-files))
1934 (defcustom org-agenda-skip-unavailable-files nil
1935 "t means to just skip non-reachable files in `org-agenda-files'.
1936 Nil means to remove them, after a query, from the list."
1937 :group 'org-agenda
1938 :type 'boolean)
1940 (defcustom org-calendar-to-agenda-key [?c]
1941 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1942 The command `org-calendar-goto-agenda' will be bound to this key. The
1943 default is the character `c' because then `c' can be used to switch back and
1944 forth between agenda and calendar."
1945 :group 'org-agenda
1946 :type 'sexp)
1948 (eval-after-load "calendar"
1949 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1950 'org-calendar-goto-agenda))
1952 (defgroup org-latex nil
1953 "Options for embedding LaTeX code into Org-mode."
1954 :tag "Org LaTeX"
1955 :group 'org)
1957 (defcustom org-format-latex-options
1958 '(:foreground default :background default :scale 1.0
1959 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1960 :matchers ("begin" "$" "$$" "\\(" "\\["))
1961 "Options for creating images from LaTeX fragments.
1962 This is a property list with the following properties:
1963 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
1964 `default' means use the foreground of the default face.
1965 :background the background color, or \"Transparent\".
1966 `default' means use the background of the default face.
1967 :scale a scaling factor for the size of the images.
1968 :html-foreground, :html-background, :html-scale
1969 the same numbers for HTML export.
1970 :matchers a list indicating which matchers should be used to
1971 find LaTeX fragments. Valid members of this list are:
1972 \"begin\" find environments
1973 \"$\" find math expressions surrounded by $...$
1974 \"$$\" find math expressions surrounded by $$....$$
1975 \"\\(\" find math expressions surrounded by \\(...\\)
1976 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1977 :group 'org-latex
1978 :type 'plist)
1980 (defcustom org-format-latex-header "\\documentclass{article}
1981 \\usepackage{fullpage} % do not remove
1982 \\usepackage{amssymb}
1983 \\usepackage[usenames]{color}
1984 \\usepackage{amsmath}
1985 \\usepackage{latexsym}
1986 \\usepackage[mathscr]{eucal}
1987 \\pagestyle{empty} % do not remove"
1988 "The document header used for processing LaTeX fragments."
1989 :group 'org-latex
1990 :type 'string)
1993 (defgroup org-font-lock nil
1994 "Font-lock settings for highlighting in Org-mode."
1995 :tag "Org Font Lock"
1996 :group 'org)
1998 (defcustom org-level-color-stars-only nil
1999 "Non-nil means fontify only the stars in each headline.
2000 When nil, the entire headline is fontified.
2001 Changing it requires restart of `font-lock-mode' to become effective
2002 also in regions already fontified."
2003 :group 'org-font-lock
2004 :type 'boolean)
2006 (defcustom org-hide-leading-stars nil
2007 "Non-nil means, hide the first N-1 stars in a headline.
2008 This works by using the face `org-hide' for these stars. This
2009 face is white for a light background, and black for a dark
2010 background. You may have to customize the face `org-hide' to
2011 make this work.
2012 Changing it requires restart of `font-lock-mode' to become effective
2013 also in regions already fontified.
2014 You may also set this on a per-file basis by adding one of the following
2015 lines to the buffer:
2017 #+STARTUP: hidestars
2018 #+STARTUP: showstars"
2019 :group 'org-font-lock
2020 :type 'boolean)
2022 (defcustom org-fontify-done-headline nil
2023 "Non-nil means, change the face of a headline if it is marked DONE.
2024 Normally, only the TODO/DONE keyword indicates the state of a headline.
2025 When this is non-nil, the headline after the keyword is set to the
2026 `org-headline-done' as an additional indication."
2027 :group 'org-font-lock
2028 :type 'boolean)
2030 (defcustom org-fontify-emphasized-text t
2031 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2032 Changing this variable requires a restart of Emacs to take effect."
2033 :group 'org-font-lock
2034 :type 'boolean)
2036 (defcustom org-highlight-latex-fragments-and-specials nil
2037 "Non-nil means, fontify what is treated specially by the exporters."
2038 :group 'org-font-lock
2039 :type 'boolean)
2041 (defcustom org-hide-emphasis-markers nil
2042 "Non-nil mean font-lock should hide the emphasis marker characters."
2043 :group 'org-font-lock
2044 :type 'boolean)
2046 (defvar org-emph-re nil
2047 "Regular expression for matching emphasis.")
2048 (defvar org-verbatim-re nil
2049 "Regular expression for matching verbatim text.")
2050 (defvar org-emphasis-regexp-components) ; defined just below
2051 (defvar org-emphasis-alist) ; defined just below
2052 (defun org-set-emph-re (var val)
2053 "Set variable and compute the emphasis regular expression."
2054 (set var val)
2055 (when (and (boundp 'org-emphasis-alist)
2056 (boundp 'org-emphasis-regexp-components)
2057 org-emphasis-alist org-emphasis-regexp-components)
2058 (let* ((e org-emphasis-regexp-components)
2059 (pre (car e))
2060 (post (nth 1 e))
2061 (border (nth 2 e))
2062 (body (nth 3 e))
2063 (nl (nth 4 e))
2064 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2065 (body1 (concat body "*?"))
2066 (markers (mapconcat 'car org-emphasis-alist ""))
2067 (vmarkers (mapconcat
2068 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2069 org-emphasis-alist "")))
2070 ;; make sure special characters appear at the right position in the class
2071 (if (string-match "\\^" markers)
2072 (setq markers (concat (replace-match "" t t markers) "^")))
2073 (if (string-match "-" markers)
2074 (setq markers (concat (replace-match "" t t markers) "-")))
2075 (if (string-match "\\^" vmarkers)
2076 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2077 (if (string-match "-" vmarkers)
2078 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2079 (if (> nl 0)
2080 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2081 (int-to-string nl) "\\}")))
2082 ;; Make the regexp
2083 (setq org-emph-re
2084 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2085 "\\("
2086 "\\([" markers "]\\)"
2087 "\\("
2088 "[^" border "]\\|"
2089 "[^" border (if (and nil stacked) markers) "]"
2090 body1
2091 "[^" border (if (and nil stacked) markers) "]"
2092 "\\)"
2093 "\\3\\)"
2094 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2095 (setq org-verbatim-re
2096 (concat "\\([" pre "]\\|^\\)"
2097 "\\("
2098 "\\([" vmarkers "]\\)"
2099 "\\("
2100 "[^" border "]\\|"
2101 "[^" border "]"
2102 body1
2103 "[^" border "]"
2104 "\\)"
2105 "\\3\\)"
2106 "\\([" post "]\\|$\\)")))))
2108 (defcustom org-emphasis-regexp-components
2109 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2110 "Components used to build the regular expression for emphasis.
2111 This is a list with 6 entries. Terminology: In an emphasis string
2112 like \" *strong word* \", we call the initial space PREMATCH, the final
2113 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2114 and \"trong wor\" is the body. The different components in this variable
2115 specify what is allowed/forbidden in each part:
2117 pre Chars allowed as prematch. Beginning of line will be allowed too.
2118 post Chars allowed as postmatch. End of line will be allowed too.
2119 border The chars *forbidden* as border characters.
2120 body-regexp A regexp like \".\" to match a body character. Don't use
2121 non-shy groups here, and don't allow newline here.
2122 newline The maximum number of newlines allowed in an emphasis exp.
2124 Use customize to modify this, or restart Emacs after changing it."
2125 :group 'org-font-lock
2126 :set 'org-set-emph-re
2127 :type '(list
2128 (sexp :tag "Allowed chars in pre ")
2129 (sexp :tag "Allowed chars in post ")
2130 (sexp :tag "Forbidden chars in border ")
2131 (sexp :tag "Regexp for body ")
2132 (integer :tag "number of newlines allowed")
2133 (option (boolean :tag "Stacking (DISABLED) "))))
2135 (defcustom org-emphasis-alist
2136 `(("*" bold "<b>" "</b>")
2137 ("/" italic "<i>" "</i>")
2138 ("_" underline "<u>" "</u>")
2139 ("=" org-code "<code>" "</code>" verbatim)
2140 ("~" org-verbatim "" "" verbatim)
2141 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2142 "<del>" "</del>")
2144 "Special syntax for emphasized text.
2145 Text starting and ending with a special character will be emphasized, for
2146 example *bold*, _underlined_ and /italic/. This variable sets the marker
2147 characters, the face to be used by font-lock for highlighting in Org-mode
2148 Emacs buffers, and the HTML tags to be used for this.
2149 Use customize to modify this, or restart Emacs after changing it."
2150 :group 'org-font-lock
2151 :set 'org-set-emph-re
2152 :type '(repeat
2153 (list
2154 (string :tag "Marker character")
2155 (choice
2156 (face :tag "Font-lock-face")
2157 (plist :tag "Face property list"))
2158 (string :tag "HTML start tag")
2159 (string :tag "HTML end tag")
2160 (option (const verbatim)))))
2162 ;;; Miscellaneous options
2164 (defgroup org-completion nil
2165 "Completion in Org-mode."
2166 :tag "Org Completion"
2167 :group 'org)
2169 (defcustom org-completion-fallback-command 'hippie-expand
2170 "The expansion command called by \\[org-complete] in normal context.
2171 Normal means, no org-mode-specific context."
2172 :group 'org-completion
2173 :type 'function)
2175 ;;; Functions and variables from ther packages
2176 ;; Declared here to avoid compiler warnings
2178 ;; XEmacs only
2179 (defvar outline-mode-menu-heading)
2180 (defvar outline-mode-menu-show)
2181 (defvar outline-mode-menu-hide)
2182 (defvar zmacs-regions) ; XEmacs regions
2184 ;; Emacs only
2185 (defvar mark-active)
2187 ;; Various packages
2188 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2189 (declare-function calendar-forward-day "cal-move" (arg))
2190 (declare-function calendar-goto-date "cal-move" (date))
2191 (declare-function calendar-goto-today "cal-move" ())
2192 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2193 (defvar calc-embedded-close-formula)
2194 (defvar calc-embedded-open-formula)
2195 (declare-function cdlatex-tab "ext:cdlatex" ())
2196 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2197 (defvar font-lock-unfontify-region-function)
2198 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2199 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2200 (defvar iswitchb-temp-buflist)
2201 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2202 (declare-function org-agenda-skip "org-agenda" ())
2203 (declare-function org-format-agenda-item "org-agenda"
2204 (extra txt &optional category tags dotime noprefix remove-re))
2205 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2206 (declare-function org-agenda-change-all-lines "org-agenda"
2207 (newhead hdmarker &optional fixface))
2208 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2209 (declare-function org-agenda-maybe-redo "org-agenda" ())
2210 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2211 (beg end))
2212 (declare-function parse-time-string "parse-time" (string))
2213 (declare-function remember "remember" (&optional initial))
2214 (declare-function remember-buffer-desc "remember" ())
2215 (declare-function remember-finalize "remember" ())
2216 (defvar remember-save-after-remembering)
2217 (defvar remember-data-file)
2218 (defvar remember-register)
2219 (defvar remember-buffer)
2220 (defvar remember-handler-functions)
2221 (defvar remember-annotation-functions)
2222 (defvar texmathp-why)
2223 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2224 (declare-function table--at-cell-p "table" (position &optional object at-column))
2226 (defvar w3m-current-url)
2227 (defvar w3m-current-title)
2229 (defvar org-latex-regexps)
2231 ;;; Autoload and prepare some org modules
2233 ;; Some table stuff that needs to be defined here, because it is used
2234 ;; by the functions setting up org-mode or checking for table context.
2236 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2237 "Detects an org-type or table-type table.")
2238 (defconst org-table-line-regexp "^[ \t]*|"
2239 "Detects an org-type table line.")
2240 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2241 "Detects an org-type table line.")
2242 (defconst org-table-hline-regexp "^[ \t]*|-"
2243 "Detects an org-type table hline.")
2244 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2245 "Detects a table-type table hline.")
2246 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2247 "Searching from within a table (any type) this finds the first line
2248 outside the table.")
2250 ;; Autoload the functions in org-table.el that are needed by functions here.
2252 (eval-and-compile
2253 (org-autoload "org-table"
2254 '(org-table-align org-table-begin org-table-blank-field
2255 org-table-convert org-table-convert-region org-table-copy-down
2256 org-table-copy-region org-table-create
2257 org-table-create-or-convert-from-region
2258 org-table-create-with-table.el org-table-current-dline
2259 org-table-cut-region org-table-delete-column org-table-edit-field
2260 org-table-edit-formulas org-table-end org-table-eval-formula
2261 org-table-export org-table-field-info
2262 org-table-get-stored-formulas org-table-goto-column
2263 org-table-hline-and-move org-table-import org-table-insert-column
2264 org-table-insert-hline org-table-insert-row org-table-iterate
2265 org-table-justify-field-maybe org-table-kill-row
2266 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2267 org-table-move-column org-table-move-column-left
2268 org-table-move-column-right org-table-move-row
2269 org-table-move-row-down org-table-move-row-up
2270 org-table-next-field org-table-next-row org-table-paste-rectangle
2271 org-table-previous-field org-table-recalculate
2272 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2273 org-table-toggle-coordinate-overlays
2274 org-table-toggle-formula-debugger org-table-wrap-region
2275 orgtbl-mode turn-on-orgtbl)))
2277 (defun org-at-table-p (&optional table-type)
2278 "Return t if the cursor is inside an org-type table.
2279 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2280 (if org-enable-table-editor
2281 (save-excursion
2282 (beginning-of-line 1)
2283 (looking-at (if table-type org-table-any-line-regexp
2284 org-table-line-regexp)))
2285 nil))
2286 (defsubst org-table-p () (org-at-table-p))
2288 (defun org-at-table.el-p ()
2289 "Return t if and only if we are at a table.el table."
2290 (and (org-at-table-p 'any)
2291 (save-excursion
2292 (goto-char (org-table-begin 'any))
2293 (looking-at org-table1-hline-regexp))))
2294 (defun org-table-recognize-table.el ()
2295 "If there is a table.el table nearby, recognize it and move into it."
2296 (if org-table-tab-recognizes-table.el
2297 (if (org-at-table.el-p)
2298 (progn
2299 (beginning-of-line 1)
2300 (if (looking-at org-table-dataline-regexp)
2302 (if (looking-at org-table1-hline-regexp)
2303 (progn
2304 (beginning-of-line 2)
2305 (if (looking-at org-table-any-border-regexp)
2306 (beginning-of-line -1)))))
2307 (if (re-search-forward "|" (org-table-end t) t)
2308 (progn
2309 (require 'table)
2310 (if (table--at-cell-p (point))
2312 (message "recognizing table.el table...")
2313 (table-recognize-table)
2314 (message "recognizing table.el table...done")))
2315 (error "This should not happen..."))
2317 nil)
2318 nil))
2320 (defun org-at-table-hline-p ()
2321 "Return t if the cursor is inside a hline in a table."
2322 (if org-enable-table-editor
2323 (save-excursion
2324 (beginning-of-line 1)
2325 (looking-at org-table-hline-regexp))
2326 nil))
2328 (defvar org-table-clean-did-remove-column nil)
2330 (defun org-table-map-tables (function)
2331 "Apply FUNCTION to the start of all tables in the buffer."
2332 (save-excursion
2333 (save-restriction
2334 (widen)
2335 (goto-char (point-min))
2336 (while (re-search-forward org-table-any-line-regexp nil t)
2337 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2338 (beginning-of-line 1)
2339 (if (looking-at org-table-line-regexp)
2340 (save-excursion (funcall function)))
2341 (re-search-forward org-table-any-border-regexp nil 1))))
2342 (message "Mapping tables: done"))
2344 ;; Declare and autoload functions from org-exp.el
2346 (declare-function org-default-export-plist "org-exp")
2347 (declare-function org-infile-export-plist "org-exp")
2348 (declare-function org-get-current-options "org-exp")
2349 (eval-and-compile
2350 (org-autoload "org-exp"
2351 '(org-export org-export-as-ascii org-export-visible
2352 org-insert-export-options-template org-export-as-html-and-open
2353 org-export-as-html-batch org-export-as-html-to-buffer
2354 org-replace-region-by-html org-export-region-as-html
2355 org-export-as-html org-export-icalendar-this-file
2356 org-export-icalendar-all-agenda-files
2357 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2359 ;; Declare and autoload functions from org-exp.el
2361 (eval-and-compile
2362 (org-autoload "org-exp"
2363 '(org-agenda org-agenda-list org-search-view
2364 org-todo-list org-tags-view org-agenda-list-stuck-projects
2365 org-diary org-agenda-to-appt)))
2367 ;; Autoload org-remember
2369 (eval-and-compile
2370 (org-autoload "org-remember"
2371 '(org-remember-insinuate org-remember-annotation
2372 org-remember-apply-template org-remember org-remember-handler)))
2374 ;; Autoload org-clock.el
2377 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2378 (beg end))
2379 (defvar org-clock-marker (make-marker)
2380 "Marker recording the last clock-in.")
2382 (eval-and-compile
2383 (org-autoload
2384 "org-clock"
2385 '(org-clock-in org-clock-out org-clock-cancel
2386 org-clock-goto org-clock-sum org-clock-display
2387 org-remove-clock-overlays org-clock-report
2388 org-clocktable-shift org-dblock-write:clocktable
2389 org-get-clocktable)))
2391 (defun org-clock-update-time-maybe ()
2392 "If this is a CLOCK line, update it and return t.
2393 Otherwise, return nil."
2394 (interactive)
2395 (save-excursion
2396 (beginning-of-line 1)
2397 (skip-chars-forward " \t")
2398 (when (looking-at org-clock-string)
2399 (let ((re (concat "[ \t]*" org-clock-string
2400 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2401 "\\([ \t]*=>.*\\)?"))
2402 ts te h m s)
2403 (if (not (looking-at re))
2405 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2406 (end-of-line 1)
2407 (setq ts (match-string 1)
2408 te (match-string 2))
2409 (setq s (- (time-to-seconds
2410 (apply 'encode-time (org-parse-time-string te)))
2411 (time-to-seconds
2412 (apply 'encode-time (org-parse-time-string ts))))
2413 h (floor (/ s 3600))
2414 s (- s (* 3600 h))
2415 m (floor (/ s 60))
2416 s (- s (* 60 s)))
2417 (insert " => " (format "%2d:%02d" h m))
2418 t)))))
2420 (defun org-check-running-clock ()
2421 "Check if the current buffer contains the running clock.
2422 If yes, offer to stop it and to save the buffer with the changes."
2423 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2424 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2425 (buffer-name))))
2426 (org-clock-out)
2427 (when (y-or-n-p "Save changed buffer?")
2428 (save-buffer))))
2430 (defun org-clocktable-try-shift (dir n)
2431 "Check if this line starts a clock table, if yes, shift the time block."
2432 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2433 (org-clocktable-shift dir n)))
2435 ;; Autoload archiving code
2436 ;; The stuff that is needed for cycling and tags has to be defined here.
2438 (defgroup org-archive nil
2439 "Options concerning archiving in Org-mode."
2440 :tag "Org Archive"
2441 :group 'org-structure)
2443 (defcustom org-archive-location "%s_archive::"
2444 "The location where subtrees should be archived.
2446 Otherwise, the value of this variable is a string, consisting of two
2447 parts, separated by a double-colon.
2449 The first part is a file name - when omitted, archiving happens in the same
2450 file. %s will be replaced by the current file name (without directory part).
2451 Archiving to a different file is useful to keep archived entries from
2452 contributing to the Org-mode Agenda.
2454 The part after the double colon is a headline. The archived entries will be
2455 filed under that headline. When omitted, the subtrees are simply filed away
2456 at the end of the file, as top-level entries.
2458 Here are a few examples:
2459 \"%s_archive::\"
2460 If the current file is Projects.org, archive in file
2461 Projects.org_archive, as top-level trees. This is the default.
2463 \"::* Archived Tasks\"
2464 Archive in the current file, under the top-level headline
2465 \"* Archived Tasks\".
2467 \"~/org/archive.org::\"
2468 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2470 \"basement::** Finished Tasks\"
2471 Archive in file ./basement (relative path), as level 3 trees
2472 below the level 2 heading \"** Finished Tasks\".
2474 You may set this option on a per-file basis by adding to the buffer a
2475 line like
2477 #+ARCHIVE: basement::** Finished Tasks
2479 You may also define it locally for a subtree by setting an ARCHIVE property
2480 in the entry. If such a property is found in an entry, or anywhere up
2481 the hierarchy, it will be used."
2482 :group 'org-archive
2483 :type 'string)
2485 (defcustom org-archive-tag "ARCHIVE"
2486 "The tag that marks a subtree as archived.
2487 An archived subtree does not open during visibility cycling, and does
2488 not contribute to the agenda listings.
2489 After changing this, font-lock must be restarted in the relevant buffers to
2490 get the proper fontification."
2491 :group 'org-archive
2492 :group 'org-keywords
2493 :type 'string)
2495 (defcustom org-agenda-skip-archived-trees t
2496 "Non-nil means, the agenda will skip any items located in archived trees.
2497 An archived tree is a tree marked with the tag ARCHIVE."
2498 :group 'org-archive
2499 :group 'org-agenda-skip
2500 :type 'boolean)
2502 (defcustom org-cycle-open-archived-trees nil
2503 "Non-nil means, `org-cycle' will open archived trees.
2504 An archived tree is a tree marked with the tag ARCHIVE.
2505 When nil, archived trees will stay folded. You can still open them with
2506 normal outline commands like `show-all', but not with the cycling commands."
2507 :group 'org-archive
2508 :group 'org-cycle
2509 :type 'boolean)
2511 (defcustom org-sparse-tree-open-archived-trees nil
2512 "Non-nil means sparse tree construction shows matches in archived trees.
2513 When nil, matches in these trees are highlighted, but the trees are kept in
2514 collapsed state."
2515 :group 'org-archive
2516 :group 'org-sparse-trees
2517 :type 'boolean)
2519 (defun org-cycle-hide-archived-subtrees (state)
2520 "Re-hide all archived subtrees after a visibility state change."
2521 (when (and (not org-cycle-open-archived-trees)
2522 (not (memq state '(overview folded))))
2523 (save-excursion
2524 (let* ((globalp (memq state '(contents all)))
2525 (beg (if globalp (point-min) (point)))
2526 (end (if globalp (point-max) (org-end-of-subtree t))))
2527 (org-hide-archived-subtrees beg end)
2528 (goto-char beg)
2529 (if (looking-at (concat ".*:" org-archive-tag ":"))
2530 (message "%s" (substitute-command-keys
2531 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2533 (defun org-force-cycle-archived ()
2534 "Cycle subtree even if it is archived."
2535 (interactive)
2536 (setq this-command 'org-cycle)
2537 (let ((org-cycle-open-archived-trees t))
2538 (call-interactively 'org-cycle)))
2540 (defun org-hide-archived-subtrees (beg end)
2541 "Re-hide all archived subtrees after a visibility state change."
2542 (save-excursion
2543 (let* ((re (concat ":" org-archive-tag ":")))
2544 (goto-char beg)
2545 (while (re-search-forward re end t)
2546 (and (org-on-heading-p) (hide-subtree))
2547 (org-end-of-subtree t)))))
2549 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2551 (eval-and-compile
2552 (org-autoload "org-archive"
2553 '(org-add-archive-files org-archive-subtree
2554 org-archive-to-archive-sibling org-toggle-archive-tag)))
2556 ;; Autoload Column View Code
2558 (declare-function org-columns-number-to-string "org-colview")
2559 (declare-function org-columns-get-format-and-top-level "org-colview")
2560 (declare-function org-columns-compute "org-colview")
2562 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2563 '(org-columns-number-to-string org-columns-get-format-and-top-level
2564 org-columns-compute org-agenda-columns org-columns-remove-overlays
2565 org-columns org-insert-columns-dblock))
2567 ;;; Variables for pre-computed regular expressions, all buffer local
2569 (defvar org-drawer-regexp nil
2570 "Matches first line of a hidden block.")
2571 (make-variable-buffer-local 'org-drawer-regexp)
2572 (defvar org-todo-regexp nil
2573 "Matches any of the TODO state keywords.")
2574 (make-variable-buffer-local 'org-todo-regexp)
2575 (defvar org-not-done-regexp nil
2576 "Matches any of the TODO state keywords except the last one.")
2577 (make-variable-buffer-local 'org-not-done-regexp)
2578 (defvar org-todo-line-regexp nil
2579 "Matches a headline and puts TODO state into group 2 if present.")
2580 (make-variable-buffer-local 'org-todo-line-regexp)
2581 (defvar org-complex-heading-regexp nil
2582 "Matches a headline and puts everything into groups:
2583 group 1: the stars
2584 group 2: The todo keyword, maybe
2585 group 3: Priority cookie
2586 group 4: True headline
2587 group 5: Tags")
2588 (make-variable-buffer-local 'org-complex-heading-regexp)
2589 (defvar org-todo-line-tags-regexp nil
2590 "Matches a headline and puts TODO state into group 2 if present.
2591 Also put tags into group 4 if tags are present.")
2592 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2593 (defvar org-nl-done-regexp nil
2594 "Matches newline followed by a headline with the DONE keyword.")
2595 (make-variable-buffer-local 'org-nl-done-regexp)
2596 (defvar org-looking-at-done-regexp nil
2597 "Matches the DONE keyword a point.")
2598 (make-variable-buffer-local 'org-looking-at-done-regexp)
2599 (defvar org-ds-keyword-length 12
2600 "Maximum length of the Deadline and SCHEDULED keywords.")
2601 (make-variable-buffer-local 'org-ds-keyword-length)
2602 (defvar org-deadline-regexp nil
2603 "Matches the DEADLINE keyword.")
2604 (make-variable-buffer-local 'org-deadline-regexp)
2605 (defvar org-deadline-time-regexp nil
2606 "Matches the DEADLINE keyword together with a time stamp.")
2607 (make-variable-buffer-local 'org-deadline-time-regexp)
2608 (defvar org-deadline-line-regexp nil
2609 "Matches the DEADLINE keyword and the rest of the line.")
2610 (make-variable-buffer-local 'org-deadline-line-regexp)
2611 (defvar org-scheduled-regexp nil
2612 "Matches the SCHEDULED keyword.")
2613 (make-variable-buffer-local 'org-scheduled-regexp)
2614 (defvar org-scheduled-time-regexp nil
2615 "Matches the SCHEDULED keyword together with a time stamp.")
2616 (make-variable-buffer-local 'org-scheduled-time-regexp)
2617 (defvar org-closed-time-regexp nil
2618 "Matches the CLOSED keyword together with a time stamp.")
2619 (make-variable-buffer-local 'org-closed-time-regexp)
2621 (defvar org-keyword-time-regexp nil
2622 "Matches any of the 4 keywords, together with the time stamp.")
2623 (make-variable-buffer-local 'org-keyword-time-regexp)
2624 (defvar org-keyword-time-not-clock-regexp nil
2625 "Matches any of the 3 keywords, together with the time stamp.")
2626 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2627 (defvar org-maybe-keyword-time-regexp nil
2628 "Matches a timestamp, possibly preceeded by a keyword.")
2629 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2630 (defvar org-planning-or-clock-line-re nil
2631 "Matches a line with planning or clock info.")
2632 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2634 (defconst org-plain-time-of-day-regexp
2635 (concat
2636 "\\(\\<[012]?[0-9]"
2637 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2638 "\\(--?"
2639 "\\(\\<[012]?[0-9]"
2640 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2641 "\\)?")
2642 "Regular expression to match a plain time or time range.
2643 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2644 groups carry important information:
2645 0 the full match
2646 1 the first time, range or not
2647 8 the second time, if it is a range.")
2649 (defconst org-plain-time-extension-regexp
2650 (concat
2651 "\\(\\<[012]?[0-9]"
2652 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2653 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2654 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2655 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2656 groups carry important information:
2657 0 the full match
2658 7 hours of duration
2659 9 minutes of duration")
2661 (defconst org-stamp-time-of-day-regexp
2662 (concat
2663 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2664 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2665 "\\(--?"
2666 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2667 "Regular expression to match a timestamp time or time range.
2668 After a match, the following groups carry important information:
2669 0 the full match
2670 1 date plus weekday, for backreferencing to make sure both times on same day
2671 2 the first time, range or not
2672 4 the second time, if it is a range.")
2674 (defconst org-startup-options
2675 '(("fold" org-startup-folded t)
2676 ("overview" org-startup-folded t)
2677 ("nofold" org-startup-folded nil)
2678 ("showall" org-startup-folded nil)
2679 ("content" org-startup-folded content)
2680 ("hidestars" org-hide-leading-stars t)
2681 ("showstars" org-hide-leading-stars nil)
2682 ("odd" org-odd-levels-only t)
2683 ("oddeven" org-odd-levels-only nil)
2684 ("align" org-startup-align-all-tables t)
2685 ("noalign" org-startup-align-all-tables nil)
2686 ("customtime" org-display-custom-times t)
2687 ("logdone" org-log-done time)
2688 ("lognotedone" org-log-done note)
2689 ("nologdone" org-log-done nil)
2690 ("lognoteclock-out" org-log-note-clock-out t)
2691 ("nolognoteclock-out" org-log-note-clock-out nil)
2692 ("logrepeat" org-log-repeat state)
2693 ("lognoterepeat" org-log-repeat note)
2694 ("nologrepeat" org-log-repeat nil)
2695 ("constcgs" constants-unit-system cgs)
2696 ("constSI" constants-unit-system SI))
2697 "Variable associated with STARTUP options for org-mode.
2698 Each element is a list of three items: The startup options as written
2699 in the #+STARTUP line, the corresponding variable, and the value to
2700 set this variable to if the option is found. An optional forth element PUSH
2701 means to push this value onto the list in the variable.")
2703 (defun org-set-regexps-and-options ()
2704 "Precompute regular expressions for current buffer."
2705 (when (org-mode-p)
2706 (org-set-local 'org-todo-kwd-alist nil)
2707 (org-set-local 'org-todo-key-alist nil)
2708 (org-set-local 'org-todo-key-trigger nil)
2709 (org-set-local 'org-todo-keywords-1 nil)
2710 (org-set-local 'org-done-keywords nil)
2711 (org-set-local 'org-todo-heads nil)
2712 (org-set-local 'org-todo-sets nil)
2713 (org-set-local 'org-todo-log-states nil)
2714 (let ((re (org-make-options-regexp
2715 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2716 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2717 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2718 (splitre "[ \t]+")
2719 kwds kws0 kwsa key log value cat arch tags const links hw dws
2720 tail sep kws1 prio props drawers
2721 ext-setup-or-nil setup-contents (start 0))
2722 (save-excursion
2723 (save-restriction
2724 (widen)
2725 (goto-char (point-min))
2726 (while (or (and ext-setup-or-nil
2727 (string-match re ext-setup-or-nil start)
2728 (setq start (match-end 0)))
2729 (and (setq ext-setup-or-nil nil start 0)
2730 (re-search-forward re nil t)))
2731 (setq key (upcase (match-string 1 ext-setup-or-nil))
2732 value (org-match-string-no-properties 2 ext-setup-or-nil))
2733 (cond
2734 ((equal key "CATEGORY")
2735 (if (string-match "[ \t]+$" value)
2736 (setq value (replace-match "" t t value)))
2737 (setq cat value))
2738 ((member key '("SEQ_TODO" "TODO"))
2739 (push (cons 'sequence (org-split-string value splitre)) kwds))
2740 ((equal key "TYP_TODO")
2741 (push (cons 'type (org-split-string value splitre)) kwds))
2742 ((equal key "TAGS")
2743 (setq tags (append tags (org-split-string value splitre))))
2744 ((equal key "COLUMNS")
2745 (org-set-local 'org-columns-default-format value))
2746 ((equal key "LINK")
2747 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2748 (push (cons (match-string 1 value)
2749 (org-trim (match-string 2 value)))
2750 links)))
2751 ((equal key "PRIORITIES")
2752 (setq prio (org-split-string value " +")))
2753 ((equal key "PROPERTY")
2754 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2755 (push (cons (match-string 1 value) (match-string 2 value))
2756 props)))
2757 ((equal key "DRAWERS")
2758 (setq drawers (org-split-string value splitre)))
2759 ((equal key "CONSTANTS")
2760 (setq const (append const (org-split-string value splitre))))
2761 ((equal key "STARTUP")
2762 (let ((opts (org-split-string value splitre))
2763 l var val)
2764 (while (setq l (pop opts))
2765 (when (setq l (assoc l org-startup-options))
2766 (setq var (nth 1 l) val (nth 2 l))
2767 (if (not (nth 3 l))
2768 (set (make-local-variable var) val)
2769 (if (not (listp (symbol-value var)))
2770 (set (make-local-variable var) nil))
2771 (set (make-local-variable var) (symbol-value var))
2772 (add-to-list var val))))))
2773 ((equal key "ARCHIVE")
2774 (string-match " *$" value)
2775 (setq arch (replace-match "" t t value))
2776 (remove-text-properties 0 (length arch)
2777 '(face t fontified t) arch))
2778 ((equal key "SETUPFILE")
2779 (setq setup-contents (org-file-contents
2780 (expand-file-name
2781 (org-remove-double-quotes value))
2782 'noerror))
2783 (if (not ext-setup-or-nil)
2784 (setq ext-setup-or-nil setup-contents start 0)
2785 (setq ext-setup-or-nil
2786 (concat (substring ext-setup-or-nil 0 start)
2787 "\n" setup-contents "\n"
2788 (substring ext-setup-or-nil start)))))
2789 ))))
2790 (when cat
2791 (org-set-local 'org-category (intern cat))
2792 (push (cons "CATEGORY" cat) props))
2793 (when prio
2794 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2795 (setq prio (mapcar 'string-to-char prio))
2796 (org-set-local 'org-highest-priority (nth 0 prio))
2797 (org-set-local 'org-lowest-priority (nth 1 prio))
2798 (org-set-local 'org-default-priority (nth 2 prio)))
2799 (and props (org-set-local 'org-local-properties (nreverse props)))
2800 (and drawers (org-set-local 'org-drawers drawers))
2801 (and arch (org-set-local 'org-archive-location arch))
2802 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2803 ;; Process the TODO keywords
2804 (unless kwds
2805 ;; Use the global values as if they had been given locally.
2806 (setq kwds (default-value 'org-todo-keywords))
2807 (if (stringp (car kwds))
2808 (setq kwds (list (cons org-todo-interpretation
2809 (default-value 'org-todo-keywords)))))
2810 (setq kwds (reverse kwds)))
2811 (setq kwds (nreverse kwds))
2812 (let (inter kws kw)
2813 (while (setq kws (pop kwds))
2814 (setq inter (pop kws) sep (member "|" kws)
2815 kws0 (delete "|" (copy-sequence kws))
2816 kwsa nil
2817 kws1 (mapcar
2818 (lambda (x)
2819 ;; 1 2
2820 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2821 (progn
2822 (setq kw (match-string 1 x)
2823 key (and (match-end 2) (match-string 2 x))
2824 log (org-extract-log-state-settings x))
2825 (push (cons kw (and key (string-to-char key))) kwsa)
2826 (and log (push log org-todo-log-states))
2828 (error "Invalid TODO keyword %s" x)))
2829 kws0)
2830 kwsa (if kwsa (append '((:startgroup))
2831 (nreverse kwsa)
2832 '((:endgroup))))
2833 hw (car kws1)
2834 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2835 tail (list inter hw (car dws) (org-last dws)))
2836 (add-to-list 'org-todo-heads hw 'append)
2837 (push kws1 org-todo-sets)
2838 (setq org-done-keywords (append org-done-keywords dws nil))
2839 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2840 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2841 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2842 (setq org-todo-sets (nreverse org-todo-sets)
2843 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2844 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2845 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2846 ;; Process the constants
2847 (when const
2848 (let (e cst)
2849 (while (setq e (pop const))
2850 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2851 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2852 (setq org-table-formula-constants-local cst)))
2854 ;; Process the tags.
2855 (when tags
2856 (let (e tgs)
2857 (while (setq e (pop tags))
2858 (cond
2859 ((equal e "{") (push '(:startgroup) tgs))
2860 ((equal e "}") (push '(:endgroup) tgs))
2861 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2862 (push (cons (match-string 1 e)
2863 (string-to-char (match-string 2 e)))
2864 tgs))
2865 (t (push (list e) tgs))))
2866 (org-set-local 'org-tag-alist nil)
2867 (while (setq e (pop tgs))
2868 (or (and (stringp (car e))
2869 (assoc (car e) org-tag-alist))
2870 (push e org-tag-alist))))))
2872 ;; Compute the regular expressions and other local variables
2873 (if (not org-done-keywords)
2874 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2875 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2876 (length org-scheduled-string)
2877 (length org-clock-string)
2878 (length org-closed-string)))
2879 org-drawer-regexp
2880 (concat "^[ \t]*:\\("
2881 (mapconcat 'regexp-quote org-drawers "\\|")
2882 "\\):[ \t]*$")
2883 org-not-done-keywords
2884 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2885 org-todo-regexp
2886 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2887 "\\|") "\\)\\>")
2888 org-not-done-regexp
2889 (concat "\\<\\("
2890 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2891 "\\)\\>")
2892 org-todo-line-regexp
2893 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2894 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2895 "\\)\\>\\)?[ \t]*\\(.*\\)")
2896 org-complex-heading-regexp
2897 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2898 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2899 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2900 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2901 org-nl-done-regexp
2902 (concat "\n\\*+[ \t]+"
2903 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2904 "\\)" "\\>")
2905 org-todo-line-tags-regexp
2906 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2907 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2908 (org-re
2909 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2910 org-looking-at-done-regexp
2911 (concat "^" "\\(?:"
2912 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2913 "\\>")
2914 org-deadline-regexp (concat "\\<" org-deadline-string)
2915 org-deadline-time-regexp
2916 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2917 org-deadline-line-regexp
2918 (concat "\\<\\(" org-deadline-string "\\).*")
2919 org-scheduled-regexp
2920 (concat "\\<" org-scheduled-string)
2921 org-scheduled-time-regexp
2922 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2923 org-closed-time-regexp
2924 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2925 org-keyword-time-regexp
2926 (concat "\\<\\(" org-scheduled-string
2927 "\\|" org-deadline-string
2928 "\\|" org-closed-string
2929 "\\|" org-clock-string "\\)"
2930 " *[[<]\\([^]>]+\\)[]>]")
2931 org-keyword-time-not-clock-regexp
2932 (concat "\\<\\(" org-scheduled-string
2933 "\\|" org-deadline-string
2934 "\\|" org-closed-string
2935 "\\)"
2936 " *[[<]\\([^]>]+\\)[]>]")
2937 org-maybe-keyword-time-regexp
2938 (concat "\\(\\<\\(" org-scheduled-string
2939 "\\|" org-deadline-string
2940 "\\|" org-closed-string
2941 "\\|" org-clock-string "\\)\\)?"
2942 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2943 org-planning-or-clock-line-re
2944 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2945 "\\|" org-deadline-string
2946 "\\|" org-closed-string "\\|" org-clock-string
2947 "\\)\\>\\)")
2949 (org-compute-latex-and-specials-regexp)
2950 (org-set-font-lock-defaults)))
2952 (defun org-file-contents (file &optional noerror)
2953 "Return the contents of FILE, as a string."
2954 (if (or (not file)
2955 (not (file-readable-p file)))
2956 (if noerror
2957 (progn
2958 (message "Cannot read file %s" file)
2959 (ding) (sit-for 2)
2961 (error "Cannot read file %s" file))
2962 (with-temp-buffer
2963 (insert-file-contents file)
2964 (buffer-string))))
2966 (defun org-extract-log-state-settings (x)
2967 "Extract the log state setting from a TODO keyword string.
2968 This will extract info from a string like \"WAIT(w@/!)\"."
2969 (let (kw key log1 log2)
2970 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2971 (setq kw (match-string 1 x)
2972 key (and (match-end 2) (match-string 2 x))
2973 log1 (and (match-end 3) (match-string 3 x))
2974 log2 (and (match-end 4) (match-string 4 x)))
2975 (and (or log1 log2)
2976 (list kw
2977 (and log1 (if (equal log1 "!") 'time 'note))
2978 (and log2 (if (equal log2 "!") 'time 'note)))))))
2980 (defun org-remove-keyword-keys (list)
2981 "Remove a pair of parenthesis at the end of each string in LIST."
2982 (mapcar (lambda (x)
2983 (if (string-match "(.*)$" x)
2984 (substring x 0 (match-beginning 0))
2986 list))
2988 ;; FIXME: this could be done much better, using second characters etc.
2989 (defun org-assign-fast-keys (alist)
2990 "Assign fast keys to a keyword-key alist.
2991 Respect keys that are already there."
2992 (let (new e k c c1 c2 (char ?a))
2993 (while (setq e (pop alist))
2994 (cond
2995 ((equal e '(:startgroup)) (push e new))
2996 ((equal e '(:endgroup)) (push e new))
2998 (setq k (car e) c2 nil)
2999 (if (cdr e)
3000 (setq c (cdr e))
3001 ;; automatically assign a character.
3002 (setq c1 (string-to-char
3003 (downcase (substring
3004 k (if (= (string-to-char k) ?@) 1 0)))))
3005 (if (or (rassoc c1 new) (rassoc c1 alist))
3006 (while (or (rassoc char new) (rassoc char alist))
3007 (setq char (1+ char)))
3008 (setq c2 c1))
3009 (setq c (or c2 char)))
3010 (push (cons k c) new))))
3011 (nreverse new)))
3013 ;;; Some variables used in various places
3015 (defvar org-window-configuration nil
3016 "Used in various places to store a window configuration.")
3017 (defvar org-finish-function nil
3018 "Function to be called when `C-c C-c' is used.
3019 This is for getting out of special buffers like remember.")
3022 ;; FIXME: Occasionally check by commenting these, to make sure
3023 ;; no other functions uses these, forgetting to let-bind them.
3024 (defvar entry)
3025 (defvar state)
3026 (defvar last-state)
3027 (defvar date)
3028 (defvar description)
3030 ;; Defined somewhere in this file, but used before definition.
3031 (defvar org-html-entities)
3032 (defvar org-struct-menu)
3033 (defvar org-org-menu)
3034 (defvar org-tbl-menu)
3035 (defvar org-agenda-keymap)
3037 ;;;; Define the Org-mode
3039 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3040 (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."))
3043 ;; We use a before-change function to check if a table might need
3044 ;; an update.
3045 (defvar org-table-may-need-update t
3046 "Indicates that a table might need an update.
3047 This variable is set by `org-before-change-function'.
3048 `org-table-align' sets it back to nil.")
3049 (defun org-before-change-function (beg end)
3050 "Every change indicates that a table might need an update."
3051 (setq org-table-may-need-update t))
3052 (defvar org-mode-map)
3053 (defvar org-mode-hook nil)
3054 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3055 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3056 (defvar org-table-buffer-is-an nil)
3057 (defconst org-outline-regexp "\\*+ ")
3059 ;;;###autoload
3060 (define-derived-mode org-mode outline-mode "Org"
3061 "Outline-based notes management and organizer, alias
3062 \"Carsten's outline-mode for keeping track of everything.\"
3064 Org-mode develops organizational tasks around a NOTES file which
3065 contains information about projects as plain text. Org-mode is
3066 implemented on top of outline-mode, which is ideal to keep the content
3067 of large files well structured. It supports ToDo items, deadlines and
3068 time stamps, which magically appear in the diary listing of the Emacs
3069 calendar. Tables are easily created with a built-in table editor.
3070 Plain text URL-like links connect to websites, emails (VM), Usenet
3071 messages (Gnus), BBDB entries, and any files related to the project.
3072 For printing and sharing of notes, an Org-mode file (or a part of it)
3073 can be exported as a structured ASCII or HTML file.
3075 The following commands are available:
3077 \\{org-mode-map}"
3079 ;; Get rid of Outline menus, they are not needed
3080 ;; Need to do this here because define-derived-mode sets up
3081 ;; the keymap so late. Still, it is a waste to call this each time
3082 ;; we switch another buffer into org-mode.
3083 (if (featurep 'xemacs)
3084 (when (boundp 'outline-mode-menu-heading)
3085 ;; Assume this is Greg's port, it used easymenu
3086 (easy-menu-remove outline-mode-menu-heading)
3087 (easy-menu-remove outline-mode-menu-show)
3088 (easy-menu-remove outline-mode-menu-hide))
3089 (define-key org-mode-map [menu-bar headings] 'undefined)
3090 (define-key org-mode-map [menu-bar hide] 'undefined)
3091 (define-key org-mode-map [menu-bar show] 'undefined))
3093 (org-load-modules-maybe)
3094 (easy-menu-add org-org-menu)
3095 (easy-menu-add org-tbl-menu)
3096 (org-install-agenda-files-menu)
3097 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3098 (org-add-to-invisibility-spec '(org-cwidth))
3099 (when (featurep 'xemacs)
3100 (org-set-local 'line-move-ignore-invisible t))
3101 (org-set-local 'outline-regexp org-outline-regexp)
3102 (org-set-local 'outline-level 'org-outline-level)
3103 (when (and org-ellipsis
3104 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3105 (fboundp 'make-glyph-code))
3106 (unless org-display-table
3107 (setq org-display-table (make-display-table)))
3108 (set-display-table-slot
3109 org-display-table 4
3110 (vconcat (mapcar
3111 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3112 org-ellipsis)))
3113 (if (stringp org-ellipsis) org-ellipsis "..."))))
3114 (setq buffer-display-table org-display-table))
3115 (org-set-regexps-and-options)
3116 ;; Calc embedded
3117 (org-set-local 'calc-embedded-open-mode "# ")
3118 (modify-syntax-entry ?# "<")
3119 (modify-syntax-entry ?@ "w")
3120 (if org-startup-truncated (setq truncate-lines t))
3121 (org-set-local 'font-lock-unfontify-region-function
3122 'org-unfontify-region)
3123 ;; Activate before-change-function
3124 (org-set-local 'org-table-may-need-update t)
3125 (org-add-hook 'before-change-functions 'org-before-change-function nil
3126 'local)
3127 ;; Check for running clock before killing a buffer
3128 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3129 ;; Paragraphs and auto-filling
3130 (org-set-autofill-regexps)
3131 (setq indent-line-function 'org-indent-line-function)
3132 (org-update-radio-target-regexp)
3134 ;; Comment characters
3135 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3136 (org-set-local 'comment-padding " ")
3138 ;; Align options lines
3139 (org-set-local
3140 'align-mode-rules-list
3141 '((org-in-buffer-settings
3142 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3143 (modes . '(org-mode)))))
3145 ;; Imenu
3146 (org-set-local 'imenu-create-index-function
3147 'org-imenu-get-tree)
3149 ;; Make isearch reveal context
3150 (if (or (featurep 'xemacs)
3151 (not (boundp 'outline-isearch-open-invisible-function)))
3152 ;; Emacs 21 and XEmacs make use of the hook
3153 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3154 ;; Emacs 22 deals with this through a special variable
3155 (org-set-local 'outline-isearch-open-invisible-function
3156 (lambda (&rest ignore) (org-show-context 'isearch))))
3158 ;; If empty file that did not turn on org-mode automatically, make it to.
3159 (if (and org-insert-mode-line-in-empty-file
3160 (interactive-p)
3161 (= (point-min) (point-max)))
3162 (insert "# -*- mode: org -*-\n\n"))
3164 (unless org-inhibit-startup
3165 (when org-startup-align-all-tables
3166 (let ((bmp (buffer-modified-p)))
3167 (org-table-map-tables 'org-table-align)
3168 (set-buffer-modified-p bmp)))
3169 (org-set-startup-visibility)))
3171 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3173 (defun org-current-time ()
3174 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3175 (if (> (car org-time-stamp-rounding-minutes) 1)
3176 (let ((r (car org-time-stamp-rounding-minutes))
3177 (time (decode-time)))
3178 (apply 'encode-time
3179 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3180 (nthcdr 2 time))))
3181 (current-time)))
3183 ;;;; Font-Lock stuff, including the activators
3185 (defvar org-mouse-map (make-sparse-keymap))
3186 (org-defkey org-mouse-map
3187 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3188 (org-defkey org-mouse-map
3189 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3190 (when org-mouse-1-follows-link
3191 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3192 (when org-tab-follows-link
3193 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3194 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3195 (when org-return-follows-link
3196 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3197 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3199 (require 'font-lock)
3201 (defconst org-non-link-chars "]\t\n\r<>")
3202 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3203 "shell" "elisp"))
3204 (defvar org-link-types-re nil
3205 "Matches a link that has a url-like prefix like \"http:\"")
3206 (defvar org-link-re-with-space nil
3207 "Matches a link with spaces, optional angular brackets around it.")
3208 (defvar org-link-re-with-space2 nil
3209 "Matches a link with spaces, optional angular brackets around it.")
3210 (defvar org-angle-link-re nil
3211 "Matches link with angular brackets, spaces are allowed.")
3212 (defvar org-plain-link-re nil
3213 "Matches plain link, without spaces.")
3214 (defvar org-bracket-link-regexp nil
3215 "Matches a link in double brackets.")
3216 (defvar org-bracket-link-analytic-regexp nil
3217 "Regular expression used to analyze links.
3218 Here is what the match groups contain after a match:
3219 1: http:
3220 2: http
3221 3: path
3222 4: [desc]
3223 5: desc")
3224 (defvar org-any-link-re nil
3225 "Regular expression matching any link.")
3227 (defun org-make-link-regexps ()
3228 "Update the link regular expressions.
3229 This should be called after the variable `org-link-types' has changed."
3230 (setq org-link-types-re
3231 (concat
3232 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3233 org-link-re-with-space
3234 (concat
3235 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3236 "\\([^" org-non-link-chars " ]"
3237 "[^" org-non-link-chars "]*"
3238 "[^" org-non-link-chars " ]\\)>?")
3239 org-link-re-with-space2
3240 (concat
3241 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3242 "\\([^" org-non-link-chars " ]"
3243 "[^]\t\n\r]*"
3244 "[^" org-non-link-chars " ]\\)>?")
3245 org-angle-link-re
3246 (concat
3247 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3248 "\\([^" org-non-link-chars " ]"
3249 "[^" org-non-link-chars "]*"
3250 "\\)>")
3251 org-plain-link-re
3252 (concat
3253 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3254 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3255 org-bracket-link-regexp
3256 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3257 org-bracket-link-analytic-regexp
3258 (concat
3259 "\\[\\["
3260 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3261 "\\([^]]+\\)"
3262 "\\]"
3263 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3264 "\\]")
3265 org-any-link-re
3266 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3267 org-angle-link-re "\\)\\|\\("
3268 org-plain-link-re "\\)")))
3270 (org-make-link-regexps)
3272 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3273 "Regular expression for fast time stamp matching.")
3274 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3275 "Regular expression for fast time stamp matching.")
3276 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3277 "Regular expression matching time strings for analysis.
3278 This one does not require the space after the date, so it can be used
3279 on a string that terminates immediately after the date.")
3280 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3281 "Regular expression matching time strings for analysis.")
3282 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3283 "Regular expression matching time stamps, with groups.")
3284 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3285 "Regular expression matching time stamps (also [..]), with groups.")
3286 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3287 "Regular expression matching a time stamp range.")
3288 (defconst org-tr-regexp-both
3289 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3290 "Regular expression matching a time stamp range.")
3291 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3292 org-ts-regexp "\\)?")
3293 "Regular expression matching a time stamp or time stamp range.")
3294 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3295 org-ts-regexp-both "\\)?")
3296 "Regular expression matching a time stamp or time stamp range.
3297 The time stamps may be either active or inactive.")
3299 (defvar org-emph-face nil)
3301 (defun org-do-emphasis-faces (limit)
3302 "Run through the buffer and add overlays to links."
3303 (let (rtn)
3304 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3305 (if (not (= (char-after (match-beginning 3))
3306 (char-after (match-beginning 4))))
3307 (progn
3308 (setq rtn t)
3309 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3310 'face
3311 (nth 1 (assoc (match-string 3)
3312 org-emphasis-alist)))
3313 (add-text-properties (match-beginning 2) (match-end 2)
3314 '(font-lock-multiline t))
3315 (when org-hide-emphasis-markers
3316 (add-text-properties (match-end 4) (match-beginning 5)
3317 '(invisible org-link))
3318 (add-text-properties (match-beginning 3) (match-end 3)
3319 '(invisible org-link)))))
3320 (backward-char 1))
3321 rtn))
3323 (defun org-emphasize (&optional char)
3324 "Insert or change an emphasis, i.e. a font like bold or italic.
3325 If there is an active region, change that region to a new emphasis.
3326 If there is no region, just insert the marker characters and position
3327 the cursor between them.
3328 CHAR should be either the marker character, or the first character of the
3329 HTML tag associated with that emphasis. If CHAR is a space, the means
3330 to remove the emphasis of the selected region.
3331 If char is not given (for example in an interactive call) it
3332 will be prompted for."
3333 (interactive)
3334 (let ((eal org-emphasis-alist) e det
3335 (erc org-emphasis-regexp-components)
3336 (prompt "")
3337 (string "") beg end move tag c s)
3338 (if (org-region-active-p)
3339 (setq beg (region-beginning) end (region-end)
3340 string (buffer-substring beg end))
3341 (setq move t))
3343 (while (setq e (pop eal))
3344 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3345 c (aref tag 0))
3346 (push (cons c (string-to-char (car e))) det)
3347 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3348 (substring tag 1)))))
3349 (unless char
3350 (message "%s" (concat "Emphasis marker or tag:" prompt))
3351 (setq char (read-char-exclusive)))
3352 (setq char (or (cdr (assoc char det)) char))
3353 (if (equal char ?\ )
3354 (setq s "" move nil)
3355 (unless (assoc (char-to-string char) org-emphasis-alist)
3356 (error "No such emphasis marker: \"%c\"" char))
3357 (setq s (char-to-string char)))
3358 (while (and (> (length string) 1)
3359 (equal (substring string 0 1) (substring string -1))
3360 (assoc (substring string 0 1) org-emphasis-alist))
3361 (setq string (substring string 1 -1)))
3362 (setq string (concat s string s))
3363 (if beg (delete-region beg end))
3364 (unless (or (bolp)
3365 (string-match (concat "[" (nth 0 erc) "\n]")
3366 (char-to-string (char-before (point)))))
3367 (insert " "))
3368 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3369 (char-to-string (char-after (point))))
3370 (insert " ") (backward-char 1))
3371 (insert string)
3372 (and move (backward-char 1))))
3374 (defconst org-nonsticky-props
3375 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3378 (defun org-activate-plain-links (limit)
3379 "Run through the buffer and add overlays to links."
3380 (catch 'exit
3381 (let (f)
3382 (while (re-search-forward org-plain-link-re limit t)
3383 (setq f (get-text-property (match-beginning 0) 'face))
3384 (if (or (eq f 'org-tag)
3385 (and (listp f) (memq 'org-tag f)))
3387 (add-text-properties (match-beginning 0) (match-end 0)
3388 (list 'mouse-face 'highlight
3389 'rear-nonsticky org-nonsticky-props
3390 'keymap org-mouse-map
3392 (throw 'exit t))))))
3394 (defun org-activate-code (limit)
3395 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3396 (unless (get-text-property (match-beginning 1) 'face)
3397 (remove-text-properties (match-beginning 0) (match-end 0)
3398 '(display t invisible t intangible t))
3399 t)))
3401 (defun org-activate-angle-links (limit)
3402 "Run through the buffer and add overlays to links."
3403 (if (re-search-forward org-angle-link-re limit t)
3404 (progn
3405 (add-text-properties (match-beginning 0) (match-end 0)
3406 (list 'mouse-face 'highlight
3407 'rear-nonsticky org-nonsticky-props
3408 'keymap org-mouse-map
3410 t)))
3412 (defun org-activate-bracket-links (limit)
3413 "Run through the buffer and add overlays to bracketed links."
3414 (if (re-search-forward org-bracket-link-regexp limit t)
3415 (let* ((help (concat "LINK: "
3416 (org-match-string-no-properties 1)))
3417 ;; FIXME: above we should remove the escapes.
3418 ;; but that requires another match, protecting match data,
3419 ;; a lot of overhead for font-lock.
3420 (ip (org-maybe-intangible
3421 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3422 'keymap org-mouse-map 'mouse-face 'highlight
3423 'font-lock-multiline t 'help-echo help)))
3424 (vp (list 'rear-nonsticky org-nonsticky-props
3425 'keymap org-mouse-map 'mouse-face 'highlight
3426 ' font-lock-multiline t 'help-echo help)))
3427 ;; We need to remove the invisible property here. Table narrowing
3428 ;; may have made some of this invisible.
3429 (remove-text-properties (match-beginning 0) (match-end 0)
3430 '(invisible nil))
3431 (if (match-end 3)
3432 (progn
3433 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3434 (add-text-properties (match-beginning 3) (match-end 3) vp)
3435 (add-text-properties (match-end 3) (match-end 0) ip))
3436 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3437 (add-text-properties (match-beginning 1) (match-end 1) vp)
3438 (add-text-properties (match-end 1) (match-end 0) ip))
3439 t)))
3441 (defun org-activate-dates (limit)
3442 "Run through the buffer and add overlays to dates."
3443 (if (re-search-forward org-tsr-regexp-both limit t)
3444 (progn
3445 (add-text-properties (match-beginning 0) (match-end 0)
3446 (list 'mouse-face 'highlight
3447 'rear-nonsticky org-nonsticky-props
3448 'keymap org-mouse-map))
3449 (when org-display-custom-times
3450 (if (match-end 3)
3451 (org-display-custom-time (match-beginning 3) (match-end 3)))
3452 (org-display-custom-time (match-beginning 1) (match-end 1)))
3453 t)))
3455 (defvar org-target-link-regexp nil
3456 "Regular expression matching radio targets in plain text.")
3457 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3458 "Regular expression matching a link target.")
3459 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3460 "Regular expression matching a radio target.")
3461 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3462 "Regular expression matching any target.")
3464 (defun org-activate-target-links (limit)
3465 "Run through the buffer and add overlays to target matches."
3466 (when org-target-link-regexp
3467 (let ((case-fold-search t))
3468 (if (re-search-forward org-target-link-regexp limit t)
3469 (progn
3470 (add-text-properties (match-beginning 0) (match-end 0)
3471 (list 'mouse-face 'highlight
3472 'rear-nonsticky org-nonsticky-props
3473 'keymap org-mouse-map
3474 'help-echo "Radio target link"
3475 'org-linked-text t))
3476 t)))))
3478 (defun org-update-radio-target-regexp ()
3479 "Find all radio targets in this file and update the regular expression."
3480 (interactive)
3481 (when (memq 'radio org-activate-links)
3482 (setq org-target-link-regexp
3483 (org-make-target-link-regexp (org-all-targets 'radio)))
3484 (org-restart-font-lock)))
3486 (defun org-hide-wide-columns (limit)
3487 (let (s e)
3488 (setq s (text-property-any (point) (or limit (point-max))
3489 'org-cwidth t))
3490 (when s
3491 (setq e (next-single-property-change s 'org-cwidth))
3492 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3493 (goto-char e)
3494 t)))
3496 (defvar org-latex-and-specials-regexp nil
3497 "Regular expression for highlighting export special stuff.")
3498 (defvar org-match-substring-regexp)
3499 (defvar org-match-substring-with-braces-regexp)
3500 (defvar org-export-html-special-string-regexps)
3502 (defun org-compute-latex-and-specials-regexp ()
3503 "Compute regular expression for stuff treated specially by exporters."
3504 (if (not org-highlight-latex-fragments-and-specials)
3505 (org-set-local 'org-latex-and-specials-regexp nil)
3506 (require 'org-exp)
3507 (let*
3508 ((matchers (plist-get org-format-latex-options :matchers))
3509 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3510 org-latex-regexps)))
3511 (options (org-combine-plists (org-default-export-plist)
3512 (org-infile-export-plist)))
3513 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3514 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3515 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3516 (org-export-html-expand (plist-get options :expand-quoted-html))
3517 (org-export-with-special-strings (plist-get options :special-strings))
3518 (re-sub
3519 (cond
3520 ((equal org-export-with-sub-superscripts '{})
3521 (list org-match-substring-with-braces-regexp))
3522 (org-export-with-sub-superscripts
3523 (list org-match-substring-regexp))
3524 (t nil)))
3525 (re-latex
3526 (if org-export-with-LaTeX-fragments
3527 (mapcar (lambda (x) (nth 1 x)) latexs)))
3528 (re-macros
3529 (if org-export-with-TeX-macros
3530 (list (concat "\\\\"
3531 (regexp-opt
3532 (append (mapcar 'car org-html-entities)
3533 (if (boundp 'org-latex-entities)
3534 org-latex-entities nil))
3535 'words))) ; FIXME
3537 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3538 (re-special (if org-export-with-special-strings
3539 (mapcar (lambda (x) (car x))
3540 org-export-html-special-string-regexps)))
3541 (re-rest
3542 (delq nil
3543 (list
3544 (if org-export-html-expand "@<[^>\n]+>")
3545 ))))
3546 (org-set-local
3547 'org-latex-and-specials-regexp
3548 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3549 re-rest) "\\|")))))
3551 (defun org-do-latex-and-special-faces (limit)
3552 "Run through the buffer and add overlays to links."
3553 (when org-latex-and-specials-regexp
3554 (let (rtn d)
3555 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3556 limit t))
3557 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3558 'face))
3559 '(org-code org-verbatim underline)))
3560 (progn
3561 (setq rtn t
3562 d (cond ((member (char-after (1+ (match-beginning 0)))
3563 '(?_ ?^)) 1)
3564 (t 0)))
3565 (font-lock-prepend-text-property
3566 (+ d (match-beginning 0)) (match-end 0)
3567 'face 'org-latex-and-export-specials)
3568 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3569 '(font-lock-multiline t)))))
3570 rtn)))
3572 (defun org-restart-font-lock ()
3573 "Restart font-lock-mode, to force refontification."
3574 (when (and (boundp 'font-lock-mode) font-lock-mode)
3575 (font-lock-mode -1)
3576 (font-lock-mode 1)))
3578 (defun org-all-targets (&optional radio)
3579 "Return a list of all targets in this file.
3580 With optional argument RADIO, only find radio targets."
3581 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3582 rtn)
3583 (save-excursion
3584 (goto-char (point-min))
3585 (while (re-search-forward re nil t)
3586 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3587 rtn)))
3589 (defun org-make-target-link-regexp (targets)
3590 "Make regular expression matching all strings in TARGETS.
3591 The regular expression finds the targets also if there is a line break
3592 between words."
3593 (and targets
3594 (concat
3595 "\\<\\("
3596 (mapconcat
3597 (lambda (x)
3598 (while (string-match " +" x)
3599 (setq x (replace-match "\\s-+" t t x)))
3601 targets
3602 "\\|")
3603 "\\)\\>")))
3605 (defun org-activate-tags (limit)
3606 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3607 (progn
3608 (add-text-properties (match-beginning 1) (match-end 1)
3609 (list 'mouse-face 'highlight
3610 'rear-nonsticky org-nonsticky-props
3611 'keymap org-mouse-map))
3612 t)))
3614 (defun org-outline-level ()
3615 (save-excursion
3616 (looking-at outline-regexp)
3617 (if (match-beginning 1)
3618 (+ (org-get-string-indentation (match-string 1)) 1000)
3619 (1- (- (match-end 0) (match-beginning 0))))))
3621 (defvar org-font-lock-keywords nil)
3623 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3624 "Regular expression matching a property line.")
3626 (defvar org-font-lock-hook nil
3627 "Functions to be called for special font loch stuff.")
3629 (defun org-font-lock-hook (limit)
3630 (run-hook-with-args 'org-font-lock-hook limit))
3632 (defun org-set-font-lock-defaults ()
3633 (let* ((em org-fontify-emphasized-text)
3634 (lk org-activate-links)
3635 (org-font-lock-extra-keywords
3636 (list
3637 ;; Call the hook
3638 '(org-font-lock-hook)
3639 ;; Headlines
3640 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3641 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3642 ;; Table lines
3643 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3644 (1 'org-table t))
3645 ;; Table internals
3646 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3647 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3648 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3649 ;; Drawers
3650 (list org-drawer-regexp '(0 'org-special-keyword t))
3651 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3652 ;; Properties
3653 (list org-property-re
3654 '(1 'org-special-keyword t)
3655 '(3 'org-property-value t))
3656 (if org-format-transports-properties-p
3657 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3658 ;; Links
3659 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3660 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3661 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3662 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3663 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3664 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3665 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3666 '(org-hide-wide-columns (0 nil append))
3667 ;; TODO lines
3668 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3669 '(1 (org-get-todo-face 1) t))
3670 ;; DONE
3671 (if org-fontify-done-headline
3672 (list (concat "^[*]+ +\\<\\("
3673 (mapconcat 'regexp-quote org-done-keywords "\\|")
3674 "\\)\\(.*\\)")
3675 '(2 'org-headline-done t))
3676 nil)
3677 ;; Priorities
3678 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3679 ;; Special keywords
3680 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3681 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3682 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3683 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3684 ;; Emphasis
3685 (if em
3686 (if (featurep 'xemacs)
3687 '(org-do-emphasis-faces (0 nil append))
3688 '(org-do-emphasis-faces)))
3689 ;; Checkboxes
3690 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3691 2 'bold prepend)
3692 (if org-provide-checkbox-statistics
3693 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3694 (0 (org-get-checkbox-statistics-face) t)))
3695 ;; Description list items
3696 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3697 2 'bold prepend)
3698 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3699 '(1 'org-archived prepend))
3700 ;; Specials
3701 '(org-do-latex-and-special-faces)
3702 ;; Code
3703 '(org-activate-code (1 'org-code t))
3704 ;; COMMENT
3705 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3706 "\\|" org-quote-string "\\)\\>")
3707 '(1 'org-special-keyword t))
3708 '("^#.*" (0 'font-lock-comment-face t))
3710 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3711 ;; Now set the full font-lock-keywords
3712 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3713 (org-set-local 'font-lock-defaults
3714 '(org-font-lock-keywords t nil nil backward-paragraph))
3715 (kill-local-variable 'font-lock-keywords) nil))
3717 (defvar org-m nil)
3718 (defvar org-l nil)
3719 (defvar org-f nil)
3720 (defun org-get-level-face (n)
3721 "Get the right face for match N in font-lock matching of healdines."
3722 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3723 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3724 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3725 (cond
3726 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3727 ((eq n 2) org-f)
3728 (t (if org-level-color-stars-only nil org-f))))
3730 (defun org-get-todo-face (kwd)
3731 "Get the right face for a TODO keyword KWD.
3732 If KWD is a number, get the corresponding match group."
3733 (if (numberp kwd) (setq kwd (match-string kwd)))
3734 (or (cdr (assoc kwd org-todo-keyword-faces))
3735 (and (member kwd org-done-keywords) 'org-done)
3736 'org-todo))
3738 (defun org-unfontify-region (beg end &optional maybe_loudly)
3739 "Remove fontification and activation overlays from links."
3740 (font-lock-default-unfontify-region beg end)
3741 (let* ((buffer-undo-list t)
3742 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3743 (inhibit-modification-hooks t)
3744 deactivate-mark buffer-file-name buffer-file-truename)
3745 (remove-text-properties beg end
3746 '(mouse-face t keymap t org-linked-text t
3747 invisible t intangible t))))
3749 ;;;; Visibility cycling, including org-goto and indirect buffer
3751 ;;; Cycling
3753 (defvar org-cycle-global-status nil)
3754 (make-variable-buffer-local 'org-cycle-global-status)
3755 (defvar org-cycle-subtree-status nil)
3756 (make-variable-buffer-local 'org-cycle-subtree-status)
3758 ;;;###autoload
3759 (defun org-cycle (&optional arg)
3760 "Visibility cycling for Org-mode.
3762 - When this function is called with a prefix argument, rotate the entire
3763 buffer through 3 states (global cycling)
3764 1. OVERVIEW: Show only top-level headlines.
3765 2. CONTENTS: Show all headlines of all levels, but no body text.
3766 3. SHOW ALL: Show everything.
3767 When called with two C-c C-u prefixes, switch to the startup visibility,
3768 determined by the variable `org-startup-folded', and by any VISIBILITY
3769 properties in the buffer.
3771 - When point is at the beginning of a headline, rotate the subtree started
3772 by this line through 3 different states (local cycling)
3773 1. FOLDED: Only the main headline is shown.
3774 2. CHILDREN: The main headline and the direct children are shown.
3775 From this state, you can move to one of the children
3776 and zoom in further.
3777 3. SUBTREE: Show the entire subtree, including body text.
3779 - When there is a numeric prefix, go up to a heading with level ARG, do
3780 a `show-subtree' and return to the previous cursor position. If ARG
3781 is negative, go up that many levels.
3783 - When point is not at the beginning of a headline, execute the global
3784 binding for TAB, which is re-indenting the line. See the option
3785 `org-cycle-emulate-tab' for details.
3787 - Special case: if point is at the beginning of the buffer and there is
3788 no headline in line 1, this function will act as if called with prefix arg.
3789 But only if also the variable `org-cycle-global-at-bob' is t."
3790 (interactive "P")
3791 (org-load-modules-maybe)
3792 (let* ((outline-regexp
3793 (if (and (org-mode-p) org-cycle-include-plain-lists)
3794 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3795 outline-regexp))
3796 (bob-special (and org-cycle-global-at-bob (bobp)
3797 (not (looking-at outline-regexp))))
3798 (org-cycle-hook
3799 (if bob-special
3800 (delq 'org-optimize-window-after-visibility-change
3801 (copy-sequence org-cycle-hook))
3802 org-cycle-hook))
3803 (pos (point)))
3805 (if (or bob-special (equal arg '(4)))
3806 ;; special case: use global cycling
3807 (setq arg t))
3809 (cond
3811 ((equal arg '(16))
3812 (org-set-startup-visibility)
3813 (message "Startup visibility, plus VISIBILITY properties."))
3815 ((org-at-table-p 'any)
3816 ;; Enter the table or move to the next field in the table
3817 (or (org-table-recognize-table.el)
3818 (progn
3819 (if arg (org-table-edit-field t)
3820 (org-table-justify-field-maybe)
3821 (call-interactively 'org-table-next-field)))))
3823 ((eq arg t) ;; Global cycling
3825 (cond
3826 ((and (eq last-command this-command)
3827 (eq org-cycle-global-status 'overview))
3828 ;; We just created the overview - now do table of contents
3829 ;; This can be slow in very large buffers, so indicate action
3830 (message "CONTENTS...")
3831 (org-content)
3832 (message "CONTENTS...done")
3833 (setq org-cycle-global-status 'contents)
3834 (run-hook-with-args 'org-cycle-hook 'contents))
3836 ((and (eq last-command this-command)
3837 (eq org-cycle-global-status 'contents))
3838 ;; We just showed the table of contents - now show everything
3839 (show-all)
3840 (message "SHOW ALL")
3841 (setq org-cycle-global-status 'all)
3842 (run-hook-with-args 'org-cycle-hook 'all))
3845 ;; Default action: go to overview
3846 (org-overview)
3847 (message "OVERVIEW")
3848 (setq org-cycle-global-status 'overview)
3849 (run-hook-with-args 'org-cycle-hook 'overview))))
3851 ((and org-drawers org-drawer-regexp
3852 (save-excursion
3853 (beginning-of-line 1)
3854 (looking-at org-drawer-regexp)))
3855 ;; Toggle block visibility
3856 (org-flag-drawer
3857 (not (get-char-property (match-end 0) 'invisible))))
3859 ((integerp arg)
3860 ;; Show-subtree, ARG levels up from here.
3861 (save-excursion
3862 (org-back-to-heading)
3863 (outline-up-heading (if (< arg 0) (- arg)
3864 (- (funcall outline-level) arg)))
3865 (org-show-subtree)))
3867 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3868 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3869 ;; At a heading: rotate between three different views
3870 (org-back-to-heading)
3871 (let ((goal-column 0) eoh eol eos)
3872 ;; First, some boundaries
3873 (save-excursion
3874 (org-back-to-heading)
3875 (save-excursion
3876 (beginning-of-line 2)
3877 (while (and (not (eobp)) ;; this is like `next-line'
3878 (get-char-property (1- (point)) 'invisible))
3879 (beginning-of-line 2)) (setq eol (point)))
3880 (outline-end-of-heading) (setq eoh (point))
3881 (org-end-of-subtree t)
3882 (unless (eobp)
3883 (skip-chars-forward " \t\n")
3884 (beginning-of-line 1) ; in case this is an item
3886 (setq eos (1- (point))))
3887 ;; Find out what to do next and set `this-command'
3888 (cond
3889 ((= eos eoh)
3890 ;; Nothing is hidden behind this heading
3891 (message "EMPTY ENTRY")
3892 (setq org-cycle-subtree-status nil)
3893 (save-excursion
3894 (goto-char eos)
3895 (outline-next-heading)
3896 (if (org-invisible-p) (org-flag-heading nil))))
3897 ((or (>= eol eos)
3898 (not (string-match "\\S-" (buffer-substring eol eos))))
3899 ;; Entire subtree is hidden in one line: open it
3900 (org-show-entry)
3901 (show-children)
3902 (message "CHILDREN")
3903 (save-excursion
3904 (goto-char eos)
3905 (outline-next-heading)
3906 (if (org-invisible-p) (org-flag-heading nil)))
3907 (setq org-cycle-subtree-status 'children)
3908 (run-hook-with-args 'org-cycle-hook 'children))
3909 ((and (eq last-command this-command)
3910 (eq org-cycle-subtree-status 'children))
3911 ;; We just showed the children, now show everything.
3912 (org-show-subtree)
3913 (message "SUBTREE")
3914 (setq org-cycle-subtree-status 'subtree)
3915 (run-hook-with-args 'org-cycle-hook 'subtree))
3917 ;; Default action: hide the subtree.
3918 (hide-subtree)
3919 (message "FOLDED")
3920 (setq org-cycle-subtree-status 'folded)
3921 (run-hook-with-args 'org-cycle-hook 'folded)))))
3923 ;; TAB emulation
3924 (buffer-read-only (org-back-to-heading))
3926 ((org-try-cdlatex-tab))
3928 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3929 (or (not (bolp))
3930 (not (looking-at outline-regexp))))
3931 (call-interactively (global-key-binding "\t")))
3933 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3934 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3935 (or (and (eq org-cycle-emulate-tab 'white)
3936 (= (match-end 0) (point-at-eol)))
3937 (and (eq org-cycle-emulate-tab 'whitestart)
3938 (>= (match-end 0) pos))))
3940 (eq org-cycle-emulate-tab t))
3941 (call-interactively (global-key-binding "\t")))
3943 (t (save-excursion
3944 (org-back-to-heading)
3945 (org-cycle))))))
3947 ;;;###autoload
3948 (defun org-global-cycle (&optional arg)
3949 "Cycle the global visibility. For details see `org-cycle'.
3950 With C-u prefix arg, switch to startup visibility.
3951 With a numeric prefix, show all headlines up to that level."
3952 (interactive "P")
3953 (let ((org-cycle-include-plain-lists
3954 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3955 (cond
3956 ((integerp arg)
3957 (show-all)
3958 (hide-sublevels arg)
3959 (setq org-cycle-global-status 'contents))
3960 ((equal arg '(4))
3961 (org-set-startup-visibility)
3962 (message "Startup visibility, plus VISIBILITY properties."))
3964 (org-cycle '(4))))))
3966 (defun org-set-startup-visibility ()
3967 "Set the visibility required by startup options and properties."
3968 (cond
3969 ((eq org-startup-folded t)
3970 (org-cycle '(4)))
3971 ((eq org-startup-folded 'content)
3972 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3973 (org-cycle '(4)) (org-cycle '(4)))))
3974 (org-set-visibility-according-to-property 'no-cleanup)
3975 (org-cycle-hide-archived-subtrees 'all)
3976 (org-cycle-hide-drawers 'all)
3977 (org-cycle-show-empty-lines 'all))
3979 (defun org-set-visibility-according-to-property (&optional no-cleanup)
3980 "Switch subtree visibilities according to :VISIBILITY: property."
3981 (interactive)
3982 (let (state)
3983 (save-excursion
3984 (goto-char (point-min))
3985 (while (re-search-forward
3986 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
3987 nil t)
3988 (setq state (match-string 1))
3989 (save-excursion
3990 (org-back-to-heading t)
3991 (hide-subtree)
3992 (org-reveal)
3993 (cond
3994 ((equal state '("fold" "folded"))
3995 (hide-subtree))
3996 ((equal state "children")
3997 (org-show-hidden-entry)
3998 (show-children))
3999 ((equal state "content")
4000 (save-excursion
4001 (save-restriction
4002 (org-narrow-to-subtree)
4003 (org-content))))
4004 ((member state '("all" "showall"))
4005 (show-subtree)))))
4006 (unless no-cleanup
4007 (org-cycle-hide-archived-subtrees 'all)
4008 (org-cycle-hide-drawers 'all)
4009 (org-cycle-show-empty-lines 'all)))))
4011 (defun org-overview ()
4012 "Switch to overview mode, shoing only top-level headlines.
4013 Really, this shows all headlines with level equal or greater than the level
4014 of the first headline in the buffer. This is important, because if the
4015 first headline is not level one, then (hide-sublevels 1) gives confusing
4016 results."
4017 (interactive)
4018 (let ((level (save-excursion
4019 (goto-char (point-min))
4020 (if (re-search-forward (concat "^" outline-regexp) nil t)
4021 (progn
4022 (goto-char (match-beginning 0))
4023 (funcall outline-level))))))
4024 (and level (hide-sublevels level))))
4026 (defun org-content (&optional arg)
4027 "Show all headlines in the buffer, like a table of contents.
4028 With numerical argument N, show content up to level N."
4029 (interactive "P")
4030 (save-excursion
4031 ;; Visit all headings and show their offspring
4032 (and (integerp arg) (org-overview))
4033 (goto-char (point-max))
4034 (catch 'exit
4035 (while (and (progn (condition-case nil
4036 (outline-previous-visible-heading 1)
4037 (error (goto-char (point-min))))
4039 (looking-at outline-regexp))
4040 (if (integerp arg)
4041 (show-children (1- arg))
4042 (show-branches))
4043 (if (bobp) (throw 'exit nil))))))
4046 (defun org-optimize-window-after-visibility-change (state)
4047 "Adjust the window after a change in outline visibility.
4048 This function is the default value of the hook `org-cycle-hook'."
4049 (when (get-buffer-window (current-buffer))
4050 (cond
4051 ; ((eq state 'overview) (org-first-headline-recenter 1))
4052 ; ((eq state 'overview) (org-beginning-of-line))
4053 ((eq state 'content) nil)
4054 ((eq state 'all) nil)
4055 ((eq state 'folded) nil)
4056 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4057 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4059 (defun org-compact-display-after-subtree-move ()
4060 (let (beg end)
4061 (save-excursion
4062 (if (org-up-heading-safe)
4063 (progn
4064 (hide-subtree)
4065 (show-entry)
4066 (show-children)
4067 (org-cycle-show-empty-lines 'children)
4068 (org-cycle-hide-drawers 'children))
4069 (org-overview)))))
4071 (defun org-cycle-show-empty-lines (state)
4072 "Show empty lines above all visible headlines.
4073 The region to be covered depends on STATE when called through
4074 `org-cycle-hook'. Lisp program can use t for STATE to get the
4075 entire buffer covered. Note that an empty line is only shown if there
4076 are at least `org-cycle-separator-lines' empty lines before the headeline."
4077 (when (> org-cycle-separator-lines 0)
4078 (save-excursion
4079 (let* ((n org-cycle-separator-lines)
4080 (re (cond
4081 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4082 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4083 (t (let ((ns (number-to-string (- n 2))))
4084 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4085 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4086 beg end)
4087 (cond
4088 ((memq state '(overview contents t))
4089 (setq beg (point-min) end (point-max)))
4090 ((memq state '(children folded))
4091 (setq beg (point) end (progn (org-end-of-subtree t t)
4092 (beginning-of-line 2)
4093 (point)))))
4094 (when beg
4095 (goto-char beg)
4096 (while (re-search-forward re end t)
4097 (if (not (get-char-property (match-end 1) 'invisible))
4098 (outline-flag-region
4099 (match-beginning 1) (match-end 1) nil)))))))
4100 ;; Never hide empty lines at the end of the file.
4101 (save-excursion
4102 (goto-char (point-max))
4103 (outline-previous-heading)
4104 (outline-end-of-heading)
4105 (if (and (looking-at "[ \t\n]+")
4106 (= (match-end 0) (point-max)))
4107 (outline-flag-region (point) (match-end 0) nil))))
4109 (defun org-cycle-hide-drawers (state)
4110 "Re-hide all drawers after a visibility state change."
4111 (when (and (org-mode-p)
4112 (not (memq state '(overview folded))))
4113 (save-excursion
4114 (let* ((globalp (memq state '(contents all)))
4115 (beg (if globalp (point-min) (point)))
4116 (end (if globalp (point-max) (org-end-of-subtree t))))
4117 (goto-char beg)
4118 (while (re-search-forward org-drawer-regexp end t)
4119 (org-flag-drawer t))))))
4121 (defun org-flag-drawer (flag)
4122 (save-excursion
4123 (beginning-of-line 1)
4124 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4125 (let ((b (match-end 0))
4126 (outline-regexp org-outline-regexp))
4127 (if (re-search-forward
4128 "^[ \t]*:END:"
4129 (save-excursion (outline-next-heading) (point)) t)
4130 (outline-flag-region b (point-at-eol) flag)
4131 (error ":END: line missing"))))))
4133 (defun org-subtree-end-visible-p ()
4134 "Is the end of the current subtree visible?"
4135 (pos-visible-in-window-p
4136 (save-excursion (org-end-of-subtree t) (point))))
4138 (defun org-first-headline-recenter (&optional N)
4139 "Move cursor to the first headline and recenter the headline.
4140 Optional argument N means, put the headline into the Nth line of the window."
4141 (goto-char (point-min))
4142 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4143 (beginning-of-line)
4144 (recenter (prefix-numeric-value N))))
4146 ;;; Org-goto
4148 (defvar org-goto-window-configuration nil)
4149 (defvar org-goto-marker nil)
4150 (defvar org-goto-map
4151 (let ((map (make-sparse-keymap)))
4152 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4153 (while (setq cmd (pop cmds))
4154 (substitute-key-definition cmd cmd map global-map)))
4155 (suppress-keymap map)
4156 (org-defkey map "\C-m" 'org-goto-ret)
4157 (org-defkey map [(return)] 'org-goto-ret)
4158 (org-defkey map [(left)] 'org-goto-left)
4159 (org-defkey map [(right)] 'org-goto-right)
4160 (org-defkey map [(control ?g)] 'org-goto-quit)
4161 (org-defkey map "\C-i" 'org-cycle)
4162 (org-defkey map [(tab)] 'org-cycle)
4163 (org-defkey map [(down)] 'outline-next-visible-heading)
4164 (org-defkey map [(up)] 'outline-previous-visible-heading)
4165 (if org-goto-auto-isearch
4166 (if (fboundp 'define-key-after)
4167 (define-key-after map [t] 'org-goto-local-auto-isearch)
4168 nil)
4169 (org-defkey map "q" 'org-goto-quit)
4170 (org-defkey map "n" 'outline-next-visible-heading)
4171 (org-defkey map "p" 'outline-previous-visible-heading)
4172 (org-defkey map "f" 'outline-forward-same-level)
4173 (org-defkey map "b" 'outline-backward-same-level)
4174 (org-defkey map "u" 'outline-up-heading))
4175 (org-defkey map "/" 'org-occur)
4176 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4177 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4178 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4179 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4180 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4181 map))
4183 (defconst org-goto-help
4184 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4185 RET=jump to location [Q]uit and return to previous location
4186 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4188 (defvar org-goto-start-pos) ; dynamically scoped parameter
4190 (defun org-goto (&optional alternative-interface)
4191 "Look up a different location in the current file, keeping current visibility.
4193 When you want look-up or go to a different location in a document, the
4194 fastest way is often to fold the entire buffer and then dive into the tree.
4195 This method has the disadvantage, that the previous location will be folded,
4196 which may not be what you want.
4198 This command works around this by showing a copy of the current buffer
4199 in an indirect buffer, in overview mode. You can dive into the tree in
4200 that copy, use org-occur and incremental search to find a location.
4201 When pressing RET or `Q', the command returns to the original buffer in
4202 which the visibility is still unchanged. After RET is will also jump to
4203 the location selected in the indirect buffer and expose the
4204 the headline hierarchy above."
4205 (interactive "P")
4206 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4207 (org-refile-use-outline-path t)
4208 (interface
4209 (if (not alternative-interface)
4210 org-goto-interface
4211 (if (eq org-goto-interface 'outline)
4212 'outline-path-completion
4213 'outline)))
4214 (org-goto-start-pos (point))
4215 (selected-point
4216 (if (eq interface 'outline)
4217 (car (org-get-location (current-buffer) org-goto-help))
4218 (nth 3 (org-refile-get-location "Goto: ")))))
4219 (if selected-point
4220 (progn
4221 (org-mark-ring-push org-goto-start-pos)
4222 (goto-char selected-point)
4223 (if (or (org-invisible-p) (org-invisible-p2))
4224 (org-show-context 'org-goto)))
4225 (message "Quit"))))
4227 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4228 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4229 (defvar org-goto-local-auto-isearch-map) ; defined below
4231 (defun org-get-location (buf help)
4232 "Let the user select a location in the Org-mode buffer BUF.
4233 This function uses a recursive edit. It returns the selected position
4234 or nil."
4235 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4236 (isearch-hide-immediately nil)
4237 (isearch-search-fun-function
4238 (lambda () 'org-goto-local-search-forward-headings))
4239 (org-goto-selected-point org-goto-exit-command))
4240 (save-excursion
4241 (save-window-excursion
4242 (delete-other-windows)
4243 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4244 (switch-to-buffer
4245 (condition-case nil
4246 (make-indirect-buffer (current-buffer) "*org-goto*")
4247 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4248 (with-output-to-temp-buffer "*Help*"
4249 (princ help))
4250 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4251 (setq buffer-read-only nil)
4252 (let ((org-startup-truncated t)
4253 (org-startup-folded nil)
4254 (org-startup-align-all-tables nil))
4255 (org-mode)
4256 (org-overview))
4257 (setq buffer-read-only t)
4258 (if (and (boundp 'org-goto-start-pos)
4259 (integer-or-marker-p org-goto-start-pos))
4260 (let ((org-show-hierarchy-above t)
4261 (org-show-siblings t)
4262 (org-show-following-heading t))
4263 (goto-char org-goto-start-pos)
4264 (and (org-invisible-p) (org-show-context)))
4265 (goto-char (point-min)))
4266 (org-beginning-of-line)
4267 (message "Select location and press RET")
4268 (use-local-map org-goto-map)
4269 (recursive-edit)
4271 (kill-buffer "*org-goto*")
4272 (cons org-goto-selected-point org-goto-exit-command)))
4274 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4275 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4276 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4277 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4279 (defun org-goto-local-search-forward-headings (string bound noerror)
4280 "Search and make sure that anu matches are in headlines."
4281 (catch 'return
4282 (while (search-forward string bound noerror)
4283 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4284 (and (member :headline context)
4285 (not (member :tags context))))
4286 (throw 'return (point))))))
4288 (defun org-goto-local-auto-isearch ()
4289 "Start isearch."
4290 (interactive)
4291 (goto-char (point-min))
4292 (let ((keys (this-command-keys)))
4293 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4294 (isearch-mode t)
4295 (isearch-process-search-char (string-to-char keys)))))
4297 (defun org-goto-ret (&optional arg)
4298 "Finish `org-goto' by going to the new location."
4299 (interactive "P")
4300 (setq org-goto-selected-point (point)
4301 org-goto-exit-command 'return)
4302 (throw 'exit nil))
4304 (defun org-goto-left ()
4305 "Finish `org-goto' by going to the new location."
4306 (interactive)
4307 (if (org-on-heading-p)
4308 (progn
4309 (beginning-of-line 1)
4310 (setq org-goto-selected-point (point)
4311 org-goto-exit-command 'left)
4312 (throw 'exit nil))
4313 (error "Not on a heading")))
4315 (defun org-goto-right ()
4316 "Finish `org-goto' by going to the new location."
4317 (interactive)
4318 (if (org-on-heading-p)
4319 (progn
4320 (setq org-goto-selected-point (point)
4321 org-goto-exit-command 'right)
4322 (throw 'exit nil))
4323 (error "Not on a heading")))
4325 (defun org-goto-quit ()
4326 "Finish `org-goto' without cursor motion."
4327 (interactive)
4328 (setq org-goto-selected-point nil)
4329 (setq org-goto-exit-command 'quit)
4330 (throw 'exit nil))
4332 ;;; Indirect buffer display of subtrees
4334 (defvar org-indirect-dedicated-frame nil
4335 "This is the frame being used for indirect tree display.")
4336 (defvar org-last-indirect-buffer nil)
4338 (defun org-tree-to-indirect-buffer (&optional arg)
4339 "Create indirect buffer and narrow it to current subtree.
4340 With numerical prefix ARG, go up to this level and then take that tree.
4341 If ARG is negative, go up that many levels.
4342 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4343 indirect buffer previously made with this command, to avoid proliferation of
4344 indirect buffers. However, when you call the command with a `C-u' prefix, or
4345 when `org-indirect-buffer-display' is `new-frame', the last buffer
4346 is kept so that you can work with several indirect buffers at the same time.
4347 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4348 requests that a new frame be made for the new buffer, so that the dedicated
4349 frame is not changed."
4350 (interactive "P")
4351 (let ((cbuf (current-buffer))
4352 (cwin (selected-window))
4353 (pos (point))
4354 beg end level heading ibuf)
4355 (save-excursion
4356 (org-back-to-heading t)
4357 (when (numberp arg)
4358 (setq level (org-outline-level))
4359 (if (< arg 0) (setq arg (+ level arg)))
4360 (while (> (setq level (org-outline-level)) arg)
4361 (outline-up-heading 1 t)))
4362 (setq beg (point)
4363 heading (org-get-heading))
4364 (org-end-of-subtree t) (setq end (point)))
4365 (if (and (buffer-live-p org-last-indirect-buffer)
4366 (not (eq org-indirect-buffer-display 'new-frame))
4367 (not arg))
4368 (kill-buffer org-last-indirect-buffer))
4369 (setq ibuf (org-get-indirect-buffer cbuf)
4370 org-last-indirect-buffer ibuf)
4371 (cond
4372 ((or (eq org-indirect-buffer-display 'new-frame)
4373 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4374 (select-frame (make-frame))
4375 (delete-other-windows)
4376 (switch-to-buffer ibuf)
4377 (org-set-frame-title heading))
4378 ((eq org-indirect-buffer-display 'dedicated-frame)
4379 (raise-frame
4380 (select-frame (or (and org-indirect-dedicated-frame
4381 (frame-live-p org-indirect-dedicated-frame)
4382 org-indirect-dedicated-frame)
4383 (setq org-indirect-dedicated-frame (make-frame)))))
4384 (delete-other-windows)
4385 (switch-to-buffer ibuf)
4386 (org-set-frame-title (concat "Indirect: " heading)))
4387 ((eq org-indirect-buffer-display 'current-window)
4388 (switch-to-buffer ibuf))
4389 ((eq org-indirect-buffer-display 'other-window)
4390 (pop-to-buffer ibuf))
4391 (t (error "Invalid value.")))
4392 (if (featurep 'xemacs)
4393 (save-excursion (org-mode) (turn-on-font-lock)))
4394 (narrow-to-region beg end)
4395 (show-all)
4396 (goto-char pos)
4397 (and (window-live-p cwin) (select-window cwin))))
4399 (defun org-get-indirect-buffer (&optional buffer)
4400 (setq buffer (or buffer (current-buffer)))
4401 (let ((n 1) (base (buffer-name buffer)) bname)
4402 (while (buffer-live-p
4403 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4404 (setq n (1+ n)))
4405 (condition-case nil
4406 (make-indirect-buffer buffer bname 'clone)
4407 (error (make-indirect-buffer buffer bname)))))
4409 (defun org-set-frame-title (title)
4410 "Set the title of the current frame to the string TITLE."
4411 ;; FIXME: how to name a single frame in XEmacs???
4412 (unless (featurep 'xemacs)
4413 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4415 ;;;; Structure editing
4417 ;;; Inserting headlines
4419 (defun org-insert-heading (&optional force-heading)
4420 "Insert a new heading or item with same depth at point.
4421 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4422 If point is at the beginning of a headline, insert a sibling before the
4423 current headline. If point is not at the beginning, do not split the line,
4424 but create the new hedline after the current line."
4425 (interactive "P")
4426 (if (= (buffer-size) 0)
4427 (insert "\n* ")
4428 (when (or force-heading (not (org-insert-item)))
4429 (let* ((head (save-excursion
4430 (condition-case nil
4431 (progn
4432 (org-back-to-heading)
4433 (match-string 0))
4434 (error "*"))))
4435 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4436 pos)
4437 (cond
4438 ((and (org-on-heading-p) (bolp)
4439 (or (bobp)
4440 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4441 ;; insert before the current line
4442 (open-line (if blank 2 1)))
4443 ((and (bolp)
4444 (or (bobp)
4445 (save-excursion
4446 (backward-char 1) (not (org-invisible-p)))))
4447 ;; insert right here
4448 nil)
4450 ;; in the middle of the line
4451 (org-show-entry)
4452 (let ((split
4453 (org-get-alist-option org-M-RET-may-split-line 'headline))
4454 tags pos)
4455 (if (org-on-heading-p)
4456 (progn
4457 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4458 (setq tags (and (match-end 2) (match-string 2)))
4459 (and (match-end 1)
4460 (delete-region (match-beginning 1) (match-end 1)))
4461 (setq pos (point-at-bol))
4462 (or split (end-of-line 1))
4463 (delete-horizontal-space)
4464 (newline (if blank 2 1))
4465 (when tags
4466 (save-excursion
4467 (goto-char pos)
4468 (end-of-line 1)
4469 (insert " " tags)
4470 (org-set-tags nil 'align))))
4471 (or split (end-of-line 1))
4472 (newline (if blank 2 1))))))
4473 (insert head) (just-one-space)
4474 (setq pos (point))
4475 (end-of-line 1)
4476 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4477 (run-hooks 'org-insert-heading-hook)))))
4479 (defun org-get-heading (&optional no-tags)
4480 "Return the heading of the current entry, without the stars."
4481 (save-excursion
4482 (org-back-to-heading t)
4483 (if (looking-at
4484 (if no-tags
4485 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4486 "\\*+[ \t]+\\([^\r\n]*\\)"))
4487 (match-string 1) "")))
4489 (defun org-insert-heading-after-current ()
4490 "Insert a new heading with same level as current, after current subtree."
4491 (interactive)
4492 (org-back-to-heading)
4493 (org-insert-heading)
4494 (org-move-subtree-down)
4495 (end-of-line 1))
4497 (defun org-insert-todo-heading (arg)
4498 "Insert a new heading with the same level and TODO state as current heading.
4499 If the heading has no TODO state, or if the state is DONE, use the first
4500 state (TODO by default). Also with prefix arg, force first state."
4501 (interactive "P")
4502 (when (not (org-insert-item 'checkbox))
4503 (org-insert-heading)
4504 (save-excursion
4505 (org-back-to-heading)
4506 (outline-previous-heading)
4507 (looking-at org-todo-line-regexp))
4508 (if (or arg
4509 (not (match-beginning 2))
4510 (member (match-string 2) org-done-keywords))
4511 (insert (car org-todo-keywords-1) " ")
4512 (insert (match-string 2) " "))))
4514 (defun org-insert-subheading (arg)
4515 "Insert a new subheading and demote it.
4516 Works for outline headings and for plain lists alike."
4517 (interactive "P")
4518 (org-insert-heading arg)
4519 (cond
4520 ((org-on-heading-p) (org-do-demote))
4521 ((org-at-item-p) (org-indent-item 1))))
4523 (defun org-insert-todo-subheading (arg)
4524 "Insert a new subheading with TODO keyword or checkbox and demote it.
4525 Works for outline headings and for plain lists alike."
4526 (interactive "P")
4527 (org-insert-todo-heading arg)
4528 (cond
4529 ((org-on-heading-p) (org-do-demote))
4530 ((org-at-item-p) (org-indent-item 1))))
4532 ;;; Promotion and Demotion
4534 (defun org-promote-subtree ()
4535 "Promote the entire subtree.
4536 See also `org-promote'."
4537 (interactive)
4538 (save-excursion
4539 (org-map-tree 'org-promote))
4540 (org-fix-position-after-promote))
4542 (defun org-demote-subtree ()
4543 "Demote the entire subtree. See `org-demote'.
4544 See also `org-promote'."
4545 (interactive)
4546 (save-excursion
4547 (org-map-tree 'org-demote))
4548 (org-fix-position-after-promote))
4551 (defun org-do-promote ()
4552 "Promote the current heading higher up the tree.
4553 If the region is active in `transient-mark-mode', promote all headings
4554 in the region."
4555 (interactive)
4556 (save-excursion
4557 (if (org-region-active-p)
4558 (org-map-region 'org-promote (region-beginning) (region-end))
4559 (org-promote)))
4560 (org-fix-position-after-promote))
4562 (defun org-do-demote ()
4563 "Demote the current heading lower down the tree.
4564 If the region is active in `transient-mark-mode', demote all headings
4565 in the region."
4566 (interactive)
4567 (save-excursion
4568 (if (org-region-active-p)
4569 (org-map-region 'org-demote (region-beginning) (region-end))
4570 (org-demote)))
4571 (org-fix-position-after-promote))
4573 (defun org-fix-position-after-promote ()
4574 "Make sure that after pro/demotion cursor position is right."
4575 (let ((pos (point)))
4576 (when (save-excursion
4577 (beginning-of-line 1)
4578 (looking-at org-todo-line-regexp)
4579 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4580 (cond ((eobp) (insert " "))
4581 ((eolp) (insert " "))
4582 ((equal (char-after) ?\ ) (forward-char 1))))))
4584 (defun org-reduced-level (l)
4585 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4587 (defun org-get-valid-level (level &optional change)
4588 "Rectify a level change under the influence of `org-odd-levels-only'
4589 LEVEL is a current level, CHANGE is by how much the level should be
4590 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4591 even level numbers will become the next higher odd number."
4592 (if org-odd-levels-only
4593 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4594 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4595 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4596 (max 1 (+ level change))))
4598 (if (boundp 'define-obsolete-function-alias)
4599 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4600 (define-obsolete-function-alias 'org-get-legal-level
4601 'org-get-valid-level)
4602 (define-obsolete-function-alias 'org-get-legal-level
4603 'org-get-valid-level "23.1")))
4605 (defun org-promote ()
4606 "Promote the current heading higher up the tree.
4607 If the region is active in `transient-mark-mode', promote all headings
4608 in the region."
4609 (org-back-to-heading t)
4610 (let* ((level (save-match-data (funcall outline-level)))
4611 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4612 (diff (abs (- level (length up-head) -1))))
4613 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4614 (replace-match up-head nil t)
4615 ;; Fixup tag positioning
4616 (and org-auto-align-tags (org-set-tags nil t))
4617 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4619 (defun org-demote ()
4620 "Demote the current heading lower down the tree.
4621 If the region is active in `transient-mark-mode', demote all headings
4622 in the region."
4623 (org-back-to-heading t)
4624 (let* ((level (save-match-data (funcall outline-level)))
4625 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4626 (diff (abs (- level (length down-head) -1))))
4627 (replace-match down-head nil t)
4628 ;; Fixup tag positioning
4629 (and org-auto-align-tags (org-set-tags nil t))
4630 (if org-adapt-indentation (org-fixup-indentation diff))))
4632 (defun org-map-tree (fun)
4633 "Call FUN for every heading underneath the current one."
4634 (org-back-to-heading)
4635 (let ((level (funcall outline-level)))
4636 (save-excursion
4637 (funcall fun)
4638 (while (and (progn
4639 (outline-next-heading)
4640 (> (funcall outline-level) level))
4641 (not (eobp)))
4642 (funcall fun)))))
4644 (defun org-map-region (fun beg end)
4645 "Call FUN for every heading between BEG and END."
4646 (let ((org-ignore-region t))
4647 (save-excursion
4648 (setq end (copy-marker end))
4649 (goto-char beg)
4650 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4651 (< (point) end))
4652 (funcall fun))
4653 (while (and (progn
4654 (outline-next-heading)
4655 (< (point) end))
4656 (not (eobp)))
4657 (funcall fun)))))
4659 (defun org-fixup-indentation (diff)
4660 "Change the indentation in the current entry by DIFF
4661 However, if any line in the current entry has no indentation, or if it
4662 would end up with no indentation after the change, nothing at all is done."
4663 (save-excursion
4664 (let ((end (save-excursion (outline-next-heading)
4665 (point-marker)))
4666 (prohibit (if (> diff 0)
4667 "^\\S-"
4668 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4669 col)
4670 (unless (save-excursion (end-of-line 1)
4671 (re-search-forward prohibit end t))
4672 (while (and (< (point) end)
4673 (re-search-forward "^[ \t]+" end t))
4674 (goto-char (match-end 0))
4675 (setq col (current-column))
4676 (if (< diff 0) (replace-match ""))
4677 (indent-to (+ diff col))))
4678 (move-marker end nil))))
4680 (defun org-convert-to-odd-levels ()
4681 "Convert an org-mode file with all levels allowed to one with odd levels.
4682 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4683 level 5 etc."
4684 (interactive)
4685 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4686 (let ((org-odd-levels-only nil) n)
4687 (save-excursion
4688 (goto-char (point-min))
4689 (while (re-search-forward "^\\*\\*+ " nil t)
4690 (setq n (- (length (match-string 0)) 2))
4691 (while (>= (setq n (1- n)) 0)
4692 (org-demote))
4693 (end-of-line 1))))))
4696 (defun org-convert-to-oddeven-levels ()
4697 "Convert an org-mode file with only odd levels to one with odd and even levels.
4698 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4699 section with an even level, conversion would destroy the structure of the file. An error
4700 is signaled in this case."
4701 (interactive)
4702 (goto-char (point-min))
4703 ;; First check if there are no even levels
4704 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4705 (org-show-context t)
4706 (error "Not all levels are odd in this file. Conversion not possible."))
4707 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4708 (let ((org-odd-levels-only nil) n)
4709 (save-excursion
4710 (goto-char (point-min))
4711 (while (re-search-forward "^\\*\\*+ " nil t)
4712 (setq n (/ (1- (length (match-string 0))) 2))
4713 (while (>= (setq n (1- n)) 0)
4714 (org-promote))
4715 (end-of-line 1))))))
4717 (defun org-tr-level (n)
4718 "Make N odd if required."
4719 (if org-odd-levels-only (1+ (/ n 2)) n))
4721 ;;; Vertical tree motion, cutting and pasting of subtrees
4723 (defun org-move-subtree-up (&optional arg)
4724 "Move the current subtree up past ARG headlines of the same level."
4725 (interactive "p")
4726 (org-move-subtree-down (- (prefix-numeric-value arg))))
4728 (defun org-move-subtree-down (&optional arg)
4729 "Move the current subtree down past ARG headlines of the same level."
4730 (interactive "p")
4731 (setq arg (prefix-numeric-value arg))
4732 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4733 'outline-get-last-sibling))
4734 (ins-point (make-marker))
4735 (cnt (abs arg))
4736 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4737 ;; Select the tree
4738 (org-back-to-heading)
4739 (setq beg0 (point))
4740 (save-excursion
4741 (setq ne-beg (org-back-over-empty-lines))
4742 (setq beg (point)))
4743 (save-match-data
4744 (save-excursion (outline-end-of-heading)
4745 (setq folded (org-invisible-p)))
4746 (outline-end-of-subtree))
4747 (outline-next-heading)
4748 (setq ne-end (org-back-over-empty-lines))
4749 (setq end (point))
4750 (goto-char beg0)
4751 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4752 ;; include less whitespace
4753 (save-excursion
4754 (goto-char beg)
4755 (forward-line (- ne-beg ne-end))
4756 (setq beg (point))))
4757 ;; Find insertion point, with error handling
4758 (while (> cnt 0)
4759 (or (and (funcall movfunc) (looking-at outline-regexp))
4760 (progn (goto-char beg0)
4761 (error "Cannot move past superior level or buffer limit")))
4762 (setq cnt (1- cnt)))
4763 (if (> arg 0)
4764 ;; Moving forward - still need to move over subtree
4765 (progn (org-end-of-subtree t t)
4766 (save-excursion
4767 (org-back-over-empty-lines)
4768 (or (bolp) (newline)))))
4769 (setq ne-ins (org-back-over-empty-lines))
4770 (move-marker ins-point (point))
4771 (setq txt (buffer-substring beg end))
4772 (org-save-markers-in-region beg end)
4773 (delete-region beg end)
4774 (outline-flag-region (1- beg) beg nil)
4775 (outline-flag-region (1- (point)) (point) nil)
4776 (let ((bbb (point)))
4777 (insert-before-markers txt)
4778 (org-reinstall-markers-in-region bbb)
4779 (move-marker ins-point bbb))
4780 (or (bolp) (insert "\n"))
4781 (setq ins-end (point))
4782 (goto-char ins-point)
4783 (org-skip-whitespace)
4784 (when (and (< arg 0)
4785 (org-first-sibling-p)
4786 (> ne-ins ne-beg))
4787 ;; Move whitespace back to beginning
4788 (save-excursion
4789 (goto-char ins-end)
4790 (let ((kill-whole-line t))
4791 (kill-line (- ne-ins ne-beg)) (point)))
4792 (insert (make-string (- ne-ins ne-beg) ?\n)))
4793 (move-marker ins-point nil)
4794 (org-compact-display-after-subtree-move)
4795 (unless folded
4796 (org-show-entry)
4797 (show-children)
4798 (org-cycle-hide-drawers 'children))))
4800 (defvar org-subtree-clip ""
4801 "Clipboard for cut and paste of subtrees.
4802 This is actually only a copy of the kill, because we use the normal kill
4803 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4805 (defvar org-subtree-clip-folded nil
4806 "Was the last copied subtree folded?
4807 This is used to fold the tree back after pasting.")
4809 (defun org-cut-subtree (&optional n)
4810 "Cut the current subtree into the clipboard.
4811 With prefix arg N, cut this many sequential subtrees.
4812 This is a short-hand for marking the subtree and then cutting it."
4813 (interactive "p")
4814 (org-copy-subtree n 'cut))
4816 (defun org-copy-subtree (&optional n cut force-store-markers)
4817 "Cut the current subtree into the clipboard.
4818 With prefix arg N, cut this many sequential subtrees.
4819 This is a short-hand for marking the subtree and then copying it.
4820 If CUT is non-nil, actually cut the subtree.
4821 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4822 of some markers in the region, even if CUT is non-nil. This is
4823 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4824 (interactive "p")
4825 (let (beg end folded (beg0 (point)))
4826 (if (interactive-p)
4827 (org-back-to-heading nil) ; take what looks like a subtree
4828 (org-back-to-heading t)) ; take what is really there
4829 (org-back-over-empty-lines)
4830 (setq beg (point))
4831 (skip-chars-forward " \t\r\n")
4832 (save-match-data
4833 (save-excursion (outline-end-of-heading)
4834 (setq folded (org-invisible-p)))
4835 (condition-case nil
4836 (outline-forward-same-level (1- n))
4837 (error nil))
4838 (org-end-of-subtree t t))
4839 (org-back-over-empty-lines)
4840 (setq end (point))
4841 (goto-char beg0)
4842 (when (> end beg)
4843 (setq org-subtree-clip-folded folded)
4844 (when (or cut force-store-markers)
4845 (org-save-markers-in-region beg end))
4846 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4847 (setq org-subtree-clip (current-kill 0))
4848 (message "%s: Subtree(s) with %d characters"
4849 (if cut "Cut" "Copied")
4850 (length org-subtree-clip)))))
4852 (defun org-paste-subtree (&optional level tree)
4853 "Paste the clipboard as a subtree, with modification of headline level.
4854 The entire subtree is promoted or demoted in order to match a new headline
4855 level. By default, the new level is derived from the visible headings
4856 before and after the insertion point, and taken to be the inferior headline
4857 level of the two. So if the previous visible heading is level 3 and the
4858 next is level 4 (or vice versa), level 4 will be used for insertion.
4859 This makes sure that the subtree remains an independent subtree and does
4860 not swallow low level entries.
4862 You can also force a different level, either by using a numeric prefix
4863 argument, or by inserting the heading marker by hand. For example, if the
4864 cursor is after \"*****\", then the tree will be shifted to level 5.
4866 If you want to insert the tree as is, just use \\[yank].
4868 If optional TREE is given, use this text instead of the kill ring."
4869 (interactive "P")
4870 (unless (org-kill-is-subtree-p tree)
4871 (error "%s"
4872 (substitute-command-keys
4873 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4874 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4875 (^re (concat "^\\(" outline-regexp "\\)"))
4876 (re (concat "\\(" outline-regexp "\\)"))
4877 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4879 (old-level (if (string-match ^re txt)
4880 (- (match-end 0) (match-beginning 0) 1)
4881 -1))
4882 (force-level (cond (level (prefix-numeric-value level))
4883 ((string-match
4884 ^re_ (buffer-substring (point-at-bol) (point)))
4885 (- (match-end 1) (match-beginning 1)))
4886 (t nil)))
4887 (previous-level (save-excursion
4888 (condition-case nil
4889 (progn
4890 (outline-previous-visible-heading 1)
4891 (if (looking-at re)
4892 (- (match-end 0) (match-beginning 0) 1)
4894 (error 1))))
4895 (next-level (save-excursion
4896 (condition-case nil
4897 (progn
4898 (or (looking-at outline-regexp)
4899 (outline-next-visible-heading 1))
4900 (if (looking-at re)
4901 (- (match-end 0) (match-beginning 0) 1)
4903 (error 1))))
4904 (new-level (or force-level (max previous-level next-level)))
4905 (shift (if (or (= old-level -1)
4906 (= new-level -1)
4907 (= old-level new-level))
4909 (- new-level old-level)))
4910 (delta (if (> shift 0) -1 1))
4911 (func (if (> shift 0) 'org-demote 'org-promote))
4912 (org-odd-levels-only nil)
4913 beg end)
4914 ;; Remove the forced level indicator
4915 (if force-level
4916 (delete-region (point-at-bol) (point)))
4917 ;; Paste
4918 (beginning-of-line 1)
4919 (org-back-over-empty-lines)
4920 (setq beg (point))
4921 (insert-before-markers txt)
4922 (unless (string-match "\n\\'" txt) (insert "\n"))
4923 (org-reinstall-markers-in-region beg)
4924 (setq end (point))
4925 (goto-char beg)
4926 (skip-chars-forward " \t\n\r")
4927 (setq beg (point))
4928 ;; Shift if necessary
4929 (unless (= shift 0)
4930 (save-restriction
4931 (narrow-to-region beg end)
4932 (while (not (= shift 0))
4933 (org-map-region func (point-min) (point-max))
4934 (setq shift (+ delta shift)))
4935 (goto-char (point-min))))
4936 (when (interactive-p)
4937 (message "Clipboard pasted as level %d subtree" new-level))
4938 (if (and kill-ring
4939 (eq org-subtree-clip (current-kill 0))
4940 org-subtree-clip-folded)
4941 ;; The tree was folded before it was killed/copied
4942 (hide-subtree))))
4944 (defun org-kill-is-subtree-p (&optional txt)
4945 "Check if the current kill is an outline subtree, or a set of trees.
4946 Returns nil if kill does not start with a headline, or if the first
4947 headline level is not the largest headline level in the tree.
4948 So this will actually accept several entries of equal levels as well,
4949 which is OK for `org-paste-subtree'.
4950 If optional TXT is given, check this string instead of the current kill."
4951 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4952 (start-level (and kill
4953 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4954 org-outline-regexp "\\)")
4955 kill)
4956 (- (match-end 2) (match-beginning 2) 1)))
4957 (re (concat "^" org-outline-regexp))
4958 (start (1+ (match-beginning 2))))
4959 (if (not start-level)
4960 (progn
4961 nil) ;; does not even start with a heading
4962 (catch 'exit
4963 (while (setq start (string-match re kill (1+ start)))
4964 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4965 (throw 'exit nil)))
4966 t))))
4968 (defvar org-markers-to-move nil
4969 "Markers that should be moved with a cut-and-paste operation.
4970 Those markers are stored together with their positions relative to
4971 the start of the region.")
4973 (defun org-save-markers-in-region (beg end)
4974 "Check markers in region.
4975 If these markers are between BEG and END, record their position relative
4976 to BEG, so that after moving the block of text, we can put the markers back
4977 into place.
4978 This function gets called just before an entry or tree gets cut from the
4979 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4980 called immediately, to move the markers with the entries."
4981 (setq org-markers-to-move nil)
4982 (when (featurep 'org-clock)
4983 (org-clock-save-markers-for-cut-and-paste beg end))
4984 (when (featurep 'org-agenda)
4985 (org-agenda-save-markers-for-cut-and-paste beg end)))
4987 (defun org-check-and-save-marker (marker beg end)
4988 "Check if MARKER is between BEG and END.
4989 If yes, remember the marker and the distance to BEG."
4990 (when (and (marker-buffer marker)
4991 (equal (marker-buffer marker) (current-buffer)))
4992 (if (and (>= marker beg) (< marker end))
4993 (push (cons marker (- marker beg)) org-markers-to-move))))
4995 (defun org-reinstall-markers-in-region (beg)
4996 "Move all remembered markers to their position relative to BEG."
4997 (mapc (lambda (x)
4998 (move-marker (car x) (+ beg (cdr x))))
4999 org-markers-to-move)
5000 (setq org-markers-to-move nil))
5002 (defun org-narrow-to-subtree ()
5003 "Narrow buffer to the current subtree."
5004 (interactive)
5005 (save-excursion
5006 (save-match-data
5007 (narrow-to-region
5008 (progn (org-back-to-heading) (point))
5009 (progn (org-end-of-subtree t t) (point))))))
5012 ;;; Outline Sorting
5014 (defun org-sort (with-case)
5015 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5016 Optional argument WITH-CASE means sort case-sensitively."
5017 (interactive "P")
5018 (if (org-at-table-p)
5019 (org-call-with-arg 'org-table-sort-lines with-case)
5020 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5022 (defun org-sort-remove-invisible (s)
5023 (remove-text-properties 0 (length s) org-rm-props s)
5024 (while (string-match org-bracket-link-regexp s)
5025 (setq s (replace-match (if (match-end 2)
5026 (match-string 3 s)
5027 (match-string 1 s)) t t s)))
5030 (defvar org-priority-regexp) ; defined later in the file
5032 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5033 "Sort entries on a certain level of an outline tree.
5034 If there is an active region, the entries in the region are sorted.
5035 Else, if the cursor is before the first entry, sort the top-level items.
5036 Else, the children of the entry at point are sorted.
5038 Sorting can be alphabetically, numerically, and by date/time as given by
5039 the first time stamp in the entry. The command prompts for the sorting
5040 type unless it has been given to the function through the SORTING-TYPE
5041 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5042 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5043 called with point at the beginning of the record. It must return either
5044 a string or a number that should serve as the sorting key for that record.
5046 Comparing entries ignores case by default. However, with an optional argument
5047 WITH-CASE, the sorting considers case as well."
5048 (interactive "P")
5049 (let ((case-func (if with-case 'identity 'downcase))
5050 start beg end stars re re2
5051 txt what tmp plain-list-p)
5052 ;; Find beginning and end of region to sort
5053 (cond
5054 ((org-region-active-p)
5055 ;; we will sort the region
5056 (setq end (region-end)
5057 what "region")
5058 (goto-char (region-beginning))
5059 (if (not (org-on-heading-p)) (outline-next-heading))
5060 (setq start (point)))
5061 ((org-at-item-p)
5062 ;; we will sort this plain list
5063 (org-beginning-of-item-list) (setq start (point))
5064 (org-end-of-item-list) (setq end (point))
5065 (goto-char start)
5066 (setq plain-list-p t
5067 what "plain list"))
5068 ((or (org-on-heading-p)
5069 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5070 ;; we will sort the children of the current headline
5071 (org-back-to-heading)
5072 (setq start (point)
5073 end (progn (org-end-of-subtree t t)
5074 (org-back-over-empty-lines)
5075 (point))
5076 what "children")
5077 (goto-char start)
5078 (show-subtree)
5079 (outline-next-heading))
5081 ;; we will sort the top-level entries in this file
5082 (goto-char (point-min))
5083 (or (org-on-heading-p) (outline-next-heading))
5084 (setq start (point) end (point-max) what "top-level")
5085 (goto-char start)
5086 (show-all)))
5088 (setq beg (point))
5089 (if (>= beg end) (error "Nothing to sort"))
5091 (unless plain-list-p
5092 (looking-at "\\(\\*+\\)")
5093 (setq stars (match-string 1)
5094 re (concat "^" (regexp-quote stars) " +")
5095 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5096 txt (buffer-substring beg end))
5097 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5098 (if (and (not (equal stars "*")) (string-match re2 txt))
5099 (error "Region to sort contains a level above the first entry")))
5101 (unless sorting-type
5102 (message
5103 (if plain-list-p
5104 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5105 "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:")
5106 what)
5107 (setq sorting-type (read-char-exclusive))
5109 (and (= (downcase sorting-type) ?f)
5110 (setq getkey-func
5111 (completing-read "Sort using function: "
5112 obarray 'fboundp t nil nil))
5113 (setq getkey-func (intern getkey-func)))
5115 (and (= (downcase sorting-type) ?r)
5116 (setq property
5117 (completing-read "Property: "
5118 (mapcar 'list (org-buffer-property-keys t))
5119 nil t))))
5121 (message "Sorting entries...")
5123 (save-restriction
5124 (narrow-to-region start end)
5126 (let ((dcst (downcase sorting-type))
5127 (now (current-time)))
5128 (sort-subr
5129 (/= dcst sorting-type)
5130 ;; This function moves to the beginning character of the "record" to
5131 ;; be sorted.
5132 (if plain-list-p
5133 (lambda nil
5134 (if (org-at-item-p) t (goto-char (point-max))))
5135 (lambda nil
5136 (if (re-search-forward re nil t)
5137 (goto-char (match-beginning 0))
5138 (goto-char (point-max)))))
5139 ;; This function moves to the last character of the "record" being
5140 ;; sorted.
5141 (if plain-list-p
5142 'org-end-of-item
5143 (lambda nil
5144 (save-match-data
5145 (condition-case nil
5146 (outline-forward-same-level 1)
5147 (error
5148 (goto-char (point-max)))))))
5150 ;; This function returns the value that gets sorted against.
5151 (if plain-list-p
5152 (lambda nil
5153 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5154 (cond
5155 ((= dcst ?n)
5156 (string-to-number (buffer-substring (match-end 0)
5157 (point-at-eol))))
5158 ((= dcst ?a)
5159 (buffer-substring (match-end 0) (point-at-eol)))
5160 ((= dcst ?t)
5161 (if (re-search-forward org-ts-regexp
5162 (point-at-eol) t)
5163 (org-time-string-to-time (match-string 0))
5164 now))
5165 ((= dcst ?f)
5166 (if getkey-func
5167 (progn
5168 (setq tmp (funcall getkey-func))
5169 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5170 tmp)
5171 (error "Invalid key function `%s'" getkey-func)))
5172 (t (error "Invalid sorting type `%c'" sorting-type)))))
5173 (lambda nil
5174 (cond
5175 ((= dcst ?n)
5176 (if (looking-at outline-regexp)
5177 (string-to-number (buffer-substring (match-end 0)
5178 (point-at-eol)))
5179 nil))
5180 ((= dcst ?a)
5181 (funcall case-func (buffer-substring (point-at-bol)
5182 (point-at-eol))))
5183 ((= dcst ?t)
5184 (if (re-search-forward org-ts-regexp
5185 (save-excursion
5186 (forward-line 2)
5187 (point)) t)
5188 (org-time-string-to-time (match-string 0))
5189 now))
5190 ((= dcst ?p)
5191 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5192 (string-to-char (match-string 2))
5193 org-default-priority))
5194 ((= dcst ?r)
5195 (or (org-entry-get nil property) ""))
5196 ((= dcst ?o)
5197 (if (looking-at org-complex-heading-regexp)
5198 (- 9999 (length (member (match-string 2)
5199 org-todo-keywords-1)))))
5200 ((= dcst ?f)
5201 (if getkey-func
5202 (progn
5203 (setq tmp (funcall getkey-func))
5204 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5205 tmp)
5206 (error "Invalid key function `%s'" getkey-func)))
5207 (t (error "Invalid sorting type `%c'" sorting-type)))))
5209 (cond
5210 ((= dcst ?a) 'string<)
5211 ((= dcst ?t) 'time-less-p)
5212 (t nil)))))
5213 (message "Sorting entries...done")))
5215 (defun org-do-sort (table what &optional with-case sorting-type)
5216 "Sort TABLE of WHAT according to SORTING-TYPE.
5217 The user will be prompted for the SORTING-TYPE if the call to this
5218 function does not specify it. WHAT is only for the prompt, to indicate
5219 what is being sorted. The sorting key will be extracted from
5220 the car of the elements of the table.
5221 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5222 (unless sorting-type
5223 (message
5224 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5225 what)
5226 (setq sorting-type (read-char-exclusive)))
5227 (let ((dcst (downcase sorting-type))
5228 extractfun comparefun)
5229 ;; Define the appropriate functions
5230 (cond
5231 ((= dcst ?n)
5232 (setq extractfun 'string-to-number
5233 comparefun (if (= dcst sorting-type) '< '>)))
5234 ((= dcst ?a)
5235 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5236 (lambda(x) (downcase (org-sort-remove-invisible x))))
5237 comparefun (if (= dcst sorting-type)
5238 'string<
5239 (lambda (a b) (and (not (string< a b))
5240 (not (string= a b)))))))
5241 ((= dcst ?t)
5242 (setq extractfun
5243 (lambda (x)
5244 (if (string-match org-ts-regexp x)
5245 (time-to-seconds
5246 (org-time-string-to-time (match-string 0 x)))
5248 comparefun (if (= dcst sorting-type) '< '>)))
5249 (t (error "Invalid sorting type `%c'" sorting-type)))
5251 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5252 table)
5253 (lambda (a b) (funcall comparefun (car a) (car b))))))
5255 ;;;; Plain list items, including checkboxes
5257 ;;; Plain list items
5259 (defun org-at-item-p ()
5260 "Is point in a line starting a hand-formatted item?"
5261 (let ((llt org-plain-list-ordered-item-terminator))
5262 (save-excursion
5263 (goto-char (point-at-bol))
5264 (looking-at
5265 (cond
5266 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5267 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5268 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5269 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5271 (defun org-in-item-p ()
5272 "It the cursor inside a plain list item.
5273 Does not have to be the first line."
5274 (save-excursion
5275 (condition-case nil
5276 (progn
5277 (org-beginning-of-item)
5278 (org-at-item-p)
5280 (error nil))))
5282 (defun org-insert-item (&optional checkbox)
5283 "Insert a new item at the current level.
5284 Return t when things worked, nil when we are not in an item."
5285 (when (save-excursion
5286 (condition-case nil
5287 (progn
5288 (org-beginning-of-item)
5289 (org-at-item-p)
5290 (if (org-invisible-p) (error "Invisible item"))
5292 (error nil)))
5293 (let* ((bul (match-string 0))
5294 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5295 (match-end 0)))
5296 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5297 pos)
5298 (cond
5299 ((and (org-at-item-p) (<= (point) eow))
5300 ;; before the bullet
5301 (beginning-of-line 1)
5302 (open-line (if blank 2 1)))
5303 ((<= (point) eow)
5304 (beginning-of-line 1))
5306 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5307 (end-of-line 1)
5308 (delete-horizontal-space))
5309 (newline (if blank 2 1))))
5310 (insert bul (if checkbox "[ ]" ""))
5311 (just-one-space)
5312 (setq pos (point))
5313 (end-of-line 1)
5314 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5315 (org-maybe-renumber-ordered-list)
5316 (and checkbox (org-update-checkbox-count-maybe))
5319 ;;; Checkboxes
5321 (defun org-at-item-checkbox-p ()
5322 "Is point at a line starting a plain-list item with a checklet?"
5323 (and (org-at-item-p)
5324 (save-excursion
5325 (goto-char (match-end 0))
5326 (skip-chars-forward " \t")
5327 (looking-at "\\[[- X]\\]"))))
5329 (defun org-toggle-checkbox (&optional arg)
5330 "Toggle the checkbox in the current line."
5331 (interactive "P")
5332 (catch 'exit
5333 (let (beg end status (firstnew 'unknown))
5334 (cond
5335 ((org-region-active-p)
5336 (setq beg (region-beginning) end (region-end)))
5337 ((org-on-heading-p)
5338 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5339 ((org-at-item-checkbox-p)
5340 (let ((pos (point)))
5341 (replace-match
5342 (cond (arg "[-]")
5343 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5344 (t "[ ]"))
5345 t t)
5346 (goto-char pos))
5347 (throw 'exit t))
5348 (t (error "Not at a checkbox or heading, and no active region")))
5349 (save-excursion
5350 (goto-char beg)
5351 (while (< (point) end)
5352 (when (org-at-item-checkbox-p)
5353 (setq status (equal (match-string 0) "[X]"))
5354 (when (eq firstnew 'unknown)
5355 (setq firstnew (not status)))
5356 (replace-match
5357 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5358 (beginning-of-line 2)))))
5359 (org-update-checkbox-count-maybe))
5361 (defun org-update-checkbox-count-maybe ()
5362 "Update checkbox statistics unless turned off by user."
5363 (when org-provide-checkbox-statistics
5364 (org-update-checkbox-count)))
5366 (defun org-update-checkbox-count (&optional all)
5367 "Update the checkbox statistics in the current section.
5368 This will find all statistic cookies like [57%] and [6/12] and update them
5369 with the current numbers. With optional prefix argument ALL, do this for
5370 the whole buffer."
5371 (interactive "P")
5372 (save-excursion
5373 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5374 (beg (condition-case nil
5375 (progn (outline-back-to-heading) (point))
5376 (error (point-min))))
5377 (end (move-marker (make-marker)
5378 (progn (outline-next-heading) (point))))
5379 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5380 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5381 (re-find (concat re "\\|" re-box))
5382 beg-cookie end-cookie is-percent c-on c-off lim
5383 eline curr-ind next-ind continue-from startsearch
5384 (cstat 0)
5386 (when all
5387 (goto-char (point-min))
5388 (outline-next-heading)
5389 (setq beg (point) end (point-max)))
5390 (goto-char end)
5391 ;; find each statistic cookie
5392 (while (re-search-backward re-find beg t)
5393 (setq beg-cookie (match-beginning 1)
5394 end-cookie (match-end 1)
5395 cstat (+ cstat (if end-cookie 1 0))
5396 startsearch (point-at-eol)
5397 continue-from (point-at-bol)
5398 is-percent (match-beginning 2)
5399 lim (cond
5400 ((org-on-heading-p) (outline-next-heading) (point))
5401 ((org-at-item-p) (org-end-of-item) (point))
5402 (t nil))
5403 c-on 0
5404 c-off 0)
5405 (when lim
5406 ;; find first checkbox for this cookie and gather
5407 ;; statistics from all that are at this indentation level
5408 (goto-char startsearch)
5409 (if (re-search-forward re-box lim t)
5410 (progn
5411 (org-beginning-of-item)
5412 (setq curr-ind (org-get-indentation))
5413 (setq next-ind curr-ind)
5414 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5415 (save-excursion (end-of-line) (setq eline (point)))
5416 (if (re-search-forward re-box eline t)
5417 (if (member (match-string 2) '("[ ]" "[-]"))
5418 (setq c-off (1+ c-off))
5419 (setq c-on (1+ c-on))
5422 (org-end-of-item)
5423 (setq next-ind (org-get-indentation))
5425 (goto-char continue-from)
5426 ;; update cookie
5427 (when end-cookie
5428 (delete-region beg-cookie end-cookie)
5429 (goto-char beg-cookie)
5430 (insert
5431 (if is-percent
5432 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5433 (format "[%d/%d]" c-on (+ c-on c-off)))))
5434 ;; update items checkbox if it has one
5435 (when (org-at-item-p)
5436 (org-beginning-of-item)
5437 (when (and (> (+ c-on c-off) 0)
5438 (re-search-forward re-box (point-at-eol) t))
5439 (setq beg-cookie (match-beginning 2)
5440 end-cookie (match-end 2))
5441 (delete-region beg-cookie end-cookie)
5442 (goto-char beg-cookie)
5443 (cond ((= c-off 0) (insert "[X]"))
5444 ((= c-on 0) (insert "[ ]"))
5445 (t (insert "[-]")))
5447 (goto-char continue-from))
5448 (when (interactive-p)
5449 (message "Checkbox satistics updated %s (%d places)"
5450 (if all "in entire file" "in current outline entry") cstat)))))
5452 (defun org-get-checkbox-statistics-face ()
5453 "Select the face for checkbox statistics.
5454 The face will be `org-done' when all relevant boxes are checked. Otherwise
5455 it will be `org-todo'."
5456 (if (match-end 1)
5457 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5458 (if (and (> (match-end 2) (match-beginning 2))
5459 (equal (match-string 2) (match-string 3)))
5460 'org-done
5461 'org-todo)))
5463 (defun org-get-indentation (&optional line)
5464 "Get the indentation of the current line, interpreting tabs.
5465 When LINE is given, assume it represents a line and compute its indentation."
5466 (if line
5467 (if (string-match "^ *" (org-remove-tabs line))
5468 (match-end 0))
5469 (save-excursion
5470 (beginning-of-line 1)
5471 (skip-chars-forward " \t")
5472 (current-column))))
5474 (defun org-remove-tabs (s &optional width)
5475 "Replace tabulators in S with spaces.
5476 Assumes that s is a single line, starting in column 0."
5477 (setq width (or width tab-width))
5478 (while (string-match "\t" s)
5479 (setq s (replace-match
5480 (make-string
5481 (- (* width (/ (+ (match-beginning 0) width) width))
5482 (match-beginning 0)) ?\ )
5483 t t s)))
5486 (defun org-fix-indentation (line ind)
5487 "Fix indentation in LINE.
5488 IND is a cons cell with target and minimum indentation.
5489 If the current indenation in LINE is smaller than the minimum,
5490 leave it alone. If it is larger than ind, set it to the target."
5491 (let* ((l (org-remove-tabs line))
5492 (i (org-get-indentation l))
5493 (i1 (car ind)) (i2 (cdr ind)))
5494 (if (>= i i2) (setq l (substring line i2)))
5495 (if (> i1 0)
5496 (concat (make-string i1 ?\ ) l)
5497 l)))
5499 (defun org-beginning-of-item ()
5500 "Go to the beginning of the current hand-formatted item.
5501 If the cursor is not in an item, throw an error."
5502 (interactive)
5503 (let ((pos (point))
5504 (limit (save-excursion
5505 (condition-case nil
5506 (progn
5507 (org-back-to-heading)
5508 (beginning-of-line 2) (point))
5509 (error (point-min)))))
5510 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5511 ind ind1)
5512 (if (org-at-item-p)
5513 (beginning-of-line 1)
5514 (beginning-of-line 1)
5515 (skip-chars-forward " \t")
5516 (setq ind (current-column))
5517 (if (catch 'exit
5518 (while t
5519 (beginning-of-line 0)
5520 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5522 (if (looking-at "[ \t]*$")
5523 (setq ind1 ind-empty)
5524 (skip-chars-forward " \t")
5525 (setq ind1 (current-column)))
5526 (if (< ind1 ind)
5527 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5529 (goto-char pos)
5530 (error "Not in an item")))))
5532 (defun org-end-of-item ()
5533 "Go to the end of the current hand-formatted item.
5534 If the cursor is not in an item, throw an error."
5535 (interactive)
5536 (let* ((pos (point))
5537 ind1
5538 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5539 (limit (save-excursion (outline-next-heading) (point)))
5540 (ind (save-excursion
5541 (org-beginning-of-item)
5542 (skip-chars-forward " \t")
5543 (current-column)))
5544 (end (catch 'exit
5545 (while t
5546 (beginning-of-line 2)
5547 (if (eobp) (throw 'exit (point)))
5548 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5549 (if (looking-at "[ \t]*$")
5550 (setq ind1 ind-empty)
5551 (skip-chars-forward " \t")
5552 (setq ind1 (current-column)))
5553 (if (<= ind1 ind)
5554 (throw 'exit (point-at-bol)))))))
5555 (if end
5556 (goto-char end)
5557 (goto-char pos)
5558 (error "Not in an item"))))
5560 (defun org-next-item ()
5561 "Move to the beginning of the next item in the current plain list.
5562 Error if not at a plain list, or if this is the last item in the list."
5563 (interactive)
5564 (let (ind ind1 (pos (point)))
5565 (org-beginning-of-item)
5566 (setq ind (org-get-indentation))
5567 (org-end-of-item)
5568 (setq ind1 (org-get-indentation))
5569 (unless (and (org-at-item-p) (= ind ind1))
5570 (goto-char pos)
5571 (error "On last item"))))
5573 (defun org-previous-item ()
5574 "Move to the beginning of the previous item in the current plain list.
5575 Error if not at a plain list, or if this is the first item in the list."
5576 (interactive)
5577 (let (beg ind ind1 (pos (point)))
5578 (org-beginning-of-item)
5579 (setq beg (point))
5580 (setq ind (org-get-indentation))
5581 (goto-char beg)
5582 (catch 'exit
5583 (while t
5584 (beginning-of-line 0)
5585 (if (looking-at "[ \t]*$")
5587 (if (<= (setq ind1 (org-get-indentation)) ind)
5588 (throw 'exit t)))))
5589 (condition-case nil
5590 (if (or (not (org-at-item-p))
5591 (< ind1 (1- ind)))
5592 (error "")
5593 (org-beginning-of-item))
5594 (error (goto-char pos)
5595 (error "On first item")))))
5597 (defun org-first-list-item-p ()
5598 "Is this heading the item in a plain list?"
5599 (unless (org-at-item-p)
5600 (error "Not at a plain list item"))
5601 (org-beginning-of-item)
5602 (= (point) (save-excursion (org-beginning-of-item-list))))
5604 (defun org-move-item-down ()
5605 "Move the plain list item at point down, i.e. swap with following item.
5606 Subitems (items with larger indentation) are considered part of the item,
5607 so this really moves item trees."
5608 (interactive)
5609 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5610 (org-beginning-of-item)
5611 (setq beg0 (point))
5612 (save-excursion
5613 (setq ne-beg (org-back-over-empty-lines))
5614 (setq beg (point)))
5615 (goto-char beg0)
5616 (setq ind (org-get-indentation))
5617 (org-end-of-item)
5618 (setq end0 (point))
5619 (setq ind1 (org-get-indentation))
5620 (setq ne-end (org-back-over-empty-lines))
5621 (setq end (point))
5622 (goto-char beg0)
5623 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5624 ;; include less whitespace
5625 (save-excursion
5626 (goto-char beg)
5627 (forward-line (- ne-beg ne-end))
5628 (setq beg (point))))
5629 (goto-char end0)
5630 (if (and (org-at-item-p) (= ind ind1))
5631 (progn
5632 (org-end-of-item)
5633 (org-back-over-empty-lines)
5634 (setq txt (buffer-substring beg end))
5635 (save-excursion
5636 (delete-region beg end))
5637 (setq pos (point))
5638 (insert txt)
5639 (goto-char pos) (org-skip-whitespace)
5640 (org-maybe-renumber-ordered-list))
5641 (goto-char pos)
5642 (error "Cannot move this item further down"))))
5644 (defun org-move-item-up (arg)
5645 "Move the plain list item at point up, i.e. swap with previous item.
5646 Subitems (items with larger indentation) are considered part of the item,
5647 so this really moves item trees."
5648 (interactive "p")
5649 (let (beg beg0 end ind ind1 (pos (point)) txt
5650 ne-beg ne-ins ins-end)
5651 (org-beginning-of-item)
5652 (setq beg0 (point))
5653 (setq ind (org-get-indentation))
5654 (save-excursion
5655 (setq ne-beg (org-back-over-empty-lines))
5656 (setq beg (point)))
5657 (goto-char beg0)
5658 (org-end-of-item)
5659 (setq end (point))
5660 (goto-char beg0)
5661 (catch 'exit
5662 (while t
5663 (beginning-of-line 0)
5664 (if (looking-at "[ \t]*$")
5665 (if org-empty-line-terminates-plain-lists
5666 (progn
5667 (goto-char pos)
5668 (error "Cannot move this item further up"))
5669 nil)
5670 (if (<= (setq ind1 (org-get-indentation)) ind)
5671 (throw 'exit t)))))
5672 (condition-case nil
5673 (org-beginning-of-item)
5674 (error (goto-char beg)
5675 (error "Cannot move this item further up")))
5676 (setq ind1 (org-get-indentation))
5677 (if (and (org-at-item-p) (= ind ind1))
5678 (progn
5679 (setq ne-ins (org-back-over-empty-lines))
5680 (setq txt (buffer-substring beg end))
5681 (save-excursion
5682 (delete-region beg end))
5683 (setq pos (point))
5684 (insert txt)
5685 (setq ins-end (point))
5686 (goto-char pos) (org-skip-whitespace)
5688 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5689 ;; Move whitespace back to beginning
5690 (save-excursion
5691 (goto-char ins-end)
5692 (let ((kill-whole-line t))
5693 (kill-line (- ne-ins ne-beg)) (point)))
5694 (insert (make-string (- ne-ins ne-beg) ?\n)))
5696 (org-maybe-renumber-ordered-list))
5697 (goto-char pos)
5698 (error "Cannot move this item further up"))))
5700 (defun org-maybe-renumber-ordered-list ()
5701 "Renumber the ordered list at point if setup allows it.
5702 This tests the user option `org-auto-renumber-ordered-lists' before
5703 doing the renumbering."
5704 (interactive)
5705 (when (and org-auto-renumber-ordered-lists
5706 (org-at-item-p))
5707 (if (match-beginning 3)
5708 (org-renumber-ordered-list 1)
5709 (org-fix-bullet-type))))
5711 (defun org-maybe-renumber-ordered-list-safe ()
5712 (condition-case nil
5713 (save-excursion
5714 (org-maybe-renumber-ordered-list))
5715 (error nil)))
5717 (defun org-cycle-list-bullet (&optional which)
5718 "Cycle through the different itemize/enumerate bullets.
5719 This cycle the entire list level through the sequence:
5721 `-' -> `+' -> `*' -> `1.' -> `1)'
5723 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5724 0 meand `-', 1 means `+' etc."
5725 (interactive "P")
5726 (org-preserve-lc
5727 (org-beginning-of-item-list)
5728 (org-at-item-p)
5729 (beginning-of-line 1)
5730 (let ((current (match-string 0))
5731 (prevp (eq which 'previous))
5732 new)
5733 (setq new (cond
5734 ((and (numberp which)
5735 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5736 ((string-match "-" current) (if prevp "1)" "+"))
5737 ((string-match "\\+" current)
5738 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5739 ((string-match "\\*" current) (if prevp "+" "1."))
5740 ((string-match "\\." current) (if prevp "*" "1)"))
5741 ((string-match ")" current) (if prevp "1." "-"))
5742 (t (error "This should not happen"))))
5743 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5744 (org-fix-bullet-type)
5745 (org-maybe-renumber-ordered-list))))
5747 (defun org-get-string-indentation (s)
5748 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5749 (let ((n -1) (i 0) (w tab-width) c)
5750 (catch 'exit
5751 (while (< (setq n (1+ n)) (length s))
5752 (setq c (aref s n))
5753 (cond ((= c ?\ ) (setq i (1+ i)))
5754 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5755 (t (throw 'exit t)))))
5758 (defun org-renumber-ordered-list (arg)
5759 "Renumber an ordered plain list.
5760 Cursor needs to be in the first line of an item, the line that starts
5761 with something like \"1.\" or \"2)\"."
5762 (interactive "p")
5763 (unless (and (org-at-item-p)
5764 (match-beginning 3))
5765 (error "This is not an ordered list"))
5766 (let ((line (org-current-line))
5767 (col (current-column))
5768 (ind (org-get-string-indentation
5769 (buffer-substring (point-at-bol) (match-beginning 3))))
5770 ;; (term (substring (match-string 3) -1))
5771 ind1 (n (1- arg))
5772 fmt)
5773 ;; find where this list begins
5774 (org-beginning-of-item-list)
5775 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5776 (setq fmt (concat "%d" (match-string 1)))
5777 (beginning-of-line 0)
5778 ;; walk forward and replace these numbers
5779 (catch 'exit
5780 (while t
5781 (catch 'next
5782 (beginning-of-line 2)
5783 (if (eobp) (throw 'exit nil))
5784 (if (looking-at "[ \t]*$") (throw 'next nil))
5785 (skip-chars-forward " \t") (setq ind1 (current-column))
5786 (if (> ind1 ind) (throw 'next t))
5787 (if (< ind1 ind) (throw 'exit t))
5788 (if (not (org-at-item-p)) (throw 'exit nil))
5789 (delete-region (match-beginning 2) (match-end 2))
5790 (goto-char (match-beginning 2))
5791 (insert (format fmt (setq n (1+ n)))))))
5792 (goto-line line)
5793 (org-move-to-column col)))
5795 (defun org-fix-bullet-type ()
5796 "Make sure all items in this list have the same bullet as the firsst item."
5797 (interactive)
5798 (unless (org-at-item-p) (error "This is not a list"))
5799 (let ((line (org-current-line))
5800 (col (current-column))
5801 (ind (current-indentation))
5802 ind1 bullet)
5803 ;; find where this list begins
5804 (org-beginning-of-item-list)
5805 (beginning-of-line 1)
5806 ;; find out what the bullet type is
5807 (looking-at "[ \t]*\\(\\S-+\\)")
5808 (setq bullet (match-string 1))
5809 ;; walk forward and replace these numbers
5810 (beginning-of-line 0)
5811 (catch 'exit
5812 (while t
5813 (catch 'next
5814 (beginning-of-line 2)
5815 (if (eobp) (throw 'exit nil))
5816 (if (looking-at "[ \t]*$") (throw 'next nil))
5817 (skip-chars-forward " \t") (setq ind1 (current-column))
5818 (if (> ind1 ind) (throw 'next t))
5819 (if (< ind1 ind) (throw 'exit t))
5820 (if (not (org-at-item-p)) (throw 'exit nil))
5821 (skip-chars-forward " \t")
5822 (looking-at "\\S-+")
5823 (replace-match bullet))))
5824 (goto-line line)
5825 (org-move-to-column col)
5826 (if (string-match "[0-9]" bullet)
5827 (org-renumber-ordered-list 1))))
5829 (defun org-beginning-of-item-list ()
5830 "Go to the beginning of the current item list.
5831 I.e. to the first item in this list."
5832 (interactive)
5833 (org-beginning-of-item)
5834 (let ((pos (point-at-bol))
5835 (ind (org-get-indentation))
5836 ind1)
5837 ;; find where this list begins
5838 (catch 'exit
5839 (while t
5840 (catch 'next
5841 (beginning-of-line 0)
5842 (if (looking-at "[ \t]*$")
5843 (throw (if (bobp) 'exit 'next) t))
5844 (skip-chars-forward " \t") (setq ind1 (current-column))
5845 (if (or (< ind1 ind)
5846 (and (= ind1 ind)
5847 (not (org-at-item-p)))
5848 (bobp))
5849 (throw 'exit t)
5850 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5851 (goto-char pos)))
5854 (defun org-end-of-item-list ()
5855 "Go to the end of the current item list.
5856 I.e. to the text after the last item."
5857 (interactive)
5858 (org-beginning-of-item)
5859 (let ((pos (point-at-bol))
5860 (ind (org-get-indentation))
5861 ind1)
5862 ;; find where this list begins
5863 (catch 'exit
5864 (while t
5865 (catch 'next
5866 (beginning-of-line 2)
5867 (if (looking-at "[ \t]*$")
5868 (throw (if (eobp) 'exit 'next) t))
5869 (skip-chars-forward " \t") (setq ind1 (current-column))
5870 (if (or (< ind1 ind)
5871 (and (= ind1 ind)
5872 (not (org-at-item-p)))
5873 (eobp))
5874 (progn
5875 (setq pos (point-at-bol))
5876 (throw 'exit t))))))
5877 (goto-char pos)))
5880 (defvar org-last-indent-begin-marker (make-marker))
5881 (defvar org-last-indent-end-marker (make-marker))
5883 (defun org-outdent-item (arg)
5884 "Outdent a local list item."
5885 (interactive "p")
5886 (org-indent-item (- arg)))
5888 (defun org-indent-item (arg)
5889 "Indent a local list item."
5890 (interactive "p")
5891 (unless (org-at-item-p)
5892 (error "Not on an item"))
5893 (save-excursion
5894 (let (beg end ind ind1 tmp delta ind-down ind-up)
5895 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5896 (setq beg org-last-indent-begin-marker
5897 end org-last-indent-end-marker)
5898 (org-beginning-of-item)
5899 (setq beg (move-marker org-last-indent-begin-marker (point)))
5900 (org-end-of-item)
5901 (setq end (move-marker org-last-indent-end-marker (point))))
5902 (goto-char beg)
5903 (setq tmp (org-item-indent-positions)
5904 ind (car tmp)
5905 ind-down (nth 2 tmp)
5906 ind-up (nth 1 tmp)
5907 delta (if (> arg 0)
5908 (if ind-down (- ind-down ind) 2)
5909 (if ind-up (- ind-up ind) -2)))
5910 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5911 (while (< (point) end)
5912 (beginning-of-line 1)
5913 (skip-chars-forward " \t") (setq ind1 (current-column))
5914 (delete-region (point-at-bol) (point))
5915 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5916 (beginning-of-line 2))))
5917 (org-fix-bullet-type)
5918 (org-maybe-renumber-ordered-list-safe)
5919 (save-excursion
5920 (beginning-of-line 0)
5921 (condition-case nil (org-beginning-of-item) (error nil))
5922 (org-maybe-renumber-ordered-list-safe)))
5924 (defun org-item-indent-positions ()
5925 "Return indentation for plain list items.
5926 This returns a list with three values: The current indentation, the
5927 parent indentation and the indentation a child should habe.
5928 Assumes cursor in item line."
5929 (let* ((bolpos (point-at-bol))
5930 (ind (org-get-indentation))
5931 ind-down ind-up pos)
5932 (save-excursion
5933 (org-beginning-of-item-list)
5934 (skip-chars-backward "\n\r \t")
5935 (when (org-in-item-p)
5936 (org-beginning-of-item)
5937 (setq ind-up (org-get-indentation))))
5938 (setq pos (point))
5939 (save-excursion
5940 (cond
5941 ((and (condition-case nil (progn (org-previous-item) t)
5942 (error nil))
5943 (or (forward-char 1) t)
5944 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5945 (setq ind-down (org-get-indentation)))
5946 ((and (goto-char pos)
5947 (org-at-item-p))
5948 (goto-char (match-end 0))
5949 (skip-chars-forward " \t")
5950 (setq ind-down (current-column)))))
5951 (list ind ind-up ind-down)))
5953 ;;; The orgstruct minor mode
5955 ;; Define a minor mode which can be used in other modes in order to
5956 ;; integrate the org-mode structure editing commands.
5958 ;; This is really a hack, because the org-mode structure commands use
5959 ;; keys which normally belong to the major mode. Here is how it
5960 ;; works: The minor mode defines all the keys necessary to operate the
5961 ;; structure commands, but wraps the commands into a function which
5962 ;; tests if the cursor is currently at a headline or a plain list
5963 ;; item. If that is the case, the structure command is used,
5964 ;; temporarily setting many Org-mode variables like regular
5965 ;; expressions for filling etc. However, when any of those keys is
5966 ;; used at a different location, function uses `key-binding' to look
5967 ;; up if the key has an associated command in another currently active
5968 ;; keymap (minor modes, major mode, global), and executes that
5969 ;; command. There might be problems if any of the keys is otherwise
5970 ;; used as a prefix key.
5972 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5973 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5974 ;; addresses this by checking explicitly for both bindings.
5976 (defvar orgstruct-mode-map (make-sparse-keymap)
5977 "Keymap for the minor `orgstruct-mode'.")
5979 (defvar org-local-vars nil
5980 "List of local variables, for use by `orgstruct-mode'")
5982 ;;;###autoload
5983 (define-minor-mode orgstruct-mode
5984 "Toggle the minor more `orgstruct-mode'.
5985 This mode is for using Org-mode structure commands in other modes.
5986 The following key behave as if Org-mode was active, if the cursor
5987 is on a headline, or on a plain list item (both in the definition
5988 of Org-mode).
5990 M-up Move entry/item up
5991 M-down Move entry/item down
5992 M-left Promote
5993 M-right Demote
5994 M-S-up Move entry/item up
5995 M-S-down Move entry/item down
5996 M-S-left Promote subtree
5997 M-S-right Demote subtree
5998 M-q Fill paragraph and items like in Org-mode
5999 C-c ^ Sort entries
6000 C-c - Cycle list bullet
6001 TAB Cycle item visibility
6002 M-RET Insert new heading/item
6003 S-M-RET Insert new TODO heading / Chekbox item
6004 C-c C-c Set tags / toggle checkbox"
6005 nil " OrgStruct" nil
6006 (org-load-modules-maybe)
6007 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6009 ;;;###autoload
6010 (defun turn-on-orgstruct ()
6011 "Unconditionally turn on `orgstruct-mode'."
6012 (orgstruct-mode 1))
6014 ;;;###autoload
6015 (defun turn-on-orgstruct++ ()
6016 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6017 In addition to setting orgstruct-mode, this also exports all indentation and
6018 autofilling variables from org-mode into the buffer. Note that turning
6019 off orgstruct-mode will *not* remove these additional settings."
6020 (orgstruct-mode 1)
6021 (let (var val)
6022 (mapc
6023 (lambda (x)
6024 (when (string-match
6025 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6026 (symbol-name (car x)))
6027 (setq var (car x) val (nth 1 x))
6028 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6029 org-local-vars)))
6031 (defun orgstruct-error ()
6032 "Error when there is no default binding for a structure key."
6033 (interactive)
6034 (error "This key has no function outside structure elements"))
6036 (defun orgstruct-setup ()
6037 "Setup orgstruct keymaps."
6038 (let ((nfunc 0)
6039 (bindings
6040 (list
6041 '([(meta up)] org-metaup)
6042 '([(meta down)] org-metadown)
6043 '([(meta left)] org-metaleft)
6044 '([(meta right)] org-metaright)
6045 '([(meta shift up)] org-shiftmetaup)
6046 '([(meta shift down)] org-shiftmetadown)
6047 '([(meta shift left)] org-shiftmetaleft)
6048 '([(meta shift right)] org-shiftmetaright)
6049 '([(shift up)] org-shiftup)
6050 '([(shift down)] org-shiftdown)
6051 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6052 '("\M-q" fill-paragraph)
6053 '("\C-c^" org-sort)
6054 '("\C-c-" org-cycle-list-bullet)))
6055 elt key fun cmd)
6056 (while (setq elt (pop bindings))
6057 (setq nfunc (1+ nfunc))
6058 (setq key (org-key (car elt))
6059 fun (nth 1 elt)
6060 cmd (orgstruct-make-binding fun nfunc key))
6061 (org-defkey orgstruct-mode-map key cmd))
6063 ;; Special treatment needed for TAB and RET
6064 (org-defkey orgstruct-mode-map [(tab)]
6065 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6066 (org-defkey orgstruct-mode-map "\C-i"
6067 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6069 (org-defkey orgstruct-mode-map "\M-\C-m"
6070 (orgstruct-make-binding 'org-insert-heading 105
6071 "\M-\C-m" [(meta return)]))
6072 (org-defkey orgstruct-mode-map [(meta return)]
6073 (orgstruct-make-binding 'org-insert-heading 106
6074 [(meta return)] "\M-\C-m"))
6076 (org-defkey orgstruct-mode-map [(shift meta return)]
6077 (orgstruct-make-binding 'org-insert-todo-heading 107
6078 [(meta return)] "\M-\C-m"))
6080 (unless org-local-vars
6081 (setq org-local-vars (org-get-local-variables)))
6085 (defun orgstruct-make-binding (fun n &rest keys)
6086 "Create a function for binding in the structure minor mode.
6087 FUN is the command to call inside a table. N is used to create a unique
6088 command name. KEYS are keys that should be checked in for a command
6089 to execute outside of tables."
6090 (eval
6091 (list 'defun
6092 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6093 '(arg)
6094 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6095 "Outside of structure, run the binding of `"
6096 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6097 "'.")
6098 '(interactive "p")
6099 (list 'if
6100 '(org-context-p 'headline 'item)
6101 (list 'org-run-like-in-org-mode (list 'quote fun))
6102 (list 'let '(orgstruct-mode)
6103 (list 'call-interactively
6104 (append '(or)
6105 (mapcar (lambda (k)
6106 (list 'key-binding k))
6107 keys)
6108 '('orgstruct-error))))))))
6110 (defun org-context-p (&rest contexts)
6111 "Check if local context is and of CONTEXTS.
6112 Possible values in the list of contexts are `table', `headline', and `item'."
6113 (let ((pos (point)))
6114 (goto-char (point-at-bol))
6115 (prog1 (or (and (memq 'table contexts)
6116 (looking-at "[ \t]*|"))
6117 (and (memq 'headline contexts)
6118 (looking-at "\\*+"))
6119 (and (memq 'item contexts)
6120 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6121 (goto-char pos))))
6123 (defun org-get-local-variables ()
6124 "Return a list of all local variables in an org-mode buffer."
6125 (let (varlist)
6126 (with-current-buffer (get-buffer-create "*Org tmp*")
6127 (erase-buffer)
6128 (org-mode)
6129 (setq varlist (buffer-local-variables)))
6130 (kill-buffer "*Org tmp*")
6131 (delq nil
6132 (mapcar
6133 (lambda (x)
6134 (setq x
6135 (if (symbolp x)
6136 (list x)
6137 (list (car x) (list 'quote (cdr x)))))
6138 (if (string-match
6139 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6140 (symbol-name (car x)))
6141 x nil))
6142 varlist))))
6144 ;;;###autoload
6145 (defun org-run-like-in-org-mode (cmd)
6146 (org-load-modules-maybe)
6147 (unless org-local-vars
6148 (setq org-local-vars (org-get-local-variables)))
6149 (eval (list 'let org-local-vars
6150 (list 'call-interactively (list 'quote cmd)))))
6152 ;;;; Archiving
6154 (defun org-get-category (&optional pos)
6155 "Get the category applying to position POS."
6156 (get-text-property (or pos (point)) 'org-category))
6158 (defun org-refresh-category-properties ()
6159 "Refresh category text properties in the buffer."
6160 (let ((def-cat (cond
6161 ((null org-category)
6162 (if buffer-file-name
6163 (file-name-sans-extension
6164 (file-name-nondirectory buffer-file-name))
6165 "???"))
6166 ((symbolp org-category) (symbol-name org-category))
6167 (t org-category)))
6168 beg end cat pos optionp)
6169 (org-unmodified
6170 (save-excursion
6171 (save-restriction
6172 (widen)
6173 (goto-char (point-min))
6174 (put-text-property (point) (point-max) 'org-category def-cat)
6175 (while (re-search-forward
6176 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6177 (setq pos (match-end 0)
6178 optionp (equal (char-after (match-beginning 0)) ?#)
6179 cat (org-trim (match-string 2)))
6180 (if optionp
6181 (setq beg (point-at-bol) end (point-max))
6182 (org-back-to-heading t)
6183 (setq beg (point) end (org-end-of-subtree t t)))
6184 (put-text-property beg end 'org-category cat)
6185 (goto-char pos)))))))
6188 ;;;; Link Stuff
6190 ;;; Link abbreviations
6192 (defun org-link-expand-abbrev (link)
6193 "Apply replacements as defined in `org-link-abbrev-alist."
6194 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6195 (let* ((key (match-string 1 link))
6196 (as (or (assoc key org-link-abbrev-alist-local)
6197 (assoc key org-link-abbrev-alist)))
6198 (tag (and (match-end 2) (match-string 3 link)))
6199 rpl)
6200 (if (not as)
6201 link
6202 (setq rpl (cdr as))
6203 (cond
6204 ((symbolp rpl) (funcall rpl tag))
6205 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6206 (t (concat rpl tag)))))
6207 link))
6209 ;;; Storing and inserting links
6211 (defvar org-insert-link-history nil
6212 "Minibuffer history for links inserted with `org-insert-link'.")
6214 (defvar org-stored-links nil
6215 "Contains the links stored with `org-store-link'.")
6217 (defvar org-store-link-plist nil
6218 "Plist with info about the most recently link created with `org-store-link'.")
6220 (defvar org-link-protocols nil
6221 "Link protocols added to Org-mode using `org-add-link-type'.")
6223 (defvar org-store-link-functions nil
6224 "List of functions that are called to create and store a link.
6225 Each function will be called in turn until one returns a non-nil
6226 value. Each function should check if it is responsible for creating
6227 this link (for example by looking at the major mode).
6228 If not, it must exit and return nil.
6229 If yes, it should return a non-nil value after a calling
6230 `org-store-link-props' with a list of properties and values.
6231 Special properties are:
6233 :type The link prefix. like \"http\". This must be given.
6234 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6235 This is obligatory as well.
6236 :description Optional default description for the second pair
6237 of brackets in an Org-mode link. The user can still change
6238 this when inserting this link into an Org-mode buffer.
6240 In addition to these, any additional properties can be specified
6241 and then used in remember templates.")
6243 (defun org-add-link-type (type &optional follow export)
6244 "Add TYPE to the list of `org-link-types'.
6245 Re-compute all regular expressions depending on `org-link-types'
6247 FOLLOW and EXPORT are two functions.
6249 FOLLOW should take the link path as the single argument and do whatever
6250 is necessary to follow the link, for example find a file or display
6251 a mail message.
6253 EXPORT should format the link path for export to one of the export formats.
6254 It should be a function accepting three arguments:
6256 path the path of the link, the text after the prefix (like \"http:\")
6257 desc the description of the link, if any, nil if there was no descripton
6258 format the export format, a symbol like `html' or `latex'.
6260 The function may use the FORMAT information to return different values
6261 depending on the format. The return value will be put literally into
6262 the exported file.
6263 Org-mode has a built-in default for exporting links. If you are happy with
6264 this default, there is no need to define an export function for the link
6265 type. For a simple example of an export function, see `org-bbdb.el'."
6266 (add-to-list 'org-link-types type t)
6267 (org-make-link-regexps)
6268 (if (assoc type org-link-protocols)
6269 (setcdr (assoc type org-link-protocols) (list follow export))
6270 (push (list type follow export) org-link-protocols)))
6273 ;;;###autoload
6274 (defun org-store-link (arg)
6275 "\\<org-mode-map>Store an org-link to the current location.
6276 This link is added to `org-stored-links' and can later be inserted
6277 into an org-buffer with \\[org-insert-link].
6279 For some link types, a prefix arg is interpreted:
6280 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6281 For file links, arg negates `org-context-in-file-links'."
6282 (interactive "P")
6283 (org-load-modules-maybe)
6284 (setq org-store-link-plist nil) ; reset
6285 (let (link cpltxt desc description search txt)
6286 (cond
6288 ((run-hook-with-args-until-success 'org-store-link-functions)
6289 (setq link (plist-get org-store-link-plist :link)
6290 desc (or (plist-get org-store-link-plist :description) link)))
6292 ((eq major-mode 'calendar-mode)
6293 (let ((cd (calendar-cursor-to-date)))
6294 (setq link
6295 (format-time-string
6296 (car org-time-stamp-formats)
6297 (apply 'encode-time
6298 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6299 nil nil nil))))
6300 (org-store-link-props :type "calendar" :date cd)))
6302 ((eq major-mode 'w3-mode)
6303 (setq cpltxt (url-view-url t)
6304 link (org-make-link cpltxt))
6305 (org-store-link-props :type "w3" :url (url-view-url t)))
6307 ((eq major-mode 'w3m-mode)
6308 (setq cpltxt (or w3m-current-title w3m-current-url)
6309 link (org-make-link w3m-current-url))
6310 (org-store-link-props :type "w3m" :url (url-view-url t)))
6312 ((setq search (run-hook-with-args-until-success
6313 'org-create-file-search-functions))
6314 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6315 "::" search))
6316 (setq cpltxt (or description link)))
6318 ((eq major-mode 'image-mode)
6319 (setq cpltxt (concat "file:"
6320 (abbreviate-file-name buffer-file-name))
6321 link (org-make-link cpltxt))
6322 (org-store-link-props :type "image" :file buffer-file-name))
6324 ((eq major-mode 'dired-mode)
6325 ;; link to the file in the current line
6326 (setq cpltxt (concat "file:"
6327 (abbreviate-file-name
6328 (expand-file-name
6329 (dired-get-filename nil t))))
6330 link (org-make-link cpltxt)))
6332 ((and buffer-file-name (org-mode-p))
6333 ;; Just link to current headline
6334 (setq cpltxt (concat "file:"
6335 (abbreviate-file-name buffer-file-name)))
6336 ;; Add a context search string
6337 (when (org-xor org-context-in-file-links arg)
6338 ;; Check if we are on a target
6339 (if (org-in-regexp "<<\\(.*?\\)>>")
6340 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6341 (setq txt (cond
6342 ((org-on-heading-p) nil)
6343 ((org-region-active-p)
6344 (buffer-substring (region-beginning) (region-end)))
6345 (t nil)))
6346 (when (or (null txt) (string-match "\\S-" txt))
6347 (setq cpltxt
6348 (concat cpltxt "::"
6349 (condition-case nil
6350 (org-make-org-heading-search-string txt)
6351 (error "")))
6352 desc "NONE"))))
6353 (if (string-match "::\\'" cpltxt)
6354 (setq cpltxt (substring cpltxt 0 -2)))
6355 (setq link (org-make-link cpltxt)))
6357 ((buffer-file-name (buffer-base-buffer))
6358 ;; Just link to this file here.
6359 (setq cpltxt (concat "file:"
6360 (abbreviate-file-name
6361 (buffer-file-name (buffer-base-buffer)))))
6362 ;; Add a context string
6363 (when (org-xor org-context-in-file-links arg)
6364 (setq txt (if (org-region-active-p)
6365 (buffer-substring (region-beginning) (region-end))
6366 (buffer-substring (point-at-bol) (point-at-eol))))
6367 ;; Only use search option if there is some text.
6368 (when (string-match "\\S-" txt)
6369 (setq cpltxt
6370 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6371 desc "NONE")))
6372 (setq link (org-make-link cpltxt)))
6374 ((interactive-p)
6375 (error "Cannot link to a buffer which is not visiting a file"))
6377 (t (setq link nil)))
6379 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6380 (setq link (or link cpltxt)
6381 desc (or desc cpltxt))
6382 (if (equal desc "NONE") (setq desc nil))
6384 (if (and (interactive-p) link)
6385 (progn
6386 (setq org-stored-links
6387 (cons (list link desc) org-stored-links))
6388 (message "Stored: %s" (or desc link)))
6389 (and link (org-make-link-string link desc)))))
6391 (defun org-store-link-props (&rest plist)
6392 "Store link properties, extract names and addresses."
6393 (let (x adr)
6394 (when (setq x (plist-get plist :from))
6395 (setq adr (mail-extract-address-components x))
6396 (plist-put plist :fromname (car adr))
6397 (plist-put plist :fromaddress (nth 1 adr)))
6398 (when (setq x (plist-get plist :to))
6399 (setq adr (mail-extract-address-components x))
6400 (plist-put plist :toname (car adr))
6401 (plist-put plist :toaddress (nth 1 adr))))
6402 (let ((from (plist-get plist :from))
6403 (to (plist-get plist :to)))
6404 (when (and from to org-from-is-user-regexp)
6405 (plist-put plist :fromto
6406 (if (string-match org-from-is-user-regexp from)
6407 (concat "to %t")
6408 (concat "from %f")))))
6409 (setq org-store-link-plist plist))
6411 (defun org-add-link-props (&rest plist)
6412 "Add these properties to the link property list."
6413 (let (key value)
6414 (while plist
6415 (setq key (pop plist) value (pop plist))
6416 (setq org-store-link-plist
6417 (plist-put org-store-link-plist key value)))))
6419 (defun org-email-link-description (&optional fmt)
6420 "Return the description part of an email link.
6421 This takes information from `org-store-link-plist' and formats it
6422 according to FMT (default from `org-email-link-description-format')."
6423 (setq fmt (or fmt org-email-link-description-format))
6424 (let* ((p org-store-link-plist)
6425 (to (plist-get p :toaddress))
6426 (from (plist-get p :fromaddress))
6427 (table
6428 (list
6429 (cons "%c" (plist-get p :fromto))
6430 (cons "%F" (plist-get p :from))
6431 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6432 (cons "%T" (plist-get p :to))
6433 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6434 (cons "%s" (plist-get p :subject))
6435 (cons "%m" (plist-get p :message-id)))))
6436 (when (string-match "%c" fmt)
6437 ;; Check if the user wrote this message
6438 (if (and org-from-is-user-regexp from to
6439 (save-match-data (string-match org-from-is-user-regexp from)))
6440 (setq fmt (replace-match "to %t" t t fmt))
6441 (setq fmt (replace-match "from %f" t t fmt))))
6442 (org-replace-escapes fmt table)))
6444 (defun org-make-org-heading-search-string (&optional string heading)
6445 "Make search string for STRING or current headline."
6446 (interactive)
6447 (let ((s (or string (org-get-heading))))
6448 (unless (and string (not heading))
6449 ;; We are using a headline, clean up garbage in there.
6450 (if (string-match org-todo-regexp s)
6451 (setq s (replace-match "" t t s)))
6452 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6453 (setq s (replace-match "" t t s)))
6454 (setq s (org-trim s))
6455 (if (string-match (concat "^\\(" org-quote-string "\\|"
6456 org-comment-string "\\)") s)
6457 (setq s (replace-match "" t t s)))
6458 (while (string-match org-ts-regexp s)
6459 (setq s (replace-match "" t t s))))
6460 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6461 (setq s (replace-match " " t t s)))
6462 (or string (setq s (concat "*" s))) ; Add * for headlines
6463 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6465 (defun org-make-link (&rest strings)
6466 "Concatenate STRINGS."
6467 (apply 'concat strings))
6469 (defun org-make-link-string (link &optional description)
6470 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6471 (unless (string-match "\\S-" link)
6472 (error "Empty link"))
6473 (when (stringp description)
6474 ;; Remove brackets from the description, they are fatal.
6475 (while (string-match "\\[" description)
6476 (setq description (replace-match "{" t t description)))
6477 (while (string-match "\\]" description)
6478 (setq description (replace-match "}" t t description))))
6479 (when (equal (org-link-escape link) description)
6480 ;; No description needed, it is identical
6481 (setq description nil))
6482 (when (and (not description)
6483 (not (equal link (org-link-escape link))))
6484 (setq description link))
6485 (concat "[[" (org-link-escape link) "]"
6486 (if description (concat "[" description "]") "")
6487 "]"))
6489 (defconst org-link-escape-chars
6490 '((?\ . "%20")
6491 (?\[ . "%5B")
6492 (?\] . "%5D")
6493 (?\340 . "%E0") ; `a
6494 (?\342 . "%E2") ; ^a
6495 (?\347 . "%E7") ; ,c
6496 (?\350 . "%E8") ; `e
6497 (?\351 . "%E9") ; 'e
6498 (?\352 . "%EA") ; ^e
6499 (?\356 . "%EE") ; ^i
6500 (?\364 . "%F4") ; ^o
6501 (?\371 . "%F9") ; `u
6502 (?\373 . "%FB") ; ^u
6503 (?\; . "%3B")
6504 (?? . "%3F")
6505 (?= . "%3D")
6506 (?+ . "%2B")
6508 "Association list of escapes for some characters problematic in links.
6509 This is the list that is used for internal purposes.")
6511 (defconst org-link-escape-chars-browser
6512 '((?\ . "%20")) ; 32 for the SPC char
6513 "Association list of escapes for some characters problematic in links.
6514 This is the list that is used before handing over to the browser.")
6516 (defun org-link-escape (text &optional table)
6517 "Escape charaters in TEXT that are problematic for links."
6518 (setq table (or table org-link-escape-chars))
6519 (when text
6520 (let ((re (mapconcat (lambda (x) (regexp-quote
6521 (char-to-string (car x))))
6522 table "\\|")))
6523 (while (string-match re text)
6524 (setq text
6525 (replace-match
6526 (cdr (assoc (string-to-char (match-string 0 text))
6527 table))
6528 t t text)))
6529 text)))
6531 (defun org-link-unescape (text &optional table)
6532 "Reverse the action of `org-link-escape'."
6533 (setq table (or table org-link-escape-chars))
6534 (when text
6535 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6536 table "\\|")))
6537 (while (string-match re text)
6538 (setq text
6539 (replace-match
6540 (char-to-string (car (rassoc (match-string 0 text) table)))
6541 t t text)))
6542 text)))
6544 (defun org-xor (a b)
6545 "Exclusive or."
6546 (if a (not b) b))
6548 (defun org-get-header (header)
6549 "Find a header field in the current buffer."
6550 (save-excursion
6551 (goto-char (point-min))
6552 (let ((case-fold-search t) s)
6553 (cond
6554 ((eq header 'from)
6555 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6556 (setq s (match-string 1)))
6557 (while (string-match "\"" s)
6558 (setq s (replace-match "" t t s)))
6559 (if (string-match "[<(].*" s)
6560 (setq s (replace-match "" t t s))))
6561 ((eq header 'message-id)
6562 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6563 (setq s (match-string 1))))
6564 ((eq header 'subject)
6565 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6566 (setq s (match-string 1)))))
6567 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6568 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6569 s)))
6572 (defun org-fixup-message-id-for-http (s)
6573 "Replace special characters in a message id, so it can be used in an http query."
6574 (while (string-match "<" s)
6575 (setq s (replace-match "%3C" t t s)))
6576 (while (string-match ">" s)
6577 (setq s (replace-match "%3E" t t s)))
6578 (while (string-match "@" s)
6579 (setq s (replace-match "%40" t t s)))
6582 ;;;###autoload
6583 (defun org-insert-link-global ()
6584 "Insert a link like Org-mode does.
6585 This command can be called in any mode to insert a link in Org-mode syntax."
6586 (interactive)
6587 (org-load-modules-maybe)
6588 (org-run-like-in-org-mode 'org-insert-link))
6590 (defun org-insert-link (&optional complete-file link-location)
6591 "Insert a link. At the prompt, enter the link.
6593 Completion can be used to select a link previously stored with
6594 `org-store-link'. When the empty string is entered (i.e. if you just
6595 press RET at the prompt), the link defaults to the most recently
6596 stored link. As SPC triggers completion in the minibuffer, you need to
6597 use M-SPC or C-q SPC to force the insertion of a space character.
6599 You will also be prompted for a description, and if one is given, it will
6600 be displayed in the buffer instead of the link.
6602 If there is already a link at point, this command will allow you to edit link
6603 and description parts.
6605 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6606 be selected using completion. The path to the file will be relative to the
6607 current directory if the file is in the current directory or a subdirectory.
6608 Otherwise, the link will be the absolute path as completed in the minibuffer
6609 \(i.e. normally ~/path/to/file).
6611 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6612 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6613 of `org-keep-stored-link-after-insertion'.
6615 If `org-make-link-description-function' is non-nil, this function will be
6616 called with the link target, and the result will be the default
6617 link description.
6619 If the LINK-LOCATION parameter is non-nil, this value will be
6620 used as the link location instead of reading one interactively."
6621 (interactive "P")
6622 (let* ((wcf (current-window-configuration))
6623 (region (if (org-region-active-p)
6624 (buffer-substring (region-beginning) (region-end))))
6625 (remove (and region (list (region-beginning) (region-end))))
6626 (desc region)
6627 tmphist ; byte-compile incorrectly complains about this
6628 (link link-location)
6629 entry file)
6630 (cond
6631 (link-location) ; specified by arg, just use it.
6632 ((org-in-regexp org-bracket-link-regexp 1)
6633 ;; We do have a link at point, and we are going to edit it.
6634 (setq remove (list (match-beginning 0) (match-end 0)))
6635 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6636 (setq link (read-string "Link: "
6637 (org-link-unescape
6638 (org-match-string-no-properties 1)))))
6639 ((or (org-in-regexp org-angle-link-re)
6640 (org-in-regexp org-plain-link-re))
6641 ;; Convert to bracket link
6642 (setq remove (list (match-beginning 0) (match-end 0))
6643 link (read-string "Link: "
6644 (org-remove-angle-brackets (match-string 0)))))
6645 ((equal complete-file '(4))
6646 ;; Completing read for file names.
6647 (setq file (read-file-name "File: "))
6648 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6649 (pwd1 (file-name-as-directory (abbreviate-file-name
6650 (expand-file-name ".")))))
6651 (cond
6652 ((equal complete-file '(16))
6653 (setq link (org-make-link
6654 "file:"
6655 (abbreviate-file-name (expand-file-name file)))))
6656 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6657 (setq link (org-make-link "file:" (match-string 1 file))))
6658 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6659 (expand-file-name file))
6660 (setq link (org-make-link
6661 "file:" (match-string 1 (expand-file-name file)))))
6662 (t (setq link (org-make-link "file:" file))))))
6664 ;; Read link, with completion for stored links.
6665 (with-output-to-temp-buffer "*Org Links*"
6666 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6667 (when org-stored-links
6668 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6669 (princ (mapconcat
6670 (lambda (x)
6671 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6672 (reverse org-stored-links) "\n"))))
6673 (let ((cw (selected-window)))
6674 (select-window (get-buffer-window "*Org Links*"))
6675 (shrink-window-if-larger-than-buffer)
6676 (setq truncate-lines t)
6677 (select-window cw))
6678 ;; Fake a link history, containing the stored links.
6679 (setq tmphist (append (mapcar 'car org-stored-links)
6680 org-insert-link-history))
6681 (unwind-protect
6682 (setq link (org-completing-read
6683 "Link: "
6684 (append
6685 (mapcar (lambda (x) (list (concat (car x) ":")))
6686 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6687 (mapcar (lambda (x) (list (concat x ":")))
6688 org-link-types))
6689 nil nil nil
6690 'tmphist
6691 (or (car (car org-stored-links)))))
6692 (set-window-configuration wcf)
6693 (kill-buffer "*Org Links*"))
6694 (setq entry (assoc link org-stored-links))
6695 (or entry (push link org-insert-link-history))
6696 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6697 (not org-keep-stored-link-after-insertion))
6698 (setq org-stored-links (delq (assoc link org-stored-links)
6699 org-stored-links)))
6700 (setq desc (or desc (nth 1 entry)))))
6702 (if (string-match org-plain-link-re link)
6703 ;; URL-like link, normalize the use of angular brackets.
6704 (setq link (org-make-link (org-remove-angle-brackets link))))
6706 ;; Check if we are linking to the current file with a search option
6707 ;; If yes, simplify the link by using only the search option.
6708 (when (and buffer-file-name
6709 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6710 (let* ((path (match-string 1 link))
6711 (case-fold-search nil)
6712 (search (match-string 2 link)))
6713 (save-match-data
6714 (if (equal (file-truename buffer-file-name) (file-truename path))
6715 ;; We are linking to this same file, with a search option
6716 (setq link search)))))
6718 ;; Check if we can/should use a relative path. If yes, simplify the link
6719 (when (string-match "\\<file:\\(.*\\)" link)
6720 (let* ((path (match-string 1 link))
6721 (origpath path)
6722 (case-fold-search nil))
6723 (cond
6724 ((eq org-link-file-path-type 'absolute)
6725 (setq path (abbreviate-file-name (expand-file-name path))))
6726 ((eq org-link-file-path-type 'noabbrev)
6727 (setq path (expand-file-name path)))
6728 ((eq org-link-file-path-type 'relative)
6729 (setq path (file-relative-name path)))
6731 (save-match-data
6732 (if (string-match (concat "^" (regexp-quote
6733 (file-name-as-directory
6734 (expand-file-name "."))))
6735 (expand-file-name path))
6736 ;; We are linking a file with relative path name.
6737 (setq path (substring (expand-file-name path)
6738 (match-end 0)))))))
6739 (setq link (concat "file:" path))
6740 (if (equal desc origpath)
6741 (setq desc path))))
6743 (if org-make-link-description-function
6744 (setq desc (funcall org-make-link-description-function link desc)))
6746 (setq desc (read-string "Description: " desc))
6747 (unless (string-match "\\S-" desc) (setq desc nil))
6748 (if remove (apply 'delete-region remove))
6749 (insert (org-make-link-string link desc))))
6751 (defun org-completing-read (&rest args)
6752 (let ((minibuffer-local-completion-map
6753 (copy-keymap minibuffer-local-completion-map)))
6754 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6755 (apply 'completing-read args)))
6757 ;;; Opening/following a link
6759 (defvar org-link-search-failed nil)
6761 (defun org-next-link ()
6762 "Move forward to the next link.
6763 If the link is in hidden text, expose it."
6764 (interactive)
6765 (when (and org-link-search-failed (eq this-command last-command))
6766 (goto-char (point-min))
6767 (message "Link search wrapped back to beginning of buffer"))
6768 (setq org-link-search-failed nil)
6769 (let* ((pos (point))
6770 (ct (org-context))
6771 (a (assoc :link ct)))
6772 (if a (goto-char (nth 2 a)))
6773 (if (re-search-forward org-any-link-re nil t)
6774 (progn
6775 (goto-char (match-beginning 0))
6776 (if (org-invisible-p) (org-show-context)))
6777 (goto-char pos)
6778 (setq org-link-search-failed t)
6779 (error "No further link found"))))
6781 (defun org-previous-link ()
6782 "Move backward to the previous link.
6783 If the link is in hidden text, expose it."
6784 (interactive)
6785 (when (and org-link-search-failed (eq this-command last-command))
6786 (goto-char (point-max))
6787 (message "Link search wrapped back to end of buffer"))
6788 (setq org-link-search-failed nil)
6789 (let* ((pos (point))
6790 (ct (org-context))
6791 (a (assoc :link ct)))
6792 (if a (goto-char (nth 1 a)))
6793 (if (re-search-backward org-any-link-re nil t)
6794 (progn
6795 (goto-char (match-beginning 0))
6796 (if (org-invisible-p) (org-show-context)))
6797 (goto-char pos)
6798 (setq org-link-search-failed t)
6799 (error "No further link found"))))
6801 (defun org-find-file-at-mouse (ev)
6802 "Open file link or URL at mouse."
6803 (interactive "e")
6804 (mouse-set-point ev)
6805 (org-open-at-point 'in-emacs))
6807 (defun org-open-at-mouse (ev)
6808 "Open file link or URL at mouse."
6809 (interactive "e")
6810 (mouse-set-point ev)
6811 (org-open-at-point))
6813 (defvar org-window-config-before-follow-link nil
6814 "The window configuration before following a link.
6815 This is saved in case the need arises to restore it.")
6817 (defvar org-open-link-marker (make-marker)
6818 "Marker pointing to the location where `org-open-at-point; was called.")
6820 ;;;###autoload
6821 (defun org-open-at-point-global ()
6822 "Follow a link like Org-mode does.
6823 This command can be called in any mode to follow a link that has
6824 Org-mode syntax."
6825 (interactive)
6826 (org-run-like-in-org-mode 'org-open-at-point))
6828 ;;;###autoload
6829 (defun org-open-link-from-string (s &optional arg)
6830 "Open a link in the string S, as if it was in Org-mode."
6831 (interactive "sLink: \nP")
6832 (with-temp-buffer
6833 (let ((org-inhibit-startup t))
6834 (org-mode)
6835 (insert s)
6836 (goto-char (point-min))
6837 (org-open-at-point arg))))
6839 (defun org-open-at-point (&optional in-emacs)
6840 "Open link at or after point.
6841 If there is no link at point, this function will search forward up to
6842 the end of the current subtree.
6843 Normally, files will be opened by an appropriate application. If the
6844 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6845 (interactive "P")
6846 (org-load-modules-maybe)
6847 (move-marker org-open-link-marker (point))
6848 (setq org-window-config-before-follow-link (current-window-configuration))
6849 (org-remove-occur-highlights nil nil t)
6850 (if (org-at-timestamp-p t)
6851 (org-follow-timestamp-link)
6852 (let (type path link line search (pos (point)))
6853 (catch 'match
6854 (save-excursion
6855 (skip-chars-forward "^]\n\r")
6856 (when (org-in-regexp org-bracket-link-regexp)
6857 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6858 (while (string-match " *\n *" link)
6859 (setq link (replace-match " " t t link)))
6860 (setq link (org-link-expand-abbrev link))
6861 (if (string-match org-link-re-with-space2 link)
6862 (setq type (match-string 1 link) path (match-string 2 link))
6863 (setq type "thisfile" path link))
6864 (throw 'match t)))
6866 (when (get-text-property (point) 'org-linked-text)
6867 (setq type "thisfile"
6868 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6869 (1+ (point)) (point))
6870 path (buffer-substring
6871 (previous-single-property-change pos 'org-linked-text)
6872 (next-single-property-change pos 'org-linked-text)))
6873 (throw 'match t))
6875 (save-excursion
6876 (when (or (org-in-regexp org-angle-link-re)
6877 (org-in-regexp org-plain-link-re))
6878 (setq type (match-string 1) path (match-string 2))
6879 (throw 'match t)))
6880 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6881 (setq type "tree-match"
6882 path (match-string 1))
6883 (throw 'match t))
6884 (save-excursion
6885 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6886 (setq type "tags"
6887 path (match-string 1))
6888 (while (string-match ":" path)
6889 (setq path (replace-match "+" t t path)))
6890 (throw 'match t))))
6891 (unless path
6892 (error "No link found"))
6893 ;; Remove any trailing spaces in path
6894 (if (string-match " +\\'" path)
6895 (setq path (replace-match "" t t path)))
6897 (cond
6899 ((assoc type org-link-protocols)
6900 (funcall (nth 1 (assoc type org-link-protocols)) path))
6902 ((equal type "mailto")
6903 (let ((cmd (car org-link-mailto-program))
6904 (args (cdr org-link-mailto-program)) args1
6905 (address path) (subject "") a)
6906 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6907 (setq address (match-string 1 path)
6908 subject (org-link-escape (match-string 2 path))))
6909 (while args
6910 (cond
6911 ((not (stringp (car args))) (push (pop args) args1))
6912 (t (setq a (pop args))
6913 (if (string-match "%a" a)
6914 (setq a (replace-match address t t a)))
6915 (if (string-match "%s" a)
6916 (setq a (replace-match subject t t a)))
6917 (push a args1))))
6918 (apply cmd (nreverse args1))))
6920 ((member type '("http" "https" "ftp" "news"))
6921 (browse-url (concat type ":" (org-link-escape
6922 path org-link-escape-chars-browser))))
6924 ((member type '("message"))
6925 (browse-url (concat type ":" path)))
6927 ((string= type "tags")
6928 (org-tags-view in-emacs path))
6929 ((string= type "thisfile")
6930 (if in-emacs
6931 (switch-to-buffer-other-window
6932 (org-get-buffer-for-internal-link (current-buffer)))
6933 (org-mark-ring-push))
6934 (let ((cmd `(org-link-search
6935 ,path
6936 ,(cond ((equal in-emacs '(4)) 'occur)
6937 ((equal in-emacs '(16)) 'org-occur)
6938 (t nil))
6939 ,pos)))
6940 (condition-case nil (eval cmd)
6941 (error (progn (widen) (eval cmd))))))
6943 ((string= type "tree-match")
6944 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6946 ((string= type "file")
6947 (if (string-match "::\\([0-9]+\\)\\'" path)
6948 (setq line (string-to-number (match-string 1 path))
6949 path (substring path 0 (match-beginning 0)))
6950 (if (string-match "::\\(.+\\)\\'" path)
6951 (setq search (match-string 1 path)
6952 path (substring path 0 (match-beginning 0)))))
6953 (if (string-match "[*?{]" (file-name-nondirectory path))
6954 (dired path)
6955 (org-open-file path in-emacs line search)))
6957 ((string= type "news")
6958 (require 'org-gnus)
6959 (org-gnus-follow-link path))
6961 ((string= type "shell")
6962 (let ((cmd path))
6963 (if (or (not org-confirm-shell-link-function)
6964 (funcall org-confirm-shell-link-function
6965 (format "Execute \"%s\" in shell? "
6966 (org-add-props cmd nil
6967 'face 'org-warning))))
6968 (progn
6969 (message "Executing %s" cmd)
6970 (shell-command cmd))
6971 (error "Abort"))))
6973 ((string= type "elisp")
6974 (let ((cmd path))
6975 (if (or (not org-confirm-elisp-link-function)
6976 (funcall org-confirm-elisp-link-function
6977 (format "Execute \"%s\" as elisp? "
6978 (org-add-props cmd nil
6979 'face 'org-warning))))
6980 (message "%s => %s" cmd (eval (read cmd)))
6981 (error "Abort"))))
6984 (browse-url-at-point)))))
6985 (move-marker org-open-link-marker nil)
6986 (run-hook-with-args 'org-follow-link-hook))
6988 ;;;; Time estimates
6990 (defun org-get-effort (&optional pom)
6991 "Get the effort estimate for the current entry."
6992 (org-entry-get pom org-effort-property))
6994 ;;; File search
6996 (defvar org-create-file-search-functions nil
6997 "List of functions to construct the right search string for a file link.
6998 These functions are called in turn with point at the location to
6999 which the link should point.
7001 A function in the hook should first test if it would like to
7002 handle this file type, for example by checking the major-mode or
7003 the file extension. If it decides not to handle this file, it
7004 should just return nil to give other functions a chance. If it
7005 does handle the file, it must return the search string to be used
7006 when following the link. The search string will be part of the
7007 file link, given after a double colon, and `org-open-at-point'
7008 will automatically search for it. If special measures must be
7009 taken to make the search successful, another function should be
7010 added to the companion hook `org-execute-file-search-functions',
7011 which see.
7013 A function in this hook may also use `setq' to set the variable
7014 `description' to provide a suggestion for the descriptive text to
7015 be used for this link when it gets inserted into an Org-mode
7016 buffer with \\[org-insert-link].")
7018 (defvar org-execute-file-search-functions nil
7019 "List of functions to execute a file search triggered by a link.
7021 Functions added to this hook must accept a single argument, the
7022 search string that was part of the file link, the part after the
7023 double colon. The function must first check if it would like to
7024 handle this search, for example by checking the major-mode or the
7025 file extension. If it decides not to handle this search, it
7026 should just return nil to give other functions a chance. If it
7027 does handle the search, it must return a non-nil value to keep
7028 other functions from trying.
7030 Each function can access the current prefix argument through the
7031 variable `current-prefix-argument'. Note that a single prefix is
7032 used to force opening a link in Emacs, so it may be good to only
7033 use a numeric or double prefix to guide the search function.
7035 In case this is needed, a function in this hook can also restore
7036 the window configuration before `org-open-at-point' was called using:
7038 (set-window-configuration org-window-config-before-follow-link)")
7040 (defun org-link-search (s &optional type avoid-pos)
7041 "Search for a link search option.
7042 If S is surrounded by forward slashes, it is interpreted as a
7043 regular expression. In org-mode files, this will create an `org-occur'
7044 sparse tree. In ordinary files, `occur' will be used to list matches.
7045 If the current buffer is in `dired-mode', grep will be used to search
7046 in all files. If AVOID-POS is given, ignore matches near that position."
7047 (let ((case-fold-search t)
7048 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7049 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7050 (append '(("") (" ") ("\t") ("\n"))
7051 org-emphasis-alist)
7052 "\\|") "\\)"))
7053 (pos (point))
7054 (pre nil) (post nil)
7055 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7056 (cond
7057 ;; First check if there are any special
7058 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7059 ;; Now try the builtin stuff
7060 ((save-excursion
7061 (goto-char (point-min))
7062 (and
7063 (re-search-forward
7064 (concat "<<" (regexp-quote s0) ">>") nil t)
7065 (setq type 'dedicated
7066 pos (match-beginning 0))))
7067 ;; There is an exact target for this
7068 (goto-char pos))
7069 ((string-match "^/\\(.*\\)/$" s)
7070 ;; A regular expression
7071 (cond
7072 ((org-mode-p)
7073 (org-occur (match-string 1 s)))
7074 ;;((eq major-mode 'dired-mode)
7075 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7076 (t (org-do-occur (match-string 1 s)))))
7078 ;; A normal search strings
7079 (when (equal (string-to-char s) ?*)
7080 ;; Anchor on headlines, post may include tags.
7081 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7082 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7083 s (substring s 1)))
7084 (remove-text-properties
7085 0 (length s)
7086 '(face nil mouse-face nil keymap nil fontified nil) s)
7087 ;; Make a series of regular expressions to find a match
7088 (setq words (org-split-string s "[ \n\r\t]+")
7090 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7091 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7092 "\\)" markers)
7093 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7094 re2a (concat "[ \t\r\n]" re2a_)
7095 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7096 re4 (concat "[^a-zA-Z_]" re4_)
7098 re1 (concat pre re2 post)
7099 re3 (concat pre (if pre re4_ re4) post)
7100 re5 (concat pre ".*" re4)
7101 re2 (concat pre re2)
7102 re2a (concat pre (if pre re2a_ re2a))
7103 re4 (concat pre (if pre re4_ re4))
7104 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7105 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7106 re5 "\\)"
7108 (cond
7109 ((eq type 'org-occur) (org-occur reall))
7110 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7111 (t (goto-char (point-min))
7112 (setq type 'fuzzy)
7113 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7114 (org-search-not-self 1 re1 nil t)
7115 (org-search-not-self 1 re2 nil t)
7116 (org-search-not-self 1 re2a nil t)
7117 (org-search-not-self 1 re3 nil t)
7118 (org-search-not-self 1 re4 nil t)
7119 (org-search-not-self 1 re5 nil t)
7121 (goto-char (match-beginning 1))
7122 (goto-char pos)
7123 (error "No match")))))
7125 ;; Normal string-search
7126 (goto-char (point-min))
7127 (if (search-forward s nil t)
7128 (goto-char (match-beginning 0))
7129 (error "No match"))))
7130 (and (org-mode-p) (org-show-context 'link-search))
7131 type))
7133 (defun org-search-not-self (group &rest args)
7134 "Execute `re-search-forward', but only accept matches that do not
7135 enclose the position of `org-open-link-marker'."
7136 (let ((m org-open-link-marker))
7137 (catch 'exit
7138 (while (apply 're-search-forward args)
7139 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7140 (goto-char (match-end group))
7141 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7142 (> (match-beginning 0) (marker-position m))
7143 (< (match-end 0) (marker-position m)))
7144 (save-match-data
7145 (or (not (org-in-regexp
7146 org-bracket-link-analytic-regexp 1))
7147 (not (match-end 4)) ; no description
7148 (and (<= (match-beginning 4) (point))
7149 (>= (match-end 4) (point))))))
7150 (throw 'exit (point))))))))
7152 (defun org-get-buffer-for-internal-link (buffer)
7153 "Return a buffer to be used for displaying the link target of internal links."
7154 (cond
7155 ((not org-display-internal-link-with-indirect-buffer)
7156 buffer)
7157 ((string-match "(Clone)$" (buffer-name buffer))
7158 (message "Buffer is already a clone, not making another one")
7159 ;; we also do not modify visibility in this case
7160 buffer)
7161 (t ; make a new indirect buffer for displaying the link
7162 (let* ((bn (buffer-name buffer))
7163 (ibn (concat bn "(Clone)"))
7164 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7165 (with-current-buffer ib (org-overview))
7166 ib))))
7168 (defun org-do-occur (regexp &optional cleanup)
7169 "Call the Emacs command `occur'.
7170 If CLEANUP is non-nil, remove the printout of the regular expression
7171 in the *Occur* buffer. This is useful if the regex is long and not useful
7172 to read."
7173 (occur regexp)
7174 (when cleanup
7175 (let ((cwin (selected-window)) win beg end)
7176 (when (setq win (get-buffer-window "*Occur*"))
7177 (select-window win))
7178 (goto-char (point-min))
7179 (when (re-search-forward "match[a-z]+" nil t)
7180 (setq beg (match-end 0))
7181 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7182 (setq end (1- (match-beginning 0)))))
7183 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7184 (goto-char (point-min))
7185 (select-window cwin))))
7187 ;;; The mark ring for links jumps
7189 (defvar org-mark-ring nil
7190 "Mark ring for positions before jumps in Org-mode.")
7191 (defvar org-mark-ring-last-goto nil
7192 "Last position in the mark ring used to go back.")
7193 ;; Fill and close the ring
7194 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7195 (loop for i from 1 to org-mark-ring-length do
7196 (push (make-marker) org-mark-ring))
7197 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7198 org-mark-ring)
7200 (defun org-mark-ring-push (&optional pos buffer)
7201 "Put the current position or POS into the mark ring and rotate it."
7202 (interactive)
7203 (setq pos (or pos (point)))
7204 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7205 (move-marker (car org-mark-ring)
7206 (or pos (point))
7207 (or buffer (current-buffer)))
7208 (message "%s"
7209 (substitute-command-keys
7210 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7212 (defun org-mark-ring-goto (&optional n)
7213 "Jump to the previous position in the mark ring.
7214 With prefix arg N, jump back that many stored positions. When
7215 called several times in succession, walk through the entire ring.
7216 Org-mode commands jumping to a different position in the current file,
7217 or to another Org-mode file, automatically push the old position
7218 onto the ring."
7219 (interactive "p")
7220 (let (p m)
7221 (if (eq last-command this-command)
7222 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7223 (setq p org-mark-ring))
7224 (setq org-mark-ring-last-goto p)
7225 (setq m (car p))
7226 (switch-to-buffer (marker-buffer m))
7227 (goto-char m)
7228 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7230 (defun org-remove-angle-brackets (s)
7231 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7232 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7234 (defun org-add-angle-brackets (s)
7235 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7236 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7238 (defun org-remove-double-quotes (s)
7239 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7240 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7243 ;;; Following specific links
7245 (defun org-follow-timestamp-link ()
7246 (cond
7247 ((org-at-date-range-p t)
7248 (let ((org-agenda-start-on-weekday)
7249 (t1 (match-string 1))
7250 (t2 (match-string 2)))
7251 (setq t1 (time-to-days (org-time-string-to-time t1))
7252 t2 (time-to-days (org-time-string-to-time t2)))
7253 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7254 ((org-at-timestamp-p t)
7255 (org-agenda-list nil (time-to-days (org-time-string-to-time
7256 (substring (match-string 1) 0 10)))
7258 (t (error "This should not happen"))))
7261 ;;; Following file links
7262 (defvar org-wait nil)
7263 (defun org-open-file (path &optional in-emacs line search)
7264 "Open the file at PATH.
7265 First, this expands any special file name abbreviations. Then the
7266 configuration variable `org-file-apps' is checked if it contains an
7267 entry for this file type, and if yes, the corresponding command is launched.
7268 If no application is found, Emacs simply visits the file.
7269 With optional argument IN-EMACS, Emacs will visit the file.
7270 Optional LINE specifies a line to go to, optional SEARCH a string to
7271 search for. If LINE or SEARCH is given, the file will always be
7272 opened in Emacs.
7273 If the file does not exist, an error is thrown."
7274 (setq in-emacs (or in-emacs line search))
7275 (let* ((file (if (equal path "")
7276 buffer-file-name
7277 (substitute-in-file-name (expand-file-name path))))
7278 (apps (append org-file-apps (org-default-apps)))
7279 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7280 (dirp (if remp nil (file-directory-p file)))
7281 (dfile (downcase file))
7282 (old-buffer (current-buffer))
7283 (old-pos (point))
7284 (old-mode major-mode)
7285 ext cmd)
7286 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7287 (setq ext (match-string 1 dfile))
7288 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7289 (setq ext (match-string 1 dfile))))
7290 (if in-emacs
7291 (setq cmd 'emacs)
7292 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7293 (and dirp (cdr (assoc 'directory apps)))
7294 (cdr (assoc ext apps))
7295 (cdr (assoc t apps)))))
7296 (when (eq cmd 'mailcap)
7297 (require 'mailcap)
7298 (mailcap-parse-mailcaps)
7299 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7300 (command (mailcap-mime-info mime-type)))
7301 (if (stringp command)
7302 (setq cmd command)
7303 (setq cmd 'emacs))))
7304 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7305 (not (file-exists-p file))
7306 (not org-open-non-existing-files))
7307 (error "No such file: %s" file))
7308 (cond
7309 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7310 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7311 (while (string-match "['\"]%s['\"]" cmd)
7312 (setq cmd (replace-match "%s" t t cmd)))
7313 (while (string-match "%s" cmd)
7314 (setq cmd (replace-match
7315 (save-match-data (shell-quote-argument file))
7316 t t cmd)))
7317 (save-window-excursion
7318 (start-process-shell-command cmd nil cmd)
7319 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7321 ((or (stringp cmd)
7322 (eq cmd 'emacs))
7323 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7324 (widen)
7325 (if line (goto-line line)
7326 (if search (org-link-search search))))
7327 ((consp cmd)
7328 (eval cmd))
7329 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7330 (and (org-mode-p) (eq old-mode 'org-mode)
7331 (or (not (equal old-buffer (current-buffer)))
7332 (not (equal old-pos (point))))
7333 (org-mark-ring-push old-pos old-buffer))))
7335 (defun org-default-apps ()
7336 "Return the default applications for this operating system."
7337 (cond
7338 ((eq system-type 'darwin)
7339 org-file-apps-defaults-macosx)
7340 ((eq system-type 'windows-nt)
7341 org-file-apps-defaults-windowsnt)
7342 (t org-file-apps-defaults-gnu)))
7344 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7345 (defun org-file-remote-p (file)
7346 "Test whether FILE specifies a location on a remote system.
7347 Return non-nil if the location is indeed remote.
7349 For example, the filename \"/user@host:/foo\" specifies a location
7350 on the system \"/user@host:\"."
7351 (cond ((fboundp 'file-remote-p)
7352 (file-remote-p file))
7353 ((fboundp 'tramp-handle-file-remote-p)
7354 (tramp-handle-file-remote-p file))
7355 ((and (boundp 'ange-ftp-name-format)
7356 (string-match (car ange-ftp-name-format) file))
7358 (t nil)))
7361 ;;;; Refiling
7363 (defun org-get-org-file ()
7364 "Read a filename, with default directory `org-directory'."
7365 (let ((default (or org-default-notes-file remember-data-file)))
7366 (read-file-name (format "File name [%s]: " default)
7367 (file-name-as-directory org-directory)
7368 default)))
7370 (defun org-notes-order-reversed-p ()
7371 "Check if the current file should receive notes in reversed order."
7372 (cond
7373 ((not org-reverse-note-order) nil)
7374 ((eq t org-reverse-note-order) t)
7375 ((not (listp org-reverse-note-order)) nil)
7376 (t (catch 'exit
7377 (let ((all org-reverse-note-order)
7378 entry)
7379 (while (setq entry (pop all))
7380 (if (string-match (car entry) buffer-file-name)
7381 (throw 'exit (cdr entry))))
7382 nil)))))
7384 (defvar org-refile-target-table nil
7385 "The list of refile targets, created by `org-refile'.")
7387 (defvar org-agenda-new-buffers nil
7388 "Buffers created to visit agenda files.")
7390 (defun org-get-refile-targets (&optional default-buffer)
7391 "Produce a table with refile targets."
7392 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7393 targets txt re files f desc descre)
7394 (with-current-buffer (or default-buffer (current-buffer))
7395 (while (setq entry (pop entries))
7396 (setq files (car entry) desc (cdr entry))
7397 (cond
7398 ((null files) (setq files (list (current-buffer))))
7399 ((eq files 'org-agenda-files)
7400 (setq files (org-agenda-files 'unrestricted)))
7401 ((and (symbolp files) (fboundp files))
7402 (setq files (funcall files)))
7403 ((and (symbolp files) (boundp files))
7404 (setq files (symbol-value files))))
7405 (if (stringp files) (setq files (list files)))
7406 (cond
7407 ((eq (car desc) :tag)
7408 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7409 ((eq (car desc) :todo)
7410 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7411 ((eq (car desc) :regexp)
7412 (setq descre (cdr desc)))
7413 ((eq (car desc) :level)
7414 (setq descre (concat "^\\*\\{" (number-to-string
7415 (if org-odd-levels-only
7416 (1- (* 2 (cdr desc)))
7417 (cdr desc)))
7418 "\\}[ \t]")))
7419 ((eq (car desc) :maxlevel)
7420 (setq descre (concat "^\\*\\{1," (number-to-string
7421 (if org-odd-levels-only
7422 (1- (* 2 (cdr desc)))
7423 (cdr desc)))
7424 "\\}[ \t]")))
7425 (t (error "Bad refiling target description %s" desc)))
7426 (while (setq f (pop files))
7427 (save-excursion
7428 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7429 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7430 (save-excursion
7431 (save-restriction
7432 (widen)
7433 (goto-char (point-min))
7434 (while (re-search-forward descre nil t)
7435 (goto-char (point-at-bol))
7436 (when (looking-at org-complex-heading-regexp)
7437 (setq txt (match-string 4)
7438 re (concat "^" (regexp-quote
7439 (buffer-substring (match-beginning 1)
7440 (match-end 4)))))
7441 (if (match-end 5) (setq re (concat re "[ \t]+"
7442 (regexp-quote
7443 (match-string 5)))))
7444 (setq re (concat re "[ \t]*$"))
7445 (when org-refile-use-outline-path
7446 (setq txt (mapconcat 'identity
7447 (append
7448 (if (eq org-refile-use-outline-path 'file)
7449 (list (file-name-nondirectory
7450 (buffer-file-name (buffer-base-buffer))))
7451 (if (eq org-refile-use-outline-path 'full-file-path)
7452 (list (buffer-file-name (buffer-base-buffer)))))
7453 (org-get-outline-path)
7454 (list txt))
7455 "/")))
7456 (push (list txt f re (point)) targets))
7457 (goto-char (point-at-eol))))))))
7458 (nreverse targets))))
7460 (defun org-get-outline-path ()
7461 "Return the outline path to the current entry, as a list."
7462 (let (rtn)
7463 (save-excursion
7464 (while (org-up-heading-safe)
7465 (when (looking-at org-complex-heading-regexp)
7466 (push (org-match-string-no-properties 4) rtn)))
7467 rtn)))
7469 (defvar org-refile-history nil
7470 "History for refiling operations.")
7472 (defun org-refile (&optional goto default-buffer)
7473 "Move the entry at point to another heading.
7474 The list of target headings is compiled using the information in
7475 `org-refile-targets', which see. This list is created before each use
7476 and will therefore always be up-to-date.
7478 At the target location, the entry is filed as a subitem of the target heading.
7479 Depending on `org-reverse-note-order', the new subitem will either be the
7480 first of the last subitem.
7482 With prefix arg GOTO, the command will only visit the target location,
7483 not actually move anything.
7484 With a double prefix `C-c C-c', go to the location where the last refiling
7485 operation has put the subtree."
7486 (interactive "P")
7487 (let* ((cbuf (current-buffer))
7488 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7489 pos it nbuf file re level reversed)
7490 (if (equal goto '(16))
7491 (org-refile-goto-last-stored)
7492 (when (setq it (org-refile-get-location
7493 (if goto "Goto: " "Refile to: ") default-buffer))
7494 (setq file (nth 1 it)
7495 re (nth 2 it)
7496 pos (nth 3 it))
7497 (setq nbuf (or (find-buffer-visiting file)
7498 (find-file-noselect file)))
7499 (if goto
7500 (progn
7501 (switch-to-buffer nbuf)
7502 (goto-char pos)
7503 (org-show-context 'org-goto))
7504 (org-copy-subtree 1 nil t)
7505 (save-excursion
7506 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7507 (find-file-noselect file))))
7508 (setq reversed (org-notes-order-reversed-p))
7509 (save-excursion
7510 (save-restriction
7511 (widen)
7512 (goto-char pos)
7513 (looking-at outline-regexp)
7514 (setq level (org-get-valid-level (funcall outline-level) 1))
7515 (goto-char
7516 (if reversed
7517 (outline-next-heading)
7518 (or (save-excursion (outline-get-next-sibling))
7519 (org-end-of-subtree t t)
7520 (point-max))))
7521 (bookmark-set "org-refile-last-stored")
7522 (org-paste-subtree level))))
7523 (org-cut-subtree)
7524 (setq org-markers-to-move nil)
7525 (message "Entry refiled to \"%s\"" (car it)))))))
7527 (defun org-refile-goto-last-stored ()
7528 "Go to the location where the last refile was stored."
7529 (interactive)
7530 (bookmark-jump "org-refile-last-stored")
7531 (message "This is the location of the last refile"))
7533 (defun org-refile-get-location (&optional prompt default-buffer)
7534 "Prompt the user for a refile location, using PROMPT."
7535 (let ((org-refile-targets org-refile-targets)
7536 (org-refile-use-outline-path org-refile-use-outline-path))
7537 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7538 (unless org-refile-target-table
7539 (error "No refile targets"))
7540 (let* ((cbuf (current-buffer))
7541 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7542 (fname (and filename (file-truename filename)))
7543 (tbl (mapcar
7544 (lambda (x)
7545 (if (not (equal fname (file-truename (nth 1 x))))
7546 (cons (concat (car x) " (" (file-name-nondirectory
7547 (nth 1 x)) ")")
7548 (cdr x))
7550 org-refile-target-table))
7551 (completion-ignore-case t))
7552 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7553 tbl)))
7555 ;;;; Dynamic blocks
7557 (defun org-find-dblock (name)
7558 "Find the first dynamic block with name NAME in the buffer.
7559 If not found, stay at current position and return nil."
7560 (let (pos)
7561 (save-excursion
7562 (goto-char (point-min))
7563 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7564 nil t)
7565 (match-beginning 0))))
7566 (if pos (goto-char pos))
7567 pos))
7569 (defconst org-dblock-start-re
7570 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7571 "Matches the startline of a dynamic block, with parameters.")
7573 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7574 "Matches the end of a dyhamic block.")
7576 (defun org-create-dblock (plist)
7577 "Create a dynamic block section, with parameters taken from PLIST.
7578 PLIST must containe a :name entry which is used as name of the block."
7579 (unless (bolp) (newline))
7580 (let ((name (plist-get plist :name)))
7581 (insert "#+BEGIN: " name)
7582 (while plist
7583 (if (eq (car plist) :name)
7584 (setq plist (cddr plist))
7585 (insert " " (prin1-to-string (pop plist)))))
7586 (insert "\n\n#+END:\n")
7587 (beginning-of-line -2)))
7589 (defun org-prepare-dblock ()
7590 "Prepare dynamic block for refresh.
7591 This empties the block, puts the cursor at the insert position and returns
7592 the property list including an extra property :name with the block name."
7593 (unless (looking-at org-dblock-start-re)
7594 (error "Not at a dynamic block"))
7595 (let* ((begdel (1+ (match-end 0)))
7596 (name (org-no-properties (match-string 1)))
7597 (params (append (list :name name)
7598 (read (concat "(" (match-string 3) ")")))))
7599 (unless (re-search-forward org-dblock-end-re nil t)
7600 (error "Dynamic block not terminated"))
7601 (setq params
7602 (append params
7603 (list :content (buffer-substring
7604 begdel (match-beginning 0)))))
7605 (delete-region begdel (match-beginning 0))
7606 (goto-char begdel)
7607 (open-line 1)
7608 params))
7610 (defun org-map-dblocks (&optional command)
7611 "Apply COMMAND to all dynamic blocks in the current buffer.
7612 If COMMAND is not given, use `org-update-dblock'."
7613 (let ((cmd (or command 'org-update-dblock))
7614 pos)
7615 (save-excursion
7616 (goto-char (point-min))
7617 (while (re-search-forward org-dblock-start-re nil t)
7618 (goto-char (setq pos (match-beginning 0)))
7619 (condition-case nil
7620 (funcall cmd)
7621 (error (message "Error during update of dynamic block")))
7622 (goto-char pos)
7623 (unless (re-search-forward org-dblock-end-re nil t)
7624 (error "Dynamic block not terminated"))))))
7626 (defun org-dblock-update (&optional arg)
7627 "User command for updating dynamic blocks.
7628 Update the dynamic block at point. With prefix ARG, update all dynamic
7629 blocks in the buffer."
7630 (interactive "P")
7631 (if arg
7632 (org-update-all-dblocks)
7633 (or (looking-at org-dblock-start-re)
7634 (org-beginning-of-dblock))
7635 (org-update-dblock)))
7637 (defun org-update-dblock ()
7638 "Update the dynamic block at point
7639 This means to empty the block, parse for parameters and then call
7640 the correct writing function."
7641 (save-window-excursion
7642 (let* ((pos (point))
7643 (line (org-current-line))
7644 (params (org-prepare-dblock))
7645 (name (plist-get params :name))
7646 (cmd (intern (concat "org-dblock-write:" name))))
7647 (message "Updating dynamic block `%s' at line %d..." name line)
7648 (funcall cmd params)
7649 (message "Updating dynamic block `%s' at line %d...done" name line)
7650 (goto-char pos))))
7652 (defun org-beginning-of-dblock ()
7653 "Find the beginning of the dynamic block at point.
7654 Error if there is no scuh block at point."
7655 (let ((pos (point))
7656 beg)
7657 (end-of-line 1)
7658 (if (and (re-search-backward org-dblock-start-re nil t)
7659 (setq beg (match-beginning 0))
7660 (re-search-forward org-dblock-end-re nil t)
7661 (> (match-end 0) pos))
7662 (goto-char beg)
7663 (goto-char pos)
7664 (error "Not in a dynamic block"))))
7666 (defun org-update-all-dblocks ()
7667 "Update all dynamic blocks in the buffer.
7668 This function can be used in a hook."
7669 (when (org-mode-p)
7670 (org-map-dblocks 'org-update-dblock)))
7673 ;;;; Completion
7675 (defconst org-additional-option-like-keywords
7676 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7677 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7678 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7680 (defcustom org-structure-template-alist
7682 ("s" "#+begin_src ?\n\n#+end_src")
7683 ("e" "#+begin_example\n?\n#+end_example")
7684 ("q" "#+begin_quote\n?\n#+end_quote")
7685 ("v" "#+begin_verse\n?\n#+end_verse")
7686 ("l" "#+begin_latex\n?\n#+end_latex")
7687 ("L" "#+latex: ")
7688 ("h" "#+begin_html\n?\n#+end_html")
7689 ("H" "#+html: ")
7690 ("a" "#+begin_ascii\n?\n#+end_ascii")
7691 ("A" "#+ascii: ")
7692 ("i" "#+include: %file ?")
7694 "Structure completion elements.
7695 This is a list of abbreviation keys and values. The value gets inserted
7696 it you type @samp{.} followed by the key and then the completion key,
7697 usually `M-TAB'. %file will be replaced by a file name after prompting
7698 for the file uning completion.
7699 This is an experimental feature, it is undecided if it is going to stay in."
7700 :group 'org-completion
7701 :type '(repeat
7702 (string :tag "Key") (string :tag "Template")))
7704 (defun org-complete-expand-structure-template (start cell)
7705 "Expand a structure template."
7706 (let ((rpl (nth 1 cell)))
7707 (delete-region start (point))
7708 (when (string-match "\\`#\\+" rpl)
7709 (cond
7710 ((bolp))
7711 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7712 (delete-region (point-at-bol) (point)))
7713 (t (newline))))
7714 (setq start (point))
7715 (if (string-match "%file" rpl)
7716 (setq rpl (replace-match
7717 (concat
7718 "\""
7719 (save-match-data
7720 (abbreviate-file-name (read-file-name "Include file: ")))
7721 "\"")
7722 t t rpl)))
7723 (insert rpl)
7724 (if (re-search-backward "\\?" start t) (delete-char 1))))
7727 (defun org-complete (&optional arg)
7728 "Perform completion on word at point.
7729 At the beginning of a headline, this completes TODO keywords as given in
7730 `org-todo-keywords'.
7731 If the current word is preceded by a backslash, completes the TeX symbols
7732 that are supported for HTML support.
7733 If the current word is preceded by \"#+\", completes special words for
7734 setting file options.
7735 In the line after \"#+STARTUP:, complete valid keywords.\"
7736 At all other locations, this simply calls the value of
7737 `org-completion-fallback-command'."
7738 (interactive "P")
7739 (org-without-partial-completion
7740 (catch 'exit
7741 (let* ((a nil)
7742 (end (point))
7743 (beg1 (save-excursion
7744 (skip-chars-backward (org-re "[:alnum:]_@"))
7745 (point)))
7746 (beg (save-excursion
7747 (skip-chars-backward "a-zA-Z0-9_:$")
7748 (point)))
7749 (confirm (lambda (x) (stringp (car x))))
7750 (searchhead (equal (char-before beg) ?*))
7751 (struct
7752 (when (and (equal (char-before beg1) ?.)
7753 (setq a (assoc (buffer-substring beg1 (point))
7754 org-structure-template-alist)))
7755 (org-complete-expand-structure-template (1- beg1) a)
7756 (throw 'exit t)))
7757 (tag (and (equal (char-before beg1) ?:)
7758 (equal (char-after (point-at-bol)) ?*)))
7759 (prop (and (equal (char-before beg1) ?:)
7760 (not (equal (char-after (point-at-bol)) ?*))))
7761 (texp (equal (char-before beg) ?\\))
7762 (link (equal (char-before beg) ?\[))
7763 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7764 beg)
7765 "#+"))
7766 (startup (string-match "^#\\+STARTUP:.*"
7767 (buffer-substring (point-at-bol) (point))))
7768 (completion-ignore-case opt)
7769 (type nil)
7770 (tbl nil)
7771 (table (cond
7772 (opt
7773 (setq type :opt)
7774 (require 'org-exp)
7775 (append
7776 (mapcar
7777 (lambda (x)
7778 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7779 (cons (match-string 2 x) (match-string 1 x)))
7780 (org-split-string (org-get-current-options) "\n"))
7781 (mapcar 'list org-additional-option-like-keywords)))
7782 (startup
7783 (setq type :startup)
7784 org-startup-options)
7785 (link (append org-link-abbrev-alist-local
7786 org-link-abbrev-alist))
7787 (texp
7788 (setq type :tex)
7789 org-html-entities)
7790 ((string-match "\\`\\*+[ \t]+\\'"
7791 (buffer-substring (point-at-bol) beg))
7792 (setq type :todo)
7793 (mapcar 'list org-todo-keywords-1))
7794 (searchhead
7795 (setq type :searchhead)
7796 (save-excursion
7797 (goto-char (point-min))
7798 (while (re-search-forward org-todo-line-regexp nil t)
7799 (push (list
7800 (org-make-org-heading-search-string
7801 (match-string 3) t))
7802 tbl)))
7803 tbl)
7804 (tag (setq type :tag beg beg1)
7805 (or org-tag-alist (org-get-buffer-tags)))
7806 (prop (setq type :prop beg beg1)
7807 (mapcar 'list (org-buffer-property-keys nil t t)))
7808 (t (progn
7809 (call-interactively org-completion-fallback-command)
7810 (throw 'exit nil)))))
7811 (pattern (buffer-substring-no-properties beg end))
7812 (completion (try-completion pattern table confirm)))
7813 (cond ((eq completion t)
7814 (if (not (assoc (upcase pattern) table))
7815 (message "Already complete")
7816 (if (and (equal type :opt)
7817 (not (member (car (assoc (upcase pattern) table))
7818 org-additional-option-like-keywords)))
7819 (insert (substring (cdr (assoc (upcase pattern) table))
7820 (length pattern)))
7821 (if (memq type '(:tag :prop)) (insert ":")))))
7822 ((null completion)
7823 (message "Can't find completion for \"%s\"" pattern)
7824 (ding))
7825 ((not (string= pattern completion))
7826 (delete-region beg end)
7827 (if (string-match " +$" completion)
7828 (setq completion (replace-match "" t t completion)))
7829 (insert completion)
7830 (if (get-buffer-window "*Completions*")
7831 (delete-window (get-buffer-window "*Completions*")))
7832 (if (assoc completion table)
7833 (if (eq type :todo) (insert " ")
7834 (if (memq type '(:tag :prop)) (insert ":"))))
7835 (if (and (equal type :opt) (assoc completion table))
7836 (message "%s" (substitute-command-keys
7837 "Press \\[org-complete] again to insert example settings"))))
7839 (message "Making completion list...")
7840 (let ((list (sort (all-completions pattern table confirm)
7841 'string<)))
7842 (with-output-to-temp-buffer "*Completions*"
7843 (condition-case nil
7844 ;; Protection needed for XEmacs and emacs 21
7845 (display-completion-list list pattern)
7846 (error (display-completion-list list)))))
7847 (message "Making completion list...%s" "done")))))))
7849 ;;;; TODO, DEADLINE, Comments
7851 (defun org-toggle-comment ()
7852 "Change the COMMENT state of an entry."
7853 (interactive)
7854 (save-excursion
7855 (org-back-to-heading)
7856 (let (case-fold-search)
7857 (if (looking-at (concat outline-regexp
7858 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7859 (replace-match "" t t nil 1)
7860 (if (looking-at outline-regexp)
7861 (progn
7862 (goto-char (match-end 0))
7863 (insert org-comment-string " ")))))))
7865 (defvar org-last-todo-state-is-todo nil
7866 "This is non-nil when the last TODO state change led to a TODO state.
7867 If the last change removed the TODO tag or switched to DONE, then
7868 this is nil.")
7870 (defvar org-setting-tags nil) ; dynamically skiped
7872 (defun org-parse-local-options (string var)
7873 "Parse STRING for startup setting relevant for variable VAR."
7874 (let ((rtn (symbol-value var))
7875 e opts)
7876 (save-match-data
7877 (if (or (not string) (not (string-match "\\S-" string)))
7879 (setq opts (delq nil (mapcar (lambda (x)
7880 (setq e (assoc x org-startup-options))
7881 (if (eq (nth 1 e) var) e nil))
7882 (org-split-string string "[ \t]+"))))
7883 (if (not opts)
7885 (setq rtn nil)
7886 (while (setq e (pop opts))
7887 (if (not (nth 3 e))
7888 (setq rtn (nth 2 e))
7889 (if (not (listp rtn)) (setq rtn nil))
7890 (push (nth 2 e) rtn)))
7891 rtn)))))
7893 (defvar org-blocker-hook nil
7894 "Hook for functions that are allowed to block a state change.
7896 Each function gets as its single argument a property list, see
7897 `org-trigger-hook' for more information about this list.
7899 If any of the functions in this hook returns nil, the state change
7900 is blocked.")
7902 (defvar org-trigger-hook nil
7903 "Hook for functions that are triggered by a state change.
7905 Each function gets as its single argument a property list with at least
7906 the following elements:
7908 (:type type-of-change :position pos-at-entry-start
7909 :from old-state :to new-state)
7911 Depending on the type, more properties may be present.
7913 This mechanism is currently implemented for:
7915 TODO state changes
7916 ------------------
7917 :type todo-state-change
7918 :from previous state (keyword as a string), or nil
7919 :to new state (keyword as a string), or nil")
7922 (defun org-todo (&optional arg)
7923 "Change the TODO state of an item.
7924 The state of an item is given by a keyword at the start of the heading,
7925 like
7926 *** TODO Write paper
7927 *** DONE Call mom
7929 The different keywords are specified in the variable `org-todo-keywords'.
7930 By default the available states are \"TODO\" and \"DONE\".
7931 So for this example: when the item starts with TODO, it is changed to DONE.
7932 When it starts with DONE, the DONE is removed. And when neither TODO nor
7933 DONE are present, add TODO at the beginning of the heading.
7935 With C-u prefix arg, use completion to determine the new state.
7936 With numeric prefix arg, switch to that state.
7938 For calling through lisp, arg is also interpreted in the following way:
7939 'none -> empty state
7940 \"\"(empty string) -> switch to empty state
7941 'done -> switch to DONE
7942 'nextset -> switch to the next set of keywords
7943 'previousset -> switch to the previous set of keywords
7944 \"WAITING\" -> switch to the specified keyword, but only if it
7945 really is a member of `org-todo-keywords'."
7946 (interactive "P")
7947 (save-excursion
7948 (catch 'exit
7949 (org-back-to-heading)
7950 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7951 (or (looking-at (concat " +" org-todo-regexp " *"))
7952 (looking-at " *"))
7953 (let* ((match-data (match-data))
7954 (startpos (point-at-bol))
7955 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7956 (org-log-done org-log-done)
7957 (org-log-repeat org-log-repeat)
7958 (org-todo-log-states org-todo-log-states)
7959 (this (match-string 1))
7960 (hl-pos (match-beginning 0))
7961 (head (org-get-todo-sequence-head this))
7962 (ass (assoc head org-todo-kwd-alist))
7963 (interpret (nth 1 ass))
7964 (done-word (nth 3 ass))
7965 (final-done-word (nth 4 ass))
7966 (last-state (or this ""))
7967 (completion-ignore-case t)
7968 (member (member this org-todo-keywords-1))
7969 (tail (cdr member))
7970 (state (cond
7971 ((and org-todo-key-trigger
7972 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7973 (and (not arg) org-use-fast-todo-selection
7974 (not (eq org-use-fast-todo-selection 'prefix)))))
7975 ;; Use fast selection
7976 (org-fast-todo-selection))
7977 ((and (equal arg '(4))
7978 (or (not org-use-fast-todo-selection)
7979 (not org-todo-key-trigger)))
7980 ;; Read a state with completion
7981 (completing-read "State: " (mapcar (lambda(x) (list x))
7982 org-todo-keywords-1)
7983 nil t))
7984 ((eq arg 'right)
7985 (if this
7986 (if tail (car tail) nil)
7987 (car org-todo-keywords-1)))
7988 ((eq arg 'left)
7989 (if (equal member org-todo-keywords-1)
7991 (if this
7992 (nth (- (length org-todo-keywords-1) (length tail) 2)
7993 org-todo-keywords-1)
7994 (org-last org-todo-keywords-1))))
7995 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7996 (setq arg nil))) ; hack to fall back to cycling
7997 (arg
7998 ;; user or caller requests a specific state
7999 (cond
8000 ((equal arg "") nil)
8001 ((eq arg 'none) nil)
8002 ((eq arg 'done) (or done-word (car org-done-keywords)))
8003 ((eq arg 'nextset)
8004 (or (car (cdr (member head org-todo-heads)))
8005 (car org-todo-heads)))
8006 ((eq arg 'previousset)
8007 (let ((org-todo-heads (reverse org-todo-heads)))
8008 (or (car (cdr (member head org-todo-heads)))
8009 (car org-todo-heads))))
8010 ((car (member arg org-todo-keywords-1)))
8011 ((nth (1- (prefix-numeric-value arg))
8012 org-todo-keywords-1))))
8013 ((null member) (or head (car org-todo-keywords-1)))
8014 ((equal this final-done-word) nil) ;; -> make empty
8015 ((null tail) nil) ;; -> first entry
8016 ((eq interpret 'sequence)
8017 (car tail))
8018 ((memq interpret '(type priority))
8019 (if (eq this-command last-command)
8020 (car tail)
8021 (if (> (length tail) 0)
8022 (or done-word (car org-done-keywords))
8023 nil)))
8024 (t nil)))
8025 (next (if state (concat " " state " ") " "))
8026 (change-plist (list :type 'todo-state-change :from this :to state
8027 :position startpos))
8028 dolog now-done-p)
8029 (when org-blocker-hook
8030 (unless (save-excursion
8031 (save-match-data
8032 (run-hook-with-args-until-failure
8033 'org-blocker-hook change-plist)))
8034 (if (interactive-p)
8035 (error "TODO state change from %s to %s blocked" this state)
8036 ;; fail silently
8037 (message "TODO state change from %s to %s blocked" this state)
8038 (throw 'exit nil))))
8039 (store-match-data match-data)
8040 (replace-match next t t)
8041 (unless (pos-visible-in-window-p hl-pos)
8042 (message "TODO state changed to %s" (org-trim next)))
8043 (unless head
8044 (setq head (org-get-todo-sequence-head state)
8045 ass (assoc head org-todo-kwd-alist)
8046 interpret (nth 1 ass)
8047 done-word (nth 3 ass)
8048 final-done-word (nth 4 ass)))
8049 (when (memq arg '(nextset previousset))
8050 (message "Keyword-Set %d/%d: %s"
8051 (- (length org-todo-sets) -1
8052 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8053 (length org-todo-sets)
8054 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8055 (setq org-last-todo-state-is-todo
8056 (not (member state org-done-keywords)))
8057 (setq now-done-p (and (member state org-done-keywords)
8058 (not (member this org-done-keywords))))
8059 (and logging (org-local-logging logging))
8060 (when (and (or org-todo-log-states org-log-done)
8061 (not (memq arg '(nextset previousset))))
8062 ;; we need to look at recording a time and note
8063 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8064 (nth 2 (assoc this org-todo-log-states))))
8065 (when (and state
8066 (member state org-not-done-keywords)
8067 (not (member this org-not-done-keywords)))
8068 ;; This is now a todo state and was not one before
8069 ;; If there was a CLOSED time stamp, get rid of it.
8070 (org-add-planning-info nil nil 'closed))
8071 (when (and now-done-p org-log-done)
8072 ;; It is now done, and it was not done before
8073 (org-add-planning-info 'closed (org-current-time))
8074 (if (and (not dolog) (eq 'note org-log-done))
8075 (org-add-log-setup 'done state 'findpos 'note)))
8076 (when (and state dolog)
8077 ;; This is a non-nil state, and we need to log it
8078 (org-add-log-setup 'state state 'findpos dolog)))
8079 ;; Fixup tag positioning
8080 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8081 (run-hooks 'org-after-todo-state-change-hook)
8082 (if (and arg (not (member state org-done-keywords)))
8083 (setq head (org-get-todo-sequence-head state)))
8084 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8085 ;; Do we need to trigger a repeat?
8086 (when now-done-p (org-auto-repeat-maybe state))
8087 ;; Fixup cursor location if close to the keyword
8088 (if (and (outline-on-heading-p)
8089 (not (bolp))
8090 (save-excursion (beginning-of-line 1)
8091 (looking-at org-todo-line-regexp))
8092 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8093 (progn
8094 (goto-char (or (match-end 2) (match-end 1)))
8095 (just-one-space)))
8096 (when org-trigger-hook
8097 (save-excursion
8098 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8100 (defun org-local-logging (value)
8101 "Get logging settings from a property VALUE."
8102 (let* (words w a)
8103 ;; directly set the variables, they are already local.
8104 (setq org-log-done nil
8105 org-log-repeat nil
8106 org-todo-log-states nil)
8107 (setq words (org-split-string value))
8108 (while (setq w (pop words))
8109 (cond
8110 ((setq a (assoc w org-startup-options))
8111 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8112 (set (nth 1 a) (nth 2 a))))
8113 ((setq a (org-extract-log-state-settings w))
8114 (and (member (car a) org-todo-keywords-1)
8115 (push a org-todo-log-states)))))))
8117 (defun org-get-todo-sequence-head (kwd)
8118 "Return the head of the TODO sequence to which KWD belongs.
8119 If KWD is not set, check if there is a text property remembering the
8120 right sequence."
8121 (let (p)
8122 (cond
8123 ((not kwd)
8124 (or (get-text-property (point-at-bol) 'org-todo-head)
8125 (progn
8126 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8127 nil (point-at-eol)))
8128 (get-text-property p 'org-todo-head))))
8129 ((not (member kwd org-todo-keywords-1))
8130 (car org-todo-keywords-1))
8131 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8133 (defun org-fast-todo-selection ()
8134 "Fast TODO keyword selection with single keys.
8135 Returns the new TODO keyword, or nil if no state change should occur."
8136 (let* ((fulltable org-todo-key-alist)
8137 (done-keywords org-done-keywords) ;; needed for the faces.
8138 (maxlen (apply 'max (mapcar
8139 (lambda (x)
8140 (if (stringp (car x)) (string-width (car x)) 0))
8141 fulltable)))
8142 (expert nil)
8143 (fwidth (+ maxlen 3 1 3))
8144 (ncol (/ (- (window-width) 4) fwidth))
8145 tg cnt e c tbl
8146 groups ingroup)
8147 (save-window-excursion
8148 (if expert
8149 (set-buffer (get-buffer-create " *Org todo*"))
8150 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8151 (erase-buffer)
8152 (org-set-local 'org-done-keywords done-keywords)
8153 (setq tbl fulltable cnt 0)
8154 (while (setq e (pop tbl))
8155 (cond
8156 ((equal e '(:startgroup))
8157 (push '() groups) (setq ingroup t)
8158 (when (not (= cnt 0))
8159 (setq cnt 0)
8160 (insert "\n"))
8161 (insert "{ "))
8162 ((equal e '(:endgroup))
8163 (setq ingroup nil cnt 0)
8164 (insert "}\n"))
8166 (setq tg (car e) c (cdr e))
8167 (if ingroup (push tg (car groups)))
8168 (setq tg (org-add-props tg nil 'face
8169 (org-get-todo-face tg)))
8170 (if (and (= cnt 0) (not ingroup)) (insert " "))
8171 (insert "[" c "] " tg (make-string
8172 (- fwidth 4 (length tg)) ?\ ))
8173 (when (= (setq cnt (1+ cnt)) ncol)
8174 (insert "\n")
8175 (if ingroup (insert " "))
8176 (setq cnt 0)))))
8177 (insert "\n")
8178 (goto-char (point-min))
8179 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8180 (fit-window-to-buffer))
8181 (message "[a-z..]:Set [SPC]:clear")
8182 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8183 (cond
8184 ((or (= c ?\C-g)
8185 (and (= c ?q) (not (rassoc c fulltable))))
8186 (setq quit-flag t))
8187 ((= c ?\ ) nil)
8188 ((setq e (rassoc c fulltable) tg (car e))
8190 (t (setq quit-flag t))))))
8192 (defun org-entry-is-todo-p ()
8193 (member (org-get-todo-state) org-not-done-keywords))
8195 (defun org-entry-is-done-p ()
8196 (member (org-get-todo-state) org-done-keywords))
8198 (defun org-get-todo-state ()
8199 (save-excursion
8200 (org-back-to-heading t)
8201 (and (looking-at org-todo-line-regexp)
8202 (match-end 2)
8203 (match-string 2))))
8205 (defun org-at-date-range-p (&optional inactive-ok)
8206 "Is the cursor inside a date range?"
8207 (interactive)
8208 (save-excursion
8209 (catch 'exit
8210 (let ((pos (point)))
8211 (skip-chars-backward "^[<\r\n")
8212 (skip-chars-backward "<[")
8213 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8214 (>= (match-end 0) pos)
8215 (throw 'exit t))
8216 (skip-chars-backward "^<[\r\n")
8217 (skip-chars-backward "<[")
8218 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8219 (>= (match-end 0) pos)
8220 (throw 'exit t)))
8221 nil)))
8223 (defun org-get-repeat ()
8224 "Check if tere is a deadline/schedule with repeater in this entry."
8225 (save-match-data
8226 (save-excursion
8227 (org-back-to-heading t)
8228 (if (re-search-forward
8229 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8230 (match-string 1)))))
8232 (defvar org-last-changed-timestamp)
8233 (defvar org-log-post-message)
8234 (defvar org-log-note-purpose)
8235 (defvar org-log-note-how)
8236 (defun org-auto-repeat-maybe (done-word)
8237 "Check if the current headline contains a repeated deadline/schedule.
8238 If yes, set TODO state back to what it was and change the base date
8239 of repeating deadline/scheduled time stamps to new date.
8240 This function is run automatically after each state change to a DONE state."
8241 ;; last-state is dynamically scoped into this function
8242 (let* ((repeat (org-get-repeat))
8243 (aa (assoc last-state org-todo-kwd-alist))
8244 (interpret (nth 1 aa))
8245 (head (nth 2 aa))
8246 (whata '(("d" . day) ("m" . month) ("y" . year)))
8247 (msg "Entry repeats: ")
8248 (org-log-done nil)
8249 (org-todo-log-states nil)
8250 (nshiftmax 10) (nshift 0)
8251 re type n what ts mb0 time)
8252 (when repeat
8253 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8254 (org-todo (if (eq interpret 'type) last-state head))
8255 (when org-log-repeat
8256 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8257 (memq 'org-add-log-note post-command-hook))
8258 ;; OK, we are already setup for some record
8259 (if (eq org-log-repeat 'note)
8260 ;; make sure we take a note, not only a time stamp
8261 (setq org-log-note-how 'note))
8262 ;; Set up for taking a record
8263 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8264 'findpos org-log-repeat)))
8265 (org-back-to-heading t)
8266 (org-add-planning-info nil nil 'closed)
8267 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8268 org-deadline-time-regexp "\\)\\|\\("
8269 org-ts-regexp "\\)"))
8270 (while (re-search-forward
8271 re (save-excursion (outline-next-heading) (point)) t)
8272 (setq type (if (match-end 1) org-scheduled-string
8273 (if (match-end 3) org-deadline-string "Plain:"))
8274 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8275 mb0 (match-beginning 0))
8276 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8277 (setq n (string-to-number (match-string 2 ts))
8278 what (match-string 3 ts))
8279 (if (equal what "w") (setq n (* n 7) what "d"))
8280 ;; Preparation, see if we need to modify the start date for the change
8281 (when (match-end 1)
8282 (setq time (save-match-data (org-time-string-to-time ts)))
8283 (cond
8284 ((equal (match-string 1 ts) ".")
8285 ;; Shift starting date to today
8286 (org-timestamp-change
8287 (- (time-to-days (current-time)) (time-to-days time))
8288 'day))
8289 ((equal (match-string 1 ts) "+")
8290 (while (or (= nshift 0)
8291 (<= (time-to-days time) (time-to-days (current-time))))
8292 (when (= (incf nshift) nshiftmax)
8293 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8294 (error "Abort")))
8295 (org-timestamp-change n (cdr (assoc what whata)))
8296 (org-at-timestamp-p t)
8297 (setq ts (match-string 1))
8298 (setq time (save-match-data (org-time-string-to-time ts))))
8299 (org-timestamp-change (- n) (cdr (assoc what whata)))
8300 ;; rematch, so that we have everything in place for the real shift
8301 (org-at-timestamp-p t)
8302 (setq ts (match-string 1))
8303 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8304 (org-timestamp-change n (cdr (assoc what whata)))
8305 (setq msg (concat msg type org-last-changed-timestamp " "))))
8306 (setq org-log-post-message msg)
8307 (message "%s" msg))))
8309 (defun org-show-todo-tree (arg)
8310 "Make a compact tree which shows all headlines marked with TODO.
8311 The tree will show the lines where the regexp matches, and all higher
8312 headlines above the match.
8313 With a \\[universal-argument] prefix, also show the DONE entries.
8314 With a numeric prefix N, construct a sparse tree for the Nth element
8315 of `org-todo-keywords-1'."
8316 (interactive "P")
8317 (let ((case-fold-search nil)
8318 (kwd-re
8319 (cond ((null arg) org-not-done-regexp)
8320 ((equal arg '(4))
8321 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8322 (mapcar 'list org-todo-keywords-1))))
8323 (concat "\\("
8324 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8325 "\\)\\>")))
8326 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8327 (regexp-quote (nth (1- (prefix-numeric-value arg))
8328 org-todo-keywords-1)))
8329 (t (error "Invalid prefix argument: %s" arg)))))
8330 (message "%d TODO entries found"
8331 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8333 (defun org-deadline (&optional remove)
8334 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8335 With argument REMOVE, remove any deadline from the item."
8336 (interactive "P")
8337 (if remove
8338 (progn
8339 (org-remove-timestamp-with-keyword org-deadline-string)
8340 (message "Item no longer has a deadline."))
8341 (org-add-planning-info 'deadline nil 'closed)))
8343 (defun org-schedule (&optional remove)
8344 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8345 With argument REMOVE, remove any scheduling date from the item."
8346 (interactive "P")
8347 (if remove
8348 (progn
8349 (org-remove-timestamp-with-keyword org-scheduled-string)
8350 (message "Item is no longer scheduled."))
8351 (org-add-planning-info 'scheduled nil 'closed)))
8353 (defun org-remove-timestamp-with-keyword (keyword)
8354 "Remove all time stamps with KEYWORD in the current entry."
8355 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8356 beg)
8357 (save-excursion
8358 (org-back-to-heading t)
8359 (setq beg (point))
8360 (org-end-of-subtree t t)
8361 (while (re-search-backward re beg t)
8362 (replace-match "")
8363 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8364 (equal (char-before) ?\ ))
8365 (backward-delete-char 1)
8366 (if (string-match "^[ \t]*$" (buffer-substring
8367 (point-at-bol) (point-at-eol)))
8368 (delete-region (point-at-bol)
8369 (min (point-max) (1+ (point-at-eol))))))))))
8371 (defun org-add-planning-info (what &optional time &rest remove)
8372 "Insert new timestamp with keyword in the line directly after the headline.
8373 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8374 If non is given, the user is prompted for a date.
8375 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8376 be removed."
8377 (interactive)
8378 (let (org-time-was-given org-end-time-was-given ts
8379 end default-time default-input)
8381 (when (and (not time) (memq what '(scheduled deadline)))
8382 ;; Try to get a default date/time from existing timestamp
8383 (save-excursion
8384 (org-back-to-heading t)
8385 (setq end (save-excursion (outline-next-heading) (point)))
8386 (when (re-search-forward (if (eq what 'scheduled)
8387 org-scheduled-time-regexp
8388 org-deadline-time-regexp)
8389 end t)
8390 (setq ts (match-string 1)
8391 default-time
8392 (apply 'encode-time (org-parse-time-string ts))
8393 default-input (and ts (org-get-compact-tod ts))))))
8394 (when what
8395 ;; If necessary, get the time from the user
8396 (setq time (or time (org-read-date nil 'to-time nil nil
8397 default-time default-input))))
8399 (when (and org-insert-labeled-timestamps-at-point
8400 (member what '(scheduled deadline)))
8401 (insert
8402 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8403 (org-insert-time-stamp time org-time-was-given
8404 nil nil nil (list org-end-time-was-given))
8405 (setq what nil))
8406 (save-excursion
8407 (save-restriction
8408 (let (col list elt ts buffer-invisibility-spec)
8409 (org-back-to-heading t)
8410 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8411 (goto-char (match-end 1))
8412 (setq col (current-column))
8413 (goto-char (match-end 0))
8414 (if (eobp) (insert "\n") (forward-char 1))
8415 (if (and (not (looking-at outline-regexp))
8416 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8417 "[^\r\n]*"))
8418 (not (equal (match-string 1) org-clock-string)))
8419 (narrow-to-region (match-beginning 0) (match-end 0))
8420 (insert-before-markers "\n")
8421 (backward-char 1)
8422 (narrow-to-region (point) (point))
8423 (org-indent-to-column col))
8424 ;; Check if we have to remove something.
8425 (setq list (cons what remove))
8426 (while list
8427 (setq elt (pop list))
8428 (goto-char (point-min))
8429 (when (or (and (eq elt 'scheduled)
8430 (re-search-forward org-scheduled-time-regexp nil t))
8431 (and (eq elt 'deadline)
8432 (re-search-forward org-deadline-time-regexp nil t))
8433 (and (eq elt 'closed)
8434 (re-search-forward org-closed-time-regexp nil t)))
8435 (replace-match "")
8436 (if (looking-at "--+<[^>]+>") (replace-match ""))
8437 (if (looking-at " +") (replace-match ""))))
8438 (goto-char (point-max))
8439 (when what
8440 (insert
8441 (if (not (equal (char-before) ?\ )) " " "")
8442 (cond ((eq what 'scheduled) org-scheduled-string)
8443 ((eq what 'deadline) org-deadline-string)
8444 ((eq what 'closed) org-closed-string))
8445 " ")
8446 (setq ts (org-insert-time-stamp
8447 time
8448 (or org-time-was-given
8449 (and (eq what 'closed) org-log-done-with-time))
8450 (eq what 'closed)
8451 nil nil (list org-end-time-was-given)))
8452 (end-of-line 1))
8453 (goto-char (point-min))
8454 (widen)
8455 (if (and (looking-at "[ \t]+\n")
8456 (equal (char-before) ?\n))
8457 (delete-region (1- (point)) (point-at-eol)))
8458 ts)))))
8460 (defvar org-log-note-marker (make-marker))
8461 (defvar org-log-note-purpose nil)
8462 (defvar org-log-note-state nil)
8463 (defvar org-log-note-how nil)
8464 (defvar org-log-note-window-configuration nil)
8465 (defvar org-log-note-return-to (make-marker))
8466 (defvar org-log-post-message nil
8467 "Message to be displayed after a log note has been stored.
8468 The auto-repeater uses this.")
8470 (defun org-add-note ()
8471 "Add a note to the current entry.
8472 This is done in the same way as adding a state change note."
8473 (interactive)
8474 (org-add-log-setup 'note nil t nil))
8476 (defun org-add-log-setup (&optional purpose state findpos how)
8477 "Set up the post command hook to take a note.
8478 If this is about to TODO state change, the new state is expected in STATE.
8479 When FINDPOS is non-nil, find the correct position for the note in
8480 the current entry. If not, assume that it can be inserted at point."
8481 (save-excursion
8482 (when findpos
8483 (org-back-to-heading t)
8484 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8485 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8486 "[^\r\n]*\\)?"))
8487 (goto-char (match-end 0))
8488 (unless org-log-states-order-reversed
8489 (and (= (char-after) ?\n) (forward-char 1))
8490 (org-skip-over-state-notes)
8491 (skip-chars-backward " \t\n\r")))
8492 (move-marker org-log-note-marker (point))
8493 (setq org-log-note-purpose purpose
8494 org-log-note-state state
8495 org-log-note-how how)
8496 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8498 (defun org-skip-over-state-notes ()
8499 "Skip past the list of State notes in an entry."
8500 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8501 (while (looking-at "[ \t]*- State")
8502 (condition-case nil
8503 (org-next-item)
8504 (error (org-end-of-item)))))
8506 (defun org-add-log-note (&optional purpose)
8507 "Pop up a window for taking a note, and add this note later at point."
8508 (remove-hook 'post-command-hook 'org-add-log-note)
8509 (setq org-log-note-window-configuration (current-window-configuration))
8510 (delete-other-windows)
8511 (move-marker org-log-note-return-to (point))
8512 (switch-to-buffer (marker-buffer org-log-note-marker))
8513 (goto-char org-log-note-marker)
8514 (org-switch-to-buffer-other-window "*Org Note*")
8515 (erase-buffer)
8516 (if (memq org-log-note-how '(time state))
8517 (org-store-log-note)
8518 (let ((org-inhibit-startup t)) (org-mode))
8519 (insert (format "# Insert note for %s.
8520 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8521 (cond
8522 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8523 ((eq org-log-note-purpose 'done) "closed todo item")
8524 ((eq org-log-note-purpose 'state)
8525 (format "state change to \"%s\"" org-log-note-state))
8526 ((eq org-log-note-purpose 'note)
8527 "this entry")
8528 (t (error "This should not happen")))))
8529 (org-set-local 'org-finish-function 'org-store-log-note)))
8531 (defvar org-note-abort nil) ; dynamically scoped
8532 (defun org-store-log-note ()
8533 "Finish taking a log note, and insert it to where it belongs."
8534 (let ((txt (buffer-string))
8535 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8536 lines ind)
8537 (kill-buffer (current-buffer))
8538 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8539 (setq txt (replace-match "" t t txt)))
8540 (if (string-match "\\s-+\\'" txt)
8541 (setq txt (replace-match "" t t txt)))
8542 (setq lines (org-split-string txt "\n"))
8543 (when (and note (string-match "\\S-" note))
8544 (setq note
8545 (org-replace-escapes
8546 note
8547 (list (cons "%u" (user-login-name))
8548 (cons "%U" user-full-name)
8549 (cons "%t" (format-time-string
8550 (org-time-stamp-format 'long 'inactive)
8551 (current-time)))
8552 (cons "%s" (if org-log-note-state
8553 (concat "\"" org-log-note-state "\"")
8554 "")))))
8555 (if lines (setq note (concat note " \\\\")))
8556 (push note lines))
8557 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8558 (when lines
8559 (save-excursion
8560 (set-buffer (marker-buffer org-log-note-marker))
8561 (save-excursion
8562 (goto-char org-log-note-marker)
8563 (move-marker org-log-note-marker nil)
8564 (end-of-line 1)
8565 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8566 (indent-relative nil)
8567 (insert "- " (pop lines))
8568 (org-indent-line-function)
8569 (beginning-of-line 1)
8570 (looking-at "[ \t]*")
8571 (setq ind (concat (match-string 0) " "))
8572 (end-of-line 1)
8573 (while lines (insert "\n" ind (pop lines)))))))
8574 (set-window-configuration org-log-note-window-configuration)
8575 (with-current-buffer (marker-buffer org-log-note-return-to)
8576 (goto-char org-log-note-return-to))
8577 (move-marker org-log-note-return-to nil)
8578 (and org-log-post-message (message "%s" org-log-post-message)))
8580 (defun org-sparse-tree (&optional arg)
8581 "Create a sparse tree, prompt for the details.
8582 This command can create sparse trees. You first need to select the type
8583 of match used to create the tree:
8585 t Show entries with a specific TODO keyword.
8586 T Show entries selected by a tags match.
8587 p Enter a property name and its value (both with completion on existing
8588 names/values) and show entries with that property.
8589 r Show entries matching a regular expression
8590 d Show deadlines due within `org-deadline-warning-days'."
8591 (interactive "P")
8592 (let (ans kwd value)
8593 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8594 (setq ans (read-char-exclusive))
8595 (cond
8596 ((equal ans ?d)
8597 (call-interactively 'org-check-deadlines))
8598 ((equal ans ?b)
8599 (call-interactively 'org-check-before-date))
8600 ((equal ans ?t)
8601 (org-show-todo-tree '(4)))
8602 ((equal ans ?T)
8603 (call-interactively 'org-tags-sparse-tree))
8604 ((member ans '(?p ?P))
8605 (setq kwd (completing-read "Property: "
8606 (mapcar 'list (org-buffer-property-keys))))
8607 (setq value (completing-read "Value: "
8608 (mapcar 'list (org-property-values kwd))))
8609 (unless (string-match "\\`{.*}\\'" value)
8610 (setq value (concat "\"" value "\"")))
8611 (org-tags-sparse-tree arg (concat kwd "=" value)))
8612 ((member ans '(?r ?R ?/))
8613 (call-interactively 'org-occur))
8614 (t (error "No such sparse tree command \"%c\"" ans)))))
8616 (defvar org-occur-highlights nil
8617 "List of overlays used for occur matches.")
8618 (make-variable-buffer-local 'org-occur-highlights)
8619 (defvar org-occur-parameters nil
8620 "Parameters of the active org-occur calls.
8621 This is a list, each call to org-occur pushes as cons cell,
8622 containing the regular expression and the callback, onto the list.
8623 The list can contain several entries if `org-occur' has been called
8624 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8625 will only contain one set of parameters. When the highlights are
8626 removed (for example with `C-c C-c', or with the next edit (depending
8627 on `org-remove-highlights-with-change'), this variable is emptied
8628 as well.")
8629 (make-variable-buffer-local 'org-occur-parameters)
8631 (defun org-occur (regexp &optional keep-previous callback)
8632 "Make a compact tree which shows all matches of REGEXP.
8633 The tree will show the lines where the regexp matches, and all higher
8634 headlines above the match. It will also show the heading after the match,
8635 to make sure editing the matching entry is easy.
8636 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8637 call to `org-occur' will be kept, to allow stacking of calls to this
8638 command.
8639 If CALLBACK is non-nil, it is a function which is called to confirm
8640 that the match should indeed be shown."
8641 (interactive "sRegexp: \nP")
8642 (unless keep-previous
8643 (org-remove-occur-highlights nil nil t))
8644 (push (cons regexp callback) org-occur-parameters)
8645 (let ((cnt 0))
8646 (save-excursion
8647 (goto-char (point-min))
8648 (if (or (not keep-previous) ; do not want to keep
8649 (not org-occur-highlights)) ; no previous matches
8650 ;; hide everything
8651 (org-overview))
8652 (while (re-search-forward regexp nil t)
8653 (when (or (not callback)
8654 (save-match-data (funcall callback)))
8655 (setq cnt (1+ cnt))
8656 (when org-highlight-sparse-tree-matches
8657 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8658 (org-show-context 'occur-tree))))
8659 (when org-remove-highlights-with-change
8660 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8661 nil 'local))
8662 (unless org-sparse-tree-open-archived-trees
8663 (org-hide-archived-subtrees (point-min) (point-max)))
8664 (run-hooks 'org-occur-hook)
8665 (if (interactive-p)
8666 (message "%d match(es) for regexp %s" cnt regexp))
8667 cnt))
8669 (defun org-show-context (&optional key)
8670 "Make sure point and context and visible.
8671 How much context is shown depends upon the variables
8672 `org-show-hierarchy-above', `org-show-following-heading'. and
8673 `org-show-siblings'."
8674 (let ((heading-p (org-on-heading-p t))
8675 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8676 (following-p (org-get-alist-option org-show-following-heading key))
8677 (entry-p (org-get-alist-option org-show-entry-below key))
8678 (siblings-p (org-get-alist-option org-show-siblings key)))
8679 (catch 'exit
8680 ;; Show heading or entry text
8681 (if (and heading-p (not entry-p))
8682 (org-flag-heading nil) ; only show the heading
8683 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8684 (org-show-hidden-entry))) ; show entire entry
8685 (when following-p
8686 ;; Show next sibling, or heading below text
8687 (save-excursion
8688 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8689 (org-flag-heading nil))))
8690 (when siblings-p (org-show-siblings))
8691 (when hierarchy-p
8692 ;; show all higher headings, possibly with siblings
8693 (save-excursion
8694 (while (and (condition-case nil
8695 (progn (org-up-heading-all 1) t)
8696 (error nil))
8697 (not (bobp)))
8698 (org-flag-heading nil)
8699 (when siblings-p (org-show-siblings))))))))
8701 (defun org-reveal (&optional siblings)
8702 "Show current entry, hierarchy above it, and the following headline.
8703 This can be used to show a consistent set of context around locations
8704 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8705 not t for the search context.
8707 With optional argument SIBLINGS, on each level of the hierarchy all
8708 siblings are shown. This repairs the tree structure to what it would
8709 look like when opened with hierarchical calls to `org-cycle'."
8710 (interactive "P")
8711 (let ((org-show-hierarchy-above t)
8712 (org-show-following-heading t)
8713 (org-show-siblings (if siblings t org-show-siblings)))
8714 (org-show-context nil)))
8716 (defun org-highlight-new-match (beg end)
8717 "Highlight from BEG to END and mark the highlight is an occur headline."
8718 (let ((ov (org-make-overlay beg end)))
8719 (org-overlay-put ov 'face 'secondary-selection)
8720 (push ov org-occur-highlights)))
8722 (defun org-remove-occur-highlights (&optional beg end noremove)
8723 "Remove the occur highlights from the buffer.
8724 BEG and END are ignored. If NOREMOVE is nil, remove this function
8725 from the `before-change-functions' in the current buffer."
8726 (interactive)
8727 (unless org-inhibit-highlight-removal
8728 (mapc 'org-delete-overlay org-occur-highlights)
8729 (setq org-occur-highlights nil)
8730 (setq org-occur-parameters nil)
8731 (unless noremove
8732 (remove-hook 'before-change-functions
8733 'org-remove-occur-highlights 'local))))
8735 ;;;; Priorities
8737 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8738 "Regular expression matching the priority indicator.")
8740 (defvar org-remove-priority-next-time nil)
8742 (defun org-priority-up ()
8743 "Increase the priority of the current item."
8744 (interactive)
8745 (org-priority 'up))
8747 (defun org-priority-down ()
8748 "Decrease the priority of the current item."
8749 (interactive)
8750 (org-priority 'down))
8752 (defun org-priority (&optional action)
8753 "Change the priority of an item by ARG.
8754 ACTION can be `set', `up', `down', or a character."
8755 (interactive)
8756 (setq action (or action 'set))
8757 (let (current new news have remove)
8758 (save-excursion
8759 (org-back-to-heading)
8760 (if (looking-at org-priority-regexp)
8761 (setq current (string-to-char (match-string 2))
8762 have t)
8763 (setq current org-default-priority))
8764 (cond
8765 ((or (eq action 'set)
8766 (if (featurep 'xemacs) (characterp action) (integerp action)))
8767 (if (not (eq action 'set))
8768 (setq new action)
8769 (message "Priority %c-%c, SPC to remove: "
8770 org-highest-priority org-lowest-priority)
8771 (setq new (read-char-exclusive)))
8772 (if (and (= (upcase org-highest-priority) org-highest-priority)
8773 (= (upcase org-lowest-priority) org-lowest-priority))
8774 (setq new (upcase new)))
8775 (cond ((equal new ?\ ) (setq remove t))
8776 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8777 (error "Priority must be between `%c' and `%c'"
8778 org-highest-priority org-lowest-priority))))
8779 ((eq action 'up)
8780 (if (and (not have) (eq last-command this-command))
8781 (setq new org-lowest-priority)
8782 (setq new (if (and org-priority-start-cycle-with-default (not have))
8783 org-default-priority (1- current)))))
8784 ((eq action 'down)
8785 (if (and (not have) (eq last-command this-command))
8786 (setq new org-highest-priority)
8787 (setq new (if (and org-priority-start-cycle-with-default (not have))
8788 org-default-priority (1+ current)))))
8789 (t (error "Invalid action")))
8790 (if (or (< (upcase new) org-highest-priority)
8791 (> (upcase new) org-lowest-priority))
8792 (setq remove t))
8793 (setq news (format "%c" new))
8794 (if have
8795 (if remove
8796 (replace-match "" t t nil 1)
8797 (replace-match news t t nil 2))
8798 (if remove
8799 (error "No priority cookie found in line")
8800 (looking-at org-todo-line-regexp)
8801 (if (match-end 2)
8802 (progn
8803 (goto-char (match-end 2))
8804 (insert " [#" news "]"))
8805 (goto-char (match-beginning 3))
8806 (insert "[#" news "] ")))))
8807 (org-preserve-lc (org-set-tags nil 'align))
8808 (if remove
8809 (message "Priority removed")
8810 (message "Priority of current item set to %s" news))))
8813 (defun org-get-priority (s)
8814 "Find priority cookie and return priority."
8815 (save-match-data
8816 (if (not (string-match org-priority-regexp s))
8817 (* 1000 (- org-lowest-priority org-default-priority))
8818 (* 1000 (- org-lowest-priority
8819 (string-to-char (match-string 2 s)))))))
8821 ;;;; Tags
8823 (defun org-scan-tags (action matcher &optional todo-only)
8824 "Scan headline tags with inheritance and produce output ACTION.
8825 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8826 evaluated, testing if a given set of tags qualifies a headline for
8827 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8828 are included in the output."
8829 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8830 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8831 (org-re
8832 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8833 (props (list 'face nil
8834 'done-face 'org-done
8835 'undone-face nil
8836 'mouse-face 'highlight
8837 'org-not-done-regexp org-not-done-regexp
8838 'org-todo-regexp org-todo-regexp
8839 'keymap org-agenda-keymap
8840 'help-echo
8841 (format "mouse-2 or RET jump to org file %s"
8842 (abbreviate-file-name
8843 (or (buffer-file-name (buffer-base-buffer))
8844 (buffer-name (buffer-base-buffer)))))))
8845 (case-fold-search nil)
8846 lspos
8847 tags tags-list tags-alist (llast 0) rtn level category i txt
8848 todo marker entry priority)
8849 (save-excursion
8850 (goto-char (point-min))
8851 (when (eq action 'sparse-tree)
8852 (org-overview)
8853 (org-remove-occur-highlights))
8854 (while (re-search-forward re nil t)
8855 (catch :skip
8856 (setq todo (if (match-end 1) (match-string 2))
8857 tags (if (match-end 4) (match-string 4)))
8858 (goto-char (setq lspos (1+ (match-beginning 0))))
8859 (setq level (org-reduced-level (funcall outline-level))
8860 category (org-get-category))
8861 (setq i llast llast level)
8862 ;; remove tag lists from same and sublevels
8863 (while (>= i level)
8864 (when (setq entry (assoc i tags-alist))
8865 (setq tags-alist (delete entry tags-alist)))
8866 (setq i (1- i)))
8867 ;; add the next tags
8868 (when tags
8869 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8870 tags-alist
8871 (cons (cons level tags) tags-alist)))
8872 ;; compile tags for current headline
8873 (setq tags-list
8874 (if org-use-tag-inheritance
8875 (apply 'append (mapcar 'cdr tags-alist))
8876 tags))
8877 (when (and tags org-use-tag-inheritance
8878 (not (eq t org-use-tag-inheritance)))
8879 ;; selective inheritance, remove uninherited ones
8880 (setcdr (car tags-alist)
8881 (org-remove-uniherited-tags (cdar tags-alist))))
8882 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8883 (eval matcher)
8884 (or (not org-agenda-skip-archived-trees)
8885 (not (member org-archive-tag tags-list))))
8886 (and (eq action 'agenda) (org-agenda-skip))
8887 ;; list this headline
8889 (if (eq action 'sparse-tree)
8890 (progn
8891 (and org-highlight-sparse-tree-matches
8892 (org-get-heading) (match-end 0)
8893 (org-highlight-new-match
8894 (match-beginning 0) (match-beginning 1)))
8895 (org-show-context 'tags-tree))
8896 (setq txt (org-format-agenda-item
8898 (concat
8899 (if org-tags-match-list-sublevels
8900 (make-string (1- level) ?.) "")
8901 (org-get-heading))
8902 category tags-list)
8903 priority (org-get-priority txt))
8904 (goto-char lspos)
8905 (setq marker (org-agenda-new-marker))
8906 (org-add-props txt props
8907 'org-marker marker 'org-hd-marker marker 'org-category category
8908 'priority priority 'type "tagsmatch")
8909 (push txt rtn))
8910 ;; if we are to skip sublevels, jump to end of subtree
8911 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8912 (when (and (eq action 'sparse-tree)
8913 (not org-sparse-tree-open-archived-trees))
8914 (org-hide-archived-subtrees (point-min) (point-max)))
8915 (nreverse rtn)))
8917 (defun org-remove-uniherited-tags (tags)
8918 "Remove all tags that are not inherited from the list TAGS."
8919 (cond
8920 ((eq org-use-tag-inheritance t) tags)
8921 ((not org-use-tag-inheritance) nil)
8922 ((stringp org-use-tag-inheritance)
8923 (delq nil (mapcar
8924 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8925 tags)))
8926 ((listp org-use-tag-inheritance)
8927 (org-delete-all org-use-tag-inheritance tags))))
8929 (defvar todo-only) ;; dynamically scoped
8931 (defun org-tags-sparse-tree (&optional todo-only match)
8932 "Create a sparse tree according to tags string MATCH.
8933 MATCH can contain positive and negative selection of tags, like
8934 \"+WORK+URGENT-WITHBOSS\".
8935 If optional argument TODO_ONLY is non-nil, only select lines that are
8936 also TODO lines."
8937 (interactive "P")
8938 (org-prepare-agenda-buffers (list (current-buffer)))
8939 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8941 (defvar org-cached-props nil)
8942 (defun org-cached-entry-get (pom property)
8943 (if (or (eq t org-use-property-inheritance)
8944 (and (stringp org-use-property-inheritance)
8945 (string-match org-use-property-inheritance property))
8946 (and (listp org-use-property-inheritance)
8947 (member property org-use-property-inheritance)))
8948 ;; Caching is not possible, check it directly
8949 (org-entry-get pom property 'inherit)
8950 ;; Get all properties, so that we can do complicated checks easily
8951 (cdr (assoc property (or org-cached-props
8952 (setq org-cached-props
8953 (org-entry-properties pom)))))))
8955 (defun org-global-tags-completion-table (&optional files)
8956 "Return the list of all tags in all agenda buffer/files."
8957 (save-excursion
8958 (org-uniquify
8959 (delq nil
8960 (apply 'append
8961 (mapcar
8962 (lambda (file)
8963 (set-buffer (find-file-noselect file))
8964 (append (org-get-buffer-tags)
8965 (mapcar (lambda (x) (if (stringp (car-safe x))
8966 (list (car-safe x)) nil))
8967 org-tag-alist)))
8968 (if (and files (car files))
8969 files
8970 (org-agenda-files))))))))
8972 (defun org-make-tags-matcher (match)
8973 "Create the TAGS//TODO matcher form for the selection string MATCH."
8974 ;; todo-only is scoped dynamically into this function, and the function
8975 ;; may change it it the matcher asksk for it.
8976 (unless match
8977 ;; Get a new match request, with completion
8978 (let ((org-last-tags-completion-table
8979 (org-global-tags-completion-table)))
8980 (setq match (completing-read
8981 "Match: " 'org-tags-completion-function nil nil nil
8982 'org-tags-history))))
8984 ;; Parse the string and create a lisp form
8985 (let ((match0 match)
8986 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8987 minus tag mm
8988 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8989 orterms term orlist re-p str-p level-p level-op
8990 prop-p pn pv po cat-p gv)
8991 (if (string-match "/+" match)
8992 ;; match contains also a todo-matching request
8993 (progn
8994 (setq tagsmatch (substring match 0 (match-beginning 0))
8995 todomatch (substring match (match-end 0)))
8996 (if (string-match "^!" todomatch)
8997 (setq todo-only t todomatch (substring todomatch 1)))
8998 (if (string-match "^\\s-*$" todomatch)
8999 (setq todomatch nil)))
9000 ;; only matching tags
9001 (setq tagsmatch match todomatch nil))
9003 ;; Make the tags matcher
9004 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9005 (setq tagsmatcher t)
9006 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9007 (while (setq term (pop orterms))
9008 (while (and (equal (substring term -1) "\\") orterms)
9009 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9010 (while (string-match re term)
9011 (setq minus (and (match-end 1)
9012 (equal (match-string 1 term) "-"))
9013 tag (match-string 2 term)
9014 re-p (equal (string-to-char tag) ?{)
9015 level-p (match-end 4)
9016 prop-p (match-end 5)
9017 mm (cond
9018 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9019 (level-p
9020 (setq level-op (org-op-to-function (match-string 3 term)))
9021 `(,level-op level ,(string-to-number
9022 (match-string 4 term))))
9023 (prop-p
9024 (setq pn (match-string 5 term)
9025 po (match-string 6 term)
9026 pv (match-string 7 term)
9027 cat-p (equal pn "CATEGORY")
9028 re-p (equal (string-to-char pv) ?{)
9029 str-p (equal (string-to-char pv) ?\")
9030 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9031 (setq po (org-op-to-function po str-p))
9032 (if (equal pn "CATEGORY")
9033 (setq gv '(get-text-property (point) 'org-category))
9034 (setq gv `(org-cached-entry-get nil ,pn)))
9035 (if re-p
9036 (if (eq po 'org<>)
9037 `(not (string-match ,pv (or ,gv "")))
9038 `(string-match ,pv (or ,gv "")))
9039 (if str-p
9040 `(,po (or ,gv "") ,pv)
9041 `(,po (string-to-number (or ,gv ""))
9042 ,(string-to-number pv) ))))
9043 (t `(member ,(downcase tag) tags-list)))
9044 mm (if minus (list 'not mm) mm)
9045 term (substring term (match-end 0)))
9046 (push mm tagsmatcher))
9047 (push (if (> (length tagsmatcher) 1)
9048 (cons 'and tagsmatcher)
9049 (car tagsmatcher))
9050 orlist)
9051 (setq tagsmatcher nil))
9052 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9053 (setq tagsmatcher
9054 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9055 ;; Make the todo matcher
9056 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9057 (setq todomatcher t)
9058 (setq orterms (org-split-string todomatch "|") orlist nil)
9059 (while (setq term (pop orterms))
9060 (while (string-match re term)
9061 (setq minus (and (match-end 1)
9062 (equal (match-string 1 term) "-"))
9063 kwd (match-string 2 term)
9064 re-p (equal (string-to-char kwd) ?{)
9065 term (substring term (match-end 0))
9066 mm (if re-p
9067 `(string-match ,(substring kwd 1 -1) todo)
9068 (list 'equal 'todo kwd))
9069 mm (if minus (list 'not mm) mm))
9070 (push mm todomatcher))
9071 (push (if (> (length todomatcher) 1)
9072 (cons 'and todomatcher)
9073 (car todomatcher))
9074 orlist)
9075 (setq todomatcher nil))
9076 (setq todomatcher (if (> (length orlist) 1)
9077 (cons 'or orlist) (car orlist))))
9079 ;; Return the string and lisp forms of the matcher
9080 (setq matcher (if todomatcher
9081 (list 'and tagsmatcher todomatcher)
9082 tagsmatcher))
9083 (cons match0 matcher)))
9085 (defun org-op-to-function (op &optional stringp)
9086 (setq op
9087 (cond
9088 ((equal op "<" ) '(< string< ))
9089 ((equal op ">" ) '(> org-string> ))
9090 ((member op '("<=" "=<")) '(<= org-string<= ))
9091 ((member op '(">=" "=>")) '(>= org-string>= ))
9092 ((member op '("=" "==")) '(= string= ))
9093 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9094 (nth (if stringp 1 0) op))
9096 (defun org<> (a b) (not (= a b)))
9097 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9098 (defun org-string>= (a b) (not (string< a b)))
9099 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9100 (defun org-string<> (a b) (not (string= a b)))
9102 (defun org-match-any-p (re list)
9103 "Does re match any element of list?"
9104 (setq list (mapcar (lambda (x) (string-match re x)) list))
9105 (delq nil list))
9107 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9108 (defvar org-tags-overlay (org-make-overlay 1 1))
9109 (org-detach-overlay org-tags-overlay)
9111 (defun org-get-tags-at (&optional pos)
9112 "Get a list of all headline tags applicable at POS.
9113 POS defaults to point. If tags are inherited, the list contains
9114 the targets in the same sequence as the headlines appear, i.e.
9115 sthe tags of the current headline come last."
9116 (interactive)
9117 (let (tags ltags lastpos parent)
9118 (save-excursion
9119 (save-restriction
9120 (widen)
9121 (goto-char (or pos (point)))
9122 (save-match-data
9123 (condition-case nil
9124 (progn
9125 (org-back-to-heading t)
9126 (while (not (equal lastpos (point)))
9127 (setq lastpos (point))
9128 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9129 (setq ltags (org-split-string
9130 (org-match-string-no-properties 1) ":"))
9131 (setq tags (append (org-remove-uniherited-tags ltags)
9132 tags)))
9133 (or org-use-tag-inheritance (error ""))
9134 (org-up-heading-all 1)
9135 (setq parent t)))
9136 (error nil))))
9137 tags)))
9139 (defun org-toggle-tag (tag &optional onoff)
9140 "Toggle the tag TAG for the current line.
9141 If ONOFF is `on' or `off', don't toggle but set to this state."
9142 (unless (org-on-heading-p t) (error "Not on headling"))
9143 (let (res current)
9144 (save-excursion
9145 (beginning-of-line)
9146 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9147 (point-at-eol) t)
9148 (progn
9149 (setq current (match-string 1))
9150 (replace-match ""))
9151 (setq current ""))
9152 (setq current (nreverse (org-split-string current ":")))
9153 (cond
9154 ((eq onoff 'on)
9155 (setq res t)
9156 (or (member tag current) (push tag current)))
9157 ((eq onoff 'off)
9158 (or (not (member tag current)) (setq current (delete tag current))))
9159 (t (if (member tag current)
9160 (setq current (delete tag current))
9161 (setq res t)
9162 (push tag current))))
9163 (end-of-line 1)
9164 (if current
9165 (progn
9166 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9167 (org-set-tags nil t))
9168 (delete-horizontal-space))
9169 (run-hooks 'org-after-tags-change-hook))
9170 res))
9172 (defun org-align-tags-here (to-col)
9173 ;; Assumes that this is a headline
9174 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9175 (beginning-of-line 1)
9176 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9177 (< pos (match-beginning 2)))
9178 (progn
9179 (setq tags-l (- (match-end 2) (match-beginning 2)))
9180 (goto-char (match-beginning 1))
9181 (insert " ")
9182 (delete-region (point) (1+ (match-beginning 2)))
9183 (setq ncol (max (1+ (current-column))
9184 (1+ col)
9185 (if (> to-col 0)
9186 to-col
9187 (- (abs to-col) tags-l))))
9188 (setq p (point))
9189 (insert (make-string (- ncol (current-column)) ?\ ))
9190 (setq ncol (current-column))
9191 (tabify p (point-at-eol))
9192 (org-move-to-column (min ncol col) t))
9193 (goto-char pos))))
9195 (defun org-set-tags (&optional arg just-align)
9196 "Set the tags for the current headline.
9197 With prefix ARG, realign all tags in headings in the current buffer."
9198 (interactive "P")
9199 (let* ((re (concat "^" outline-regexp))
9200 (current (org-get-tags-string))
9201 (col (current-column))
9202 (org-setting-tags t)
9203 table current-tags inherited-tags ; computed below when needed
9204 tags p0 c0 c1 rpl)
9205 (if arg
9206 (save-excursion
9207 (goto-char (point-min))
9208 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9209 (while (re-search-forward re nil t)
9210 (org-set-tags nil t)
9211 (end-of-line 1)))
9212 (message "All tags realigned to column %d" org-tags-column))
9213 (if just-align
9214 (setq tags current)
9215 ;; Get a new set of tags from the user
9216 (save-excursion
9217 (setq table (or org-tag-alist (org-get-buffer-tags))
9218 org-last-tags-completion-table table
9219 current-tags (org-split-string current ":")
9220 inherited-tags (nreverse
9221 (nthcdr (length current-tags)
9222 (nreverse (org-get-tags-at))))
9223 tags
9224 (if (or (eq t org-use-fast-tag-selection)
9225 (and org-use-fast-tag-selection
9226 (delq nil (mapcar 'cdr table))))
9227 (org-fast-tag-selection
9228 current-tags inherited-tags table
9229 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9230 (let ((org-add-colon-after-tag-completion t))
9231 (org-trim
9232 (org-without-partial-completion
9233 (completing-read "Tags: " 'org-tags-completion-function
9234 nil nil current 'org-tags-history)))))))
9235 (while (string-match "[-+&]+" tags)
9236 ;; No boolean logic, just a list
9237 (setq tags (replace-match ":" t t tags))))
9239 (if (string-match "\\`[\t ]*\\'" tags)
9240 (setq tags "")
9241 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9242 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9244 ;; Insert new tags at the correct column
9245 (beginning-of-line 1)
9246 (cond
9247 ((and (equal current "") (equal tags "")))
9248 ((re-search-forward
9249 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9250 (point-at-eol) t)
9251 (if (equal tags "")
9252 (setq rpl "")
9253 (goto-char (match-beginning 0))
9254 (setq c0 (current-column) p0 (point)
9255 c1 (max (1+ c0) (if (> org-tags-column 0)
9256 org-tags-column
9257 (- (- org-tags-column) (length tags))))
9258 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9259 (replace-match rpl t t)
9260 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9261 tags)
9262 (t (error "Tags alignment failed")))
9263 (org-move-to-column col)
9264 (unless just-align
9265 (run-hooks 'org-after-tags-change-hook)))))
9267 (defun org-change-tag-in-region (beg end tag off)
9268 "Add or remove TAG for each entry in the region.
9269 This works in the agenda, and also in an org-mode buffer."
9270 (interactive
9271 (list (region-beginning) (region-end)
9272 (let ((org-last-tags-completion-table
9273 (if (org-mode-p)
9274 (org-get-buffer-tags)
9275 (org-global-tags-completion-table))))
9276 (completing-read
9277 "Tag: " 'org-tags-completion-function nil nil nil
9278 'org-tags-history))
9279 (progn
9280 (message "[s]et or [r]emove? ")
9281 (equal (read-char-exclusive) ?r))))
9282 (if (fboundp 'deactivate-mark) (deactivate-mark))
9283 (let ((agendap (equal major-mode 'org-agenda-mode))
9284 l1 l2 m buf pos newhead (cnt 0))
9285 (goto-char end)
9286 (setq l2 (1- (org-current-line)))
9287 (goto-char beg)
9288 (setq l1 (org-current-line))
9289 (loop for l from l1 to l2 do
9290 (goto-line l)
9291 (setq m (get-text-property (point) 'org-hd-marker))
9292 (when (or (and (org-mode-p) (org-on-heading-p))
9293 (and agendap m))
9294 (setq buf (if agendap (marker-buffer m) (current-buffer))
9295 pos (if agendap m (point)))
9296 (with-current-buffer buf
9297 (save-excursion
9298 (save-restriction
9299 (goto-char pos)
9300 (setq cnt (1+ cnt))
9301 (org-toggle-tag tag (if off 'off 'on))
9302 (setq newhead (org-get-heading)))))
9303 (and agendap (org-agenda-change-all-lines newhead m))))
9304 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9306 (defun org-tags-completion-function (string predicate &optional flag)
9307 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9308 (confirm (lambda (x) (stringp (car x)))))
9309 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9310 (setq s1 (match-string 1 string)
9311 s2 (match-string 2 string))
9312 (setq s1 "" s2 string))
9313 (cond
9314 ((eq flag nil)
9315 ;; try completion
9316 (setq rtn (try-completion s2 ctable confirm))
9317 (if (stringp rtn)
9318 (setq rtn
9319 (concat s1 s2 (substring rtn (length s2))
9320 (if (and org-add-colon-after-tag-completion
9321 (assoc rtn ctable))
9322 ":" ""))))
9323 rtn)
9324 ((eq flag t)
9325 ;; all-completions
9326 (all-completions s2 ctable confirm)
9328 ((eq flag 'lambda)
9329 ;; exact match?
9330 (assoc s2 ctable)))
9333 (defun org-fast-tag-insert (kwd tags face &optional end)
9334 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9335 (insert (format "%-12s" (concat kwd ":"))
9336 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9337 (or end "")))
9339 (defun org-fast-tag-show-exit (flag)
9340 (save-excursion
9341 (goto-line 3)
9342 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9343 (replace-match ""))
9344 (when flag
9345 (end-of-line 1)
9346 (org-move-to-column (- (window-width) 19) t)
9347 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9349 (defun org-set-current-tags-overlay (current prefix)
9350 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9351 (if (featurep 'xemacs)
9352 (org-overlay-display org-tags-overlay (concat prefix s)
9353 'secondary-selection)
9354 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9355 (org-overlay-display org-tags-overlay (concat prefix s)))))
9357 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9358 "Fast tag selection with single keys.
9359 CURRENT is the current list of tags in the headline, INHERITED is the
9360 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9361 possibly with grouping information. TODO-TABLE is a similar table with
9362 TODO keywords, should these have keys assigned to them.
9363 If the keys are nil, a-z are automatically assigned.
9364 Returns the new tags string, or nil to not change the current settings."
9365 (let* ((fulltable (append table todo-table))
9366 (maxlen (apply 'max (mapcar
9367 (lambda (x)
9368 (if (stringp (car x)) (string-width (car x)) 0))
9369 fulltable)))
9370 (buf (current-buffer))
9371 (expert (eq org-fast-tag-selection-single-key 'expert))
9372 (buffer-tags nil)
9373 (fwidth (+ maxlen 3 1 3))
9374 (ncol (/ (- (window-width) 4) fwidth))
9375 (i-face 'org-done)
9376 (c-face 'org-todo)
9377 tg cnt e c char c1 c2 ntable tbl rtn
9378 ov-start ov-end ov-prefix
9379 (exit-after-next org-fast-tag-selection-single-key)
9380 (done-keywords org-done-keywords)
9381 groups ingroup)
9382 (save-excursion
9383 (beginning-of-line 1)
9384 (if (looking-at
9385 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9386 (setq ov-start (match-beginning 1)
9387 ov-end (match-end 1)
9388 ov-prefix "")
9389 (setq ov-start (1- (point-at-eol))
9390 ov-end (1+ ov-start))
9391 (skip-chars-forward "^\n\r")
9392 (setq ov-prefix
9393 (concat
9394 (buffer-substring (1- (point)) (point))
9395 (if (> (current-column) org-tags-column)
9397 (make-string (- org-tags-column (current-column)) ?\ ))))))
9398 (org-move-overlay org-tags-overlay ov-start ov-end)
9399 (save-window-excursion
9400 (if expert
9401 (set-buffer (get-buffer-create " *Org tags*"))
9402 (delete-other-windows)
9403 (split-window-vertically)
9404 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9405 (erase-buffer)
9406 (org-set-local 'org-done-keywords done-keywords)
9407 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9408 (org-fast-tag-insert "Current" current c-face "\n\n")
9409 (org-fast-tag-show-exit exit-after-next)
9410 (org-set-current-tags-overlay current ov-prefix)
9411 (setq tbl fulltable char ?a cnt 0)
9412 (while (setq e (pop tbl))
9413 (cond
9414 ((equal e '(:startgroup))
9415 (push '() groups) (setq ingroup t)
9416 (when (not (= cnt 0))
9417 (setq cnt 0)
9418 (insert "\n"))
9419 (insert "{ "))
9420 ((equal e '(:endgroup))
9421 (setq ingroup nil cnt 0)
9422 (insert "}\n"))
9424 (setq tg (car e) c2 nil)
9425 (if (cdr e)
9426 (setq c (cdr e))
9427 ;; automatically assign a character.
9428 (setq c1 (string-to-char
9429 (downcase (substring
9430 tg (if (= (string-to-char tg) ?@) 1 0)))))
9431 (if (or (rassoc c1 ntable) (rassoc c1 table))
9432 (while (or (rassoc char ntable) (rassoc char table))
9433 (setq char (1+ char)))
9434 (setq c2 c1))
9435 (setq c (or c2 char)))
9436 (if ingroup (push tg (car groups)))
9437 (setq tg (org-add-props tg nil 'face
9438 (cond
9439 ((not (assoc tg table))
9440 (org-get-todo-face tg))
9441 ((member tg current) c-face)
9442 ((member tg inherited) i-face)
9443 (t nil))))
9444 (if (and (= cnt 0) (not ingroup)) (insert " "))
9445 (insert "[" c "] " tg (make-string
9446 (- fwidth 4 (length tg)) ?\ ))
9447 (push (cons tg c) ntable)
9448 (when (= (setq cnt (1+ cnt)) ncol)
9449 (insert "\n")
9450 (if ingroup (insert " "))
9451 (setq cnt 0)))))
9452 (setq ntable (nreverse ntable))
9453 (insert "\n")
9454 (goto-char (point-min))
9455 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9456 (fit-window-to-buffer))
9457 (setq rtn
9458 (catch 'exit
9459 (while t
9460 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9461 (if groups " [!] no groups" " [!]groups")
9462 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9463 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9464 (cond
9465 ((= c ?\r) (throw 'exit t))
9466 ((= c ?!)
9467 (setq groups (not groups))
9468 (goto-char (point-min))
9469 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9470 ((= c ?\C-c)
9471 (if (not expert)
9472 (org-fast-tag-show-exit
9473 (setq exit-after-next (not exit-after-next)))
9474 (setq expert nil)
9475 (delete-other-windows)
9476 (split-window-vertically)
9477 (org-switch-to-buffer-other-window " *Org tags*")
9478 (and (fboundp 'fit-window-to-buffer)
9479 (fit-window-to-buffer))))
9480 ((or (= c ?\C-g)
9481 (and (= c ?q) (not (rassoc c ntable))))
9482 (org-detach-overlay org-tags-overlay)
9483 (setq quit-flag t))
9484 ((= c ?\ )
9485 (setq current nil)
9486 (if exit-after-next (setq exit-after-next 'now)))
9487 ((= c ?\t)
9488 (condition-case nil
9489 (setq tg (completing-read
9490 "Tag: "
9491 (or buffer-tags
9492 (with-current-buffer buf
9493 (org-get-buffer-tags)))))
9494 (quit (setq tg "")))
9495 (when (string-match "\\S-" tg)
9496 (add-to-list 'buffer-tags (list tg))
9497 (if (member tg current)
9498 (setq current (delete tg current))
9499 (push tg current)))
9500 (if exit-after-next (setq exit-after-next 'now)))
9501 ((setq e (rassoc c todo-table) tg (car e))
9502 (with-current-buffer buf
9503 (save-excursion (org-todo tg)))
9504 (if exit-after-next (setq exit-after-next 'now)))
9505 ((setq e (rassoc c ntable) tg (car e))
9506 (if (member tg current)
9507 (setq current (delete tg current))
9508 (loop for g in groups do
9509 (if (member tg g)
9510 (mapc (lambda (x)
9511 (setq current (delete x current)))
9512 g)))
9513 (push tg current))
9514 (if exit-after-next (setq exit-after-next 'now))))
9516 ;; Create a sorted list
9517 (setq current
9518 (sort current
9519 (lambda (a b)
9520 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9521 (if (eq exit-after-next 'now) (throw 'exit t))
9522 (goto-char (point-min))
9523 (beginning-of-line 2)
9524 (delete-region (point) (point-at-eol))
9525 (org-fast-tag-insert "Current" current c-face)
9526 (org-set-current-tags-overlay current ov-prefix)
9527 (while (re-search-forward
9528 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9529 (setq tg (match-string 1))
9530 (add-text-properties
9531 (match-beginning 1) (match-end 1)
9532 (list 'face
9533 (cond
9534 ((member tg current) c-face)
9535 ((member tg inherited) i-face)
9536 (t (get-text-property (match-beginning 1) 'face))))))
9537 (goto-char (point-min)))))
9538 (org-detach-overlay org-tags-overlay)
9539 (if rtn
9540 (mapconcat 'identity current ":")
9541 nil))))
9543 (defun org-get-tags-string ()
9544 "Get the TAGS string in the current headline."
9545 (unless (org-on-heading-p t)
9546 (error "Not on a heading"))
9547 (save-excursion
9548 (beginning-of-line 1)
9549 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9550 (org-match-string-no-properties 1)
9551 "")))
9553 (defun org-get-tags ()
9554 "Get the list of tags specified in the current headline."
9555 (org-split-string (org-get-tags-string) ":"))
9557 (defun org-get-buffer-tags ()
9558 "Get a table of all tags used in the buffer, for completion."
9559 (let (tags)
9560 (save-excursion
9561 (goto-char (point-min))
9562 (while (re-search-forward
9563 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9564 (when (equal (char-after (point-at-bol 0)) ?*)
9565 (mapc (lambda (x) (add-to-list 'tags x))
9566 (org-split-string (org-match-string-no-properties 1) ":")))))
9567 (mapcar 'list tags)))
9570 ;;;; Properties
9572 ;;; Setting and retrieving properties
9574 (defconst org-special-properties
9575 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9576 "TIMESTAMP" "TIMESTAMP_IA")
9577 "The special properties valid in Org-mode.
9579 These are properties that are not defined in the property drawer,
9580 but in some other way.")
9582 (defconst org-default-properties
9583 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9584 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9585 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE")
9586 "Some properties that are used by Org-mode for various purposes.
9587 Being in this list makes sure that they are offered for completion.")
9589 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9590 "Regular expression matching the first line of a property drawer.")
9592 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9593 "Regular expression matching the first line of a property drawer.")
9595 (defun org-property-action ()
9596 "Do an action on properties."
9597 (interactive)
9598 (let (c)
9599 (org-at-property-p)
9600 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9601 (setq c (read-char-exclusive))
9602 (cond
9603 ((equal c ?s)
9604 (call-interactively 'org-set-property))
9605 ((equal c ?d)
9606 (call-interactively 'org-delete-property))
9607 ((equal c ?D)
9608 (call-interactively 'org-delete-property-globally))
9609 ((equal c ?c)
9610 (call-interactively 'org-compute-property-at-point))
9611 (t (error "No such property action %c" c)))))
9613 (defun org-at-property-p ()
9614 "Is the cursor in a property line?"
9615 ;; FIXME: Does not check if we are actually in the drawer.
9616 ;; FIXME: also returns true on any drawers.....
9617 ;; This is used by C-c C-c for property action.
9618 (save-excursion
9619 (beginning-of-line 1)
9620 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9622 (defun org-get-property-block (&optional beg end force)
9623 "Return the (beg . end) range of the body of the property drawer.
9624 BEG and END can be beginning and end of subtree, if not given
9625 they will be found.
9626 If the drawer does not exist and FORCE is non-nil, create the drawer."
9627 (catch 'exit
9628 (save-excursion
9629 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9630 (end (or end (progn (outline-next-heading) (point)))))
9631 (goto-char beg)
9632 (if (re-search-forward org-property-start-re end t)
9633 (setq beg (1+ (match-end 0)))
9634 (if force
9635 (save-excursion
9636 (org-insert-property-drawer)
9637 (setq end (progn (outline-next-heading) (point))))
9638 (throw 'exit nil))
9639 (goto-char beg)
9640 (if (re-search-forward org-property-start-re end t)
9641 (setq beg (1+ (match-end 0)))))
9642 (if (re-search-forward org-property-end-re end t)
9643 (setq end (match-beginning 0))
9644 (or force (throw 'exit nil))
9645 (goto-char beg)
9646 (setq end beg)
9647 (org-indent-line-function)
9648 (insert ":END:\n"))
9649 (cons beg end)))))
9651 (defun org-entry-properties (&optional pom which)
9652 "Get all properties of the entry at point-or-marker POM.
9653 This includes the TODO keyword, the tags, time strings for deadline,
9654 scheduled, and clocking, and any additional properties defined in the
9655 entry. The return value is an alist, keys may occur multiple times
9656 if the property key was used several times.
9657 POM may also be nil, in which case the current entry is used.
9658 If WHICH is nil or `all', get all properties. If WHICH is
9659 `special' or `standard', only get that subclass."
9660 (setq which (or which 'all))
9661 (org-with-point-at pom
9662 (let ((clockstr (substring org-clock-string 0 -1))
9663 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9664 beg end range props sum-props key value string clocksum)
9665 (save-excursion
9666 (when (condition-case nil (org-back-to-heading t) (error nil))
9667 (setq beg (point))
9668 (setq sum-props (get-text-property (point) 'org-summaries))
9669 (setq clocksum (get-text-property (point) :org-clock-minutes))
9670 (outline-next-heading)
9671 (setq end (point))
9672 (when (memq which '(all special))
9673 ;; Get the special properties, like TODO and tags
9674 (goto-char beg)
9675 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9676 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9677 (when (looking-at org-priority-regexp)
9678 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9679 (when (and (setq value (org-get-tags-string))
9680 (string-match "\\S-" value))
9681 (push (cons "TAGS" value) props))
9682 (when (setq value (org-get-tags-at))
9683 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9684 props))
9685 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9686 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9687 string (if (equal key clockstr)
9688 (org-no-properties
9689 (org-trim
9690 (buffer-substring
9691 (match-beginning 3) (goto-char (point-at-eol)))))
9692 (substring (org-match-string-no-properties 3) 1 -1)))
9693 (unless key
9694 (if (= (char-after (match-beginning 3)) ?\[)
9695 (setq key "TIMESTAMP_IA")
9696 (setq key "TIMESTAMP")))
9697 (when (or (equal key clockstr) (not (assoc key props)))
9698 (push (cons key string) props)))
9702 (when (memq which '(all standard))
9703 ;; Get the standard properties, like :PORP: ...
9704 (setq range (org-get-property-block beg end))
9705 (when range
9706 (goto-char (car range))
9707 (while (re-search-forward
9708 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9709 (cdr range) t)
9710 (setq key (org-match-string-no-properties 1)
9711 value (org-trim (or (org-match-string-no-properties 2) "")))
9712 (unless (member key excluded)
9713 (push (cons key (or value "")) props)))))
9714 (if clocksum
9715 (push (cons "CLOCKSUM"
9716 (org-columns-number-to-string (/ (float clocksum) 60.)
9717 'add_times))
9718 props))
9719 (append sum-props (nreverse props)))))))
9721 (defun org-entry-get (pom property &optional inherit)
9722 "Get value of PROPERTY for entry at point-or-marker POM.
9723 If INHERIT is non-nil and the entry does not have the property,
9724 then also check higher levels of the hierarchy.
9725 If INHERIT is the symbol `selective', use inheritance only if the setting
9726 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9727 If the property is present but empty, the return value is the empty string.
9728 If the property is not present at all, nil is returned."
9729 (org-with-point-at pom
9730 (if (and inherit (if (eq inherit 'selective)
9731 (org-property-inherit-p property)
9733 (org-entry-get-with-inheritance property)
9734 (if (member property org-special-properties)
9735 ;; We need a special property. Use brute force, get all properties.
9736 (cdr (assoc property (org-entry-properties nil 'special)))
9737 (let ((range (org-get-property-block)))
9738 (if (and range
9739 (goto-char (car range))
9740 (re-search-forward
9741 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9742 (cdr range) t))
9743 ;; Found the property, return it.
9744 (if (match-end 1)
9745 (org-match-string-no-properties 1)
9746 "")))))))
9748 (defun org-property-or-variable-value (var &optional inherit)
9749 "Check if there is a property fixing the value of VAR.
9750 If yes, return this value. If not, return the current value of the variable."
9751 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9752 (if (and prop (stringp prop) (string-match "\\S-" prop))
9753 (read prop)
9754 (symbol-value var))))
9756 (defun org-entry-delete (pom property)
9757 "Delete the property PROPERTY from entry at point-or-marker POM."
9758 (org-with-point-at pom
9759 (if (member property org-special-properties)
9760 nil ; cannot delete these properties.
9761 (let ((range (org-get-property-block)))
9762 (if (and range
9763 (goto-char (car range))
9764 (re-search-forward
9765 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9766 (cdr range) t))
9767 (progn
9768 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9770 nil)))))
9772 ;; Multi-values properties are properties that contain multiple values
9773 ;; These values are assumed to be single words, separated by whitespace.
9774 (defun org-entry-add-to-multivalued-property (pom property value)
9775 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9776 (let* ((old (org-entry-get pom property))
9777 (values (and old (org-split-string old "[ \t]"))))
9778 (unless (member value values)
9779 (setq values (cons value values))
9780 (org-entry-put pom property
9781 (mapconcat 'identity values " ")))))
9783 (defun org-entry-remove-from-multivalued-property (pom property value)
9784 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9785 (let* ((old (org-entry-get pom property))
9786 (values (and old (org-split-string old "[ \t]"))))
9787 (when (member value values)
9788 (setq values (delete value values))
9789 (org-entry-put pom property
9790 (mapconcat 'identity values " ")))))
9792 (defun org-entry-member-in-multivalued-property (pom property value)
9793 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9794 (let* ((old (org-entry-get pom property))
9795 (values (and old (org-split-string old "[ \t]"))))
9796 (member value values)))
9798 (defvar org-entry-property-inherited-from (make-marker))
9800 (defun org-entry-get-with-inheritance (property)
9801 "Get entry property, and search higher levels if not present."
9802 (let (tmp)
9803 (save-excursion
9804 (save-restriction
9805 (widen)
9806 (catch 'ex
9807 (while t
9808 (when (setq tmp (org-entry-get nil property))
9809 (org-back-to-heading t)
9810 (move-marker org-entry-property-inherited-from (point))
9811 (throw 'ex tmp))
9812 (or (org-up-heading-safe) (throw 'ex nil)))))
9813 (or tmp
9814 (cdr (assoc property org-local-properties))
9815 (cdr (assoc property org-global-properties))
9816 (cdr (assoc property org-global-properties-fixed))))))
9818 (defun org-entry-put (pom property value)
9819 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9820 (org-with-point-at pom
9821 (org-back-to-heading t)
9822 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9823 range)
9824 (cond
9825 ((equal property "TODO")
9826 (when (and (stringp value) (string-match "\\S-" value)
9827 (not (member value org-todo-keywords-1)))
9828 (error "\"%s\" is not a valid TODO state" value))
9829 (if (or (not value)
9830 (not (string-match "\\S-" value)))
9831 (setq value 'none))
9832 (org-todo value)
9833 (org-set-tags nil 'align))
9834 ((equal property "PRIORITY")
9835 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9836 (string-to-char value) ?\ ))
9837 (org-set-tags nil 'align))
9838 ((equal property "SCHEDULED")
9839 (if (re-search-forward org-scheduled-time-regexp end t)
9840 (cond
9841 ((eq value 'earlier) (org-timestamp-change -1 'day))
9842 ((eq value 'later) (org-timestamp-change 1 'day))
9843 (t (call-interactively 'org-schedule)))
9844 (call-interactively 'org-schedule)))
9845 ((equal property "DEADLINE")
9846 (if (re-search-forward org-deadline-time-regexp end t)
9847 (cond
9848 ((eq value 'earlier) (org-timestamp-change -1 'day))
9849 ((eq value 'later) (org-timestamp-change 1 'day))
9850 (t (call-interactively 'org-deadline)))
9851 (call-interactively 'org-deadline)))
9852 ((member property org-special-properties)
9853 (error "The %s property can not yet be set with `org-entry-put'"
9854 property))
9855 (t ; a non-special property
9856 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9857 (setq range (org-get-property-block beg end 'force))
9858 (goto-char (car range))
9859 (if (re-search-forward
9860 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9861 (progn
9862 (delete-region (match-beginning 1) (match-end 1))
9863 (goto-char (match-beginning 1)))
9864 (goto-char (cdr range))
9865 (insert "\n")
9866 (backward-char 1)
9867 (org-indent-line-function)
9868 (insert ":" property ":"))
9869 (and value (insert " " value))
9870 (org-indent-line-function)))))))
9872 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9873 "Get all property keys in the current buffer.
9874 With INCLUDE-SPECIALS, also list the special properties that relect things
9875 like tags and TODO state.
9876 With INCLUDE-DEFAULTS, also include properties that has special meaning
9877 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9878 With INCLUDE-COLUMNS, also include property names given in COLUMN
9879 formats in the current buffer."
9880 (let (rtn range cfmt cols s p)
9881 (save-excursion
9882 (save-restriction
9883 (widen)
9884 (goto-char (point-min))
9885 (while (re-search-forward org-property-start-re nil t)
9886 (setq range (org-get-property-block))
9887 (goto-char (car range))
9888 (while (re-search-forward
9889 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9890 (cdr range) t)
9891 (add-to-list 'rtn (org-match-string-no-properties 1)))
9892 (outline-next-heading))))
9894 (when include-specials
9895 (setq rtn (append org-special-properties rtn)))
9897 (when include-defaults
9898 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9900 (when include-columns
9901 (save-excursion
9902 (save-restriction
9903 (widen)
9904 (goto-char (point-min))
9905 (while (re-search-forward
9906 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9907 nil t)
9908 (setq cfmt (match-string 2) s 0)
9909 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9910 cfmt s)
9911 (setq s (match-end 0)
9912 p (match-string 1 cfmt))
9913 (unless (or (equal p "ITEM")
9914 (member p org-special-properties))
9915 (add-to-list 'rtn (match-string 1 cfmt))))))))
9917 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9919 (defun org-property-values (key)
9920 "Return a list of all values of property KEY."
9921 (save-excursion
9922 (save-restriction
9923 (widen)
9924 (goto-char (point-min))
9925 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9926 values)
9927 (while (re-search-forward re nil t)
9928 (add-to-list 'values (org-trim (match-string 1))))
9929 (delete "" values)))))
9931 (defun org-insert-property-drawer ()
9932 "Insert a property drawer into the current entry."
9933 (interactive)
9934 (org-back-to-heading t)
9935 (looking-at outline-regexp)
9936 (let ((indent (- (match-end 0)(match-beginning 0)))
9937 (beg (point))
9938 (re (concat "^[ \t]*" org-keyword-time-regexp))
9939 end hiddenp)
9940 (outline-next-heading)
9941 (setq end (point))
9942 (goto-char beg)
9943 (while (re-search-forward re end t))
9944 (setq hiddenp (org-invisible-p))
9945 (end-of-line 1)
9946 (and (equal (char-after) ?\n) (forward-char 1))
9947 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9948 (beginning-of-line 2))
9949 (org-skip-over-state-notes)
9950 (skip-chars-backward " \t\n\r")
9951 (if (eq (char-before) ?*) (forward-char 1))
9952 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9953 (beginning-of-line 0)
9954 (org-indent-to-column indent)
9955 (beginning-of-line 2)
9956 (org-indent-to-column indent)
9957 (beginning-of-line 0)
9958 (if hiddenp
9959 (save-excursion
9960 (org-back-to-heading t)
9961 (hide-entry))
9962 (org-flag-drawer t))))
9964 (defun org-set-property (property value)
9965 "In the current entry, set PROPERTY to VALUE.
9966 When called interactively, this will prompt for a property name, offering
9967 completion on existing and default properties. And then it will prompt
9968 for a value, offering competion either on allowed values (via an inherited
9969 xxx_ALL property) or on existing values in other instances of this property
9970 in the current file."
9971 (interactive
9972 (let* ((completion-ignore-case t)
9973 (keys (org-buffer-property-keys nil t t))
9974 (prop0 (completing-read "Property: " (mapcar 'list keys)))
9975 (prop (if (member prop0 keys)
9976 prop0
9977 (or (cdr (assoc (downcase prop0)
9978 (mapcar (lambda (x) (cons (downcase x) x))
9979 keys)))
9980 prop0)))
9981 (cur (org-entry-get nil prop))
9982 (allowed (org-property-get-allowed-values nil prop 'table))
9983 (existing (mapcar 'list (org-property-values prop)))
9984 (val (if allowed
9985 (org-completing-read "Value: " allowed nil 'req-match)
9986 (org-completing-read
9987 (concat "Value" (if (and cur (string-match "\\S-" cur))
9988 (concat "[" cur "]") "")
9989 ": ")
9990 existing nil nil "" nil cur))))
9991 (list prop (if (equal val "") cur val))))
9992 (unless (equal (org-entry-get nil property) value)
9993 (org-entry-put nil property value)))
9995 (defun org-delete-property (property)
9996 "In the current entry, delete PROPERTY."
9997 (interactive
9998 (let* ((completion-ignore-case t)
9999 (prop (completing-read
10000 "Property: " (org-entry-properties nil 'standard))))
10001 (list prop)))
10002 (message "Property %s %s" property
10003 (if (org-entry-delete nil property)
10004 "deleted"
10005 "was not present in the entry")))
10007 (defun org-delete-property-globally (property)
10008 "Remove PROPERTY globally, from all entries."
10009 (interactive
10010 (let* ((completion-ignore-case t)
10011 (prop (completing-read
10012 "Globally remove property: "
10013 (mapcar 'list (org-buffer-property-keys)))))
10014 (list prop)))
10015 (save-excursion
10016 (save-restriction
10017 (widen)
10018 (goto-char (point-min))
10019 (let ((cnt 0))
10020 (while (re-search-forward
10021 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10022 nil t)
10023 (setq cnt (1+ cnt))
10024 (replace-match ""))
10025 (message "Property \"%s\" removed from %d entries" property cnt)))))
10027 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10029 (defun org-compute-property-at-point ()
10030 "Compute the property at point.
10031 This looks for an enclosing column format, extracts the operator and
10032 then applies it to the proerty in the column format's scope."
10033 (interactive)
10034 (unless (org-at-property-p)
10035 (error "Not at a property"))
10036 (let ((prop (org-match-string-no-properties 2)))
10037 (org-columns-get-format-and-top-level)
10038 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10039 (error "No operator defined for property %s" prop))
10040 (org-columns-compute prop)))
10042 (defun org-property-get-allowed-values (pom property &optional table)
10043 "Get allowed values for the property PROPERTY.
10044 When TABLE is non-nil, return an alist that can directly be used for
10045 completion."
10046 (let (vals)
10047 (cond
10048 ((equal property "TODO")
10049 (setq vals (org-with-point-at pom
10050 (append org-todo-keywords-1 '("")))))
10051 ((equal property "PRIORITY")
10052 (let ((n org-lowest-priority))
10053 (while (>= n org-highest-priority)
10054 (push (char-to-string n) vals)
10055 (setq n (1- n)))))
10056 ((member property org-special-properties))
10058 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10060 (when (and vals (string-match "\\S-" vals))
10061 (setq vals (car (read-from-string (concat "(" vals ")"))))
10062 (setq vals (mapcar (lambda (x)
10063 (cond ((stringp x) x)
10064 ((numberp x) (number-to-string x))
10065 ((symbolp x) (symbol-name x))
10066 (t "???")))
10067 vals)))))
10068 (if table (mapcar 'list vals) vals)))
10070 (defun org-property-previous-allowed-value (&optional previous)
10071 "Switch to the next allowed value for this property."
10072 (interactive)
10073 (org-property-next-allowed-value t))
10075 (defun org-property-next-allowed-value (&optional previous)
10076 "Switch to the next allowed value for this property."
10077 (interactive)
10078 (unless (org-at-property-p)
10079 (error "Not at a property"))
10080 (let* ((key (match-string 2))
10081 (value (match-string 3))
10082 (allowed (or (org-property-get-allowed-values (point) key)
10083 (and (member value '("[ ]" "[-]" "[X]"))
10084 '("[ ]" "[X]"))))
10085 nval)
10086 (unless allowed
10087 (error "Allowed values for this property have not been defined"))
10088 (if previous (setq allowed (reverse allowed)))
10089 (if (member value allowed)
10090 (setq nval (car (cdr (member value allowed)))))
10091 (setq nval (or nval (car allowed)))
10092 (if (equal nval value)
10093 (error "Only one allowed value for this property"))
10094 (org-at-property-p)
10095 (replace-match (concat " :" key ": " nval) t t)
10096 (org-indent-line-function)
10097 (beginning-of-line 1)
10098 (skip-chars-forward " \t")))
10100 (defun org-find-entry-with-id (ident)
10101 "Locate the entry that contains the ID property with exact value IDENT.
10102 IDENT can be a string, a symbol or a number, this function will search for
10103 the string representation of it.
10104 Return the position where this entry starts, or nil if there is no such entry."
10105 (let ((id (cond
10106 ((stringp ident) ident)
10107 ((symbol-name ident) (symbol-name ident))
10108 ((numberp ident) (number-to-string ident))
10109 (t (error "IDENT %s must be a string, symbol or number" ident))))
10110 (case-fold-search nil))
10111 (save-excursion
10112 (save-restriction
10113 (widen)
10114 (goto-char (point-min))
10115 (when (re-search-forward
10116 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10117 nil t)
10118 (org-back-to-heading)
10119 (point))))))
10121 ;;;; Timestamps
10123 (defvar org-last-changed-timestamp nil)
10124 (defvar org-time-was-given) ; dynamically scoped parameter
10125 (defvar org-end-time-was-given) ; dynamically scoped parameter
10126 (defvar org-ts-what) ; dynamically scoped parameter
10128 (defun org-time-stamp (arg)
10129 "Prompt for a date/time and insert a time stamp.
10130 If the user specifies a time like HH:MM, or if this command is called
10131 with a prefix argument, the time stamp will contain date and time.
10132 Otherwise, only the date will be included. All parts of a date not
10133 specified by the user will be filled in from the current date/time.
10134 So if you press just return without typing anything, the time stamp
10135 will represent the current date/time. If there is already a timestamp
10136 at the cursor, it will be modified."
10137 (interactive "P")
10138 (let* ((ts nil)
10139 (default-time
10140 ;; Default time is either today, or, when entering a range,
10141 ;; the range start.
10142 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10143 (save-excursion
10144 (re-search-backward
10145 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10146 (- (point) 20) t)))
10147 (apply 'encode-time (org-parse-time-string (match-string 1)))
10148 (current-time)))
10149 (default-input (and ts (org-get-compact-tod ts)))
10150 org-time-was-given org-end-time-was-given time)
10151 (cond
10152 ((and (org-at-timestamp-p)
10153 (eq last-command 'org-time-stamp)
10154 (eq this-command 'org-time-stamp))
10155 (insert "--")
10156 (setq time (let ((this-command this-command))
10157 (org-read-date arg 'totime nil nil default-time default-input)))
10158 (org-insert-time-stamp time (or org-time-was-given arg)))
10159 ((org-at-timestamp-p)
10160 (setq time (let ((this-command this-command))
10161 (org-read-date arg 'totime nil nil default-time default-input)))
10162 (when (org-at-timestamp-p) ; just to get the match data
10163 (replace-match "")
10164 (setq org-last-changed-timestamp
10165 (org-insert-time-stamp
10166 time (or org-time-was-given arg)
10167 nil nil nil (list org-end-time-was-given))))
10168 (message "Timestamp updated"))
10170 (setq time (let ((this-command this-command))
10171 (org-read-date arg 'totime nil nil default-time default-input)))
10172 (org-insert-time-stamp time (or org-time-was-given arg)
10173 nil nil nil (list org-end-time-was-given))))))
10175 ;; FIXME: can we use this for something else, like computing time differences?
10176 (defun org-get-compact-tod (s)
10177 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10178 (let* ((t1 (match-string 1 s))
10179 (h1 (string-to-number (match-string 2 s)))
10180 (m1 (string-to-number (match-string 3 s)))
10181 (t2 (and (match-end 4) (match-string 5 s)))
10182 (h2 (and t2 (string-to-number (match-string 6 s))))
10183 (m2 (and t2 (string-to-number (match-string 7 s))))
10184 dh dm)
10185 (if (not t2)
10187 (setq dh (- h2 h1) dm (- m2 m1))
10188 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10189 (concat t1 "+" (number-to-string dh)
10190 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10192 (defun org-time-stamp-inactive (&optional arg)
10193 "Insert an inactive time stamp.
10194 An inactive time stamp is enclosed in square brackets instead of angle
10195 brackets. It is inactive in the sense that it does not trigger agenda entries,
10196 does not link to the calendar and cannot be changed with the S-cursor keys.
10197 So these are more for recording a certain time/date."
10198 (interactive "P")
10199 (let (org-time-was-given org-end-time-was-given time)
10200 (setq time (org-read-date arg 'totime))
10201 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10202 nil nil (list org-end-time-was-given))))
10204 (defvar org-date-ovl (org-make-overlay 1 1))
10205 (org-overlay-put org-date-ovl 'face 'org-warning)
10206 (org-detach-overlay org-date-ovl)
10208 (defvar org-ans1) ; dynamically scoped parameter
10209 (defvar org-ans2) ; dynamically scoped parameter
10211 (defvar org-plain-time-of-day-regexp) ; defined below
10213 (defvar org-read-date-overlay nil)
10214 (defvar org-dcst nil) ; dynamically scoped
10216 (defun org-read-date (&optional with-time to-time from-string prompt
10217 default-time default-input)
10218 "Read a date, possibly a time, and make things smooth for the user.
10219 The prompt will suggest to enter an ISO date, but you can also enter anything
10220 which will at least partially be understood by `parse-time-string'.
10221 Unrecognized parts of the date will default to the current day, month, year,
10222 hour and minute. If this command is called to replace a timestamp at point,
10223 of to enter the second timestamp of a range, the default time is taken from the
10224 existing stamp. For example,
10225 3-2-5 --> 2003-02-05
10226 feb 15 --> currentyear-02-15
10227 sep 12 9 --> 2009-09-12
10228 12:45 --> today 12:45
10229 22 sept 0:34 --> currentyear-09-22 0:34
10230 12 --> currentyear-currentmonth-12
10231 Fri --> nearest Friday (today or later)
10232 etc.
10234 Furthermore you can specify a relative date by giving, as the *first* thing
10235 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10236 change in days weeks, months, years.
10237 With a single plus or minus, the date is relative to today. With a double
10238 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10239 +4d --> four days from today
10240 +4 --> same as above
10241 +2w --> two weeks from today
10242 ++5 --> five days from default date
10244 The function understands only English month and weekday abbreviations,
10245 but this can be configured with the variables `parse-time-months' and
10246 `parse-time-weekdays'.
10248 While prompting, a calendar is popped up - you can also select the
10249 date with the mouse (button 1). The calendar shows a period of three
10250 months. To scroll it to other months, use the keys `>' and `<'.
10251 If you don't like the calendar, turn it off with
10252 \(setq org-read-date-popup-calendar nil)
10254 With optional argument TO-TIME, the date will immediately be converted
10255 to an internal time.
10256 With an optional argument WITH-TIME, the prompt will suggest to also
10257 insert a time. Note that when WITH-TIME is not set, you can still
10258 enter a time, and this function will inform the calling routine about
10259 this change. The calling routine may then choose to change the format
10260 used to insert the time stamp into the buffer to include the time.
10261 With optional argument FROM-STRING, read from this string instead from
10262 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10263 the time/date that is used for everything that is not specified by the
10264 user."
10265 (require 'parse-time)
10266 (let* ((org-time-stamp-rounding-minutes
10267 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10268 (org-dcst org-display-custom-times)
10269 (ct (org-current-time))
10270 (def (or default-time ct))
10271 (defdecode (decode-time def))
10272 (dummy (progn
10273 (when (< (nth 2 defdecode) org-extend-today-until)
10274 (setcar (nthcdr 2 defdecode) -1)
10275 (setcar (nthcdr 1 defdecode) 59)
10276 (setq def (apply 'encode-time defdecode)
10277 defdecode (decode-time def)))))
10278 (calendar-move-hook nil)
10279 (calendar-view-diary-initially-flag nil)
10280 (view-diary-entries-initially nil)
10281 (calendar-view-holidays-initially-flag nil)
10282 (view-calendar-holidays-initially nil)
10283 (timestr (format-time-string
10284 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10285 (prompt (concat (if prompt (concat prompt " ") "")
10286 (format "Date+time [%s]: " timestr)))
10287 ans (org-ans0 "") org-ans1 org-ans2 final)
10289 (cond
10290 (from-string (setq ans from-string))
10291 (org-read-date-popup-calendar
10292 (save-excursion
10293 (save-window-excursion
10294 (calendar)
10295 (calendar-forward-day (- (time-to-days def)
10296 (calendar-absolute-from-gregorian
10297 (calendar-current-date))))
10298 (org-eval-in-calendar nil t)
10299 (let* ((old-map (current-local-map))
10300 (map (copy-keymap calendar-mode-map))
10301 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10302 (org-defkey map (kbd "RET") 'org-calendar-select)
10303 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10304 'org-calendar-select-mouse)
10305 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10306 'org-calendar-select-mouse)
10307 (org-defkey minibuffer-local-map [(meta shift left)]
10308 (lambda () (interactive)
10309 (org-eval-in-calendar '(calendar-backward-month 1))))
10310 (org-defkey minibuffer-local-map [(meta shift right)]
10311 (lambda () (interactive)
10312 (org-eval-in-calendar '(calendar-forward-month 1))))
10313 (org-defkey minibuffer-local-map [(meta shift up)]
10314 (lambda () (interactive)
10315 (org-eval-in-calendar '(calendar-backward-year 1))))
10316 (org-defkey minibuffer-local-map [(meta shift down)]
10317 (lambda () (interactive)
10318 (org-eval-in-calendar '(calendar-forward-year 1))))
10319 (org-defkey minibuffer-local-map [(shift up)]
10320 (lambda () (interactive)
10321 (org-eval-in-calendar '(calendar-backward-week 1))))
10322 (org-defkey minibuffer-local-map [(shift down)]
10323 (lambda () (interactive)
10324 (org-eval-in-calendar '(calendar-forward-week 1))))
10325 (org-defkey minibuffer-local-map [(shift left)]
10326 (lambda () (interactive)
10327 (org-eval-in-calendar '(calendar-backward-day 1))))
10328 (org-defkey minibuffer-local-map [(shift right)]
10329 (lambda () (interactive)
10330 (org-eval-in-calendar '(calendar-forward-day 1))))
10331 (org-defkey minibuffer-local-map ">"
10332 (lambda () (interactive)
10333 (org-eval-in-calendar '(scroll-calendar-left 1))))
10334 (org-defkey minibuffer-local-map "<"
10335 (lambda () (interactive)
10336 (org-eval-in-calendar '(scroll-calendar-right 1))))
10337 (unwind-protect
10338 (progn
10339 (use-local-map map)
10340 (add-hook 'post-command-hook 'org-read-date-display)
10341 (setq org-ans0 (read-string prompt default-input nil nil))
10342 ;; org-ans0: from prompt
10343 ;; org-ans1: from mouse click
10344 ;; org-ans2: from calendar motion
10345 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10346 (remove-hook 'post-command-hook 'org-read-date-display)
10347 (use-local-map old-map)
10348 (when org-read-date-overlay
10349 (org-delete-overlay org-read-date-overlay)
10350 (setq org-read-date-overlay nil)))))))
10352 (t ; Naked prompt only
10353 (unwind-protect
10354 (setq ans (read-string prompt default-input nil timestr))
10355 (when org-read-date-overlay
10356 (org-delete-overlay org-read-date-overlay)
10357 (setq org-read-date-overlay nil)))))
10359 (setq final (org-read-date-analyze ans def defdecode))
10361 (if to-time
10362 (apply 'encode-time final)
10363 (if (and (boundp 'org-time-was-given) org-time-was-given)
10364 (format "%04d-%02d-%02d %02d:%02d"
10365 (nth 5 final) (nth 4 final) (nth 3 final)
10366 (nth 2 final) (nth 1 final))
10367 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10368 (defvar def)
10369 (defvar defdecode)
10370 (defvar with-time)
10371 (defun org-read-date-display ()
10372 "Display the currrent date prompt interpretation in the minibuffer."
10373 (when org-read-date-display-live
10374 (when org-read-date-overlay
10375 (org-delete-overlay org-read-date-overlay))
10376 (let ((p (point)))
10377 (end-of-line 1)
10378 (while (not (equal (buffer-substring
10379 (max (point-min) (- (point) 4)) (point))
10380 " "))
10381 (insert " "))
10382 (goto-char p))
10383 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10384 " " (or org-ans1 org-ans2)))
10385 (org-end-time-was-given nil)
10386 (f (org-read-date-analyze ans def defdecode))
10387 (fmts (if org-dcst
10388 org-time-stamp-custom-formats
10389 org-time-stamp-formats))
10390 (fmt (if (or with-time
10391 (and (boundp 'org-time-was-given) org-time-was-given))
10392 (cdr fmts)
10393 (car fmts)))
10394 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10395 (when (and org-end-time-was-given
10396 (string-match org-plain-time-of-day-regexp txt))
10397 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10398 org-end-time-was-given
10399 (substring txt (match-end 0)))))
10400 (setq org-read-date-overlay
10401 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10402 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10404 (defun org-read-date-analyze (ans def defdecode)
10405 "Analyze the combined answer of the date prompt."
10406 ;; FIXME: cleanup and comment
10407 (let (delta deltan deltaw deltadef year month day
10408 hour minute second wday pm h2 m2 tl wday1
10409 iso-year iso-weekday iso-week iso-year iso-date)
10411 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10412 (setq ans "+0"))
10414 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10415 (setq ans (replace-match "" t t ans)
10416 deltan (car delta)
10417 deltaw (nth 1 delta)
10418 deltadef (nth 2 delta)))
10420 ;; Check if there is an iso week date in there
10421 ;; If yes, sore the info and ostpone interpreting it until the rest
10422 ;; of the parsing is done
10423 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10424 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10425 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10426 iso-week (string-to-number (match-string 2 ans)))
10427 (setq ans (replace-match "" t t ans)))
10429 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10430 (when (string-match
10431 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10432 (setq year (if (match-end 2)
10433 (string-to-number (match-string 2 ans))
10434 (string-to-number (format-time-string "%Y")))
10435 month (string-to-number (match-string 3 ans))
10436 day (string-to-number (match-string 4 ans)))
10437 (if (< year 100) (setq year (+ 2000 year)))
10438 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10439 t nil ans)))
10440 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10441 ;; If there is a time with am/pm, and *no* time without it, we convert
10442 ;; so that matching will be successful.
10443 (loop for i from 1 to 2 do ; twice, for end time as well
10444 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10445 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10446 (setq hour (string-to-number (match-string 1 ans))
10447 minute (if (match-end 3)
10448 (string-to-number (match-string 3 ans))
10450 pm (equal ?p
10451 (string-to-char (downcase (match-string 4 ans)))))
10452 (if (and (= hour 12) (not pm))
10453 (setq hour 0)
10454 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10455 (setq ans (replace-match (format "%02d:%02d" hour minute)
10456 t t ans))))
10458 ;; Check if a time range is given as a duration
10459 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10460 (setq hour (string-to-number (match-string 1 ans))
10461 h2 (+ hour (string-to-number (match-string 3 ans)))
10462 minute (string-to-number (match-string 2 ans))
10463 m2 (+ minute (if (match-end 5) (string-to-number
10464 (match-string 5 ans))0)))
10465 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10466 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10467 t t ans)))
10469 ;; Check if there is a time range
10470 (when (boundp 'org-end-time-was-given)
10471 (setq org-time-was-given nil)
10472 (when (and (string-match org-plain-time-of-day-regexp ans)
10473 (match-end 8))
10474 (setq org-end-time-was-given (match-string 8 ans))
10475 (setq ans (concat (substring ans 0 (match-beginning 7))
10476 (substring ans (match-end 7))))))
10478 (setq tl (parse-time-string ans)
10479 day (or (nth 3 tl) (nth 3 defdecode))
10480 month (or (nth 4 tl)
10481 (if (and org-read-date-prefer-future
10482 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10483 (1+ (nth 4 defdecode))
10484 (nth 4 defdecode)))
10485 year (or (nth 5 tl)
10486 (if (and org-read-date-prefer-future
10487 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10488 (1+ (nth 5 defdecode))
10489 (nth 5 defdecode)))
10490 hour (or (nth 2 tl) (nth 2 defdecode))
10491 minute (or (nth 1 tl) (nth 1 defdecode))
10492 second (or (nth 0 tl) 0)
10493 wday (nth 6 tl))
10495 ;; Special date definitions below
10496 (cond
10497 (iso-week
10498 ;; There was an iso week
10499 (setq year (or iso-year year)
10500 day (or iso-weekday wday 1)
10501 wday nil ; to make sure that the trigger below does not match
10502 iso-date (calendar-gregorian-from-absolute
10503 (calendar-absolute-from-iso
10504 (list iso-week day year))))
10505 ; FIXME: Should we also push ISO weeks into the future?
10506 ; (when (and org-read-date-prefer-future
10507 ; (not iso-year)
10508 ; (< (calendar-absolute-from-gregorian iso-date)
10509 ; (time-to-days (current-time))))
10510 ; (setq year (1+ year)
10511 ; iso-date (calendar-gregorian-from-absolute
10512 ; (calendar-absolute-from-iso
10513 ; (list iso-week day year)))))
10514 (setq month (car iso-date)
10515 year (nth 2 iso-date)
10516 day (nth 1 iso-date)))
10517 (deltan
10518 (unless deltadef
10519 (let ((now (decode-time (current-time))))
10520 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10521 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10522 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10523 ((equal deltaw "m") (setq month (+ month deltan)))
10524 ((equal deltaw "y") (setq year (+ year deltan)))))
10525 ((and wday (not (nth 3 tl)))
10526 ;; Weekday was given, but no day, so pick that day in the week
10527 ;; on or after the derived date.
10528 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10529 (unless (equal wday wday1)
10530 (setq day (+ day (% (- wday wday1 -7) 7))))))
10531 (if (and (boundp 'org-time-was-given)
10532 (nth 2 tl))
10533 (setq org-time-was-given t))
10534 (if (< year 100) (setq year (+ 2000 year)))
10535 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10536 (list second minute hour day month year)))
10538 (defvar parse-time-weekdays)
10540 (defun org-read-date-get-relative (s today default)
10541 "Check string S for special relative date string.
10542 TODAY and DEFAULT are internal times, for today and for a default.
10543 Return shift list (N what def-flag)
10544 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10545 N is the number of WHATs to shift.
10546 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10547 the DEFAULT date rather than TODAY."
10548 (when (and
10549 (string-match
10550 (concat
10551 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10552 "\\([0-9]+\\)?"
10553 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10554 "\\([ \t]\\|$\\)") s)
10555 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10556 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10557 (string-to-char (substring (match-string 1 s) -1))
10558 ?+))
10559 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10560 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10561 (what (if (match-end 3) (match-string 3 s) "d"))
10562 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10563 (date (if rel default today))
10564 (wday (nth 6 (decode-time date)))
10565 delta)
10566 (if wday1
10567 (progn
10568 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10569 (if (= dir ?-) (setq delta (- delta 7)))
10570 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10571 (list delta "d" rel))
10572 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10574 (defun org-eval-in-calendar (form &optional keepdate)
10575 "Eval FORM in the calendar window and return to current window.
10576 Also, store the cursor date in variable org-ans2."
10577 (let ((sw (selected-window)))
10578 (select-window (get-buffer-window "*Calendar*"))
10579 (eval form)
10580 (when (and (not keepdate) (calendar-cursor-to-date))
10581 (let* ((date (calendar-cursor-to-date))
10582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10583 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10584 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10585 (select-window sw)))
10587 ; ;; Update the prompt to show new default date
10588 ; (save-excursion
10589 ; (goto-char (point-min))
10590 ; (when (and org-ans2
10591 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10592 ; (get-text-property (match-end 0) 'field))
10593 ; (let ((inhibit-read-only t))
10594 ; (replace-match (concat "[" org-ans2 "]") t t)
10595 ; (add-text-properties (point-min) (1+ (match-end 0))
10596 ; (text-properties-at (1+ (point-min)))))))))
10598 (defun org-calendar-select ()
10599 "Return to `org-read-date' with the date currently selected.
10600 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10601 (interactive)
10602 (when (calendar-cursor-to-date)
10603 (let* ((date (calendar-cursor-to-date))
10604 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10605 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10606 (if (active-minibuffer-window) (exit-minibuffer))))
10608 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10609 "Insert a date stamp for the date given by the internal TIME.
10610 WITH-HM means, use the stamp format that includes the time of the day.
10611 INACTIVE means use square brackets instead of angular ones, so that the
10612 stamp will not contribute to the agenda.
10613 PRE and POST are optional strings to be inserted before and after the
10614 stamp.
10615 The command returns the inserted time stamp."
10616 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10617 stamp)
10618 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10619 (insert-before-markers (or pre ""))
10620 (insert-before-markers (setq stamp (format-time-string fmt time)))
10621 (when (listp extra)
10622 (setq extra (car extra))
10623 (if (and (stringp extra)
10624 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10625 (setq extra (format "-%02d:%02d"
10626 (string-to-number (match-string 1 extra))
10627 (string-to-number (match-string 2 extra))))
10628 (setq extra nil)))
10629 (when extra
10630 (backward-char 1)
10631 (insert-before-markers extra)
10632 (forward-char 1))
10633 (insert-before-markers (or post ""))
10634 stamp))
10636 (defun org-toggle-time-stamp-overlays ()
10637 "Toggle the use of custom time stamp formats."
10638 (interactive)
10639 (setq org-display-custom-times (not org-display-custom-times))
10640 (unless org-display-custom-times
10641 (let ((p (point-min)) (bmp (buffer-modified-p)))
10642 (while (setq p (next-single-property-change p 'display))
10643 (if (and (get-text-property p 'display)
10644 (eq (get-text-property p 'face) 'org-date))
10645 (remove-text-properties
10646 p (setq p (next-single-property-change p 'display))
10647 '(display t))))
10648 (set-buffer-modified-p bmp)))
10649 (if (featurep 'xemacs)
10650 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10651 (org-restart-font-lock)
10652 (setq org-table-may-need-update t)
10653 (if org-display-custom-times
10654 (message "Time stamps are overlayed with custom format")
10655 (message "Time stamp overlays removed")))
10657 (defun org-display-custom-time (beg end)
10658 "Overlay modified time stamp format over timestamp between BEG and END."
10659 (let* ((ts (buffer-substring beg end))
10660 t1 w1 with-hm tf time str w2 (off 0))
10661 (save-match-data
10662 (setq t1 (org-parse-time-string ts t))
10663 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10664 (setq off (- (match-end 0) (match-beginning 0)))))
10665 (setq end (- end off))
10666 (setq w1 (- end beg)
10667 with-hm (and (nth 1 t1) (nth 2 t1))
10668 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10669 time (org-fix-decoded-time t1)
10670 str (org-add-props
10671 (format-time-string
10672 (substring tf 1 -1) (apply 'encode-time time))
10673 nil 'mouse-face 'highlight)
10674 w2 (length str))
10675 (if (not (= w2 w1))
10676 (add-text-properties (1+ beg) (+ 2 beg)
10677 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10678 (if (featurep 'xemacs)
10679 (progn
10680 (put-text-property beg end 'invisible t)
10681 (put-text-property beg end 'end-glyph (make-glyph str)))
10682 (put-text-property beg end 'display str))))
10684 (defun org-translate-time (string)
10685 "Translate all timestamps in STRING to custom format.
10686 But do this only if the variable `org-display-custom-times' is set."
10687 (when org-display-custom-times
10688 (save-match-data
10689 (let* ((start 0)
10690 (re org-ts-regexp-both)
10691 t1 with-hm inactive tf time str beg end)
10692 (while (setq start (string-match re string start))
10693 (setq beg (match-beginning 0)
10694 end (match-end 0)
10695 t1 (save-match-data
10696 (org-parse-time-string (substring string beg end) t))
10697 with-hm (and (nth 1 t1) (nth 2 t1))
10698 inactive (equal (substring string beg (1+ beg)) "[")
10699 tf (funcall (if with-hm 'cdr 'car)
10700 org-time-stamp-custom-formats)
10701 time (org-fix-decoded-time t1)
10702 str (format-time-string
10703 (concat
10704 (if inactive "[" "<") (substring tf 1 -1)
10705 (if inactive "]" ">"))
10706 (apply 'encode-time time))
10707 string (replace-match str t t string)
10708 start (+ start (length str)))))))
10709 string)
10711 (defun org-fix-decoded-time (time)
10712 "Set 0 instead of nil for the first 6 elements of time.
10713 Don't touch the rest."
10714 (let ((n 0))
10715 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10717 (defun org-days-to-time (timestamp-string)
10718 "Difference between TIMESTAMP-STRING and now in days."
10719 (- (time-to-days (org-time-string-to-time timestamp-string))
10720 (time-to-days (current-time))))
10722 (defun org-deadline-close (timestamp-string &optional ndays)
10723 "Is the time in TIMESTAMP-STRING close to the current date?"
10724 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10725 (and (< (org-days-to-time timestamp-string) ndays)
10726 (not (org-entry-is-done-p))))
10728 (defun org-get-wdays (ts)
10729 "Get the deadline lead time appropriate for timestring TS."
10730 (cond
10731 ((<= org-deadline-warning-days 0)
10732 ;; 0 or negative, enforce this value no matter what
10733 (- org-deadline-warning-days))
10734 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10735 ;; lead time is specified.
10736 (floor (* (string-to-number (match-string 1 ts))
10737 (cdr (assoc (match-string 2 ts)
10738 '(("d" . 1) ("w" . 7)
10739 ("m" . 30.4) ("y" . 365.25)))))))
10740 ;; go for the default.
10741 (t org-deadline-warning-days)))
10743 (defun org-calendar-select-mouse (ev)
10744 "Return to `org-read-date' with the date currently selected.
10745 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10746 (interactive "e")
10747 (mouse-set-point ev)
10748 (when (calendar-cursor-to-date)
10749 (let* ((date (calendar-cursor-to-date))
10750 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10751 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10752 (if (active-minibuffer-window) (exit-minibuffer))))
10754 (defun org-check-deadlines (ndays)
10755 "Check if there are any deadlines due or past due.
10756 A deadline is considered due if it happens within `org-deadline-warning-days'
10757 days from today's date. If the deadline appears in an entry marked DONE,
10758 it is not shown. The prefix arg NDAYS can be used to test that many
10759 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10760 (interactive "P")
10761 (let* ((org-warn-days
10762 (cond
10763 ((equal ndays '(4)) 100000)
10764 (ndays (prefix-numeric-value ndays))
10765 (t (abs org-deadline-warning-days))))
10766 (case-fold-search nil)
10767 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10768 (callback
10769 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10771 (message "%d deadlines past-due or due within %d days"
10772 (org-occur regexp nil callback)
10773 org-warn-days)))
10775 (defun org-check-before-date (date)
10776 "Check if there are deadlines or scheduled entries before DATE."
10777 (interactive (list (org-read-date)))
10778 (let ((case-fold-search nil)
10779 (regexp (concat "\\<\\(" org-deadline-string
10780 "\\|" org-scheduled-string
10781 "\\) *<\\([^>]+\\)>"))
10782 (callback
10783 (lambda () (time-less-p
10784 (org-time-string-to-time (match-string 2))
10785 (org-time-string-to-time date)))))
10786 (message "%d entries before %s"
10787 (org-occur regexp nil callback) date)))
10789 (defun org-evaluate-time-range (&optional to-buffer)
10790 "Evaluate a time range by computing the difference between start and end.
10791 Normally the result is just printed in the echo area, but with prefix arg
10792 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10793 If the time range is actually in a table, the result is inserted into the
10794 next column.
10795 For time difference computation, a year is assumed to be exactly 365
10796 days in order to avoid rounding problems."
10797 (interactive "P")
10799 (org-clock-update-time-maybe)
10800 (save-excursion
10801 (unless (org-at-date-range-p t)
10802 (goto-char (point-at-bol))
10803 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10804 (if (not (org-at-date-range-p t))
10805 (error "Not at a time-stamp range, and none found in current line")))
10806 (let* ((ts1 (match-string 1))
10807 (ts2 (match-string 2))
10808 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10809 (match-end (match-end 0))
10810 (time1 (org-time-string-to-time ts1))
10811 (time2 (org-time-string-to-time ts2))
10812 (t1 (time-to-seconds time1))
10813 (t2 (time-to-seconds time2))
10814 (diff (abs (- t2 t1)))
10815 (negative (< (- t2 t1) 0))
10816 ;; (ys (floor (* 365 24 60 60)))
10817 (ds (* 24 60 60))
10818 (hs (* 60 60))
10819 (fy "%dy %dd %02d:%02d")
10820 (fy1 "%dy %dd")
10821 (fd "%dd %02d:%02d")
10822 (fd1 "%dd")
10823 (fh "%02d:%02d")
10824 y d h m align)
10825 (if havetime
10826 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10828 d (floor (/ diff ds)) diff (mod diff ds)
10829 h (floor (/ diff hs)) diff (mod diff hs)
10830 m (floor (/ diff 60)))
10831 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10833 d (floor (+ (/ diff ds) 0.5))
10834 h 0 m 0))
10835 (if (not to-buffer)
10836 (message "%s" (org-make-tdiff-string y d h m))
10837 (if (org-at-table-p)
10838 (progn
10839 (goto-char match-end)
10840 (setq align t)
10841 (and (looking-at " *|") (goto-char (match-end 0))))
10842 (goto-char match-end))
10843 (if (looking-at
10844 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10845 (replace-match ""))
10846 (if negative (insert " -"))
10847 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10848 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10849 (insert " " (format fh h m))))
10850 (if align (org-table-align))
10851 (message "Time difference inserted")))))
10853 (defun org-make-tdiff-string (y d h m)
10854 (let ((fmt "")
10855 (l nil))
10856 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10857 l (push y l)))
10858 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10859 l (push d l)))
10860 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10861 l (push h l)))
10862 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10863 l (push m l)))
10864 (apply 'format fmt (nreverse l))))
10866 (defun org-time-string-to-time (s)
10867 (apply 'encode-time (org-parse-time-string s)))
10869 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10870 "Convert a time stamp to an absolute day number.
10871 If there is a specifyer for a cyclic time stamp, get the closest date to
10872 DAYNR.
10873 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10874 (cond
10875 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10876 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10877 daynr
10878 (+ daynr 1000)))
10879 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10880 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10881 (time-to-days (current-time))) (match-string 0 s)
10882 prefer show-all))
10883 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10885 (defun org-days-to-iso-week (days)
10886 "Return the iso week number."
10887 (require 'cal-iso)
10888 (car (calendar-iso-from-absolute days)))
10890 (defun org-small-year-to-year (year)
10891 "Convert 2-digit years into 4-digit years.
10892 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10893 The year 2000 cannot be abbreviated. Any year lager than 99
10894 is retrned unchanged."
10895 (if (< year 38)
10896 (setq year (+ 2000 year))
10897 (if (< year 100)
10898 (setq year (+ 1900 year))))
10899 year)
10901 (defun org-time-from-absolute (d)
10902 "Return the time corresponding to date D.
10903 D may be an absolute day number, or a calendar-type list (month day year)."
10904 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10905 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10907 (defun org-calendar-holiday ()
10908 "List of holidays, for Diary display in Org-mode."
10909 (require 'holidays)
10910 (let ((hl (funcall
10911 (if (fboundp 'calendar-check-holidays)
10912 'calendar-check-holidays 'check-calendar-holidays) date)))
10913 (if hl (mapconcat 'identity hl "; "))))
10915 (defun org-diary-sexp-entry (sexp entry date)
10916 "Process a SEXP diary ENTRY for DATE."
10917 (require 'diary-lib)
10918 (let ((result (if calendar-debug-sexp
10919 (let ((stack-trace-on-error t))
10920 (eval (car (read-from-string sexp))))
10921 (condition-case nil
10922 (eval (car (read-from-string sexp)))
10923 (error
10924 (beep)
10925 (message "Bad sexp at line %d in %s: %s"
10926 (org-current-line)
10927 (buffer-file-name) sexp)
10928 (sleep-for 2))))))
10929 (cond ((stringp result) result)
10930 ((and (consp result)
10931 (stringp (cdr result))) (cdr result))
10932 (result entry)
10933 (t nil))))
10935 (defun org-diary-to-ical-string (frombuf)
10936 "Get iCalendar entries from diary entries in buffer FROMBUF.
10937 This uses the icalendar.el library."
10938 (let* ((tmpdir (if (featurep 'xemacs)
10939 (temp-directory)
10940 temporary-file-directory))
10941 (tmpfile (make-temp-name
10942 (expand-file-name "orgics" tmpdir)))
10943 buf rtn b e)
10944 (save-excursion
10945 (set-buffer frombuf)
10946 (icalendar-export-region (point-min) (point-max) tmpfile)
10947 (setq buf (find-buffer-visiting tmpfile))
10948 (set-buffer buf)
10949 (goto-char (point-min))
10950 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10951 (setq b (match-beginning 0)))
10952 (goto-char (point-max))
10953 (if (re-search-backward "^END:VEVENT" nil t)
10954 (setq e (match-end 0)))
10955 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10956 (kill-buffer buf)
10957 (kill-buffer frombuf)
10958 (delete-file tmpfile)
10959 rtn))
10961 (defun org-closest-date (start current change prefer show-all)
10962 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10963 When PREFER is `past' return a date that is either CURRENT or past.
10964 When PREFER is `future', return a date that is either CURRENT or future.
10965 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10966 ;; Make the proper lists from the dates
10967 (catch 'exit
10968 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10969 dn dw sday cday n1 n2
10970 d m y y1 y2 date1 date2 nmonths nm ny m2)
10972 (setq start (org-date-to-gregorian start)
10973 current (org-date-to-gregorian
10974 (if show-all
10975 current
10976 (time-to-days (current-time))))
10977 sday (calendar-absolute-from-gregorian start)
10978 cday (calendar-absolute-from-gregorian current))
10980 (if (<= cday sday) (throw 'exit sday))
10982 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10983 (setq dn (string-to-number (match-string 1 change))
10984 dw (cdr (assoc (match-string 2 change) a1)))
10985 (error "Invalid change specifyer: %s" change))
10986 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10987 (cond
10988 ((eq dw 'day)
10989 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10990 n2 (+ n1 dn)))
10991 ((eq dw 'year)
10992 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10993 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10994 (setq date1 (list m d y1)
10995 n1 (calendar-absolute-from-gregorian date1)
10996 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10997 n2 (calendar-absolute-from-gregorian date2)))
10998 ((eq dw 'month)
10999 ;; approx number of month between the tow dates
11000 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11001 ;; How often does dn fit in there?
11002 (setq d (nth 1 start) m (car start) y (nth 2 start)
11003 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11004 m (+ m nm)
11005 ny (floor (/ m 12))
11006 y (+ y ny)
11007 m (- m (* ny 12)))
11008 (while (> m 12) (setq m (- m 12) y (1+ y)))
11009 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11010 (setq m2 (+ m dn) y2 y)
11011 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11012 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11013 (while (< n2 cday)
11014 (setq n1 n2 m m2 y y2)
11015 (setq m2 (+ m dn) y2 y)
11016 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11017 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11019 (if show-all
11020 (cond
11021 ((eq prefer 'past) n1)
11022 ((eq prefer 'future) (if (= cday n1) n1 n2))
11023 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11024 (cond
11025 ((eq prefer 'past) n1)
11026 ((eq prefer 'future) (if (= cday n1) n1 n2))
11027 (t (if (= cday n1) n1 n2)))))))
11029 (defun org-date-to-gregorian (date)
11030 "Turn any specification of DATE into a gregorian date for the calendar."
11031 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11032 ((and (listp date) (= (length date) 3)) date)
11033 ((stringp date)
11034 (setq date (org-parse-time-string date))
11035 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11036 ((listp date)
11037 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11039 (defun org-parse-time-string (s &optional nodefault)
11040 "Parse the standard Org-mode time string.
11041 This should be a lot faster than the normal `parse-time-string'.
11042 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11043 hour and minute fields will be nil if not given."
11044 (if (string-match org-ts-regexp0 s)
11045 (list 0
11046 (if (or (match-beginning 8) (not nodefault))
11047 (string-to-number (or (match-string 8 s) "0")))
11048 (if (or (match-beginning 7) (not nodefault))
11049 (string-to-number (or (match-string 7 s) "0")))
11050 (string-to-number (match-string 4 s))
11051 (string-to-number (match-string 3 s))
11052 (string-to-number (match-string 2 s))
11053 nil nil nil)
11054 (make-list 9 0)))
11056 (defun org-timestamp-up (&optional arg)
11057 "Increase the date item at the cursor by one.
11058 If the cursor is on the year, change the year. If it is on the month or
11059 the day, change that.
11060 With prefix ARG, change by that many units."
11061 (interactive "p")
11062 (org-timestamp-change (prefix-numeric-value arg)))
11064 (defun org-timestamp-down (&optional arg)
11065 "Decrease the date item at the cursor by one.
11066 If the cursor is on the year, change the year. If it is on the month or
11067 the day, change that.
11068 With prefix ARG, change by that many units."
11069 (interactive "p")
11070 (org-timestamp-change (- (prefix-numeric-value arg))))
11072 (defun org-timestamp-up-day (&optional arg)
11073 "Increase the date in the time stamp by one day.
11074 With prefix ARG, change that many days."
11075 (interactive "p")
11076 (if (and (not (org-at-timestamp-p t))
11077 (org-on-heading-p))
11078 (org-todo 'up)
11079 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11081 (defun org-timestamp-down-day (&optional arg)
11082 "Decrease the date in the time stamp by one day.
11083 With prefix ARG, change that many days."
11084 (interactive "p")
11085 (if (and (not (org-at-timestamp-p t))
11086 (org-on-heading-p))
11087 (org-todo 'down)
11088 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11090 (defun org-at-timestamp-p (&optional inactive-ok)
11091 "Determine if the cursor is in or at a timestamp."
11092 (interactive)
11093 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11094 (pos (point))
11095 (ans (or (looking-at tsr)
11096 (save-excursion
11097 (skip-chars-backward "^[<\n\r\t")
11098 (if (> (point) (point-min)) (backward-char 1))
11099 (and (looking-at tsr)
11100 (> (- (match-end 0) pos) -1))))))
11101 (and ans
11102 (boundp 'org-ts-what)
11103 (setq org-ts-what
11104 (cond
11105 ((= pos (match-beginning 0)) 'bracket)
11106 ((= pos (1- (match-end 0))) 'bracket)
11107 ((org-pos-in-match-range pos 2) 'year)
11108 ((org-pos-in-match-range pos 3) 'month)
11109 ((org-pos-in-match-range pos 7) 'hour)
11110 ((org-pos-in-match-range pos 8) 'minute)
11111 ((or (org-pos-in-match-range pos 4)
11112 (org-pos-in-match-range pos 5)) 'day)
11113 ((and (> pos (or (match-end 8) (match-end 5)))
11114 (< pos (match-end 0)))
11115 (- pos (or (match-end 8) (match-end 5))))
11116 (t 'day))))
11117 ans))
11119 (defun org-toggle-timestamp-type ()
11120 "Toggle the type (<active> or [inactive]) of a time stamp."
11121 (interactive)
11122 (when (org-at-timestamp-p t)
11123 (save-excursion
11124 (goto-char (match-beginning 0))
11125 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11126 (goto-char (1- (match-end 0)))
11127 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11128 (message "Timestamp is now %sactive"
11129 (if (equal (char-before) ?>) "in" ""))))
11131 (defun org-timestamp-change (n &optional what)
11132 "Change the date in the time stamp at point.
11133 The date will be changed by N times WHAT. WHAT can be `day', `month',
11134 `year', `minute', `second'. If WHAT is not given, the cursor position
11135 in the timestamp determines what will be changed."
11136 (let ((pos (point))
11137 with-hm inactive
11138 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11139 org-ts-what
11140 extra rem
11141 ts time time0)
11142 (if (not (org-at-timestamp-p t))
11143 (error "Not at a timestamp"))
11144 (if (and (not what) (eq org-ts-what 'bracket))
11145 (org-toggle-timestamp-type)
11146 (if (and (not what) (not (eq org-ts-what 'day))
11147 org-display-custom-times
11148 (get-text-property (point) 'display)
11149 (not (get-text-property (1- (point)) 'display)))
11150 (setq org-ts-what 'day))
11151 (setq org-ts-what (or what org-ts-what)
11152 inactive (= (char-after (match-beginning 0)) ?\[)
11153 ts (match-string 0))
11154 (replace-match "")
11155 (if (string-match
11156 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11158 (setq extra (match-string 1 ts)))
11159 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11160 (setq with-hm t))
11161 (setq time0 (org-parse-time-string ts))
11162 (when (and (eq org-ts-what 'minute)
11163 (eq current-prefix-arg nil))
11164 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11165 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11166 (setcar (cdr time0) (+ (nth 1 time0)
11167 (if (> n 0) (- rem) (- dm rem))))))
11168 (setq time
11169 (encode-time (or (car time0) 0)
11170 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11171 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11172 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11173 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11174 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11175 (nthcdr 6 time0)))
11176 (when (integerp org-ts-what)
11177 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11178 (if (eq what 'calendar)
11179 (let ((cal-date (org-get-date-from-calendar)))
11180 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11181 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11182 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11183 (setcar time0 (or (car time0) 0))
11184 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11185 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11186 (setq time (apply 'encode-time time0))))
11187 (setq org-last-changed-timestamp
11188 (org-insert-time-stamp time with-hm inactive nil nil extra))
11189 (org-clock-update-time-maybe)
11190 (goto-char pos)
11191 ;; Try to recenter the calendar window, if any
11192 (if (and org-calendar-follow-timestamp-change
11193 (get-buffer-window "*Calendar*" t)
11194 (memq org-ts-what '(day month year)))
11195 (org-recenter-calendar (time-to-days time))))))
11197 (defun org-modify-ts-extra (s pos n dm)
11198 "Change the different parts of the lead-time and repeat fields in timestamp."
11199 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11200 ng h m new rem)
11201 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11202 (cond
11203 ((or (org-pos-in-match-range pos 2)
11204 (org-pos-in-match-range pos 3))
11205 (setq m (string-to-number (match-string 3 s))
11206 h (string-to-number (match-string 2 s)))
11207 (if (org-pos-in-match-range pos 2)
11208 (setq h (+ h n))
11209 (setq n (* dm (org-no-warnings (signum n))))
11210 (when (not (= 0 (setq rem (% m dm))))
11211 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11212 (setq m (+ m n)))
11213 (if (< m 0) (setq m (+ m 60) h (1- h)))
11214 (if (> m 59) (setq m (- m 60) h (1+ h)))
11215 (setq h (min 24 (max 0 h)))
11216 (setq ng 1 new (format "-%02d:%02d" h m)))
11217 ((org-pos-in-match-range pos 6)
11218 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11219 ((org-pos-in-match-range pos 5)
11220 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11222 ((org-pos-in-match-range pos 9)
11223 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11224 ((org-pos-in-match-range pos 8)
11225 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11227 (when ng
11228 (setq s (concat
11229 (substring s 0 (match-beginning ng))
11231 (substring s (match-end ng))))))
11234 (defun org-recenter-calendar (date)
11235 "If the calendar is visible, recenter it to DATE."
11236 (let* ((win (selected-window))
11237 (cwin (get-buffer-window "*Calendar*" t))
11238 (calendar-move-hook nil))
11239 (when cwin
11240 (select-window cwin)
11241 (calendar-goto-date (if (listp date) date
11242 (calendar-gregorian-from-absolute date)))
11243 (select-window win))))
11245 (defun org-goto-calendar (&optional arg)
11246 "Go to the Emacs calendar at the current date.
11247 If there is a time stamp in the current line, go to that date.
11248 A prefix ARG can be used to force the current date."
11249 (interactive "P")
11250 (let ((tsr org-ts-regexp) diff
11251 (calendar-move-hook nil)
11252 (calendar-view-holidays-initially-flag nil)
11253 (view-calendar-holidays-initially nil)
11254 (calendar-view-diary-initially-flag nil)
11255 (view-diary-entries-initially nil))
11256 (if (or (org-at-timestamp-p)
11257 (save-excursion
11258 (beginning-of-line 1)
11259 (looking-at (concat ".*" tsr))))
11260 (let ((d1 (time-to-days (current-time)))
11261 (d2 (time-to-days
11262 (org-time-string-to-time (match-string 1)))))
11263 (setq diff (- d2 d1))))
11264 (calendar)
11265 (calendar-goto-today)
11266 (if (and diff (not arg)) (calendar-forward-day diff))))
11268 (defun org-get-date-from-calendar ()
11269 "Return a list (month day year) of date at point in calendar."
11270 (with-current-buffer "*Calendar*"
11271 (save-match-data
11272 (calendar-cursor-to-date))))
11274 (defun org-date-from-calendar ()
11275 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11276 If there is already a time stamp at the cursor position, update it."
11277 (interactive)
11278 (if (org-at-timestamp-p t)
11279 (org-timestamp-change 0 'calendar)
11280 (let ((cal-date (org-get-date-from-calendar)))
11281 (org-insert-time-stamp
11282 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11284 (defun org-minutes-to-hh:mm-string (m)
11285 "Compute H:MM from a number of minutes."
11286 (let ((h (/ m 60)))
11287 (setq m (- m (* 60 h)))
11288 (format "%d:%02d" h m)))
11290 (defun org-hh:mm-string-to-minutes (s)
11291 "Convert a string H:MM to a number of minutes."
11292 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11293 (+ (* (string-to-number (match-string 1 s)) 60)
11294 (string-to-number (match-string 2 s)))
11297 ;;;; Agenda files
11299 ;;;###autoload
11300 (defun org-iswitchb (&optional arg)
11301 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11302 With a prefix argument, restrict available to files.
11303 With two prefix arguments, restrict available buffers to agenda files.
11305 Due to some yet unresolved reason, global function
11306 `iswitchb-mode' needs to be active for this function to work."
11307 (interactive "P")
11308 (require 'iswitchb)
11309 (let ((enabled iswitchb-mode) blist)
11310 (or enabled (iswitchb-mode 1))
11311 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11312 ((equal arg '(16)) (org-buffer-list 'agenda))
11313 (t (org-buffer-list))))
11314 (unwind-protect
11315 (let ((iswitchb-make-buflist-hook
11316 (lambda ()
11317 (setq iswitchb-temp-buflist
11318 (mapcar 'buffer-name blist)))))
11319 (switch-to-buffer
11320 (iswitchb-read-buffer
11321 "Switch-to: " nil t))
11322 (or enabled (iswitchb-mode -1))))))
11324 (defun org-buffer-list (&optional predicate tmp)
11325 "Return a list of Org buffers.
11326 PREDICATE can be either 'export, 'files or 'agenda.
11328 'export restrict the list to Export buffers.
11329 'files restrict the list to buffers visiting Org files.
11330 'agenda restrict the list to buffers visiting agenda files.
11332 If TMP is non-nil, don't include temporary buffers."
11333 (let (filter blist)
11334 (setq filter
11335 (cond ((eq predicate 'files) "\.org$")
11336 ((eq predicate 'export) "\*Org .*Export")
11337 (t "\*Org \\|\.org$")))
11338 (setq blist
11339 (mapcar
11340 (lambda(b)
11341 (let ((bname (buffer-name b))
11342 (bfile (buffer-file-name b)))
11343 (if (and (string-match filter bname)
11344 (if (eq predicate 'agenda)
11345 (member bfile
11346 (mapcar (lambda(f) (file-truename f))
11347 org-agenda-files)) t)
11348 (if tmp (not (string-match "tmp" bname)) t)) b)))
11349 (buffer-list)))
11350 (delete nil blist)))
11352 (defun org-agenda-files (&optional unrestricted ext)
11353 "Get the list of agenda files.
11354 Optional UNRESTRICTED means return the full list even if a restriction
11355 is currently in place.
11356 When EXT is non-nil, try to add all files that are created by adding EXT
11357 to the file nemes. Basically, this is a way to add the archive files
11358 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11359 a string, \"_archive\" will be used."
11360 (let ((files
11361 (cond
11362 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11363 ((stringp org-agenda-files) (org-read-agenda-file-list))
11364 ((listp org-agenda-files) org-agenda-files)
11365 (t (error "Invalid value of `org-agenda-files'")))))
11366 (setq files (apply 'append
11367 (mapcar (lambda (f)
11368 (if (file-directory-p f)
11369 (directory-files
11370 f t org-agenda-file-regexp)
11371 (list f)))
11372 files)))
11373 (when org-agenda-skip-unavailable-files
11374 (setq files (delq nil
11375 (mapcar (function
11376 (lambda (file)
11377 (and (file-readable-p file) file)))
11378 files))))
11379 (when ext
11380 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11381 ext "_archive"))
11382 (setq files (apply 'append
11383 (mapcar
11384 (lambda (f)
11385 (if (file-exists-p (concat f ext))
11386 (list f (concat f ext))
11387 (list f)))
11388 files))))
11389 files))
11391 (defun org-edit-agenda-file-list ()
11392 "Edit the list of agenda files.
11393 Depending on setup, this either uses customize to edit the variable
11394 `org-agenda-files', or it visits the file that is holding the list. In the
11395 latter case, the buffer is set up in a way that saving it automatically kills
11396 the buffer and restores the previous window configuration."
11397 (interactive)
11398 (if (stringp org-agenda-files)
11399 (let ((cw (current-window-configuration)))
11400 (find-file org-agenda-files)
11401 (org-set-local 'org-window-configuration cw)
11402 (org-add-hook 'after-save-hook
11403 (lambda ()
11404 (set-window-configuration
11405 (prog1 org-window-configuration
11406 (kill-buffer (current-buffer))))
11407 (org-install-agenda-files-menu)
11408 (message "New agenda file list installed"))
11409 nil 'local)
11410 (message "%s" (substitute-command-keys
11411 "Edit list and finish with \\[save-buffer]")))
11412 (customize-variable 'org-agenda-files)))
11414 (defun org-store-new-agenda-file-list (list)
11415 "Set new value for the agenda file list and save it correcly."
11416 (if (stringp org-agenda-files)
11417 (let ((f org-agenda-files) b)
11418 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11419 (with-temp-file f
11420 (insert (mapconcat 'identity list "\n") "\n")))
11421 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11422 (setq org-agenda-files list)
11423 (customize-save-variable 'org-agenda-files org-agenda-files))))
11425 (defun org-read-agenda-file-list ()
11426 "Read the list of agenda files from a file."
11427 (when (file-directory-p org-agenda-files)
11428 (error "`org-agenda-files' cannot be a single directory"))
11429 (when (stringp org-agenda-files)
11430 (with-temp-buffer
11431 (insert-file-contents org-agenda-files)
11432 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11435 ;;;###autoload
11436 (defun org-cycle-agenda-files ()
11437 "Cycle through the files in `org-agenda-files'.
11438 If the current buffer visits an agenda file, find the next one in the list.
11439 If the current buffer does not, find the first agenda file."
11440 (interactive)
11441 (let* ((fs (org-agenda-files t))
11442 (files (append fs (list (car fs))))
11443 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11444 file)
11445 (unless files (error "No agenda files"))
11446 (catch 'exit
11447 (while (setq file (pop files))
11448 (if (equal (file-truename file) tcf)
11449 (when (car files)
11450 (find-file (car files))
11451 (throw 'exit t))))
11452 (find-file (car fs)))
11453 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11455 (defun org-agenda-file-to-front (&optional to-end)
11456 "Move/add the current file to the top of the agenda file list.
11457 If the file is not present in the list, it is added to the front. If it is
11458 present, it is moved there. With optional argument TO-END, add/move to the
11459 end of the list."
11460 (interactive "P")
11461 (let ((org-agenda-skip-unavailable-files nil)
11462 (file-alist (mapcar (lambda (x)
11463 (cons (file-truename x) x))
11464 (org-agenda-files t)))
11465 (ctf (file-truename buffer-file-name))
11466 x had)
11467 (setq x (assoc ctf file-alist) had x)
11469 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11470 (if to-end
11471 (setq file-alist (append (delq x file-alist) (list x)))
11472 (setq file-alist (cons x (delq x file-alist))))
11473 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11474 (org-install-agenda-files-menu)
11475 (message "File %s to %s of agenda file list"
11476 (if had "moved" "added") (if to-end "end" "front"))))
11478 (defun org-remove-file (&optional file)
11479 "Remove current file from the list of files in variable `org-agenda-files'.
11480 These are the files which are being checked for agenda entries.
11481 Optional argument FILE means, use this file instead of the current."
11482 (interactive)
11483 (let* ((org-agenda-skip-unavailable-files nil)
11484 (file (or file buffer-file-name))
11485 (true-file (file-truename file))
11486 (afile (abbreviate-file-name file))
11487 (files (delq nil (mapcar
11488 (lambda (x)
11489 (if (equal true-file
11490 (file-truename x))
11491 nil x))
11492 (org-agenda-files t)))))
11493 (if (not (= (length files) (length (org-agenda-files t))))
11494 (progn
11495 (org-store-new-agenda-file-list files)
11496 (org-install-agenda-files-menu)
11497 (message "Removed file: %s" afile))
11498 (message "File was not in list: %s (not removed)" afile))))
11500 (defun org-file-menu-entry (file)
11501 (vector file (list 'find-file file) t))
11503 (defun org-check-agenda-file (file)
11504 "Make sure FILE exists. If not, ask user what to do."
11505 (when (not (file-exists-p file))
11506 (message "non-existent file %s. [R]emove from list or [A]bort?"
11507 (abbreviate-file-name file))
11508 (let ((r (downcase (read-char-exclusive))))
11509 (cond
11510 ((equal r ?r)
11511 (org-remove-file file)
11512 (throw 'nextfile t))
11513 (t (error "Abort"))))))
11515 (defun org-get-agenda-file-buffer (file)
11516 "Get a buffer visiting FILE. If the buffer needs to be created, add
11517 it to the list of buffers which might be released later."
11518 (let ((buf (org-find-base-buffer-visiting file)))
11519 (if buf
11520 buf ; just return it
11521 ;; Make a new buffer and remember it
11522 (setq buf (find-file-noselect file))
11523 (if buf (push buf org-agenda-new-buffers))
11524 buf)))
11526 (defun org-release-buffers (blist)
11527 "Release all buffers in list, asking the user for confirmation when needed.
11528 When a buffer is unmodified, it is just killed. When modified, it is saved
11529 \(if the user agrees) and then killed."
11530 (let (buf file)
11531 (while (setq buf (pop blist))
11532 (setq file (buffer-file-name buf))
11533 (when (and (buffer-modified-p buf)
11534 file
11535 (y-or-n-p (format "Save file %s? " file)))
11536 (with-current-buffer buf (save-buffer)))
11537 (kill-buffer buf))))
11539 (defun org-prepare-agenda-buffers (files)
11540 "Create buffers for all agenda files, protect archived trees and comments."
11541 (interactive)
11542 (let ((pa '(:org-archived t))
11543 (pc '(:org-comment t))
11544 (pall '(:org-archived t :org-comment t))
11545 (inhibit-read-only t)
11546 (rea (concat ":" org-archive-tag ":"))
11547 bmp file re)
11548 (save-excursion
11549 (save-restriction
11550 (while (setq file (pop files))
11551 (if (bufferp file)
11552 (set-buffer file)
11553 (org-check-agenda-file file)
11554 (set-buffer (org-get-agenda-file-buffer file)))
11555 (widen)
11556 (setq bmp (buffer-modified-p))
11557 (org-refresh-category-properties)
11558 (setq org-todo-keywords-for-agenda
11559 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11560 (setq org-done-keywords-for-agenda
11561 (append org-done-keywords-for-agenda org-done-keywords))
11562 (save-excursion
11563 (remove-text-properties (point-min) (point-max) pall)
11564 (when org-agenda-skip-archived-trees
11565 (goto-char (point-min))
11566 (while (re-search-forward rea nil t)
11567 (if (org-on-heading-p t)
11568 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11569 (goto-char (point-min))
11570 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11571 (while (re-search-forward re nil t)
11572 (add-text-properties
11573 (match-beginning 0) (org-end-of-subtree t) pc)))
11574 (set-buffer-modified-p bmp))))))
11576 ;;;; Embedded LaTeX
11578 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11579 "Keymap for the minor `org-cdlatex-mode'.")
11581 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11582 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11583 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11584 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11585 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11587 (defvar org-cdlatex-texmathp-advice-is-done nil
11588 "Flag remembering if we have applied the advice to texmathp already.")
11590 (define-minor-mode org-cdlatex-mode
11591 "Toggle the minor `org-cdlatex-mode'.
11592 This mode supports entering LaTeX environment and math in LaTeX fragments
11593 in Org-mode.
11594 \\{org-cdlatex-mode-map}"
11595 nil " OCDL" nil
11596 (when org-cdlatex-mode (require 'cdlatex))
11597 (unless org-cdlatex-texmathp-advice-is-done
11598 (setq org-cdlatex-texmathp-advice-is-done t)
11599 (defadvice texmathp (around org-math-always-on activate)
11600 "Always return t in org-mode buffers.
11601 This is because we want to insert math symbols without dollars even outside
11602 the LaTeX math segments. If Orgmode thinks that point is actually inside
11603 en embedded LaTeX fragement, let texmathp do its job.
11604 \\[org-cdlatex-mode-map]"
11605 (interactive)
11606 (let (p)
11607 (cond
11608 ((not (org-mode-p)) ad-do-it)
11609 ((eq this-command 'cdlatex-math-symbol)
11610 (setq ad-return-value t
11611 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11613 (let ((p (org-inside-LaTeX-fragment-p)))
11614 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11615 (setq ad-return-value t
11616 texmathp-why '("Org-mode embedded math" . 0))
11617 (if p ad-do-it)))))))))
11619 (defun turn-on-org-cdlatex ()
11620 "Unconditionally turn on `org-cdlatex-mode'."
11621 (org-cdlatex-mode 1))
11623 (defun org-inside-LaTeX-fragment-p ()
11624 "Test if point is inside a LaTeX fragment.
11625 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11626 sequence appearing also before point.
11627 Even though the matchers for math are configurable, this function assumes
11628 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11629 delimiters are skipped when they have been removed by customization.
11630 The return value is nil, or a cons cell with the delimiter and
11631 and the position of this delimiter.
11633 This function does a reasonably good job, but can locally be fooled by
11634 for example currency specifications. For example it will assume being in
11635 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11636 fragments that are properly closed, but during editing, we have to live
11637 with the uncertainty caused by missing closing delimiters. This function
11638 looks only before point, not after."
11639 (catch 'exit
11640 (let ((pos (point))
11641 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11642 (lim (progn
11643 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11644 (point)))
11645 dd-on str (start 0) m re)
11646 (goto-char pos)
11647 (when dodollar
11648 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11649 re (nth 1 (assoc "$" org-latex-regexps)))
11650 (while (string-match re str start)
11651 (cond
11652 ((= (match-end 0) (length str))
11653 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11654 ((= (match-end 0) (- (length str) 5))
11655 (throw 'exit nil))
11656 (t (setq start (match-end 0))))))
11657 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11658 (goto-char pos)
11659 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11660 (and (match-beginning 2) (throw 'exit nil))
11661 ;; count $$
11662 (while (re-search-backward "\\$\\$" lim t)
11663 (setq dd-on (not dd-on)))
11664 (goto-char pos)
11665 (if dd-on (cons "$$" m))))))
11668 (defun org-try-cdlatex-tab ()
11669 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11670 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11671 - inside a LaTeX fragment, or
11672 - after the first word in a line, where an abbreviation expansion could
11673 insert a LaTeX environment."
11674 (when org-cdlatex-mode
11675 (cond
11676 ((save-excursion
11677 (skip-chars-backward "a-zA-Z0-9*")
11678 (skip-chars-backward " \t")
11679 (bolp))
11680 (cdlatex-tab) t)
11681 ((org-inside-LaTeX-fragment-p)
11682 (cdlatex-tab) t)
11683 (t nil))))
11685 (defun org-cdlatex-underscore-caret (&optional arg)
11686 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11687 Revert to the normal definition outside of these fragments."
11688 (interactive "P")
11689 (if (org-inside-LaTeX-fragment-p)
11690 (call-interactively 'cdlatex-sub-superscript)
11691 (let (org-cdlatex-mode)
11692 (call-interactively (key-binding (vector last-input-event))))))
11694 (defun org-cdlatex-math-modify (&optional arg)
11695 "Execute `cdlatex-math-modify' in LaTeX fragments.
11696 Revert to the normal definition outside of these fragments."
11697 (interactive "P")
11698 (if (org-inside-LaTeX-fragment-p)
11699 (call-interactively 'cdlatex-math-modify)
11700 (let (org-cdlatex-mode)
11701 (call-interactively (key-binding (vector last-input-event))))))
11703 (defvar org-latex-fragment-image-overlays nil
11704 "List of overlays carrying the images of latex fragments.")
11705 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11707 (defun org-remove-latex-fragment-image-overlays ()
11708 "Remove all overlays with LaTeX fragment images in current buffer."
11709 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11710 (setq org-latex-fragment-image-overlays nil))
11712 (defun org-preview-latex-fragment (&optional subtree)
11713 "Preview the LaTeX fragment at point, or all locally or globally.
11714 If the cursor is in a LaTeX fragment, create the image and overlay
11715 it over the source code. If there is no fragment at point, display
11716 all fragments in the current text, from one headline to the next. With
11717 prefix SUBTREE, display all fragments in the current subtree. With a
11718 double prefix `C-u C-u', or when the cursor is before the first headline,
11719 display all fragments in the buffer.
11720 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11721 (interactive "P")
11722 (org-remove-latex-fragment-image-overlays)
11723 (save-excursion
11724 (save-restriction
11725 (let (beg end at msg)
11726 (cond
11727 ((or (equal subtree '(16))
11728 (not (save-excursion
11729 (re-search-backward (concat "^" outline-regexp) nil t))))
11730 (setq beg (point-min) end (point-max)
11731 msg "Creating images for buffer...%s"))
11732 ((equal subtree '(4))
11733 (org-back-to-heading)
11734 (setq beg (point) end (org-end-of-subtree t)
11735 msg "Creating images for subtree...%s"))
11737 (if (setq at (org-inside-LaTeX-fragment-p))
11738 (goto-char (max (point-min) (- (cdr at) 2)))
11739 (org-back-to-heading))
11740 (setq beg (point) end (progn (outline-next-heading) (point))
11741 msg (if at "Creating image...%s"
11742 "Creating images for entry...%s"))))
11743 (message msg "")
11744 (narrow-to-region beg end)
11745 (goto-char beg)
11746 (org-format-latex
11747 (concat "ltxpng/" (file-name-sans-extension
11748 (file-name-nondirectory
11749 buffer-file-name)))
11750 default-directory 'overlays msg at 'forbuffer)
11751 (message msg "done. Use `C-c C-c' to remove images.")))))
11753 (defvar org-latex-regexps
11754 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11755 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11756 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11757 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11758 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11759 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11760 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11761 "Regular expressions for matching embedded LaTeX.")
11763 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11764 "Replace LaTeX fragments with links to an image, and produce images."
11765 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11766 (let* ((prefixnodir (file-name-nondirectory prefix))
11767 (absprefix (expand-file-name prefix dir))
11768 (todir (file-name-directory absprefix))
11769 (opt org-format-latex-options)
11770 (matchers (plist-get opt :matchers))
11771 (re-list org-latex-regexps)
11772 (cnt 0) txt link beg end re e checkdir
11773 m n block linkfile movefile ov)
11774 ;; Check if there are old images files with this prefix, and remove them
11775 (when (file-directory-p todir)
11776 (mapc 'delete-file
11777 (directory-files
11778 todir 'full
11779 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11780 ;; Check the different regular expressions
11781 (while (setq e (pop re-list))
11782 (setq m (car e) re (nth 1 e) n (nth 2 e)
11783 block (if (nth 3 e) "\n\n" ""))
11784 (when (member m matchers)
11785 (goto-char (point-min))
11786 (while (re-search-forward re nil t)
11787 (when (or (not at) (equal (cdr at) (match-beginning n)))
11788 (setq txt (match-string n)
11789 beg (match-beginning n) end (match-end n)
11790 cnt (1+ cnt)
11791 linkfile (format "%s_%04d.png" prefix cnt)
11792 movefile (format "%s_%04d.png" absprefix cnt)
11793 link (concat block "[[file:" linkfile "]]" block))
11794 (if msg (message msg cnt))
11795 (goto-char beg)
11796 (unless checkdir ; make sure the directory exists
11797 (setq checkdir t)
11798 (or (file-directory-p todir) (make-directory todir)))
11799 (org-create-formula-image
11800 txt movefile opt forbuffer)
11801 (if overlays
11802 (progn
11803 (setq ov (org-make-overlay beg end))
11804 (if (featurep 'xemacs)
11805 (progn
11806 (org-overlay-put ov 'invisible t)
11807 (org-overlay-put
11808 ov 'end-glyph
11809 (make-glyph (vector 'png :file movefile))))
11810 (org-overlay-put
11811 ov 'display
11812 (list 'image :type 'png :file movefile :ascent 'center)))
11813 (push ov org-latex-fragment-image-overlays)
11814 (goto-char end))
11815 (delete-region beg end)
11816 (insert link))))))))
11818 ;; This function borrows from Ganesh Swami's latex2png.el
11819 (defun org-create-formula-image (string tofile options buffer)
11820 (let* ((tmpdir (if (featurep 'xemacs)
11821 (temp-directory)
11822 temporary-file-directory))
11823 (texfilebase (make-temp-name
11824 (expand-file-name "orgtex" tmpdir)))
11825 (texfile (concat texfilebase ".tex"))
11826 (dvifile (concat texfilebase ".dvi"))
11827 (pngfile (concat texfilebase ".png"))
11828 (fnh (if (featurep 'xemacs)
11829 (font-height (get-face-font 'default))
11830 (face-attribute 'default :height nil)))
11831 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11832 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11833 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11834 "Black"))
11835 (bg (or (plist-get options (if buffer :background :html-background))
11836 "Transparent")))
11837 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11838 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11839 (with-temp-file texfile
11840 (insert org-format-latex-header
11841 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11842 (let ((dir default-directory))
11843 (condition-case nil
11844 (progn
11845 (cd tmpdir)
11846 (call-process "latex" nil nil nil texfile))
11847 (error nil))
11848 (cd dir))
11849 (if (not (file-exists-p dvifile))
11850 (progn (message "Failed to create dvi file from %s" texfile) nil)
11851 (call-process "dvipng" nil nil nil
11852 "-E" "-fg" fg "-bg" bg
11853 "-D" dpi
11854 ;;"-x" scale "-y" scale
11855 "-T" "tight"
11856 "-o" pngfile
11857 dvifile)
11858 (if (not (file-exists-p pngfile))
11859 (progn (message "Failed to create png file from %s" texfile) nil)
11860 ;; Use the requested file name and clean up
11861 (copy-file pngfile tofile 'replace)
11862 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11863 (delete-file (concat texfilebase e)))
11864 pngfile))))
11866 (defun org-dvipng-color (attr)
11867 "Return an rgb color specification for dvipng."
11868 (apply 'format "rgb %s %s %s"
11869 (mapcar 'org-normalize-color
11870 (color-values (face-attribute 'default attr nil)))))
11872 (defun org-normalize-color (value)
11873 "Return string to be used as color value for an RGB component."
11874 (format "%g" (/ value 65535.0)))
11877 ;;;; Key bindings
11879 ;; Make `C-c C-x' a prefix key
11880 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11882 ;; TAB key with modifiers
11883 (org-defkey org-mode-map "\C-i" 'org-cycle)
11884 (org-defkey org-mode-map [(tab)] 'org-cycle)
11885 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11886 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11887 (org-defkey org-mode-map "\M-\t" 'org-complete)
11888 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11889 ;; The following line is necessary under Suse GNU/Linux
11890 (unless (featurep 'xemacs)
11891 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11892 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11893 (define-key org-mode-map [backtab] 'org-shifttab)
11895 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11896 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11897 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11899 ;; Cursor keys with modifiers
11900 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11901 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11902 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11903 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11905 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11906 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11907 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11908 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11910 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11911 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11912 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11913 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11915 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11916 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11918 ;;; Extra keys for tty access.
11919 ;; We only set them when really needed because otherwise the
11920 ;; menus don't show the simple keys
11922 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11923 (not window-system))
11924 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11925 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11926 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11927 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11928 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11929 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11930 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11931 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11932 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11933 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11934 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11935 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11936 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11937 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11938 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11939 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11940 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11941 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11942 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11943 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11944 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11945 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11947 ;; All the other keys
11949 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11950 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11951 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11952 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11953 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11954 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11955 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11956 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11957 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11958 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11959 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11960 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11961 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11962 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11963 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11964 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11965 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11966 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11967 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11968 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11969 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11970 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11971 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11972 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11973 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11974 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11975 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11976 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11977 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11978 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11979 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11980 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11981 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11982 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11983 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11984 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11985 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11986 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11987 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11988 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11989 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11990 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11991 (org-defkey org-mode-map "\C-c^" 'org-sort)
11992 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11993 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11994 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11995 (org-defkey org-mode-map "\C-m" 'org-return)
11996 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11997 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11998 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11999 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12000 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12001 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
12002 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12003 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12004 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12005 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12006 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12007 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12008 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12009 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12010 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12011 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12013 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12014 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12015 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12016 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12018 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12019 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12020 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12021 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12022 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12023 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12024 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12025 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12026 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12027 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12028 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12029 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12031 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12033 (when (featurep 'xemacs)
12034 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12036 (defvar org-table-auto-blank-field) ; defined in org-table.el
12037 (defun org-self-insert-command (N)
12038 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12039 If the cursor is in a table looking at whitespace, the whitespace is
12040 overwritten, and the table is not marked as requiring realignment."
12041 (interactive "p")
12042 (if (and (org-table-p)
12043 (progn
12044 ;; check if we blank the field, and if that triggers align
12045 (and (featurep 'org-table) org-table-auto-blank-field
12046 (member last-command
12047 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12048 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12049 ;; got extra space, this field does not determine column width
12050 (let (org-table-may-need-update) (org-table-blank-field))
12051 ;; no extra space, this field may determine column width
12052 (org-table-blank-field)))
12054 (eq N 1)
12055 (looking-at "[^|\n]* |"))
12056 (let (org-table-may-need-update)
12057 (goto-char (1- (match-end 0)))
12058 (delete-backward-char 1)
12059 (goto-char (match-beginning 0))
12060 (self-insert-command N))
12061 (setq org-table-may-need-update t)
12062 (self-insert-command N)
12063 (org-fix-tags-on-the-fly)))
12065 (defun org-fix-tags-on-the-fly ()
12066 (when (and (equal (char-after (point-at-bol)) ?*)
12067 (org-on-heading-p))
12068 (org-align-tags-here org-tags-column)))
12070 (defun org-delete-backward-char (N)
12071 "Like `delete-backward-char', insert whitespace at field end in tables.
12072 When deleting backwards, in tables this function will insert whitespace in
12073 front of the next \"|\" separator, to keep the table aligned. The table will
12074 still be marked for re-alignment if the field did fill the entire column,
12075 because, in this case the deletion might narrow the column."
12076 (interactive "p")
12077 (if (and (org-table-p)
12078 (eq N 1)
12079 (string-match "|" (buffer-substring (point-at-bol) (point)))
12080 (looking-at ".*?|"))
12081 (let ((pos (point))
12082 (noalign (looking-at "[^|\n\r]* |"))
12083 (c org-table-may-need-update))
12084 (backward-delete-char N)
12085 (skip-chars-forward "^|")
12086 (insert " ")
12087 (goto-char (1- pos))
12088 ;; noalign: if there were two spaces at the end, this field
12089 ;; does not determine the width of the column.
12090 (if noalign (setq org-table-may-need-update c)))
12091 (backward-delete-char N)
12092 (org-fix-tags-on-the-fly)))
12094 (defun org-delete-char (N)
12095 "Like `delete-char', but insert whitespace at field end in tables.
12096 When deleting characters, in tables this function will insert whitespace in
12097 front of the next \"|\" separator, to keep the table aligned. The table will
12098 still be marked for re-alignment if the field did fill the entire column,
12099 because, in this case the deletion might narrow the column."
12100 (interactive "p")
12101 (if (and (org-table-p)
12102 (not (bolp))
12103 (not (= (char-after) ?|))
12104 (eq N 1))
12105 (if (looking-at ".*?|")
12106 (let ((pos (point))
12107 (noalign (looking-at "[^|\n\r]* |"))
12108 (c org-table-may-need-update))
12109 (replace-match (concat
12110 (substring (match-string 0) 1 -1)
12111 " |"))
12112 (goto-char pos)
12113 ;; noalign: if there were two spaces at the end, this field
12114 ;; does not determine the width of the column.
12115 (if noalign (setq org-table-may-need-update c)))
12116 (delete-char N))
12117 (delete-char N)
12118 (org-fix-tags-on-the-fly)))
12120 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12121 (put 'org-self-insert-command 'delete-selection t)
12122 (put 'orgtbl-self-insert-command 'delete-selection t)
12123 (put 'org-delete-char 'delete-selection 'supersede)
12124 (put 'org-delete-backward-char 'delete-selection 'supersede)
12126 ;; Make `flyspell-mode' delay after some commands
12127 (put 'org-self-insert-command 'flyspell-delayed t)
12128 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12129 (put 'org-delete-char 'flyspell-delayed t)
12130 (put 'org-delete-backward-char 'flyspell-delayed t)
12132 ;; Make pabbrev-mode expand after org-mode commands
12133 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12134 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12136 ;; How to do this: Measure non-white length of current string
12137 ;; If equal to column width, we should realign.
12139 (defun org-remap (map &rest commands)
12140 "In MAP, remap the functions given in COMMANDS.
12141 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12142 (let (new old)
12143 (while commands
12144 (setq old (pop commands) new (pop commands))
12145 (if (fboundp 'command-remapping)
12146 (org-defkey map (vector 'remap old) new)
12147 (substitute-key-definition old new map global-map)))))
12149 (when (eq org-enable-table-editor 'optimized)
12150 ;; If the user wants maximum table support, we need to hijack
12151 ;; some standard editing functions
12152 (org-remap org-mode-map
12153 'self-insert-command 'org-self-insert-command
12154 'delete-char 'org-delete-char
12155 'delete-backward-char 'org-delete-backward-char)
12156 (org-defkey org-mode-map "|" 'org-force-self-insert))
12158 (defun org-shiftcursor-error ()
12159 "Throw an error because Shift-Cursor command was applied in wrong context."
12160 (error "This command is active in special context like tables, headlines or timestamps"))
12162 (defun org-shifttab (&optional arg)
12163 "Global visibility cycling or move to previous table field.
12164 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12165 on context.
12166 See the individual commands for more information."
12167 (interactive "P")
12168 (cond
12169 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12170 ((integerp arg)
12171 (message "Content view to level: %d" arg)
12172 (org-content (prefix-numeric-value arg))
12173 (setq org-cycle-global-status 'overview))
12174 (t (call-interactively 'org-global-cycle))))
12176 (defun org-shiftmetaleft ()
12177 "Promote subtree or delete table column.
12178 Calls `org-promote-subtree', `org-outdent-item',
12179 or `org-table-delete-column', depending on context.
12180 See the individual commands for more information."
12181 (interactive)
12182 (cond
12183 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12184 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12185 ((org-at-item-p) (call-interactively 'org-outdent-item))
12186 (t (org-shiftcursor-error))))
12188 (defun org-shiftmetaright ()
12189 "Demote subtree or insert table column.
12190 Calls `org-demote-subtree', `org-indent-item',
12191 or `org-table-insert-column', depending on context.
12192 See the individual commands for more information."
12193 (interactive)
12194 (cond
12195 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12196 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12197 ((org-at-item-p) (call-interactively 'org-indent-item))
12198 (t (org-shiftcursor-error))))
12200 (defun org-shiftmetaup (&optional arg)
12201 "Move subtree up or kill table row.
12202 Calls `org-move-subtree-up' or `org-table-kill-row' or
12203 `org-move-item-up' depending on context. See the individual commands
12204 for more information."
12205 (interactive "P")
12206 (cond
12207 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12208 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12209 ((org-at-item-p) (call-interactively 'org-move-item-up))
12210 (t (org-shiftcursor-error))))
12211 (defun org-shiftmetadown (&optional arg)
12212 "Move subtree down or insert table row.
12213 Calls `org-move-subtree-down' or `org-table-insert-row' or
12214 `org-move-item-down', depending on context. See the individual
12215 commands for more information."
12216 (interactive "P")
12217 (cond
12218 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12219 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12220 ((org-at-item-p) (call-interactively 'org-move-item-down))
12221 (t (org-shiftcursor-error))))
12223 (defun org-metaleft (&optional arg)
12224 "Promote heading or move table column to left.
12225 Calls `org-do-promote' or `org-table-move-column', depending on context.
12226 With no specific context, calls the Emacs default `backward-word'.
12227 See the individual commands for more information."
12228 (interactive "P")
12229 (cond
12230 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12231 ((or (org-on-heading-p) (org-region-active-p))
12232 (call-interactively 'org-do-promote))
12233 ((org-at-item-p) (call-interactively 'org-outdent-item))
12234 (t (call-interactively 'backward-word))))
12236 (defun org-metaright (&optional arg)
12237 "Demote subtree or move table column to right.
12238 Calls `org-do-demote' or `org-table-move-column', depending on context.
12239 With no specific context, calls the Emacs default `forward-word'.
12240 See the individual commands for more information."
12241 (interactive "P")
12242 (cond
12243 ((org-at-table-p) (call-interactively 'org-table-move-column))
12244 ((or (org-on-heading-p) (org-region-active-p))
12245 (call-interactively 'org-do-demote))
12246 ((org-at-item-p) (call-interactively 'org-indent-item))
12247 (t (call-interactively 'forward-word))))
12249 (defun org-metaup (&optional arg)
12250 "Move subtree up or move table row up.
12251 Calls `org-move-subtree-up' or `org-table-move-row' or
12252 `org-move-item-up', depending on context. See the individual commands
12253 for more information."
12254 (interactive "P")
12255 (cond
12256 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12257 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12258 ((org-at-item-p) (call-interactively 'org-move-item-up))
12259 (t (transpose-lines 1) (beginning-of-line -1))))
12261 (defun org-metadown (&optional arg)
12262 "Move subtree down or move table row down.
12263 Calls `org-move-subtree-down' or `org-table-move-row' or
12264 `org-move-item-down', depending on context. See the individual
12265 commands for more information."
12266 (interactive "P")
12267 (cond
12268 ((org-at-table-p) (call-interactively 'org-table-move-row))
12269 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12270 ((org-at-item-p) (call-interactively 'org-move-item-down))
12271 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12273 (defun org-shiftup (&optional arg)
12274 "Increase item in timestamp or increase priority of current headline.
12275 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12276 depending on context. See the individual commands for more information."
12277 (interactive "P")
12278 (cond
12279 ((org-at-timestamp-p t)
12280 (call-interactively (if org-edit-timestamp-down-means-later
12281 'org-timestamp-down 'org-timestamp-up)))
12282 ((org-on-heading-p) (call-interactively 'org-priority-up))
12283 ((org-at-item-p) (call-interactively 'org-previous-item))
12284 ((org-clocktable-try-shift 'up arg))
12285 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12287 (defun org-shiftdown (&optional arg)
12288 "Decrease item in timestamp or decrease priority of current headline.
12289 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12290 depending on context. See the individual commands for more information."
12291 (interactive "P")
12292 (cond
12293 ((org-at-timestamp-p t)
12294 (call-interactively (if org-edit-timestamp-down-means-later
12295 'org-timestamp-up 'org-timestamp-down)))
12296 ((org-on-heading-p) (call-interactively 'org-priority-down))
12297 ((org-clocktable-try-shift 'down arg))
12298 (t (call-interactively 'org-next-item))))
12300 (defun org-shiftright (&optional arg)
12301 "Next TODO keyword or timestamp one day later, depending on context."
12302 (interactive "P")
12303 (cond
12304 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12305 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12306 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12307 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12308 ((org-clocktable-try-shift 'right arg))
12309 (t (org-shiftcursor-error))))
12311 (defun org-shiftleft (&optional arg)
12312 "Previous TODO keyword or timestamp one day earlier, depending on context."
12313 (interactive "P")
12314 (cond
12315 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12316 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12317 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12318 ((org-at-property-p)
12319 (call-interactively 'org-property-previous-allowed-value))
12320 ((org-clocktable-try-shift 'left arg))
12321 (t (org-shiftcursor-error))))
12323 (defun org-shiftcontrolright ()
12324 "Switch to next TODO set."
12325 (interactive)
12326 (cond
12327 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12328 (t (org-shiftcursor-error))))
12330 (defun org-shiftcontrolleft ()
12331 "Switch to previous TODO set."
12332 (interactive)
12333 (cond
12334 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12335 (t (org-shiftcursor-error))))
12337 (defun org-ctrl-c-ret ()
12338 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12339 (interactive)
12340 (cond
12341 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12342 (t (call-interactively 'org-insert-heading))))
12344 (defun org-copy-special ()
12345 "Copy region in table or copy current subtree.
12346 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12347 See the individual commands for more information."
12348 (interactive)
12349 (call-interactively
12350 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12352 (defun org-cut-special ()
12353 "Cut region in table or cut current subtree.
12354 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12355 See the individual commands for more information."
12356 (interactive)
12357 (call-interactively
12358 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12360 (defun org-paste-special (arg)
12361 "Paste rectangular region into table, or past subtree relative to level.
12362 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12363 See the individual commands for more information."
12364 (interactive "P")
12365 (if (org-at-table-p)
12366 (org-table-paste-rectangle)
12367 (org-paste-subtree arg)))
12369 (defun org-ctrl-c-ctrl-c (&optional arg)
12370 "Set tags in headline, or update according to changed information at point.
12372 This command does many different things, depending on context:
12374 - If the cursor is in a headline, prompt for tags and insert them
12375 into the current line, aligned to `org-tags-column'. When called
12376 with prefix arg, realign all tags in the current buffer.
12378 - If the cursor is in one of the special #+KEYWORD lines, this
12379 triggers scanning the buffer for these lines and updating the
12380 information.
12382 - If the cursor is inside a table, realign the table. This command
12383 works even if the automatic table editor has been turned off.
12385 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12386 the entire table.
12388 - If the cursor is a the beginning of a dynamic block, update it.
12390 - If the cursor is inside a table created by the table.el package,
12391 activate that table.
12393 - If the current buffer is a remember buffer, close note and file it.
12394 with a prefix argument, file it without further interaction to the default
12395 location.
12397 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12398 links in this buffer.
12400 - If the cursor is on a numbered item in a plain list, renumber the
12401 ordered list.
12403 - If the cursor is on a checkbox, toggle it."
12404 (interactive "P")
12405 (let ((org-enable-table-editor t))
12406 (cond
12407 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12408 org-occur-highlights
12409 org-latex-fragment-image-overlays)
12410 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12411 (org-remove-occur-highlights)
12412 (org-remove-latex-fragment-image-overlays)
12413 (message "Temporary highlights/overlays removed from current buffer"))
12414 ((and (local-variable-p 'org-finish-function (current-buffer))
12415 (fboundp org-finish-function))
12416 (funcall org-finish-function))
12417 ((org-at-property-p)
12418 (call-interactively 'org-property-action))
12419 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12420 ((org-on-heading-p) (call-interactively 'org-set-tags))
12421 ((org-at-table.el-p)
12422 (require 'table)
12423 (beginning-of-line 1)
12424 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12425 (call-interactively 'table-recognize-table))
12426 ((org-at-table-p)
12427 (org-table-maybe-eval-formula)
12428 (if arg
12429 (call-interactively 'org-table-recalculate)
12430 (org-table-maybe-recalculate-line))
12431 (call-interactively 'org-table-align))
12432 ((org-at-item-checkbox-p)
12433 (call-interactively 'org-toggle-checkbox))
12434 ((org-at-item-p)
12435 (call-interactively 'org-maybe-renumber-ordered-list))
12436 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12437 ;; Dynamic block
12438 (beginning-of-line 1)
12439 (org-update-dblock))
12440 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12441 (cond
12442 ((equal (match-string 1) "TBLFM")
12443 ;; Recalculate the table before this line
12444 (save-excursion
12445 (beginning-of-line 1)
12446 (skip-chars-backward " \r\n\t")
12447 (if (org-at-table-p)
12448 (org-call-with-arg 'org-table-recalculate t))))
12450 ; (org-set-regexps-and-options)
12451 ; (org-restart-font-lock)
12452 (let ((org-inhibit-startup t)) (org-mode-restart))
12453 (message "Local setup has been refreshed"))))
12454 (t (error "C-c C-c can do nothing useful at this location.")))))
12456 (defun org-mode-restart ()
12457 "Restart Org-mode, to scan again for special lines.
12458 Also updates the keyword regular expressions."
12459 (interactive)
12460 (org-mode)
12461 (message "Org-mode restarted"))
12463 (defun org-kill-note-or-show-branches ()
12464 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12465 (interactive)
12466 (if (not org-finish-function)
12467 (call-interactively 'show-branches)
12468 (let ((org-note-abort t))
12469 (funcall org-finish-function))))
12471 (defun org-return (&optional indent)
12472 "Goto next table row or insert a newline.
12473 Calls `org-table-next-row' or `newline', depending on context.
12474 See the individual commands for more information."
12475 (interactive)
12476 (cond
12477 ((bobp) (if indent (newline-and-indent) (newline)))
12478 ((and (org-at-heading-p)
12479 (looking-at
12480 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12481 (org-show-entry)
12482 (end-of-line 1)
12483 (newline))
12484 ((org-at-table-p)
12485 (org-table-justify-field-maybe)
12486 (call-interactively 'org-table-next-row))
12487 (t (if indent (newline-and-indent) (newline)))))
12489 (defun org-return-indent ()
12490 "Goto next table row or insert a newline and indent.
12491 Calls `org-table-next-row' or `newline-and-indent', depending on
12492 context. See the individual commands for more information."
12493 (interactive)
12494 (org-return t))
12496 (defun org-ctrl-c-star ()
12497 "Compute table, or change heading status of lines.
12498 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12499 depending on context. This will also turn a plain list item or a normal
12500 line into a subheading."
12501 (interactive)
12502 (cond
12503 ((org-at-table-p)
12504 (call-interactively 'org-table-recalculate))
12505 ((org-region-active-p)
12506 ;; Convert all lines in region to list items
12507 (call-interactively 'org-toggle-region-headings))
12508 ((org-on-heading-p)
12509 (org-toggle-region-headings (point-at-bol)
12510 (min (1+ (point-at-eol)) (point-max))))
12511 ((org-at-item-p)
12512 ;; Convert to heading
12513 (let ((level (save-match-data
12514 (save-excursion
12515 (condition-case nil
12516 (progn
12517 (org-back-to-heading t)
12518 (funcall outline-level))
12519 (error 0))))))
12520 (replace-match
12521 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12522 (t (org-toggle-region-headings (point-at-bol)
12523 (min (1+ (point-at-eol)) (point-max))))))
12525 (defun org-ctrl-c-minus ()
12526 "Insert separator line in table or modify bullet status of line.
12527 Also turns a plain line or a region of lines into list items.
12528 Calls `org-table-insert-hline', `org-toggle-region-items', or
12529 `org-cycle-list-bullet', depending on context."
12530 (interactive)
12531 (cond
12532 ((org-at-table-p)
12533 (call-interactively 'org-table-insert-hline))
12534 ((org-on-heading-p)
12535 ;; Convert to item
12536 (save-excursion
12537 (beginning-of-line 1)
12538 (if (looking-at "\\*+ ")
12539 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12540 ((org-region-active-p)
12541 ;; Convert all lines in region to list items
12542 (call-interactively 'org-toggle-region-items))
12543 ((org-in-item-p)
12544 (call-interactively 'org-cycle-list-bullet))
12545 (t (org-toggle-region-items (point-at-bol)
12546 (min (1+ (point-at-eol)) (point-max))))))
12548 (defun org-toggle-region-items (beg end)
12549 "Convert all lines in region to list items.
12550 If the first line is already an item, convert all list items in the region
12551 to normal lines."
12552 (interactive "r")
12553 (let (l2 l)
12554 (save-excursion
12555 (goto-char end)
12556 (setq l2 (org-current-line))
12557 (goto-char beg)
12558 (beginning-of-line 1)
12559 (setq l (1- (org-current-line)))
12560 (if (org-at-item-p)
12561 ;; We already have items, de-itemize
12562 (while (< (setq l (1+ l)) l2)
12563 (when (org-at-item-p)
12564 (goto-char (match-beginning 2))
12565 (delete-region (match-beginning 2) (match-end 2))
12566 (and (looking-at "[ \t]+") (replace-match "")))
12567 (beginning-of-line 2))
12568 (while (< (setq l (1+ l)) l2)
12569 (unless (org-at-item-p)
12570 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12571 (replace-match "\\1- \\2")))
12572 (beginning-of-line 2))))))
12574 (defun org-toggle-region-headings (beg end)
12575 "Convert all lines in region to list items.
12576 If the first line is already an item, convert all list items in the region
12577 to normal lines."
12578 (interactive "r")
12579 (let (l2 l)
12580 (save-excursion
12581 (goto-char end)
12582 (setq l2 (org-current-line))
12583 (goto-char beg)
12584 (beginning-of-line 1)
12585 (setq l (1- (org-current-line)))
12586 (if (org-on-heading-p)
12587 ;; We already have headlines, de-star them
12588 (while (< (setq l (1+ l)) l2)
12589 (when (org-on-heading-p t)
12590 (and (looking-at outline-regexp) (replace-match "")))
12591 (beginning-of-line 2))
12592 (let* ((stars (save-excursion
12593 (re-search-backward org-complex-heading-regexp nil t)
12594 (or (match-string 1) "*")))
12595 (add-stars (if org-odd-levels-only "**" "*"))
12596 (rpl (concat stars add-stars " \\2")))
12597 (while (< (setq l (1+ l)) l2)
12598 (unless (org-on-heading-p)
12599 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12600 (replace-match rpl)))
12601 (beginning-of-line 2)))))))
12603 (defun org-meta-return (&optional arg)
12604 "Insert a new heading or wrap a region in a table.
12605 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12606 See the individual commands for more information."
12607 (interactive "P")
12608 (cond
12609 ((org-at-table-p)
12610 (call-interactively 'org-table-wrap-region))
12611 (t (call-interactively 'org-insert-heading))))
12613 ;;; Menu entries
12615 ;; Define the Org-mode menus
12616 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12617 '("Tbl"
12618 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12619 ["Next Field" org-cycle (org-at-table-p)]
12620 ["Previous Field" org-shifttab (org-at-table-p)]
12621 ["Next Row" org-return (org-at-table-p)]
12622 "--"
12623 ["Blank Field" org-table-blank-field (org-at-table-p)]
12624 ["Edit Field" org-table-edit-field (org-at-table-p)]
12625 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12626 "--"
12627 ("Column"
12628 ["Move Column Left" org-metaleft (org-at-table-p)]
12629 ["Move Column Right" org-metaright (org-at-table-p)]
12630 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12631 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12632 ("Row"
12633 ["Move Row Up" org-metaup (org-at-table-p)]
12634 ["Move Row Down" org-metadown (org-at-table-p)]
12635 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12636 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12637 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12638 "--"
12639 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12640 ("Rectangle"
12641 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12642 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12643 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12644 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12645 "--"
12646 ("Calculate"
12647 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12648 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12649 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12650 "--"
12651 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12652 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12653 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12654 "--"
12655 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12656 "--"
12657 ["Sum Column/Rectangle" org-table-sum
12658 (or (org-at-table-p) (org-region-active-p))]
12659 ["Which Column?" org-table-current-column (org-at-table-p)])
12660 ["Debug Formulas"
12661 org-table-toggle-formula-debugger
12662 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12663 ["Show Col/Row Numbers"
12664 org-table-toggle-coordinate-overlays
12665 :style toggle
12666 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12667 "--"
12668 ["Create" org-table-create (and (not (org-at-table-p))
12669 org-enable-table-editor)]
12670 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12671 ["Import from File" org-table-import (not (org-at-table-p))]
12672 ["Export to File" org-table-export (org-at-table-p)]
12673 "--"
12674 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12676 (easy-menu-define org-org-menu org-mode-map "Org menu"
12677 '("Org"
12678 ("Show/Hide"
12679 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12680 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12681 ["Sparse Tree..." org-sparse-tree t]
12682 ["Reveal Context" org-reveal t]
12683 ["Show All" show-all t]
12684 "--"
12685 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12686 "--"
12687 ["New Heading" org-insert-heading t]
12688 ("Navigate Headings"
12689 ["Up" outline-up-heading t]
12690 ["Next" outline-next-visible-heading t]
12691 ["Previous" outline-previous-visible-heading t]
12692 ["Next Same Level" outline-forward-same-level t]
12693 ["Previous Same Level" outline-backward-same-level t]
12694 "--"
12695 ["Jump" org-goto t])
12696 ("Edit Structure"
12697 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12698 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12699 "--"
12700 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12701 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12702 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12703 "--"
12704 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12705 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12706 ["Demote Heading" org-metaright (not (org-at-table-p))]
12707 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12708 "--"
12709 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12710 "--"
12711 ["Convert to odd levels" org-convert-to-odd-levels t]
12712 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12713 ("Editing"
12714 ["Emphasis..." org-emphasize t])
12715 ("Archive"
12716 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12717 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12718 ; :active t :keys "C-u C-c C-x C-a"]
12719 ["Sparse trees open ARCHIVE trees"
12720 (setq org-sparse-tree-open-archived-trees
12721 (not org-sparse-tree-open-archived-trees))
12722 :style toggle :selected org-sparse-tree-open-archived-trees]
12723 ["Cycling opens ARCHIVE trees"
12724 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12725 :style toggle :selected org-cycle-open-archived-trees]
12726 ["Agenda includes ARCHIVE trees"
12727 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12728 :style toggle :selected (not org-agenda-skip-archived-trees)]
12729 "--"
12730 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12731 ; ["Check and Move Children" (org-archive-subtree '(4))
12732 ; :active t :keys "C-u C-c C-x C-s"]
12734 "--"
12735 ("TODO Lists"
12736 ["TODO/DONE/-" org-todo t]
12737 ("Select keyword"
12738 ["Next keyword" org-shiftright (org-on-heading-p)]
12739 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12740 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12741 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12742 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12743 ["Show TODO Tree" org-show-todo-tree t]
12744 ["Global TODO list" org-todo-list t]
12745 "--"
12746 ["Set Priority" org-priority t]
12747 ["Priority Up" org-shiftup t]
12748 ["Priority Down" org-shiftdown t])
12749 ("TAGS and Properties"
12750 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12751 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12752 "--"
12753 ["Set property" 'org-set-property t]
12754 ["Column view of properties" org-columns t]
12755 ["Insert Column View DBlock" org-insert-columns-dblock t])
12756 ("Dates and Scheduling"
12757 ["Timestamp" org-time-stamp t]
12758 ["Timestamp (inactive)" org-time-stamp-inactive t]
12759 ("Change Date"
12760 ["1 Day Later" org-shiftright t]
12761 ["1 Day Earlier" org-shiftleft t]
12762 ["1 ... Later" org-shiftup t]
12763 ["1 ... Earlier" org-shiftdown t])
12764 ["Compute Time Range" org-evaluate-time-range t]
12765 ["Schedule Item" org-schedule t]
12766 ["Deadline" org-deadline t]
12767 "--"
12768 ["Custom time format" org-toggle-time-stamp-overlays
12769 :style radio :selected org-display-custom-times]
12770 "--"
12771 ["Goto Calendar" org-goto-calendar t]
12772 ["Date from Calendar" org-date-from-calendar t])
12773 ("Logging work"
12774 ["Clock in" org-clock-in t]
12775 ["Clock out" org-clock-out t]
12776 ["Clock cancel" org-clock-cancel t]
12777 ["Goto running clock" org-clock-goto t]
12778 ["Display times" org-clock-display t]
12779 ["Create clock table" org-clock-report t]
12780 "--"
12781 ["Record DONE time"
12782 (progn (setq org-log-done (not org-log-done))
12783 (message "Switching to %s will %s record a timestamp"
12784 (car org-done-keywords)
12785 (if org-log-done "automatically" "not")))
12786 :style toggle :selected org-log-done])
12787 "--"
12788 ["Agenda Command..." org-agenda t]
12789 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12790 ("File List for Agenda")
12791 ("Special views current file"
12792 ["TODO Tree" org-show-todo-tree t]
12793 ["Check Deadlines" org-check-deadlines t]
12794 ["Timeline" org-timeline t]
12795 ["Tags Tree" org-tags-sparse-tree t])
12796 "--"
12797 ("Hyperlinks"
12798 ["Store Link (Global)" org-store-link t]
12799 ["Insert Link" org-insert-link t]
12800 ["Follow Link" org-open-at-point t]
12801 "--"
12802 ["Next link" org-next-link t]
12803 ["Previous link" org-previous-link t]
12804 "--"
12805 ["Descriptive Links"
12806 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12807 :style radio
12808 :selected (member '(org-link) buffer-invisibility-spec)]
12809 ["Literal Links"
12810 (progn
12811 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12812 :style radio
12813 :selected (not (member '(org-link) buffer-invisibility-spec))])
12814 "--"
12815 ["Export/Publish..." org-export t]
12816 ("LaTeX"
12817 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12818 :selected org-cdlatex-mode]
12819 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12820 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12821 ["Modify math symbol" org-cdlatex-math-modify
12822 (org-inside-LaTeX-fragment-p)]
12823 ["Export LaTeX fragments as images"
12824 (if (featurep 'org-exp)
12825 (setq org-export-with-LaTeX-fragments
12826 (not org-export-with-LaTeX-fragments))
12827 (require 'org-exp))
12828 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12829 org-export-with-LaTeX-fragments)])
12830 "--"
12831 ("Documentation"
12832 ["Show Version" org-version t]
12833 ["Info Documentation" org-info t])
12834 ("Customize"
12835 ["Browse Org Group" org-customize t]
12836 "--"
12837 ["Expand This Menu" org-create-customize-menu
12838 (fboundp 'customize-menu-create)])
12839 "--"
12840 ["Refresh setup" org-mode-restart t]
12843 (defun org-info (&optional node)
12844 "Read documentation for Org-mode in the info system.
12845 With optional NODE, go directly to that node."
12846 (interactive)
12847 (info (format "(org)%s" (or node ""))))
12849 (defun org-install-agenda-files-menu ()
12850 (let ((bl (buffer-list)))
12851 (save-excursion
12852 (while bl
12853 (set-buffer (pop bl))
12854 (if (org-mode-p) (setq bl nil)))
12855 (when (org-mode-p)
12856 (easy-menu-change
12857 '("Org") "File List for Agenda"
12858 (append
12859 (list
12860 ["Edit File List" (org-edit-agenda-file-list) t]
12861 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12862 ["Remove Current File from List" org-remove-file t]
12863 ["Cycle through agenda files" org-cycle-agenda-files t]
12864 ["Occur in all agenda files" org-occur-in-agenda-files t]
12865 "--")
12866 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12868 ;;;; Documentation
12870 (defun org-require-autoloaded-modules ()
12871 (interactive)
12872 (mapc 'require
12873 '(org-agenda org-archive org-clock org-colview
12874 org-exp org-export-latex org-publish
12875 org-remember org-table)))
12877 (defun org-customize ()
12878 "Call the customize function with org as argument."
12879 (interactive)
12880 (org-load-modules-maybe)
12881 (org-require-autoloaded-modules)
12882 (customize-browse 'org))
12884 (defun org-create-customize-menu ()
12885 "Create a full customization menu for Org-mode, insert it into the menu."
12886 (interactive)
12887 (org-load-modules-maybe)
12888 (org-require-autoloaded-modules)
12889 (if (fboundp 'customize-menu-create)
12890 (progn
12891 (easy-menu-change
12892 '("Org") "Customize"
12893 `(["Browse Org group" org-customize t]
12894 "--"
12895 ,(customize-menu-create 'org)
12896 ["Set" Custom-set t]
12897 ["Save" Custom-save t]
12898 ["Reset to Current" Custom-reset-current t]
12899 ["Reset to Saved" Custom-reset-saved t]
12900 ["Reset to Standard Settings" Custom-reset-standard t]))
12901 (message "\"Org\"-menu now contains full customization menu"))
12902 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12904 ;;;; Miscellaneous stuff
12906 ;;; Generally useful functions
12908 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12909 "Display the given MESSAGE as a warning."
12910 (if (fboundp 'display-warning)
12911 (display-warning 'org message
12912 (if (featurep 'xemacs)
12913 'warning
12914 :warning))
12915 (let ((buf (get-buffer-create "*Org warnings*")))
12916 (with-current-buffer buf
12917 (goto-char (point-max))
12918 (insert "Warning (Org): " message)
12919 (unless (bolp)
12920 (newline)))
12921 (display-buffer buf)
12922 (sit-for 0))))
12924 (defun org-quote-csv-field (s)
12925 "Quote field for inclusion in CSV material."
12926 (if (string-match "[\",]" s)
12927 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
12930 (defun org-plist-delete (plist property)
12931 "Delete PROPERTY from PLIST.
12932 This is in contrast to merely setting it to 0."
12933 (let (p)
12934 (while plist
12935 (if (not (eq property (car plist)))
12936 (setq p (plist-put p (car plist) (nth 1 plist))))
12937 (setq plist (cddr plist)))
12940 (defun org-force-self-insert (N)
12941 "Needed to enforce self-insert under remapping."
12942 (interactive "p")
12943 (self-insert-command N))
12945 (defun org-string-width (s)
12946 "Compute width of string, ignoring invisible characters.
12947 This ignores character with invisibility property `org-link', and also
12948 characters with property `org-cwidth', because these will become invisible
12949 upon the next fontification round."
12950 (let (b l)
12951 (when (or (eq t buffer-invisibility-spec)
12952 (assq 'org-link buffer-invisibility-spec))
12953 (while (setq b (text-property-any 0 (length s)
12954 'invisible 'org-link s))
12955 (setq s (concat (substring s 0 b)
12956 (substring s (or (next-single-property-change
12957 b 'invisible s) (length s)))))))
12958 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12959 (setq s (concat (substring s 0 b)
12960 (substring s (or (next-single-property-change
12961 b 'org-cwidth s) (length s))))))
12962 (setq l (string-width s) b -1)
12963 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12964 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12967 (defun org-base-buffer (buffer)
12968 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12969 (if (not buffer)
12970 buffer
12971 (or (buffer-base-buffer buffer)
12972 buffer)))
12974 (defun org-trim (s)
12975 "Remove whitespace at beginning and end of string."
12976 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12977 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12980 (defun org-wrap (string &optional width lines)
12981 "Wrap string to either a number of lines, or a width in characters.
12982 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12983 that costs. If there is a word longer than WIDTH, the text is actually
12984 wrapped to the length of that word.
12985 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12986 many lines, whatever width that takes.
12987 The return value is a list of lines, without newlines at the end."
12988 (let* ((words (org-split-string string "[ \t\n]+"))
12989 (maxword (apply 'max (mapcar 'org-string-width words)))
12990 w ll)
12991 (cond (width
12992 (org-do-wrap words (max maxword width)))
12993 (lines
12994 (setq w maxword)
12995 (setq ll (org-do-wrap words maxword))
12996 (if (<= (length ll) lines)
12998 (setq ll words)
12999 (while (> (length ll) lines)
13000 (setq w (1+ w))
13001 (setq ll (org-do-wrap words w)))
13002 ll))
13003 (t (error "Cannot wrap this")))))
13005 (defun org-do-wrap (words width)
13006 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13007 (let (lines line)
13008 (while words
13009 (setq line (pop words))
13010 (while (and words (< (+ (length line) (length (car words))) width))
13011 (setq line (concat line " " (pop words))))
13012 (setq lines (push line lines)))
13013 (nreverse lines)))
13015 (defun org-split-string (string &optional separators)
13016 "Splits STRING into substrings at SEPARATORS.
13017 No empty strings are returned if there are matches at the beginning
13018 and end of string."
13019 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13020 (start 0)
13021 notfirst
13022 (list nil))
13023 (while (and (string-match rexp string
13024 (if (and notfirst
13025 (= start (match-beginning 0))
13026 (< start (length string)))
13027 (1+ start) start))
13028 (< (match-beginning 0) (length string)))
13029 (setq notfirst t)
13030 (or (eq (match-beginning 0) 0)
13031 (and (eq (match-beginning 0) (match-end 0))
13032 (eq (match-beginning 0) start))
13033 (setq list
13034 (cons (substring string start (match-beginning 0))
13035 list)))
13036 (setq start (match-end 0)))
13037 (or (eq start (length string))
13038 (setq list
13039 (cons (substring string start)
13040 list)))
13041 (nreverse list)))
13043 (defun org-context ()
13044 "Return a list of contexts of the current cursor position.
13045 If several contexts apply, all are returned.
13046 Each context entry is a list with a symbol naming the context, and
13047 two positions indicating start and end of the context. Possible
13048 contexts are:
13050 :headline anywhere in a headline
13051 :headline-stars on the leading stars in a headline
13052 :todo-keyword on a TODO keyword (including DONE) in a headline
13053 :tags on the TAGS in a headline
13054 :priority on the priority cookie in a headline
13055 :item on the first line of a plain list item
13056 :item-bullet on the bullet/number of a plain list item
13057 :checkbox on the checkbox in a plain list item
13058 :table in an org-mode table
13059 :table-special on a special filed in a table
13060 :table-table in a table.el table
13061 :link on a hyperlink
13062 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13063 :target on a <<target>>
13064 :radio-target on a <<<radio-target>>>
13065 :latex-fragment on a LaTeX fragment
13066 :latex-preview on a LaTeX fragment with overlayed preview image
13068 This function expects the position to be visible because it uses font-lock
13069 faces as a help to recognize the following contexts: :table-special, :link,
13070 and :keyword."
13071 (let* ((f (get-text-property (point) 'face))
13072 (faces (if (listp f) f (list f)))
13073 (p (point)) clist o)
13074 ;; First the large context
13075 (cond
13076 ((org-on-heading-p t)
13077 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13078 (when (progn
13079 (beginning-of-line 1)
13080 (looking-at org-todo-line-tags-regexp))
13081 (push (org-point-in-group p 1 :headline-stars) clist)
13082 (push (org-point-in-group p 2 :todo-keyword) clist)
13083 (push (org-point-in-group p 4 :tags) clist))
13084 (goto-char p)
13085 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13086 (if (looking-at "\\[#[A-Z0-9]\\]")
13087 (push (org-point-in-group p 0 :priority) clist)))
13089 ((org-at-item-p)
13090 (push (org-point-in-group p 2 :item-bullet) clist)
13091 (push (list :item (point-at-bol)
13092 (save-excursion (org-end-of-item) (point)))
13093 clist)
13094 (and (org-at-item-checkbox-p)
13095 (push (org-point-in-group p 0 :checkbox) clist)))
13097 ((org-at-table-p)
13098 (push (list :table (org-table-begin) (org-table-end)) clist)
13099 (if (memq 'org-formula faces)
13100 (push (list :table-special
13101 (previous-single-property-change p 'face)
13102 (next-single-property-change p 'face)) clist)))
13103 ((org-at-table-p 'any)
13104 (push (list :table-table) clist)))
13105 (goto-char p)
13107 ;; Now the small context
13108 (cond
13109 ((org-at-timestamp-p)
13110 (push (org-point-in-group p 0 :timestamp) clist))
13111 ((memq 'org-link faces)
13112 (push (list :link
13113 (previous-single-property-change p 'face)
13114 (next-single-property-change p 'face)) clist))
13115 ((memq 'org-special-keyword faces)
13116 (push (list :keyword
13117 (previous-single-property-change p 'face)
13118 (next-single-property-change p 'face)) clist))
13119 ((org-on-target-p)
13120 (push (org-point-in-group p 0 :target) clist)
13121 (goto-char (1- (match-beginning 0)))
13122 (if (looking-at org-radio-target-regexp)
13123 (push (org-point-in-group p 0 :radio-target) clist))
13124 (goto-char p))
13125 ((setq o (car (delq nil
13126 (mapcar
13127 (lambda (x)
13128 (if (memq x org-latex-fragment-image-overlays) x))
13129 (org-overlays-at (point))))))
13130 (push (list :latex-fragment
13131 (org-overlay-start o) (org-overlay-end o)) clist)
13132 (push (list :latex-preview
13133 (org-overlay-start o) (org-overlay-end o)) clist))
13134 ((org-inside-LaTeX-fragment-p)
13135 ;; FIXME: positions wrong.
13136 (push (list :latex-fragment (point) (point)) clist)))
13138 (setq clist (nreverse (delq nil clist)))
13139 clist))
13141 ;; FIXME: Compare with at-regexp-p Do we need both?
13142 (defun org-in-regexp (re &optional nlines visually)
13143 "Check if point is inside a match of regexp.
13144 Normally only the current line is checked, but you can include NLINES extra
13145 lines both before and after point into the search.
13146 If VISUALLY is set, require that the cursor is not after the match but
13147 really on, so that the block visually is on the match."
13148 (catch 'exit
13149 (let ((pos (point))
13150 (eol (point-at-eol (+ 1 (or nlines 0))))
13151 (inc (if visually 1 0)))
13152 (save-excursion
13153 (beginning-of-line (- 1 (or nlines 0)))
13154 (while (re-search-forward re eol t)
13155 (if (and (<= (match-beginning 0) pos)
13156 (>= (+ inc (match-end 0)) pos))
13157 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13159 (defun org-at-regexp-p (regexp)
13160 "Is point inside a match of REGEXP in the current line?"
13161 (catch 'exit
13162 (save-excursion
13163 (let ((pos (point)) (end (point-at-eol)))
13164 (beginning-of-line 1)
13165 (while (re-search-forward regexp end t)
13166 (if (and (<= (match-beginning 0) pos)
13167 (>= (match-end 0) pos))
13168 (throw 'exit t)))
13169 nil))))
13171 (defun org-occur-in-agenda-files (regexp &optional nlines)
13172 "Call `multi-occur' with buffers for all agenda files."
13173 (interactive "sOrg-files matching: \np")
13174 (let* ((files (org-agenda-files))
13175 (tnames (mapcar 'file-truename files))
13176 (extra org-agenda-text-search-extra-files)
13178 (when (eq (car extra) 'agenda-archives)
13179 (setq extra (cdr extra))
13180 (setq files (org-add-archive-files files)))
13181 (while (setq f (pop extra))
13182 (unless (member (file-truename f) tnames)
13183 (add-to-list 'files f 'append)
13184 (add-to-list 'tnames (file-truename f) 'append)))
13185 (multi-occur
13186 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13187 regexp)))
13189 (if (boundp 'occur-mode-find-occurrence-hook)
13190 ;; Emacs 23
13191 (add-hook 'occur-mode-find-occurrence-hook
13192 (lambda ()
13193 (when (org-mode-p)
13194 (org-reveal))))
13195 ;; Emacs 22
13196 (defadvice occur-mode-goto-occurrence
13197 (after org-occur-reveal activate)
13198 (and (org-mode-p) (org-reveal)))
13199 (defadvice occur-mode-goto-occurrence-other-window
13200 (after org-occur-reveal activate)
13201 (and (org-mode-p) (org-reveal)))
13202 (defadvice occur-mode-display-occurrence
13203 (after org-occur-reveal activate)
13204 (when (org-mode-p)
13205 (let ((pos (occur-mode-find-occurrence)))
13206 (with-current-buffer (marker-buffer pos)
13207 (save-excursion
13208 (goto-char pos)
13209 (org-reveal)))))))
13211 (defun org-uniquify (list)
13212 "Remove duplicate elements from LIST."
13213 (let (res)
13214 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13215 res))
13217 (defun org-delete-all (elts list)
13218 "Remove all elements in ELTS from LIST."
13219 (while elts
13220 (setq list (delete (pop elts) list)))
13221 list)
13223 (defun org-back-over-empty-lines ()
13224 "Move backwards over witespace, to the beginning of the first empty line.
13225 Returns the number of empty lines passed."
13226 (let ((pos (point)))
13227 (skip-chars-backward " \t\n\r")
13228 (beginning-of-line 2)
13229 (goto-char (min (point) pos))
13230 (count-lines (point) pos)))
13232 (defun org-skip-whitespace ()
13233 (skip-chars-forward " \t\n\r"))
13235 (defun org-point-in-group (point group &optional context)
13236 "Check if POINT is in match-group GROUP.
13237 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13238 match. If the match group does ot exist or point is not inside it,
13239 return nil."
13240 (and (match-beginning group)
13241 (>= point (match-beginning group))
13242 (<= point (match-end group))
13243 (if context
13244 (list context (match-beginning group) (match-end group))
13245 t)))
13247 (defun org-switch-to-buffer-other-window (&rest args)
13248 "Switch to buffer in a second window on the current frame.
13249 In particular, do not allow pop-up frames."
13250 (let (pop-up-frames special-display-buffer-names special-display-regexps
13251 special-display-function)
13252 (apply 'switch-to-buffer-other-window args)))
13254 (defun org-combine-plists (&rest plists)
13255 "Create a single property list from all plists in PLISTS.
13256 The process starts by copying the first list, and then setting properties
13257 from the other lists. Settings in the last list are the most significant
13258 ones and overrule settings in the other lists."
13259 (let ((rtn (copy-sequence (pop plists)))
13260 p v ls)
13261 (while plists
13262 (setq ls (pop plists))
13263 (while ls
13264 (setq p (pop ls) v (pop ls))
13265 (setq rtn (plist-put rtn p v))))
13266 rtn))
13268 (defun org-move-line-down (arg)
13269 "Move the current line down. With prefix argument, move it past ARG lines."
13270 (interactive "p")
13271 (let ((col (current-column))
13272 beg end pos)
13273 (beginning-of-line 1) (setq beg (point))
13274 (beginning-of-line 2) (setq end (point))
13275 (beginning-of-line (+ 1 arg))
13276 (setq pos (move-marker (make-marker) (point)))
13277 (insert (delete-and-extract-region beg end))
13278 (goto-char pos)
13279 (org-move-to-column col)))
13281 (defun org-move-line-up (arg)
13282 "Move the current line up. With prefix argument, move it past ARG lines."
13283 (interactive "p")
13284 (let ((col (current-column))
13285 beg end pos)
13286 (beginning-of-line 1) (setq beg (point))
13287 (beginning-of-line 2) (setq end (point))
13288 (beginning-of-line (- arg))
13289 (setq pos (move-marker (make-marker) (point)))
13290 (insert (delete-and-extract-region beg end))
13291 (goto-char pos)
13292 (org-move-to-column col)))
13294 (defun org-replace-escapes (string table)
13295 "Replace %-escapes in STRING with values in TABLE.
13296 TABLE is an association list with keys like \"%a\" and string values.
13297 The sequences in STRING may contain normal field width and padding information,
13298 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13299 so values can contain further %-escapes if they are define later in TABLE."
13300 (let ((case-fold-search nil)
13301 e re rpl)
13302 (while (setq e (pop table))
13303 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13304 (while (string-match re string)
13305 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13306 (cdr e)))
13307 (setq string (replace-match rpl t t string))))
13308 string))
13311 (defun org-sublist (list start end)
13312 "Return a section of LIST, from START to END.
13313 Counting starts at 1."
13314 (let (rtn (c start))
13315 (setq list (nthcdr (1- start) list))
13316 (while (and list (<= c end))
13317 (push (pop list) rtn)
13318 (setq c (1+ c)))
13319 (nreverse rtn)))
13321 (defun org-find-base-buffer-visiting (file)
13322 "Like `find-buffer-visiting' but alway return the base buffer and
13323 not an indirect buffer."
13324 (let ((buf (find-buffer-visiting file)))
13325 (if buf
13326 (or (buffer-base-buffer buf) buf)
13327 nil)))
13329 (defun org-image-file-name-regexp ()
13330 "Return regexp matching the file names of images."
13331 (if (fboundp 'image-file-name-regexp)
13332 (image-file-name-regexp)
13333 (let ((image-file-name-extensions
13334 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13335 "xbm" "xpm" "pbm" "pgm" "ppm")))
13336 (concat "\\."
13337 (regexp-opt (nconc (mapcar 'upcase
13338 image-file-name-extensions)
13339 image-file-name-extensions)
13341 "\\'"))))
13343 (defun org-file-image-p (file)
13344 "Return non-nil if FILE is an image."
13345 (save-match-data
13346 (string-match (org-image-file-name-regexp) file)))
13348 ;;; Paragraph filling stuff.
13349 ;; We want this to be just right, so use the full arsenal.
13351 (defun org-indent-line-function ()
13352 "Indent line like previous, but further if previous was headline or item."
13353 (interactive)
13354 (let* ((pos (point))
13355 (itemp (org-at-item-p))
13356 column bpos bcol tpos tcol bullet btype bullet-type)
13357 ;; Find the previous relevant line
13358 (beginning-of-line 1)
13359 (cond
13360 ((looking-at "#") (setq column 0))
13361 ((looking-at "\\*+ ") (setq column 0))
13363 (beginning-of-line 0)
13364 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13365 (beginning-of-line 0))
13366 (cond
13367 ((looking-at "\\*+[ \t]+")
13368 (goto-char (match-end 0))
13369 (setq column (current-column)))
13370 ((org-in-item-p)
13371 (org-beginning-of-item)
13372 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13373 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13374 (setq bpos (match-beginning 1) tpos (match-end 0)
13375 bcol (progn (goto-char bpos) (current-column))
13376 tcol (progn (goto-char tpos) (current-column))
13377 bullet (match-string 1)
13378 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13379 (if (not itemp)
13380 (setq column tcol)
13381 (goto-char pos)
13382 (beginning-of-line 1)
13383 (if (looking-at "\\S-")
13384 (progn
13385 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13386 (setq bullet (match-string 1)
13387 btype (if (string-match "[0-9]" bullet) "n" bullet))
13388 (setq column (if (equal btype bullet-type) bcol tcol)))
13389 (setq column (org-get-indentation)))))
13390 (t (setq column (org-get-indentation))))))
13391 (goto-char pos)
13392 (if (<= (current-column) (current-indentation))
13393 (org-indent-line-to column)
13394 (save-excursion (org-indent-line-to column)))
13395 (setq column (current-column))
13396 (beginning-of-line 1)
13397 (if (looking-at
13398 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13399 (replace-match (concat "\\1" (format org-property-format
13400 (match-string 2) (match-string 3)))
13401 t nil))
13402 (org-move-to-column column)))
13404 (defun org-set-autofill-regexps ()
13405 (interactive)
13406 ;; In the paragraph separator we include headlines, because filling
13407 ;; text in a line directly attached to a headline would otherwise
13408 ;; fill the headline as well.
13409 (org-set-local 'comment-start-skip "^#+[ \t]*")
13410 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13411 ;; The paragraph starter includes hand-formatted lists.
13412 (org-set-local 'paragraph-start
13413 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13414 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13415 ;; But only if the user has not turned off tables or fixed-width regions
13416 (org-set-local
13417 'auto-fill-inhibit-regexp
13418 (concat "\\*+ \\|#\\+"
13419 "\\|[ \t]*" org-keyword-time-regexp
13420 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13421 (concat
13422 "\\|[ \t]*["
13423 (if org-enable-table-editor "|" "")
13424 (if org-enable-fixed-width-editor ":" "")
13425 "]"))))
13426 ;; We use our own fill-paragraph function, to make sure that tables
13427 ;; and fixed-width regions are not wrapped. That function will pass
13428 ;; through to `fill-paragraph' when appropriate.
13429 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13430 ; Adaptive filling: To get full control, first make sure that
13431 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13432 (org-set-local 'adaptive-fill-regexp "\000")
13433 (org-set-local 'adaptive-fill-function
13434 'org-adaptive-fill-function)
13435 (org-set-local
13436 'align-mode-rules-list
13437 '((org-in-buffer-settings
13438 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13439 (modes . '(org-mode))))))
13441 (defun org-fill-paragraph (&optional justify)
13442 "Re-align a table, pass through to fill-paragraph if no table."
13443 (let ((table-p (org-at-table-p))
13444 (table.el-p (org-at-table.el-p)))
13445 (cond ((and (equal (char-after (point-at-bol)) ?*)
13446 (save-excursion (goto-char (point-at-bol))
13447 (looking-at outline-regexp)))
13448 t) ; skip headlines
13449 (table.el-p t) ; skip table.el tables
13450 (table-p (org-table-align) t) ; align org-mode tables
13451 (t nil)))) ; call paragraph-fill
13453 ;; For reference, this is the default value of adaptive-fill-regexp
13454 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13456 (defun org-adaptive-fill-function ()
13457 "Return a fill prefix for org-mode files.
13458 In particular, this makes sure hanging paragraphs for hand-formatted lists
13459 work correctly."
13460 (cond ((looking-at "#[ \t]+")
13461 (match-string 0))
13462 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13463 (save-excursion
13464 (goto-char (match-end 0))
13465 (make-string (current-column) ?\ )))
13466 (t nil)))
13468 ;;; Other stuff.
13470 (defun org-toggle-fixed-width-section (arg)
13471 "Toggle the fixed-width export.
13472 If there is no active region, the QUOTE keyword at the current headline is
13473 inserted or removed. When present, it causes the text between this headline
13474 and the next to be exported as fixed-width text, and unmodified.
13475 If there is an active region, this command adds or removes a colon as the
13476 first character of this line. If the first character of a line is a colon,
13477 this line is also exported in fixed-width font."
13478 (interactive "P")
13479 (let* ((cc 0)
13480 (regionp (org-region-active-p))
13481 (beg (if regionp (region-beginning) (point)))
13482 (end (if regionp (region-end)))
13483 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13484 (case-fold-search nil)
13485 (re "[ \t]*\\(:\\)")
13486 off)
13487 (if regionp
13488 (save-excursion
13489 (goto-char beg)
13490 (setq cc (current-column))
13491 (beginning-of-line 1)
13492 (setq off (looking-at re))
13493 (while (> nlines 0)
13494 (setq nlines (1- nlines))
13495 (beginning-of-line 1)
13496 (cond
13497 (arg
13498 (org-move-to-column cc t)
13499 (insert ":\n")
13500 (forward-line -1))
13501 ((and off (looking-at re))
13502 (replace-match "" t t nil 1))
13503 ((not off) (org-move-to-column cc t) (insert ":")))
13504 (forward-line 1)))
13505 (save-excursion
13506 (org-back-to-heading)
13507 (if (looking-at (concat outline-regexp
13508 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13509 (replace-match "" t t nil 1)
13510 (if (looking-at outline-regexp)
13511 (progn
13512 (goto-char (match-end 0))
13513 (insert org-quote-string " "))))))))
13515 ;;;; Functions extending outline functionality
13517 (defun org-beginning-of-line (&optional arg)
13518 "Go to the beginning of the current line. If that is invisible, continue
13519 to a visible line beginning. This makes the function of C-a more intuitive.
13520 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13521 first attempt, and only move to after the tags when the cursor is already
13522 beyond the end of the headline."
13523 (interactive "P")
13524 (let ((pos (point)))
13525 (beginning-of-line 1)
13526 (if (bobp)
13528 (backward-char 1)
13529 (if (org-invisible-p)
13530 (while (and (not (bobp)) (org-invisible-p))
13531 (backward-char 1)
13532 (beginning-of-line 1))
13533 (forward-char 1)))
13534 (when org-special-ctrl-a/e
13535 (cond
13536 ((and (looking-at org-todo-line-regexp)
13537 (= (char-after (match-end 1)) ?\ ))
13538 (goto-char
13539 (if (eq org-special-ctrl-a/e t)
13540 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13541 ((= pos (point)) (match-beginning 3))
13542 (t (point)))
13543 (cond ((> pos (point)) (point))
13544 ((not (eq last-command this-command)) (point))
13545 (t (match-beginning 3))))))
13546 ((org-at-item-p)
13547 (goto-char
13548 (if (eq org-special-ctrl-a/e t)
13549 (cond ((> pos (match-end 4)) (match-end 4))
13550 ((= pos (point)) (match-end 4))
13551 (t (point)))
13552 (cond ((> pos (point)) (point))
13553 ((not (eq last-command this-command)) (point))
13554 (t (match-end 4))))))))))
13556 (defun org-end-of-line (&optional arg)
13557 "Go to the end of the line.
13558 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13559 first attempt, and only move to after the tags when the cursor is already
13560 beyond the end of the headline."
13561 (interactive "P")
13562 (if (or (not org-special-ctrl-a/e)
13563 (not (org-on-heading-p)))
13564 (end-of-line arg)
13565 (let ((pos (point)))
13566 (beginning-of-line 1)
13567 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13568 (if (eq org-special-ctrl-a/e t)
13569 (if (or (< pos (match-beginning 1))
13570 (= pos (match-end 0)))
13571 (goto-char (match-beginning 1))
13572 (goto-char (match-end 0)))
13573 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13574 (goto-char (match-end 0))
13575 (goto-char (match-beginning 1))))
13576 (end-of-line arg)))))
13578 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13579 (define-key org-mode-map "\C-e" 'org-end-of-line)
13581 (defun org-kill-line (&optional arg)
13582 "Kill line, to tags or end of line."
13583 (interactive "P")
13584 (cond
13585 ((or (not org-special-ctrl-k)
13586 (bolp)
13587 (not (org-on-heading-p)))
13588 (call-interactively 'kill-line))
13589 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13590 (kill-region (point) (match-beginning 1))
13591 (org-set-tags nil t))
13592 (t (kill-region (point) (point-at-eol)))))
13594 (define-key org-mode-map "\C-k" 'org-kill-line)
13596 (defun org-invisible-p ()
13597 "Check if point is at a character currently not visible."
13598 ;; Early versions of noutline don't have `outline-invisible-p'.
13599 (if (fboundp 'outline-invisible-p)
13600 (outline-invisible-p)
13601 (get-char-property (point) 'invisible)))
13603 (defun org-invisible-p2 ()
13604 "Check if point is at a character currently not visible."
13605 (save-excursion
13606 (if (and (eolp) (not (bobp))) (backward-char 1))
13607 ;; Early versions of noutline don't have `outline-invisible-p'.
13608 (if (fboundp 'outline-invisible-p)
13609 (outline-invisible-p)
13610 (get-char-property (point) 'invisible))))
13612 (defalias 'org-back-to-heading 'outline-back-to-heading)
13613 (defalias 'org-on-heading-p 'outline-on-heading-p)
13614 (defalias 'org-at-heading-p 'outline-on-heading-p)
13615 (defun org-at-heading-or-item-p ()
13616 (or (org-on-heading-p) (org-at-item-p)))
13618 (defun org-on-target-p ()
13619 (or (org-in-regexp org-radio-target-regexp)
13620 (org-in-regexp org-target-regexp)))
13622 (defun org-up-heading-all (arg)
13623 "Move to the heading line of which the present line is a subheading.
13624 This function considers both visible and invisible heading lines.
13625 With argument, move up ARG levels."
13626 (if (fboundp 'outline-up-heading-all)
13627 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13628 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13630 (defun org-up-heading-safe ()
13631 "Move to the heading line of which the present line is a subheading.
13632 This version will not throw an error. It will return the level of the
13633 headline found, or nil if no higher level is found."
13634 (let ((pos (point)) start-level level
13635 (re (concat "^" outline-regexp)))
13636 (catch 'exit
13637 (outline-back-to-heading t)
13638 (setq start-level (funcall outline-level))
13639 (if (equal start-level 1) (throw 'exit nil))
13640 (while (re-search-backward re nil t)
13641 (setq level (funcall outline-level))
13642 (if (< level start-level) (throw 'exit level)))
13643 nil)))
13645 (defun org-first-sibling-p ()
13646 "Is this heading the first child of its parents?"
13647 (interactive)
13648 (let ((re (concat "^" outline-regexp))
13649 level l)
13650 (unless (org-at-heading-p t)
13651 (error "Not at a heading"))
13652 (setq level (funcall outline-level))
13653 (save-excursion
13654 (if (not (re-search-backward re nil t))
13656 (setq l (funcall outline-level))
13657 (< l level)))))
13659 (defun org-goto-sibling (&optional previous)
13660 "Goto the next sibling, even if it is invisible.
13661 When PREVIOUS is set, go to the previous sibling instead. Returns t
13662 when a sibling was found. When none is found, return nil and don't
13663 move point."
13664 (let ((fun (if previous 're-search-backward 're-search-forward))
13665 (pos (point))
13666 (re (concat "^" outline-regexp))
13667 level l)
13668 (when (condition-case nil (org-back-to-heading t) (error nil))
13669 (setq level (funcall outline-level))
13670 (catch 'exit
13671 (or previous (forward-char 1))
13672 (while (funcall fun re nil t)
13673 (setq l (funcall outline-level))
13674 (when (< l level) (goto-char pos) (throw 'exit nil))
13675 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13676 (goto-char pos)
13677 nil))))
13679 (defun org-show-siblings ()
13680 "Show all siblings of the current headline."
13681 (save-excursion
13682 (while (org-goto-sibling) (org-flag-heading nil)))
13683 (save-excursion
13684 (while (org-goto-sibling 'previous)
13685 (org-flag-heading nil))))
13687 (defun org-show-hidden-entry ()
13688 "Show an entry where even the heading is hidden."
13689 (save-excursion
13690 (org-show-entry)))
13692 (defun org-flag-heading (flag &optional entry)
13693 "Flag the current heading. FLAG non-nil means make invisible.
13694 When ENTRY is non-nil, show the entire entry."
13695 (save-excursion
13696 (org-back-to-heading t)
13697 ;; Check if we should show the entire entry
13698 (if entry
13699 (progn
13700 (org-show-entry)
13701 (save-excursion
13702 (and (outline-next-heading)
13703 (org-flag-heading nil))))
13704 (outline-flag-region (max (point-min) (1- (point)))
13705 (save-excursion (outline-end-of-heading) (point))
13706 flag))))
13708 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13709 ;; This is an exact copy of the original function, but it uses
13710 ;; `org-back-to-heading', to make it work also in invisible
13711 ;; trees. And is uses an invisible-OK argument.
13712 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13713 (org-back-to-heading invisible-OK)
13714 (let ((first t)
13715 (level (funcall outline-level)))
13716 (while (and (not (eobp))
13717 (or first (> (funcall outline-level) level)))
13718 (setq first nil)
13719 (outline-next-heading))
13720 (unless to-heading
13721 (if (memq (preceding-char) '(?\n ?\^M))
13722 (progn
13723 ;; Go to end of line before heading
13724 (forward-char -1)
13725 (if (memq (preceding-char) '(?\n ?\^M))
13726 ;; leave blank line before heading
13727 (forward-char -1))))))
13728 (point))
13730 (defun org-show-subtree ()
13731 "Show everything after this heading at deeper levels."
13732 (outline-flag-region
13733 (point)
13734 (save-excursion
13735 (outline-end-of-subtree) (outline-next-heading) (point))
13736 nil))
13738 (defun org-show-entry ()
13739 "Show the body directly following this heading.
13740 Show the heading too, if it is currently invisible."
13741 (interactive)
13742 (save-excursion
13743 (condition-case nil
13744 (progn
13745 (org-back-to-heading t)
13746 (outline-flag-region
13747 (max (point-min) (1- (point)))
13748 (save-excursion
13749 (re-search-forward
13750 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13751 (or (match-beginning 1) (point-max)))
13752 nil))
13753 (error nil))))
13755 (defun org-make-options-regexp (kwds)
13756 "Make a regular expression for keyword lines."
13757 (concat
13759 "#?[ \t]*\\+\\("
13760 (mapconcat 'regexp-quote kwds "\\|")
13761 "\\):[ \t]*"
13762 "\\(.+\\)"))
13764 ;; Make isearch reveal the necessary context
13765 (defun org-isearch-end ()
13766 "Reveal context after isearch exits."
13767 (when isearch-success ; only if search was successful
13768 (if (featurep 'xemacs)
13769 ;; Under XEmacs, the hook is run in the correct place,
13770 ;; we directly show the context.
13771 (org-show-context 'isearch)
13772 ;; In Emacs the hook runs *before* restoring the overlays.
13773 ;; So we have to use a one-time post-command-hook to do this.
13774 ;; (Emacs 22 has a special variable, see function `org-mode')
13775 (unless (and (boundp 'isearch-mode-end-hook-quit)
13776 isearch-mode-end-hook-quit)
13777 ;; Only when the isearch was not quitted.
13778 (org-add-hook 'post-command-hook 'org-isearch-post-command
13779 'append 'local)))))
13781 (defun org-isearch-post-command ()
13782 "Remove self from hook, and show context."
13783 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13784 (org-show-context 'isearch))
13787 ;;;; Integration with and fixes for other packages
13789 ;;; Imenu support
13791 (defvar org-imenu-markers nil
13792 "All markers currently used by Imenu.")
13793 (make-variable-buffer-local 'org-imenu-markers)
13795 (defun org-imenu-new-marker (&optional pos)
13796 "Return a new marker for use by Imenu, and remember the marker."
13797 (let ((m (make-marker)))
13798 (move-marker m (or pos (point)))
13799 (push m org-imenu-markers)
13802 (defun org-imenu-get-tree ()
13803 "Produce the index for Imenu."
13804 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13805 (setq org-imenu-markers nil)
13806 (let* ((n org-imenu-depth)
13807 (re (concat "^" outline-regexp))
13808 (subs (make-vector (1+ n) nil))
13809 (last-level 0)
13810 m tree level head)
13811 (save-excursion
13812 (save-restriction
13813 (widen)
13814 (goto-char (point-max))
13815 (while (re-search-backward re nil t)
13816 (setq level (org-reduced-level (funcall outline-level)))
13817 (when (<= level n)
13818 (looking-at org-complex-heading-regexp)
13819 (setq head (org-match-string-no-properties 4)
13820 m (org-imenu-new-marker))
13821 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13822 (if (>= level last-level)
13823 (push (cons head m) (aref subs level))
13824 (push (cons head (aref subs (1+ level))) (aref subs level))
13825 (loop for i from (1+ level) to n do (aset subs i nil)))
13826 (setq last-level level)))))
13827 (aref subs 1)))
13829 (eval-after-load "imenu"
13830 '(progn
13831 (add-hook 'imenu-after-jump-hook
13832 (lambda () (org-show-context 'org-goto)))))
13834 ;; Speedbar support
13836 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13837 "Overlay marking the agenda restriction line in speedbar.")
13838 (org-overlay-put org-speedbar-restriction-lock-overlay
13839 'face 'org-agenda-restriction-lock)
13840 (org-overlay-put org-speedbar-restriction-lock-overlay
13841 'help-echo "Agendas are currently limited to this item.")
13842 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13844 (defun org-speedbar-set-agenda-restriction ()
13845 "Restrict future agenda commands to the location at point in speedbar.
13846 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13847 (interactive)
13848 (require 'org-agenda)
13849 (let (p m tp np dir txt w)
13850 (cond
13851 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13852 'org-imenu t))
13853 (setq m (get-text-property p 'org-imenu-marker))
13854 (save-excursion
13855 (save-restriction
13856 (set-buffer (marker-buffer m))
13857 (goto-char m)
13858 (org-agenda-set-restriction-lock 'subtree))))
13859 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13860 'speedbar-function 'speedbar-find-file))
13861 (setq tp (previous-single-property-change
13862 (1+ p) 'speedbar-function)
13863 np (next-single-property-change
13864 tp 'speedbar-function)
13865 dir (speedbar-line-directory)
13866 txt (buffer-substring-no-properties (or tp (point-min))
13867 (or np (point-max))))
13868 (save-excursion
13869 (save-restriction
13870 (set-buffer (find-file-noselect
13871 (let ((default-directory dir))
13872 (expand-file-name txt))))
13873 (unless (org-mode-p)
13874 (error "Cannot restrict to non-Org-mode file"))
13875 (org-agenda-set-restriction-lock 'file))))
13876 (t (error "Don't know how to restrict Org-mode's agenda")))
13877 (org-move-overlay org-speedbar-restriction-lock-overlay
13878 (point-at-bol) (point-at-eol))
13879 (setq current-prefix-arg nil)
13880 (org-agenda-maybe-redo)))
13882 (eval-after-load "speedbar"
13883 '(progn
13884 (speedbar-add-supported-extension ".org")
13885 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13886 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13887 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13888 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13889 (add-hook 'speedbar-visiting-tag-hook
13890 (lambda () (org-show-context 'org-goto)))))
13893 ;;; Fixes and Hacks for problems with other packages
13895 ;; Make flyspell not check words in links, to not mess up our keymap
13896 (defun org-mode-flyspell-verify ()
13897 "Don't let flyspell put overlays at active buttons."
13898 (not (get-text-property (point) 'keymap)))
13900 ;; Make `bookmark-jump' show the jump location if it was hidden.
13901 (eval-after-load "bookmark"
13902 '(if (boundp 'bookmark-after-jump-hook)
13903 ;; We can use the hook
13904 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13905 ;; Hook not available, use advice
13906 (defadvice bookmark-jump (after org-make-visible activate)
13907 "Make the position visible."
13908 (org-bookmark-jump-unhide))))
13910 (defun org-bookmark-jump-unhide ()
13911 "Unhide the current position, to show the bookmark location."
13912 (and (org-mode-p)
13913 (or (org-invisible-p)
13914 (save-excursion (goto-char (max (point-min) (1- (point))))
13915 (org-invisible-p)))
13916 (org-show-context 'bookmark-jump)))
13918 ;; Make session.el ignore our circular variable
13919 (eval-after-load "session"
13920 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13922 ;;;; Experimental code
13924 (defun org-closed-in-range ()
13925 "Sparse tree of items closed in a certain time range.
13926 Still experimental, may disappear in the future."
13927 (interactive)
13928 ;; Get the time interval from the user.
13929 (let* ((time1 (time-to-seconds
13930 (org-read-date nil 'to-time nil "Starting date: ")))
13931 (time2 (time-to-seconds
13932 (org-read-date nil 'to-time nil "End date:")))
13933 ;; callback function
13934 (callback (lambda ()
13935 (let ((time
13936 (time-to-seconds
13937 (apply 'encode-time
13938 (org-parse-time-string
13939 (match-string 1))))))
13940 ;; check if time in interval
13941 (and (>= time time1) (<= time time2))))))
13942 ;; make tree, check each match with the callback
13943 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13946 ;;;; Finish up
13948 (provide 'org)
13950 (run-hooks 'org-load-hook)
13952 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13954 ;;; org.el ends here