Release 6.03.
[org-mode/org-tableheadings.git] / lisp / org.el
blob23fc42153d2b2508195f5ab701d7e07bfb37517a
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.03
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.03"
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)
752 (defcustom org-description-max-indent 20
753 "Maximum indentation for the second line of a description list.
754 When the indentation would be larger than this, it will become
755 5 characters instead."
756 :group 'org-plain-lists
757 :type 'integer)
759 (defgroup org-imenu-and-speedbar nil
760 "Options concerning imenu and speedbar in Org-mode."
761 :tag "Org Imenu and Speedbar"
762 :group 'org-structure)
764 (defcustom org-imenu-depth 2
765 "The maximum level for Imenu access to Org-mode headlines.
766 This also applied for speedbar access."
767 :group 'org-imenu-and-speedbar
768 :type 'number)
770 (defgroup org-table nil
771 "Options concerning tables in Org-mode."
772 :tag "Org Table"
773 :group 'org)
775 (defcustom org-enable-table-editor 'optimized
776 "Non-nil means, lines starting with \"|\" are handled by the table editor.
777 When nil, such lines will be treated like ordinary lines.
779 When equal to the symbol `optimized', the table editor will be optimized to
780 do the following:
781 - Automatic overwrite mode in front of whitespace in table fields.
782 This makes the structure of the table stay in tact as long as the edited
783 field does not exceed the column width.
784 - Minimize the number of realigns. Normally, the table is aligned each time
785 TAB or RET are pressed to move to another field. With optimization this
786 happens only if changes to a field might have changed the column width.
787 Optimization requires replacing the functions `self-insert-command',
788 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
789 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
790 very good at guessing when a re-align will be necessary, but you can always
791 force one with \\[org-ctrl-c-ctrl-c].
793 If you would like to use the optimized version in Org-mode, but the
794 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
796 This variable can be used to turn on and off the table editor during a session,
797 but in order to toggle optimization, a restart is required.
799 See also the variable `org-table-auto-blank-field'."
800 :group 'org-table
801 :type '(choice
802 (const :tag "off" nil)
803 (const :tag "on" t)
804 (const :tag "on, optimized" optimized)))
806 (defcustom org-table-tab-recognizes-table.el t
807 "Non-nil means, TAB will automatically notice a table.el table.
808 When it sees such a table, it moves point into it and - if necessary -
809 calls `table-recognize-table'."
810 :group 'org-table-editing
811 :type 'boolean)
813 (defgroup org-link nil
814 "Options concerning links in Org-mode."
815 :tag "Org Link"
816 :group 'org)
818 (defvar org-link-abbrev-alist-local nil
819 "Buffer-local version of `org-link-abbrev-alist', which see.
820 The value of this is taken from the #+LINK lines.")
821 (make-variable-buffer-local 'org-link-abbrev-alist-local)
823 (defcustom org-link-abbrev-alist nil
824 "Alist of link abbreviations.
825 The car of each element is a string, to be replaced at the start of a link.
826 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
827 links in Org-mode buffers can have an optional tag after a double colon, e.g.
829 [[linkkey:tag][description]]
831 If REPLACE is a string, the tag will simply be appended to create the link.
832 If the string contains \"%s\", the tag will be inserted there.
834 REPLACE may also be a function that will be called with the tag as the
835 only argument to create the link, which should be returned as a string.
837 See the manual for examples."
838 :group 'org-link
839 :type 'alist)
841 (defcustom org-descriptive-links t
842 "Non-nil means, hide link part and only show description of bracket links.
843 Bracket links are like [[link][descritpion]]. This variable sets the initial
844 state in new org-mode buffers. The setting can then be toggled on a
845 per-buffer basis from the Org->Hyperlinks menu."
846 :group 'org-link
847 :type 'boolean)
849 (defcustom org-link-file-path-type 'adaptive
850 "How the path name in file links should be stored.
851 Valid values are:
853 relative Relative to the current directory, i.e. the directory of the file
854 into which the link is being inserted.
855 absolute Absolute path, if possible with ~ for home directory.
856 noabbrev Absolute path, no abbreviation of home directory.
857 adaptive Use relative path for files in the current directory and sub-
858 directories of it. For other files, use an absolute path."
859 :group 'org-link
860 :type '(choice
861 (const relative)
862 (const absolute)
863 (const noabbrev)
864 (const adaptive)))
866 (defcustom org-activate-links '(bracket angle plain radio tag date)
867 "Types of links that should be activated in Org-mode files.
868 This is a list of symbols, each leading to the activation of a certain link
869 type. In principle, it does not hurt to turn on most link types - there may
870 be a small gain when turning off unused link types. The types are:
872 bracket The recommended [[link][description]] or [[link]] links with hiding.
873 angular Links in angular brackes that may contain whitespace like
874 <bbdb:Carsten Dominik>.
875 plain Plain links in normal text, no whitespace, like http://google.com.
876 radio Text that is matched by a radio target, see manual for details.
877 tag Tag settings in a headline (link to tag search).
878 date Time stamps (link to calendar).
880 Changing this variable requires a restart of Emacs to become effective."
881 :group 'org-link
882 :type '(set (const :tag "Double bracket links (new style)" bracket)
883 (const :tag "Angular bracket links (old style)" angular)
884 (const :tag "Plain text links" plain)
885 (const :tag "Radio target matches" radio)
886 (const :tag "Tags" tag)
887 (const :tag "Timestamps" date)))
889 (defcustom org-make-link-description-function nil
890 "Function to use to generate link descriptions from links. If
891 nil the link location will be used. This function must take two
892 parameters; the first is the link and the second the description
893 org-insert-link has generated, and should return the description
894 to use."
895 :group 'org-link
896 :type 'function)
898 (defgroup org-link-store nil
899 "Options concerning storing links in Org-mode."
900 :tag "Org Store Link"
901 :group 'org-link)
903 (defcustom org-email-link-description-format "Email %c: %.30s"
904 "Format of the description part of a link to an email or usenet message.
905 The following %-excapes will be replaced by corresponding information:
907 %F full \"From\" field
908 %f name, taken from \"From\" field, address if no name
909 %T full \"To\" field
910 %t first name in \"To\" field, address if no name
911 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
912 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
913 %s subject
914 %m message-id.
916 You may use normal field width specification between the % and the letter.
917 This is for example useful to limit the length of the subject.
919 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
920 :group 'org-link-store
921 :type 'string)
923 (defcustom org-from-is-user-regexp
924 (let (r1 r2)
925 (when (and user-mail-address (not (string= user-mail-address "")))
926 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
927 (when (and user-full-name (not (string= user-full-name "")))
928 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
929 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
930 "Regexp mached against the \"From:\" header of an email or usenet message.
931 It should match if the message is from the user him/herself."
932 :group 'org-link-store
933 :type 'regexp)
935 (defcustom org-context-in-file-links t
936 "Non-nil means, file links from `org-store-link' contain context.
937 A search string will be added to the file name with :: as separator and
938 used to find the context when the link is activated by the command
939 `org-open-at-point'.
940 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
941 negates this setting for the duration of the command."
942 :group 'org-link-store
943 :type 'boolean)
945 (defcustom org-keep-stored-link-after-insertion nil
946 "Non-nil means, keep link in list for entire session.
948 The command `org-store-link' adds a link pointing to the current
949 location to an internal list. These links accumulate during a session.
950 The command `org-insert-link' can be used to insert links into any
951 Org-mode file (offering completion for all stored links). When this
952 option is nil, every link which has been inserted once using \\[org-insert-link]
953 will be removed from the list, to make completing the unused links
954 more efficient."
955 :group 'org-link-store
956 :type 'boolean)
958 (defgroup org-link-follow nil
959 "Options concerning following links in Org-mode."
960 :tag "Org Follow Link"
961 :group 'org-link)
963 (defcustom org-follow-link-hook nil
964 "Hook that is run after a link has been followed."
965 :group 'org-link-follow
966 :type 'hook)
968 (defcustom org-tab-follows-link nil
969 "Non-nil means, on links TAB 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-return-follows-link nil
975 "Non-nil means, on links RET will follow the link.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-mouse-1-follows-link
981 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
982 "Non-nil means, mouse-1 on a link will follow the link.
983 A longer mouse click will still set point. Does not work on XEmacs.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
988 (defcustom org-mark-ring-length 4
989 "Number of different positions to be recorded in the ring
990 Changing this requires a restart of Emacs to work correctly."
991 :group 'org-link-follow
992 :type 'interger)
994 (defcustom org-link-frame-setup
995 '((vm . vm-visit-folder-other-frame)
996 (gnus . gnus-other-frame)
997 (file . find-file-other-window))
998 "Setup the frame configuration for following links.
999 When following a link with Emacs, it may often be useful to display
1000 this link in another window or frame. This variable can be used to
1001 set this up for the different types of links.
1002 For VM, use any of
1003 `vm-visit-folder'
1004 `vm-visit-folder-other-frame'
1005 For Gnus, use any of
1006 `gnus'
1007 `gnus-other-frame'
1008 For FILE, use any of
1009 `find-file'
1010 `find-file-other-window'
1011 `find-file-other-frame'
1012 For the calendar, use the variable `calendar-setup'.
1013 For BBDB, it is currently only possible to display the matches in
1014 another window."
1015 :group 'org-link-follow
1016 :type '(list
1017 (cons (const vm)
1018 (choice
1019 (const vm-visit-folder)
1020 (const vm-visit-folder-other-window)
1021 (const vm-visit-folder-other-frame)))
1022 (cons (const gnus)
1023 (choice
1024 (const gnus)
1025 (const gnus-other-frame)))
1026 (cons (const file)
1027 (choice
1028 (const find-file)
1029 (const find-file-other-window)
1030 (const find-file-other-frame)))))
1032 (defcustom org-display-internal-link-with-indirect-buffer nil
1033 "Non-nil means, use indirect buffer to display infile links.
1034 Activating internal links (from one location in a file to another location
1035 in the same file) normally just jumps to the location. When the link is
1036 activated with a C-u prefix (or with mouse-3), the link is displayed in
1037 another window. When this option is set, the other window actually displays
1038 an indirect buffer clone of the current buffer, to avoid any visibility
1039 changes to the current buffer."
1040 :group 'org-link-follow
1041 :type 'boolean)
1043 (defcustom org-open-non-existing-files nil
1044 "Non-nil means, `org-open-file' will open non-existing files.
1045 When nil, an error will be generated."
1046 :group 'org-link-follow
1047 :type 'boolean)
1049 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1050 "Function and arguments to call for following mailto links.
1051 This is a list with the first element being a lisp function, and the
1052 remaining elements being arguments to the function. In string arguments,
1053 %a will be replaced by the address, and %s will be replaced by the subject
1054 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1055 :group 'org-link-follow
1056 :type '(choice
1057 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1058 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1059 (const :tag "message-mail" (message-mail "%a" "%s"))
1060 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1062 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1063 "Non-nil means, ask for confirmation before executing shell links.
1064 Shell links can be dangerous: just think about a link
1066 [[shell:rm -rf ~/*][Google Search]]
1068 This link would show up in your Org-mode document as \"Google Search\",
1069 but really it would remove your entire home directory.
1070 Therefore we advise against setting this variable to nil.
1071 Just change it to `y-or-n-p' of you want to confirm with a
1072 single keystroke rather than having to type \"yes\"."
1073 :group 'org-link-follow
1074 :type '(choice
1075 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1076 (const :tag "with y-or-n (faster)" y-or-n-p)
1077 (const :tag "no confirmation (dangerous)" nil)))
1079 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1080 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1081 Elisp links can be dangerous: just think about a link
1083 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1085 This link would show up in your Org-mode document as \"Google Search\",
1086 but really it would remove your entire home directory.
1087 Therefore we advise against setting this variable to nil.
1088 Just change it to `y-or-n-p' of you want to confirm with a
1089 single keystroke rather than having to type \"yes\"."
1090 :group 'org-link-follow
1091 :type '(choice
1092 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1093 (const :tag "with y-or-n (faster)" y-or-n-p)
1094 (const :tag "no confirmation (dangerous)" nil)))
1096 (defconst org-file-apps-defaults-gnu
1097 '((remote . emacs)
1098 (t . mailcap))
1099 "Default file applications on a UNIX or GNU/Linux system.
1100 See `org-file-apps'.")
1102 (defconst org-file-apps-defaults-macosx
1103 '((remote . emacs)
1104 (t . "open %s")
1105 ("ps" . "gv %s")
1106 ("ps.gz" . "gv %s")
1107 ("eps" . "gv %s")
1108 ("eps.gz" . "gv %s")
1109 ("dvi" . "xdvi %s")
1110 ("fig" . "xfig %s"))
1111 "Default file applications on a MacOS X system.
1112 The system \"open\" is known as a default, but we use X11 applications
1113 for some files for which the OS does not have a good default.
1114 See `org-file-apps'.")
1116 (defconst org-file-apps-defaults-windowsnt
1117 (list
1118 '(remote . emacs)
1119 (cons t
1120 (list (if (featurep 'xemacs)
1121 'mswindows-shell-execute
1122 'w32-shell-execute)
1123 "open" 'file)))
1124 "Default file applications on a Windows NT system.
1125 The system \"open\" is used for most files.
1126 See `org-file-apps'.")
1128 (defcustom org-file-apps
1130 ("txt" . emacs)
1131 ("tex" . emacs)
1132 ("ltx" . emacs)
1133 ("org" . emacs)
1134 ("el" . emacs)
1135 ("bib" . emacs)
1137 "External applications for opening `file:path' items in a document.
1138 Org-mode uses system defaults for different file types, but
1139 you can use this variable to set the application for a given file
1140 extension. The entries in this list are cons cells where the car identifies
1141 files and the cdr the corresponding command. Possible values for the
1142 file identifier are
1143 \"ext\" A string identifying an extension
1144 `directory' Matches a directory
1145 `remote' Matches a remote file, accessible through tramp or efs.
1146 Remote files most likely should be visited through Emacs
1147 because external applications cannot handle such paths.
1148 t Default for all remaining files
1150 Possible values for the command are:
1151 `emacs' The file will be visited by the current Emacs process.
1152 `default' Use the default application for this file type.
1153 string A command to be executed by a shell; %s will be replaced
1154 by the path to the file.
1155 sexp A Lisp form which will be evaluated. The file path will
1156 be available in the Lisp variable `file'.
1157 For more examples, see the system specific constants
1158 `org-file-apps-defaults-macosx'
1159 `org-file-apps-defaults-windowsnt'
1160 `org-file-apps-defaults-gnu'."
1161 :group 'org-link-follow
1162 :type '(repeat
1163 (cons (choice :value ""
1164 (string :tag "Extension")
1165 (const :tag "Default for unrecognized files" t)
1166 (const :tag "Remote file" remote)
1167 (const :tag "Links to a directory" directory))
1168 (choice :value ""
1169 (const :tag "Visit with Emacs" emacs)
1170 (const :tag "Use system default" default)
1171 (string :tag "Command")
1172 (sexp :tag "Lisp form")))))
1174 (defgroup org-refile nil
1175 "Options concerning refiling entries in Org-mode."
1176 :tag "Org Remember"
1177 :group 'org)
1179 (defcustom org-directory "~/org"
1180 "Directory with org files.
1181 This directory will be used as default to prompt for org files.
1182 Used by the hooks for remember.el."
1183 :group 'org-refile
1184 :group 'org-remember
1185 :type 'directory)
1187 (defcustom org-default-notes-file "~/.notes"
1188 "Default target for storing notes.
1189 Used by the hooks for remember.el. This can be a string, or nil to mean
1190 the value of `remember-data-file'.
1191 You can set this on a per-template basis with the variable
1192 `org-remember-templates'."
1193 :group 'org-refile
1194 :group 'org-remember
1195 :type '(choice
1196 (const :tag "Default from remember-data-file" nil)
1197 file))
1199 (defcustom org-goto-interface 'outline
1200 "The default interface to be used for `org-goto'.
1201 Allowed vaues are:
1202 outline The interface shows an outline of the relevant file
1203 and the correct heading is found by moving through
1204 the outline or by searching with incremental search.
1205 outline-path-completion Headlines in the current buffer are offered via
1206 completion."
1207 :group 'org-refile
1208 :type '(choice
1209 (const :tag "Outline" outline)
1210 (const :tag "Outline-path-completion" outline-path-completion)))
1212 (defcustom org-reverse-note-order nil
1213 "Non-nil means, store new notes at the beginning of a file or entry.
1214 When nil, new notes will be filed to the end of a file or entry.
1215 This can also be a list with cons cells of regular expressions that
1216 are matched against file names, and values."
1217 :group 'org-remember
1218 :type '(choice
1219 (const :tag "Reverse always" t)
1220 (const :tag "Reverse never" nil)
1221 (repeat :tag "By file name regexp"
1222 (cons regexp boolean))))
1224 (defcustom org-refile-targets nil
1225 "Targets for refiling entries with \\[org-refile].
1226 This is list of cons cells. Each cell contains:
1227 - a specification of the files to be considered, either a list of files,
1228 or a symbol whose function or variable value will be used to retrieve
1229 a file name or a list of file names. Nil means, refile to a different
1230 heading in the current buffer.
1231 - A specification of how to find candidate refile targets. This may be
1232 any of
1233 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1234 This tag has to be present in all target headlines, inheritance will
1235 not be considered.
1236 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1237 todo keyword.
1238 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1239 headlines that are refiling targets.
1240 - a cons cell (:level . N). Any headline of level N is considered a target.
1241 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1242 :group 'org-remember
1243 :type '(repeat
1244 (cons
1245 (choice :value org-agenda-files
1246 (const :tag "All agenda files" org-agenda-files)
1247 (const :tag "Current buffer" nil)
1248 (function) (variable) (file))
1249 (choice :tag "Identify target headline by"
1250 (cons :tag "Specific tag" (const :tag) (string))
1251 (cons :tag "TODO keyword" (const :todo) (string))
1252 (cons :tag "Regular expression" (const :regexp) (regexp))
1253 (cons :tag "Level number" (const :level) (integer))
1254 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1256 (defcustom org-refile-use-outline-path nil
1257 "Non-nil means, provide refile targets as paths.
1258 So a level 3 headline will be available as level1/level2/level3.
1259 When the value is `file', also include the file name (without directory)
1260 into the path. When `full-file-path', include the full file path."
1261 :group 'org-remember
1262 :type '(choice
1263 (const :tag "Not" nil)
1264 (const :tag "Yes" t)
1265 (const :tag "Start with file name" file)
1266 (const :tag "Start with full file path" full-file-path)))
1268 (defgroup org-todo nil
1269 "Options concerning TODO items in Org-mode."
1270 :tag "Org TODO"
1271 :group 'org)
1273 (defgroup org-progress nil
1274 "Options concerning Progress logging in Org-mode."
1275 :tag "Org Progress"
1276 :group 'org-time)
1278 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1279 "List of TODO entry keyword sequences and their interpretation.
1280 \\<org-mode-map>This is a list of sequences.
1282 Each sequence starts with a symbol, either `sequence' or `type',
1283 indicating if the keywords should be interpreted as a sequence of
1284 action steps, or as different types of TODO items. The first
1285 keywords are states requiring action - these states will select a headline
1286 for inclusion into the global TODO list Org-mode produces. If one of
1287 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1288 signify that no further action is necessary. If \"|\" is not found,
1289 the last keyword is treated as the only DONE state of the sequence.
1291 The command \\[org-todo] cycles an entry through these states, and one
1292 additional state where no keyword is present. For details about this
1293 cycling, see the manual.
1295 TODO keywords and interpretation can also be set on a per-file basis with
1296 the special #+SEQ_TODO and #+TYP_TODO lines.
1298 Each keyword can optionally specify a character for fast state selection
1299 \(in combination with the variable `org-use-fast-todo-selection')
1300 and specifiers for state change logging, using the same syntax
1301 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1302 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1303 indicates to record a time stamp each time this state is selected.
1305 Each keyword may also specify if a timestamp or a note should be
1306 recorded when entering or leaving the state, by adding additional
1307 characters in the parenthesis after the keyword. This looks like this:
1308 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1309 record only the time of the state change. With X and Y being either
1310 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1311 Y when leaving the state if and only if the *target* state does not
1312 define X. You may omit any of the fast-selection key or X or /Y,
1313 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1315 For backward compatibility, this variable may also be just a list
1316 of keywords - in this case the interptetation (sequence or type) will be
1317 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1318 :group 'org-todo
1319 :group 'org-keywords
1320 :type '(choice
1321 (repeat :tag "Old syntax, just keywords"
1322 (string :tag "Keyword"))
1323 (repeat :tag "New syntax"
1324 (cons
1325 (choice
1326 :tag "Interpretation"
1327 (const :tag "Sequence (cycling hits every state)" sequence)
1328 (const :tag "Type (cycling directly to DONE)" type))
1329 (repeat
1330 (string :tag "Keyword"))))))
1332 (defvar org-todo-keywords-1 nil
1333 "All TODO and DONE keywords active in a buffer.")
1334 (make-variable-buffer-local 'org-todo-keywords-1)
1335 (defvar org-todo-keywords-for-agenda nil)
1336 (defvar org-done-keywords-for-agenda nil)
1337 (defvar org-agenda-contributing-files nil)
1338 (defvar org-not-done-keywords nil)
1339 (make-variable-buffer-local 'org-not-done-keywords)
1340 (defvar org-done-keywords nil)
1341 (make-variable-buffer-local 'org-done-keywords)
1342 (defvar org-todo-heads nil)
1343 (make-variable-buffer-local 'org-todo-heads)
1344 (defvar org-todo-sets nil)
1345 (make-variable-buffer-local 'org-todo-sets)
1346 (defvar org-todo-log-states nil)
1347 (make-variable-buffer-local 'org-todo-log-states)
1348 (defvar org-todo-kwd-alist nil)
1349 (make-variable-buffer-local 'org-todo-kwd-alist)
1350 (defvar org-todo-key-alist nil)
1351 (make-variable-buffer-local 'org-todo-key-alist)
1352 (defvar org-todo-key-trigger nil)
1353 (make-variable-buffer-local 'org-todo-key-trigger)
1355 (defcustom org-todo-interpretation 'sequence
1356 "Controls how TODO keywords are interpreted.
1357 This variable is in principle obsolete and is only used for
1358 backward compatibility, if the interpretation of todo keywords is
1359 not given already in `org-todo-keywords'. See that variable for
1360 more information."
1361 :group 'org-todo
1362 :group 'org-keywords
1363 :type '(choice (const sequence)
1364 (const type)))
1366 (defcustom org-use-fast-todo-selection 'prefix
1367 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1368 This variable describes if and under what circumstances the cycling
1369 mechanism for TODO keywords will be replaced by a single-key, direct
1370 selection scheme.
1372 When nil, fast selection is never used.
1374 When the symbol `prefix', it will be used when `org-todo' is called with
1375 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1376 in an agenda buffer.
1378 When t, fast selection is used by default. In this case, the prefix
1379 argument forces cycling instead.
1381 In all cases, the special interface is only used if access keys have actually
1382 been assigned by the user, i.e. if keywords in the configuration are followed
1383 by a letter in parenthesis, like TODO(t)."
1384 :group 'org-todo
1385 :type '(choice
1386 (const :tag "Never" nil)
1387 (const :tag "By default" t)
1388 (const :tag "Only with C-u C-c C-t" prefix)))
1390 (defcustom org-after-todo-state-change-hook nil
1391 "Hook which is run after the state of a TODO item was changed.
1392 The new state (a string with a TODO keyword, or nil) is available in the
1393 Lisp variable `state'."
1394 :group 'org-todo
1395 :type 'hook)
1397 (defcustom org-log-done nil
1398 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1399 When equal to the list (done), also prompt for a closing note.
1400 This can also be configured on a per-file basis by adding one of
1401 the following lines anywhere in the buffer:
1403 #+STARTUP: logdone
1404 #+STARTUP: lognotedone
1405 #+STARTUP: nologdone"
1406 :group 'org-todo
1407 :group 'org-progress
1408 :type '(choice
1409 (const :tag "No logging" nil)
1410 (const :tag "Record CLOSED timestamp" time)
1411 (const :tag "Record CLOSED timestamp with closing note." note)))
1413 ;; Normalize old uses of org-log-done.
1414 (cond
1415 ((eq org-log-done t) (setq org-log-done 'time))
1416 ((and (listp org-log-done) (memq 'done org-log-done))
1417 (setq org-log-done 'note)))
1419 (defcustom org-log-note-clock-out nil
1420 "Non-nil means, recored a note when clocking out of an item.
1421 This can also be configured on a per-file basis by adding one of
1422 the following lines anywhere in the buffer:
1424 #+STARTUP: lognoteclock-out
1425 #+STARTUP: nolognoteclock-out"
1426 :group 'org-todo
1427 :group 'org-progress
1428 :type 'boolean)
1430 (defcustom org-log-done-with-time t
1431 "Non-nil means, the CLOSED time stamp will contain date and time.
1432 When nil, only the date will be recorded."
1433 :group 'org-progress
1434 :type 'boolean)
1436 (defcustom org-log-note-headings
1437 '((done . "CLOSING NOTE %t")
1438 (state . "State %-12s %t")
1439 (note . "Note taken on %t")
1440 (clock-out . ""))
1441 "Headings for notes added to entries.
1442 The value is an alist, with the car being a symbol indicating the note
1443 context, and the cdr is the heading to be used. The heading may also be the
1444 empty string.
1445 %t in the heading will be replaced by a time stamp.
1446 %s will be replaced by the new TODO state, in double quotes.
1447 %u will be replaced by the user name.
1448 %U will be replaced by the full user name."
1449 :group 'org-todo
1450 :group 'org-progress
1451 :type '(list :greedy t
1452 (cons (const :tag "Heading when closing an item" done) string)
1453 (cons (const :tag
1454 "Heading when changing todo state (todo sequence only)"
1455 state) string)
1456 (cons (const :tag "Heading when just taking a note" note) string)
1457 (cons (const :tag "Heading when clocking out" clock-out) string)))
1459 (unless (assq 'note org-log-note-headings)
1460 (push '(note . "%t") org-log-note-headings))
1462 (defcustom org-log-states-order-reversed t
1463 "Non-nil means, the latest state change note will be directly after heading.
1464 When nil, the notes will be orderer according to time."
1465 :group 'org-todo
1466 :group 'org-progress
1467 :type 'boolean)
1469 (defcustom org-log-repeat 'time
1470 "Non-nil means, record moving through the DONE state when triggering repeat.
1471 An auto-repeating tasks is immediately switched back to TODO when marked
1472 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1473 the TODO keyword definition, or recording a closing note by setting
1474 `org-log-done', there will be no record of the task moving through DONE.
1475 This variable forces taking a note anyway. Possible values are:
1477 nil Don't force a record
1478 time Record a time stamp
1479 note Record a note
1481 This option can also be set with on a per-file-basis with
1483 #+STARTUP: logrepeat
1484 #+STARTUP: lognoterepeat
1485 #+STARTUP: nologrepeat
1487 You can have local logging settings for a subtree by setting the LOGGING
1488 property to one or more of these keywords."
1489 :group 'org-todo
1490 :group 'org-progress
1491 :type '(choice
1492 (const :tag "Don't force a record" nil)
1493 (const :tag "Force recording the DONE state" time)
1494 (const :tag "Force recording a note with the DONE state" note)))
1497 (defgroup org-priorities nil
1498 "Priorities in Org-mode."
1499 :tag "Org Priorities"
1500 :group 'org-todo)
1502 (defcustom org-highest-priority ?A
1503 "The highest priority of TODO items. A character like ?A, ?B etc.
1504 Must have a smaller ASCII number than `org-lowest-priority'."
1505 :group 'org-priorities
1506 :type 'character)
1508 (defcustom org-lowest-priority ?C
1509 "The lowest priority of TODO items. A character like ?A, ?B etc.
1510 Must have a larger ASCII number than `org-highest-priority'."
1511 :group 'org-priorities
1512 :type 'character)
1514 (defcustom org-default-priority ?B
1515 "The default priority of TODO items.
1516 This is the priority an item get if no explicit priority is given."
1517 :group 'org-priorities
1518 :type 'character)
1520 (defcustom org-priority-start-cycle-with-default t
1521 "Non-nil means, start with default priority when starting to cycle.
1522 When this is nil, the first step in the cycle will be (depending on the
1523 command used) one higher or lower that the default priority."
1524 :group 'org-priorities
1525 :type 'boolean)
1527 (defgroup org-time nil
1528 "Options concerning time stamps and deadlines in Org-mode."
1529 :tag "Org Time"
1530 :group 'org)
1532 (defcustom org-insert-labeled-timestamps-at-point nil
1533 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1534 When nil, these labeled time stamps are forces into the second line of an
1535 entry, just after the headline. When scheduling from the global TODO list,
1536 the time stamp will always be forced into the second line."
1537 :group 'org-time
1538 :type 'boolean)
1540 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1541 "Formats for `format-time-string' which are used for time stamps.
1542 It is not recommended to change this constant.")
1544 (defcustom org-time-stamp-rounding-minutes '(0 5)
1545 "Number of minutes to round time stamps to.
1546 These are two values, the first applies when first creating a time stamp.
1547 The second applies when changing it with the commands `S-up' and `S-down'.
1548 When changing the time stamp, this means that it will change in steps
1549 of N minutes, as given by the second value.
1551 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1552 numbers should be factors of 60, so for example 5, 10, 15.
1554 When this is larger than 1, you can still force an exact time-stamp by using
1555 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1556 and by using a prefix arg to `S-up/down' to specify the exact number
1557 of minutes to shift."
1558 :group 'org-time
1559 :get '(lambda (var) ; Make sure all entries have 5 elements
1560 (if (integerp (default-value var))
1561 (list (default-value var) 5)
1562 (default-value var)))
1563 :type '(list
1564 (integer :tag "when inserting times")
1565 (integer :tag "when modifying times")))
1567 ;; Normalize old customizations of this variable.
1568 (when (integerp org-time-stamp-rounding-minutes)
1569 (setq org-time-stamp-rounding-minutes
1570 (list org-time-stamp-rounding-minutes
1571 org-time-stamp-rounding-minutes)))
1573 (defcustom org-display-custom-times nil
1574 "Non-nil means, overlay custom formats over all time stamps.
1575 The formats are defined through the variable `org-time-stamp-custom-formats'.
1576 To turn this on on a per-file basis, insert anywhere in the file:
1577 #+STARTUP: customtime"
1578 :group 'org-time
1579 :set 'set-default
1580 :type 'sexp)
1581 (make-variable-buffer-local 'org-display-custom-times)
1583 (defcustom org-time-stamp-custom-formats
1584 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1585 "Custom formats for time stamps. See `format-time-string' for the syntax.
1586 These are overlayed over the default ISO format if the variable
1587 `org-display-custom-times' is set. Time like %H:%M should be at the
1588 end of the second format."
1589 :group 'org-time
1590 :type 'sexp)
1592 (defun org-time-stamp-format (&optional long inactive)
1593 "Get the right format for a time string."
1594 (let ((f (if long (cdr org-time-stamp-formats)
1595 (car org-time-stamp-formats))))
1596 (if inactive
1597 (concat "[" (substring f 1 -1) "]")
1598 f)))
1600 (defcustom org-deadline-warning-days 14
1601 "No. of days before expiration during which a deadline becomes active.
1602 This variable governs the display in sparse trees and in the agenda.
1603 When 0 or negative, it means use this number (the absolute value of it)
1604 even if a deadline has a different individual lead time specified."
1605 :group 'org-time
1606 :group 'org-agenda-daily/weekly
1607 :type 'number)
1609 (defcustom org-read-date-prefer-future t
1610 "Non-nil means, assume future for incomplete date input from user.
1611 This affects the following situations:
1612 1. The user gives a day, but no month.
1613 For example, if today is the 15th, and you enter \"3\", Org-mode will
1614 read this as the third of *next* month. However, if you enter \"17\",
1615 it will be considered as *this* month.
1616 2. The user gives a month but not a year.
1617 For example, if it is april and you enter \"feb 2\", this will be read
1618 as feb 2, *next* year. \"May 5\", however, will be this year.
1620 Currently this does not work for ISO week specifications.
1622 When this option is nil, the current month and year will always be used
1623 as defaults."
1624 :group 'org-time
1625 :type 'boolean)
1627 (defcustom org-read-date-display-live t
1628 "Non-nil means, display current interpretation of date prompt live.
1629 This display will be in an overlay, in the minibuffer."
1630 :group 'org-time
1631 :type 'boolean)
1633 (defcustom org-read-date-popup-calendar t
1634 "Non-nil means, pop up a calendar when prompting for a date.
1635 In the calendar, the date can be selected with mouse-1. However, the
1636 minibuffer will also be active, and you can simply enter the date as well.
1637 When nil, only the minibuffer will be available."
1638 :group 'org-time
1639 :type 'boolean)
1640 (if (fboundp 'defvaralias)
1641 (defvaralias 'org-popup-calendar-for-date-prompt
1642 'org-read-date-popup-calendar))
1644 (defcustom org-extend-today-until 0
1645 "The hour when your day really ends.
1646 This has influence for the following applications:
1647 - When switching the agenda to \"today\". It it is still earlier than
1648 the time given here, the day recognized as TODAY is actually yesterday.
1649 - When a date is read from the user and it is still before the time given
1650 here, the current date and time will be assumed to be yesterday, 23:59.
1652 FIXME:
1653 IMPORTANT: This is still a very experimental feature, it may disappear
1654 again or it may be extended to mean more things."
1655 :group 'org-time
1656 :type 'number)
1658 (defcustom org-edit-timestamp-down-means-later nil
1659 "Non-nil means, S-down will increase the time in a time stamp.
1660 When nil, S-up will increase."
1661 :group 'org-time
1662 :type 'boolean)
1664 (defcustom org-calendar-follow-timestamp-change t
1665 "Non-nil means, make the calendar window follow timestamp changes.
1666 When a timestamp is modified and the calendar window is visible, it will be
1667 moved to the new date."
1668 :group 'org-time
1669 :type 'boolean)
1671 (defgroup org-tags nil
1672 "Options concerning tags in Org-mode."
1673 :tag "Org Tags"
1674 :group 'org)
1676 (defcustom org-tag-alist nil
1677 "List of tags allowed in Org-mode files.
1678 When this list is nil, Org-mode will base TAG input on what is already in the
1679 buffer.
1680 The value of this variable is an alist, the car of each entry must be a
1681 keyword as a string, the cdr may be a character that is used to select
1682 that tag through the fast-tag-selection interface.
1683 See the manual for details."
1684 :group 'org-tags
1685 :type '(repeat
1686 (choice
1687 (cons (string :tag "Tag name")
1688 (character :tag "Access char"))
1689 (const :tag "Start radio group" (:startgroup))
1690 (const :tag "End radio group" (:endgroup)))))
1692 (defcustom org-use-fast-tag-selection 'auto
1693 "Non-nil means, use fast tag selection scheme.
1694 This is a special interface to select and deselect tags with single keys.
1695 When nil, fast selection is never used.
1696 When the symbol `auto', fast selection is used if and only if selection
1697 characters for tags have been configured, either through the variable
1698 `org-tag-alist' or through a #+TAGS line in the buffer.
1699 When t, fast selection is always used and selection keys are assigned
1700 automatically if necessary."
1701 :group 'org-tags
1702 :type '(choice
1703 (const :tag "Always" t)
1704 (const :tag "Never" nil)
1705 (const :tag "When selection characters are configured" 'auto)))
1707 (defcustom org-fast-tag-selection-single-key nil
1708 "Non-nil means, fast tag selection exits after first change.
1709 When nil, you have to press RET to exit it.
1710 During fast tag selection, you can toggle this flag with `C-c'.
1711 This variable can also have the value `expert'. In this case, the window
1712 displaying the tags menu is not even shown, until you press C-c again."
1713 :group 'org-tags
1714 :type '(choice
1715 (const :tag "No" nil)
1716 (const :tag "Yes" t)
1717 (const :tag "Expert" expert)))
1719 (defvar org-fast-tag-selection-include-todo nil
1720 "Non-nil means, fast tags selection interface will also offer TODO states.
1721 This is an undocumented feature, you should not rely on it.")
1723 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1724 "The column to which tags should be indented in a headline.
1725 If this number is positive, it specifies the column. If it is negative,
1726 it means that the tags should be flushright to that column. For example,
1727 -80 works well for a normal 80 character screen."
1728 :group 'org-tags
1729 :type 'integer)
1731 (defcustom org-auto-align-tags t
1732 "Non-nil means, realign tags after pro/demotion of TODO state change.
1733 These operations change the length of a headline and therefore shift
1734 the tags around. With this options turned on, after each such operation
1735 the tags are again aligned to `org-tags-column'."
1736 :group 'org-tags
1737 :type 'boolean)
1739 (defcustom org-use-tag-inheritance t
1740 "Non-nil means, tags in levels apply also for sublevels.
1741 When nil, only the tags directly given in a specific line apply there.
1742 If you turn off this option, you very likely want to turn on the
1743 companion option `org-tags-match-list-sublevels'.
1745 This may also be a list of tags that should be inherited, or a regexp that
1746 matches tags that should be inherited."
1747 :group 'org-tags
1748 :type '(choice
1749 (const :tag "Not" nil)
1750 (const :tag "Always" t)
1751 (repeat :tag "Specific tags" (string :tag "Tag"))
1752 (regexp :tag "Tags matched by regexp")))
1754 (defun org-tag-inherit-p (tag)
1755 "Check if TAG is one that should be inherited."
1756 (cond
1757 ((eq org-use-tag-inheritance t) t)
1758 ((not org-use-tag-inheritance) nil)
1759 ((stringp org-use-tag-inheritance)
1760 (string-match org-use-tag-inheritance tag))
1761 ((listp org-use-tag-inheritance)
1762 (member tag org-use-tag-inheritance))
1763 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1765 (defcustom org-tags-match-list-sublevels nil
1766 "Non-nil means list also sublevels of headlines matching tag search.
1767 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1768 the sublevels of a headline matching a tag search often also match
1769 the same search. Listing all of them can create very long lists.
1770 Setting this variable to nil causes subtrees of a match to be skipped.
1771 This option is off by default, because inheritance in on. If you turn
1772 inheritance off, you very likely want to turn this option on.
1774 As a special case, if the tag search is restricted to TODO items, the
1775 value of this variable is ignored and sublevels are always checked, to
1776 make sure all corresponding TODO items find their way into the list."
1777 :group 'org-tags
1778 :type 'boolean)
1780 (defvar org-tags-history nil
1781 "History of minibuffer reads for tags.")
1782 (defvar org-last-tags-completion-table nil
1783 "The last used completion table for tags.")
1784 (defvar org-after-tags-change-hook nil
1785 "Hook that is run after the tags in a line have changed.")
1787 (defgroup org-properties nil
1788 "Options concerning properties in Org-mode."
1789 :tag "Org Properties"
1790 :group 'org)
1792 (defcustom org-property-format "%-10s %s"
1793 "How property key/value pairs should be formatted by `indent-line'.
1794 When `indent-line' hits a property definition, it will format the line
1795 according to this format, mainly to make sure that the values are
1796 lined-up with respect to each other."
1797 :group 'org-properties
1798 :type 'string)
1800 (defcustom org-use-property-inheritance nil
1801 "Non-nil means, properties apply also for sublevels.
1803 This setting is chiefly used during property searches. Turning it on can
1804 cause significant overhead when doing a search, which is why it is not
1805 on by default.
1807 When nil, only the properties directly given in the current entry count.
1808 When t, every property is inherited. The value may also be a list of
1809 properties that should have inheritance, or a regular expression matching
1810 properties that should be inherited.
1812 However, note that some special properties use inheritance under special
1813 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1814 and the properties ending in \"_ALL\" when they are used as descriptor
1815 for valid values of a property.
1817 Note for programmers:
1818 When querying an entry with `org-entry-get', you can control if inheritance
1819 should be used. By default, `org-entry-get' looks only at the local
1820 properties. You can request inheritance by setting the inherit argument
1821 to t (to force inheritance) or to `selective' (to respect the setting
1822 in this variable)."
1823 :group 'org-properties
1824 :type '(choice
1825 (const :tag "Not" nil)
1826 (const :tag "Always" t)
1827 (repeat :tag "Specific properties" (string :tag "Property"))
1828 (regexp :tag "Properties matched by regexp")))
1830 (defun org-property-inherit-p (property)
1831 "Check if PROPERTY is one that should be inherited."
1832 (cond
1833 ((eq org-use-property-inheritance t) t)
1834 ((not org-use-property-inheritance) nil)
1835 ((stringp org-use-property-inheritance)
1836 (string-match org-use-property-inheritance property))
1837 ((listp org-use-property-inheritance)
1838 (member property org-use-property-inheritance))
1839 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1841 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1842 "The default column format, if no other format has been defined.
1843 This variable can be set on the per-file basis by inserting a line
1845 #+COLUMNS: %25ITEM ....."
1846 :group 'org-properties
1847 :type 'string)
1849 (defcustom org-effort-property "Effort"
1850 "The property that is being used to keep track of effort estimates.
1851 Effort estimates given in this property need to have the format H:MM."
1852 :group 'org-properties
1853 :group 'org-progress
1854 :type '(string :tag "Property"))
1856 (defconst org-global-properties-fixed
1857 '(("VISIBILITY_ALL" . "folded children content all"))
1858 "List of property/value pairs that can be inherited by any entry.
1859 These are fixed values, for the preset properties.")
1862 (defcustom org-global-properties nil
1863 "List of property/value pairs that can be inherited by any entry.
1864 You can set buffer-local values for this by adding lines like
1866 #+PROPERTY: NAME VALUE"
1867 :group 'org-properties
1868 :type '(repeat
1869 (cons (string :tag "Property")
1870 (string :tag "Value"))))
1872 (defvar org-local-properties nil
1873 "List of property/value pairs that can be inherited by any entry.
1874 Valid for the current buffer.
1875 This variable is populated from #+PROPERTY lines.")
1877 (defgroup org-agenda nil
1878 "Options concerning agenda views in Org-mode."
1879 :tag "Org Agenda"
1880 :group 'org)
1882 (defvar org-category nil
1883 "Variable used by org files to set a category for agenda display.
1884 Such files should use a file variable to set it, for example
1886 # -*- mode: org; org-category: \"ELisp\"
1888 or contain a special line
1890 #+CATEGORY: ELisp
1892 If the file does not specify a category, then file's base name
1893 is used instead.")
1894 (make-variable-buffer-local 'org-category)
1896 (defcustom org-agenda-files nil
1897 "The files to be used for agenda display.
1898 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1899 \\[org-remove-file]. You can also use customize to edit the list.
1901 If an entry is a directory, all files in that directory that are matched by
1902 `org-agenda-file-regexp' will be part of the file list.
1904 If the value of the variable is not a list but a single file name, then
1905 the list of agenda files is actually stored and maintained in that file, one
1906 agenda file per line."
1907 :group 'org-agenda
1908 :type '(choice
1909 (repeat :tag "List of files and directories" file)
1910 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1912 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1913 "Regular expression to match files for `org-agenda-files'.
1914 If any element in the list in that variable contains a directory instead
1915 of a normal file, all files in that directory that are matched by this
1916 regular expression will be included."
1917 :group 'org-agenda
1918 :type 'regexp)
1920 (defcustom org-agenda-text-search-extra-files nil
1921 "List of extra files to be searched by text search commands.
1922 These files will be search in addition to the agenda files by the
1923 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1924 Note that these files will only be searched for text search commands,
1925 not for the other agenda views like todo lists, tag searches or the weekly
1926 agenda. This variable is intended to list notes and possibly archive files
1927 that should also be searched by these two commands.
1928 In fact, if the first element in the list is the symbol `agenda-archives',
1929 than all archive files of all agenda files will be added to the search
1930 scope."
1931 :group 'org-agenda
1932 :type '(set :greedy t
1933 (const :tag "Agenda Archives" agenda-archives)
1934 (repeat :inline t (file))))
1936 (if (fboundp 'defvaralias)
1937 (defvaralias 'org-agenda-multi-occur-extra-files
1938 'org-agenda-text-search-extra-files))
1940 (defcustom org-agenda-skip-unavailable-files nil
1941 "t means to just skip non-reachable files in `org-agenda-files'.
1942 Nil means to remove them, after a query, from the list."
1943 :group 'org-agenda
1944 :type 'boolean)
1946 (defcustom org-calendar-to-agenda-key [?c]
1947 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1948 The command `org-calendar-goto-agenda' will be bound to this key. The
1949 default is the character `c' because then `c' can be used to switch back and
1950 forth between agenda and calendar."
1951 :group 'org-agenda
1952 :type 'sexp)
1954 (eval-after-load "calendar"
1955 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1956 'org-calendar-goto-agenda))
1958 (defgroup org-latex nil
1959 "Options for embedding LaTeX code into Org-mode."
1960 :tag "Org LaTeX"
1961 :group 'org)
1963 (defcustom org-format-latex-options
1964 '(:foreground default :background default :scale 1.0
1965 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1966 :matchers ("begin" "$" "$$" "\\(" "\\["))
1967 "Options for creating images from LaTeX fragments.
1968 This is a property list with the following properties:
1969 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
1970 `default' means use the foreground of the default face.
1971 :background the background color, or \"Transparent\".
1972 `default' means use the background of the default face.
1973 :scale a scaling factor for the size of the images.
1974 :html-foreground, :html-background, :html-scale
1975 the same numbers for HTML export.
1976 :matchers a list indicating which matchers should be used to
1977 find LaTeX fragments. Valid members of this list are:
1978 \"begin\" find environments
1979 \"$\" find math expressions surrounded by $...$
1980 \"$$\" find math expressions surrounded by $$....$$
1981 \"\\(\" find math expressions surrounded by \\(...\\)
1982 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1983 :group 'org-latex
1984 :type 'plist)
1986 (defcustom org-format-latex-header "\\documentclass{article}
1987 \\usepackage{fullpage} % do not remove
1988 \\usepackage{amssymb}
1989 \\usepackage[usenames]{color}
1990 \\usepackage{amsmath}
1991 \\usepackage{latexsym}
1992 \\usepackage[mathscr]{eucal}
1993 \\pagestyle{empty} % do not remove"
1994 "The document header used for processing LaTeX fragments."
1995 :group 'org-latex
1996 :type 'string)
1999 (defgroup org-font-lock nil
2000 "Font-lock settings for highlighting in Org-mode."
2001 :tag "Org Font Lock"
2002 :group 'org)
2004 (defcustom org-level-color-stars-only nil
2005 "Non-nil means fontify only the stars in each headline.
2006 When nil, the entire headline is fontified.
2007 Changing it requires restart of `font-lock-mode' to become effective
2008 also in regions already fontified."
2009 :group 'org-font-lock
2010 :type 'boolean)
2012 (defcustom org-hide-leading-stars nil
2013 "Non-nil means, hide the first N-1 stars in a headline.
2014 This works by using the face `org-hide' for these stars. This
2015 face is white for a light background, and black for a dark
2016 background. You may have to customize the face `org-hide' to
2017 make this work.
2018 Changing it requires restart of `font-lock-mode' to become effective
2019 also in regions already fontified.
2020 You may also set this on a per-file basis by adding one of the following
2021 lines to the buffer:
2023 #+STARTUP: hidestars
2024 #+STARTUP: showstars"
2025 :group 'org-font-lock
2026 :type 'boolean)
2028 (defcustom org-fontify-done-headline nil
2029 "Non-nil means, change the face of a headline if it is marked DONE.
2030 Normally, only the TODO/DONE keyword indicates the state of a headline.
2031 When this is non-nil, the headline after the keyword is set to the
2032 `org-headline-done' as an additional indication."
2033 :group 'org-font-lock
2034 :type 'boolean)
2036 (defcustom org-fontify-emphasized-text t
2037 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2038 Changing this variable requires a restart of Emacs to take effect."
2039 :group 'org-font-lock
2040 :type 'boolean)
2042 (defcustom org-highlight-latex-fragments-and-specials nil
2043 "Non-nil means, fontify what is treated specially by the exporters."
2044 :group 'org-font-lock
2045 :type 'boolean)
2047 (defcustom org-hide-emphasis-markers nil
2048 "Non-nil mean font-lock should hide the emphasis marker characters."
2049 :group 'org-font-lock
2050 :type 'boolean)
2052 (defvar org-emph-re nil
2053 "Regular expression for matching emphasis.")
2054 (defvar org-verbatim-re nil
2055 "Regular expression for matching verbatim text.")
2056 (defvar org-emphasis-regexp-components) ; defined just below
2057 (defvar org-emphasis-alist) ; defined just below
2058 (defun org-set-emph-re (var val)
2059 "Set variable and compute the emphasis regular expression."
2060 (set var val)
2061 (when (and (boundp 'org-emphasis-alist)
2062 (boundp 'org-emphasis-regexp-components)
2063 org-emphasis-alist org-emphasis-regexp-components)
2064 (let* ((e org-emphasis-regexp-components)
2065 (pre (car e))
2066 (post (nth 1 e))
2067 (border (nth 2 e))
2068 (body (nth 3 e))
2069 (nl (nth 4 e))
2070 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2071 (body1 (concat body "*?"))
2072 (markers (mapconcat 'car org-emphasis-alist ""))
2073 (vmarkers (mapconcat
2074 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2075 org-emphasis-alist "")))
2076 ;; make sure special characters appear at the right position in the class
2077 (if (string-match "\\^" markers)
2078 (setq markers (concat (replace-match "" t t markers) "^")))
2079 (if (string-match "-" markers)
2080 (setq markers (concat (replace-match "" t t markers) "-")))
2081 (if (string-match "\\^" vmarkers)
2082 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2083 (if (string-match "-" vmarkers)
2084 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2085 (if (> nl 0)
2086 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2087 (int-to-string nl) "\\}")))
2088 ;; Make the regexp
2089 (setq org-emph-re
2090 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2091 "\\("
2092 "\\([" markers "]\\)"
2093 "\\("
2094 "[^" border "]\\|"
2095 "[^" border (if (and nil stacked) markers) "]"
2096 body1
2097 "[^" border (if (and nil stacked) markers) "]"
2098 "\\)"
2099 "\\3\\)"
2100 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2101 (setq org-verbatim-re
2102 (concat "\\([" pre "]\\|^\\)"
2103 "\\("
2104 "\\([" vmarkers "]\\)"
2105 "\\("
2106 "[^" border "]\\|"
2107 "[^" border "]"
2108 body1
2109 "[^" border "]"
2110 "\\)"
2111 "\\3\\)"
2112 "\\([" post "]\\|$\\)")))))
2114 (defcustom org-emphasis-regexp-components
2115 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2116 "Components used to build the regular expression for emphasis.
2117 This is a list with 6 entries. Terminology: In an emphasis string
2118 like \" *strong word* \", we call the initial space PREMATCH, the final
2119 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2120 and \"trong wor\" is the body. The different components in this variable
2121 specify what is allowed/forbidden in each part:
2123 pre Chars allowed as prematch. Beginning of line will be allowed too.
2124 post Chars allowed as postmatch. End of line will be allowed too.
2125 border The chars *forbidden* as border characters.
2126 body-regexp A regexp like \".\" to match a body character. Don't use
2127 non-shy groups here, and don't allow newline here.
2128 newline The maximum number of newlines allowed in an emphasis exp.
2130 Use customize to modify this, or restart Emacs after changing it."
2131 :group 'org-font-lock
2132 :set 'org-set-emph-re
2133 :type '(list
2134 (sexp :tag "Allowed chars in pre ")
2135 (sexp :tag "Allowed chars in post ")
2136 (sexp :tag "Forbidden chars in border ")
2137 (sexp :tag "Regexp for body ")
2138 (integer :tag "number of newlines allowed")
2139 (option (boolean :tag "Stacking (DISABLED) "))))
2141 (defcustom org-emphasis-alist
2142 `(("*" bold "<b>" "</b>")
2143 ("/" italic "<i>" "</i>")
2144 ("_" underline "<u>" "</u>")
2145 ("=" org-code "<code>" "</code>" verbatim)
2146 ("~" org-verbatim "" "" verbatim)
2147 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2148 "<del>" "</del>")
2150 "Special syntax for emphasized text.
2151 Text starting and ending with a special character will be emphasized, for
2152 example *bold*, _underlined_ and /italic/. This variable sets the marker
2153 characters, the face to be used by font-lock for highlighting in Org-mode
2154 Emacs buffers, and the HTML tags to be used for this.
2155 Use customize to modify this, or restart Emacs after changing it."
2156 :group 'org-font-lock
2157 :set 'org-set-emph-re
2158 :type '(repeat
2159 (list
2160 (string :tag "Marker character")
2161 (choice
2162 (face :tag "Font-lock-face")
2163 (plist :tag "Face property list"))
2164 (string :tag "HTML start tag")
2165 (string :tag "HTML end tag")
2166 (option (const verbatim)))))
2168 ;;; Miscellaneous options
2170 (defgroup org-completion nil
2171 "Completion in Org-mode."
2172 :tag "Org Completion"
2173 :group 'org)
2175 (defcustom org-completion-fallback-command 'hippie-expand
2176 "The expansion command called by \\[org-complete] in normal context.
2177 Normal means, no org-mode-specific context."
2178 :group 'org-completion
2179 :type 'function)
2181 ;;; Functions and variables from ther packages
2182 ;; Declared here to avoid compiler warnings
2184 ;; XEmacs only
2185 (defvar outline-mode-menu-heading)
2186 (defvar outline-mode-menu-show)
2187 (defvar outline-mode-menu-hide)
2188 (defvar zmacs-regions) ; XEmacs regions
2190 ;; Emacs only
2191 (defvar mark-active)
2193 ;; Various packages
2194 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2195 (declare-function calendar-forward-day "cal-move" (arg))
2196 (declare-function calendar-goto-date "cal-move" (date))
2197 (declare-function calendar-goto-today "cal-move" ())
2198 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2199 (defvar calc-embedded-close-formula)
2200 (defvar calc-embedded-open-formula)
2201 (declare-function cdlatex-tab "ext:cdlatex" ())
2202 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2203 (defvar font-lock-unfontify-region-function)
2204 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2205 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2206 (defvar iswitchb-temp-buflist)
2207 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2208 (declare-function org-agenda-skip "org-agenda" ())
2209 (declare-function org-format-agenda-item "org-agenda"
2210 (extra txt &optional category tags dotime noprefix remove-re))
2211 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2212 (declare-function org-agenda-change-all-lines "org-agenda"
2213 (newhead hdmarker &optional fixface))
2214 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2215 (declare-function org-agenda-maybe-redo "org-agenda" ())
2216 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2217 (beg end))
2218 (declare-function parse-time-string "parse-time" (string))
2219 (declare-function remember "remember" (&optional initial))
2220 (declare-function remember-buffer-desc "remember" ())
2221 (declare-function remember-finalize "remember" ())
2222 (defvar remember-save-after-remembering)
2223 (defvar remember-data-file)
2224 (defvar remember-register)
2225 (defvar remember-buffer)
2226 (defvar remember-handler-functions)
2227 (defvar remember-annotation-functions)
2228 (defvar texmathp-why)
2229 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2230 (declare-function table--at-cell-p "table" (position &optional object at-column))
2232 (defvar w3m-current-url)
2233 (defvar w3m-current-title)
2235 (defvar org-latex-regexps)
2237 ;;; Autoload and prepare some org modules
2239 ;; Some table stuff that needs to be defined here, because it is used
2240 ;; by the functions setting up org-mode or checking for table context.
2242 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2243 "Detects an org-type or table-type table.")
2244 (defconst org-table-line-regexp "^[ \t]*|"
2245 "Detects an org-type table line.")
2246 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2247 "Detects an org-type table line.")
2248 (defconst org-table-hline-regexp "^[ \t]*|-"
2249 "Detects an org-type table hline.")
2250 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2251 "Detects a table-type table hline.")
2252 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2253 "Searching from within a table (any type) this finds the first line
2254 outside the table.")
2256 ;; Autoload the functions in org-table.el that are needed by functions here.
2258 (eval-and-compile
2259 (org-autoload "org-table"
2260 '(org-table-align org-table-begin org-table-blank-field
2261 org-table-convert org-table-convert-region org-table-copy-down
2262 org-table-copy-region org-table-create
2263 org-table-create-or-convert-from-region
2264 org-table-create-with-table.el org-table-current-dline
2265 org-table-cut-region org-table-delete-column org-table-edit-field
2266 org-table-edit-formulas org-table-end org-table-eval-formula
2267 org-table-export org-table-field-info
2268 org-table-get-stored-formulas org-table-goto-column
2269 org-table-hline-and-move org-table-import org-table-insert-column
2270 org-table-insert-hline org-table-insert-row org-table-iterate
2271 org-table-justify-field-maybe org-table-kill-row
2272 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2273 org-table-move-column org-table-move-column-left
2274 org-table-move-column-right org-table-move-row
2275 org-table-move-row-down org-table-move-row-up
2276 org-table-next-field org-table-next-row org-table-paste-rectangle
2277 org-table-previous-field org-table-recalculate
2278 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2279 org-table-toggle-coordinate-overlays
2280 org-table-toggle-formula-debugger org-table-wrap-region
2281 orgtbl-mode turn-on-orgtbl)))
2283 (defun org-at-table-p (&optional table-type)
2284 "Return t if the cursor is inside an org-type table.
2285 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2286 (if org-enable-table-editor
2287 (save-excursion
2288 (beginning-of-line 1)
2289 (looking-at (if table-type org-table-any-line-regexp
2290 org-table-line-regexp)))
2291 nil))
2292 (defsubst org-table-p () (org-at-table-p))
2294 (defun org-at-table.el-p ()
2295 "Return t if and only if we are at a table.el table."
2296 (and (org-at-table-p 'any)
2297 (save-excursion
2298 (goto-char (org-table-begin 'any))
2299 (looking-at org-table1-hline-regexp))))
2300 (defun org-table-recognize-table.el ()
2301 "If there is a table.el table nearby, recognize it and move into it."
2302 (if org-table-tab-recognizes-table.el
2303 (if (org-at-table.el-p)
2304 (progn
2305 (beginning-of-line 1)
2306 (if (looking-at org-table-dataline-regexp)
2308 (if (looking-at org-table1-hline-regexp)
2309 (progn
2310 (beginning-of-line 2)
2311 (if (looking-at org-table-any-border-regexp)
2312 (beginning-of-line -1)))))
2313 (if (re-search-forward "|" (org-table-end t) t)
2314 (progn
2315 (require 'table)
2316 (if (table--at-cell-p (point))
2318 (message "recognizing table.el table...")
2319 (table-recognize-table)
2320 (message "recognizing table.el table...done")))
2321 (error "This should not happen..."))
2323 nil)
2324 nil))
2326 (defun org-at-table-hline-p ()
2327 "Return t if the cursor is inside a hline in a table."
2328 (if org-enable-table-editor
2329 (save-excursion
2330 (beginning-of-line 1)
2331 (looking-at org-table-hline-regexp))
2332 nil))
2334 (defvar org-table-clean-did-remove-column nil)
2336 (defun org-table-map-tables (function)
2337 "Apply FUNCTION to the start of all tables in the buffer."
2338 (save-excursion
2339 (save-restriction
2340 (widen)
2341 (goto-char (point-min))
2342 (while (re-search-forward org-table-any-line-regexp nil t)
2343 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2344 (beginning-of-line 1)
2345 (if (looking-at org-table-line-regexp)
2346 (save-excursion (funcall function)))
2347 (re-search-forward org-table-any-border-regexp nil 1))))
2348 (message "Mapping tables: done"))
2350 ;; Declare and autoload functions from org-exp.el
2352 (declare-function org-default-export-plist "org-exp")
2353 (declare-function org-infile-export-plist "org-exp")
2354 (declare-function org-get-current-options "org-exp")
2355 (eval-and-compile
2356 (org-autoload "org-exp"
2357 '(org-export org-export-as-ascii org-export-visible
2358 org-insert-export-options-template org-export-as-html-and-open
2359 org-export-as-html-batch org-export-as-html-to-buffer
2360 org-replace-region-by-html org-export-region-as-html
2361 org-export-as-html org-export-icalendar-this-file
2362 org-export-icalendar-all-agenda-files
2363 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2365 ;; Declare and autoload functions from org-exp.el
2367 (eval-and-compile
2368 (org-autoload "org-exp"
2369 '(org-agenda org-agenda-list org-search-view
2370 org-todo-list org-tags-view org-agenda-list-stuck-projects
2371 org-diary org-agenda-to-appt)))
2373 ;; Autoload org-remember
2375 (eval-and-compile
2376 (org-autoload "org-remember"
2377 '(org-remember-insinuate org-remember-annotation
2378 org-remember-apply-template org-remember org-remember-handler)))
2380 ;; Autoload org-clock.el
2383 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2384 (beg end))
2385 (defvar org-clock-marker (make-marker)
2386 "Marker recording the last clock-in.")
2388 (eval-and-compile
2389 (org-autoload
2390 "org-clock"
2391 '(org-clock-in org-clock-out org-clock-cancel
2392 org-clock-goto org-clock-sum org-clock-display
2393 org-remove-clock-overlays org-clock-report
2394 org-clocktable-shift org-dblock-write:clocktable
2395 org-get-clocktable)))
2397 (defun org-clock-update-time-maybe ()
2398 "If this is a CLOCK line, update it and return t.
2399 Otherwise, return nil."
2400 (interactive)
2401 (save-excursion
2402 (beginning-of-line 1)
2403 (skip-chars-forward " \t")
2404 (when (looking-at org-clock-string)
2405 (let ((re (concat "[ \t]*" org-clock-string
2406 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2407 "\\([ \t]*=>.*\\)?"))
2408 ts te h m s)
2409 (if (not (looking-at re))
2411 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2412 (end-of-line 1)
2413 (setq ts (match-string 1)
2414 te (match-string 2))
2415 (setq s (- (time-to-seconds
2416 (apply 'encode-time (org-parse-time-string te)))
2417 (time-to-seconds
2418 (apply 'encode-time (org-parse-time-string ts))))
2419 h (floor (/ s 3600))
2420 s (- s (* 3600 h))
2421 m (floor (/ s 60))
2422 s (- s (* 60 s)))
2423 (insert " => " (format "%2d:%02d" h m))
2424 t)))))
2426 (defun org-check-running-clock ()
2427 "Check if the current buffer contains the running clock.
2428 If yes, offer to stop it and to save the buffer with the changes."
2429 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2430 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2431 (buffer-name))))
2432 (org-clock-out)
2433 (when (y-or-n-p "Save changed buffer?")
2434 (save-buffer))))
2436 (defun org-clocktable-try-shift (dir n)
2437 "Check if this line starts a clock table, if yes, shift the time block."
2438 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2439 (org-clocktable-shift dir n)))
2441 ;; Autoload archiving code
2442 ;; The stuff that is needed for cycling and tags has to be defined here.
2444 (defgroup org-archive nil
2445 "Options concerning archiving in Org-mode."
2446 :tag "Org Archive"
2447 :group 'org-structure)
2449 (defcustom org-archive-location "%s_archive::"
2450 "The location where subtrees should be archived.
2452 Otherwise, the value of this variable is a string, consisting of two
2453 parts, separated by a double-colon.
2455 The first part is a file name - when omitted, archiving happens in the same
2456 file. %s will be replaced by the current file name (without directory part).
2457 Archiving to a different file is useful to keep archived entries from
2458 contributing to the Org-mode Agenda.
2460 The part after the double colon is a headline. The archived entries will be
2461 filed under that headline. When omitted, the subtrees are simply filed away
2462 at the end of the file, as top-level entries.
2464 Here are a few examples:
2465 \"%s_archive::\"
2466 If the current file is Projects.org, archive in file
2467 Projects.org_archive, as top-level trees. This is the default.
2469 \"::* Archived Tasks\"
2470 Archive in the current file, under the top-level headline
2471 \"* Archived Tasks\".
2473 \"~/org/archive.org::\"
2474 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2476 \"basement::** Finished Tasks\"
2477 Archive in file ./basement (relative path), as level 3 trees
2478 below the level 2 heading \"** Finished Tasks\".
2480 You may set this option on a per-file basis by adding to the buffer a
2481 line like
2483 #+ARCHIVE: basement::** Finished Tasks
2485 You may also define it locally for a subtree by setting an ARCHIVE property
2486 in the entry. If such a property is found in an entry, or anywhere up
2487 the hierarchy, it will be used."
2488 :group 'org-archive
2489 :type 'string)
2491 (defcustom org-archive-tag "ARCHIVE"
2492 "The tag that marks a subtree as archived.
2493 An archived subtree does not open during visibility cycling, and does
2494 not contribute to the agenda listings.
2495 After changing this, font-lock must be restarted in the relevant buffers to
2496 get the proper fontification."
2497 :group 'org-archive
2498 :group 'org-keywords
2499 :type 'string)
2501 (defcustom org-agenda-skip-archived-trees t
2502 "Non-nil means, the agenda will skip any items located in archived trees.
2503 An archived tree is a tree marked with the tag ARCHIVE."
2504 :group 'org-archive
2505 :group 'org-agenda-skip
2506 :type 'boolean)
2508 (defcustom org-cycle-open-archived-trees nil
2509 "Non-nil means, `org-cycle' will open archived trees.
2510 An archived tree is a tree marked with the tag ARCHIVE.
2511 When nil, archived trees will stay folded. You can still open them with
2512 normal outline commands like `show-all', but not with the cycling commands."
2513 :group 'org-archive
2514 :group 'org-cycle
2515 :type 'boolean)
2517 (defcustom org-sparse-tree-open-archived-trees nil
2518 "Non-nil means sparse tree construction shows matches in archived trees.
2519 When nil, matches in these trees are highlighted, but the trees are kept in
2520 collapsed state."
2521 :group 'org-archive
2522 :group 'org-sparse-trees
2523 :type 'boolean)
2525 (defun org-cycle-hide-archived-subtrees (state)
2526 "Re-hide all archived subtrees after a visibility state change."
2527 (when (and (not org-cycle-open-archived-trees)
2528 (not (memq state '(overview folded))))
2529 (save-excursion
2530 (let* ((globalp (memq state '(contents all)))
2531 (beg (if globalp (point-min) (point)))
2532 (end (if globalp (point-max) (org-end-of-subtree t))))
2533 (org-hide-archived-subtrees beg end)
2534 (goto-char beg)
2535 (if (looking-at (concat ".*:" org-archive-tag ":"))
2536 (message "%s" (substitute-command-keys
2537 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2539 (defun org-force-cycle-archived ()
2540 "Cycle subtree even if it is archived."
2541 (interactive)
2542 (setq this-command 'org-cycle)
2543 (let ((org-cycle-open-archived-trees t))
2544 (call-interactively 'org-cycle)))
2546 (defun org-hide-archived-subtrees (beg end)
2547 "Re-hide all archived subtrees after a visibility state change."
2548 (save-excursion
2549 (let* ((re (concat ":" org-archive-tag ":")))
2550 (goto-char beg)
2551 (while (re-search-forward re end t)
2552 (and (org-on-heading-p) (hide-subtree))
2553 (org-end-of-subtree t)))))
2555 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2557 (eval-and-compile
2558 (org-autoload "org-archive"
2559 '(org-add-archive-files org-archive-subtree
2560 org-archive-to-archive-sibling org-toggle-archive-tag)))
2562 ;; Autoload Column View Code
2564 (declare-function org-columns-number-to-string "org-colview")
2565 (declare-function org-columns-get-format-and-top-level "org-colview")
2566 (declare-function org-columns-compute "org-colview")
2568 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2569 '(org-columns-number-to-string org-columns-get-format-and-top-level
2570 org-columns-compute org-agenda-columns org-columns-remove-overlays
2571 org-columns org-insert-columns-dblock))
2573 ;;; Variables for pre-computed regular expressions, all buffer local
2575 (defvar org-drawer-regexp nil
2576 "Matches first line of a hidden block.")
2577 (make-variable-buffer-local 'org-drawer-regexp)
2578 (defvar org-todo-regexp nil
2579 "Matches any of the TODO state keywords.")
2580 (make-variable-buffer-local 'org-todo-regexp)
2581 (defvar org-not-done-regexp nil
2582 "Matches any of the TODO state keywords except the last one.")
2583 (make-variable-buffer-local 'org-not-done-regexp)
2584 (defvar org-todo-line-regexp nil
2585 "Matches a headline and puts TODO state into group 2 if present.")
2586 (make-variable-buffer-local 'org-todo-line-regexp)
2587 (defvar org-complex-heading-regexp nil
2588 "Matches a headline and puts everything into groups:
2589 group 1: the stars
2590 group 2: The todo keyword, maybe
2591 group 3: Priority cookie
2592 group 4: True headline
2593 group 5: Tags")
2594 (make-variable-buffer-local 'org-complex-heading-regexp)
2595 (defvar org-todo-line-tags-regexp nil
2596 "Matches a headline and puts TODO state into group 2 if present.
2597 Also put tags into group 4 if tags are present.")
2598 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2599 (defvar org-nl-done-regexp nil
2600 "Matches newline followed by a headline with the DONE keyword.")
2601 (make-variable-buffer-local 'org-nl-done-regexp)
2602 (defvar org-looking-at-done-regexp nil
2603 "Matches the DONE keyword a point.")
2604 (make-variable-buffer-local 'org-looking-at-done-regexp)
2605 (defvar org-ds-keyword-length 12
2606 "Maximum length of the Deadline and SCHEDULED keywords.")
2607 (make-variable-buffer-local 'org-ds-keyword-length)
2608 (defvar org-deadline-regexp nil
2609 "Matches the DEADLINE keyword.")
2610 (make-variable-buffer-local 'org-deadline-regexp)
2611 (defvar org-deadline-time-regexp nil
2612 "Matches the DEADLINE keyword together with a time stamp.")
2613 (make-variable-buffer-local 'org-deadline-time-regexp)
2614 (defvar org-deadline-line-regexp nil
2615 "Matches the DEADLINE keyword and the rest of the line.")
2616 (make-variable-buffer-local 'org-deadline-line-regexp)
2617 (defvar org-scheduled-regexp nil
2618 "Matches the SCHEDULED keyword.")
2619 (make-variable-buffer-local 'org-scheduled-regexp)
2620 (defvar org-scheduled-time-regexp nil
2621 "Matches the SCHEDULED keyword together with a time stamp.")
2622 (make-variable-buffer-local 'org-scheduled-time-regexp)
2623 (defvar org-closed-time-regexp nil
2624 "Matches the CLOSED keyword together with a time stamp.")
2625 (make-variable-buffer-local 'org-closed-time-regexp)
2627 (defvar org-keyword-time-regexp nil
2628 "Matches any of the 4 keywords, together with the time stamp.")
2629 (make-variable-buffer-local 'org-keyword-time-regexp)
2630 (defvar org-keyword-time-not-clock-regexp nil
2631 "Matches any of the 3 keywords, together with the time stamp.")
2632 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2633 (defvar org-maybe-keyword-time-regexp nil
2634 "Matches a timestamp, possibly preceeded by a keyword.")
2635 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2636 (defvar org-planning-or-clock-line-re nil
2637 "Matches a line with planning or clock info.")
2638 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2640 (defconst org-plain-time-of-day-regexp
2641 (concat
2642 "\\(\\<[012]?[0-9]"
2643 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2644 "\\(--?"
2645 "\\(\\<[012]?[0-9]"
2646 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2647 "\\)?")
2648 "Regular expression to match a plain time or time range.
2649 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2650 groups carry important information:
2651 0 the full match
2652 1 the first time, range or not
2653 8 the second time, if it is a range.")
2655 (defconst org-plain-time-extension-regexp
2656 (concat
2657 "\\(\\<[012]?[0-9]"
2658 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2659 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2660 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2661 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2662 groups carry important information:
2663 0 the full match
2664 7 hours of duration
2665 9 minutes of duration")
2667 (defconst org-stamp-time-of-day-regexp
2668 (concat
2669 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2670 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2671 "\\(--?"
2672 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2673 "Regular expression to match a timestamp time or time range.
2674 After a match, the following groups carry important information:
2675 0 the full match
2676 1 date plus weekday, for backreferencing to make sure both times on same day
2677 2 the first time, range or not
2678 4 the second time, if it is a range.")
2680 (defconst org-startup-options
2681 '(("fold" org-startup-folded t)
2682 ("overview" org-startup-folded t)
2683 ("nofold" org-startup-folded nil)
2684 ("showall" org-startup-folded nil)
2685 ("content" org-startup-folded content)
2686 ("hidestars" org-hide-leading-stars t)
2687 ("showstars" org-hide-leading-stars nil)
2688 ("odd" org-odd-levels-only t)
2689 ("oddeven" org-odd-levels-only nil)
2690 ("align" org-startup-align-all-tables t)
2691 ("noalign" org-startup-align-all-tables nil)
2692 ("customtime" org-display-custom-times t)
2693 ("logdone" org-log-done time)
2694 ("lognotedone" org-log-done note)
2695 ("nologdone" org-log-done nil)
2696 ("lognoteclock-out" org-log-note-clock-out t)
2697 ("nolognoteclock-out" org-log-note-clock-out nil)
2698 ("logrepeat" org-log-repeat state)
2699 ("lognoterepeat" org-log-repeat note)
2700 ("nologrepeat" org-log-repeat nil)
2701 ("constcgs" constants-unit-system cgs)
2702 ("constSI" constants-unit-system SI))
2703 "Variable associated with STARTUP options for org-mode.
2704 Each element is a list of three items: The startup options as written
2705 in the #+STARTUP line, the corresponding variable, and the value to
2706 set this variable to if the option is found. An optional forth element PUSH
2707 means to push this value onto the list in the variable.")
2709 (defun org-set-regexps-and-options ()
2710 "Precompute regular expressions for current buffer."
2711 (when (org-mode-p)
2712 (org-set-local 'org-todo-kwd-alist nil)
2713 (org-set-local 'org-todo-key-alist nil)
2714 (org-set-local 'org-todo-key-trigger nil)
2715 (org-set-local 'org-todo-keywords-1 nil)
2716 (org-set-local 'org-done-keywords nil)
2717 (org-set-local 'org-todo-heads nil)
2718 (org-set-local 'org-todo-sets nil)
2719 (org-set-local 'org-todo-log-states nil)
2720 (let ((re (org-make-options-regexp
2721 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2722 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2723 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2724 (splitre "[ \t]+")
2725 kwds kws0 kwsa key log value cat arch tags const links hw dws
2726 tail sep kws1 prio props drawers
2727 ext-setup-or-nil setup-contents (start 0))
2728 (save-excursion
2729 (save-restriction
2730 (widen)
2731 (goto-char (point-min))
2732 (while (or (and ext-setup-or-nil
2733 (string-match re ext-setup-or-nil start)
2734 (setq start (match-end 0)))
2735 (and (setq ext-setup-or-nil nil start 0)
2736 (re-search-forward re nil t)))
2737 (setq key (upcase (match-string 1 ext-setup-or-nil))
2738 value (org-match-string-no-properties 2 ext-setup-or-nil))
2739 (cond
2740 ((equal key "CATEGORY")
2741 (if (string-match "[ \t]+$" value)
2742 (setq value (replace-match "" t t value)))
2743 (setq cat value))
2744 ((member key '("SEQ_TODO" "TODO"))
2745 (push (cons 'sequence (org-split-string value splitre)) kwds))
2746 ((equal key "TYP_TODO")
2747 (push (cons 'type (org-split-string value splitre)) kwds))
2748 ((equal key "TAGS")
2749 (setq tags (append tags (org-split-string value splitre))))
2750 ((equal key "COLUMNS")
2751 (org-set-local 'org-columns-default-format value))
2752 ((equal key "LINK")
2753 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2754 (push (cons (match-string 1 value)
2755 (org-trim (match-string 2 value)))
2756 links)))
2757 ((equal key "PRIORITIES")
2758 (setq prio (org-split-string value " +")))
2759 ((equal key "PROPERTY")
2760 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2761 (push (cons (match-string 1 value) (match-string 2 value))
2762 props)))
2763 ((equal key "DRAWERS")
2764 (setq drawers (org-split-string value splitre)))
2765 ((equal key "CONSTANTS")
2766 (setq const (append const (org-split-string value splitre))))
2767 ((equal key "STARTUP")
2768 (let ((opts (org-split-string value splitre))
2769 l var val)
2770 (while (setq l (pop opts))
2771 (when (setq l (assoc l org-startup-options))
2772 (setq var (nth 1 l) val (nth 2 l))
2773 (if (not (nth 3 l))
2774 (set (make-local-variable var) val)
2775 (if (not (listp (symbol-value var)))
2776 (set (make-local-variable var) nil))
2777 (set (make-local-variable var) (symbol-value var))
2778 (add-to-list var val))))))
2779 ((equal key "ARCHIVE")
2780 (string-match " *$" value)
2781 (setq arch (replace-match "" t t value))
2782 (remove-text-properties 0 (length arch)
2783 '(face t fontified t) arch))
2784 ((equal key "SETUPFILE")
2785 (setq setup-contents (org-file-contents
2786 (expand-file-name
2787 (org-remove-double-quotes value))
2788 'noerror))
2789 (if (not ext-setup-or-nil)
2790 (setq ext-setup-or-nil setup-contents start 0)
2791 (setq ext-setup-or-nil
2792 (concat (substring ext-setup-or-nil 0 start)
2793 "\n" setup-contents "\n"
2794 (substring ext-setup-or-nil start)))))
2795 ))))
2796 (when cat
2797 (org-set-local 'org-category (intern cat))
2798 (push (cons "CATEGORY" cat) props))
2799 (when prio
2800 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2801 (setq prio (mapcar 'string-to-char prio))
2802 (org-set-local 'org-highest-priority (nth 0 prio))
2803 (org-set-local 'org-lowest-priority (nth 1 prio))
2804 (org-set-local 'org-default-priority (nth 2 prio)))
2805 (and props (org-set-local 'org-local-properties (nreverse props)))
2806 (and drawers (org-set-local 'org-drawers drawers))
2807 (and arch (org-set-local 'org-archive-location arch))
2808 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2809 ;; Process the TODO keywords
2810 (unless kwds
2811 ;; Use the global values as if they had been given locally.
2812 (setq kwds (default-value 'org-todo-keywords))
2813 (if (stringp (car kwds))
2814 (setq kwds (list (cons org-todo-interpretation
2815 (default-value 'org-todo-keywords)))))
2816 (setq kwds (reverse kwds)))
2817 (setq kwds (nreverse kwds))
2818 (let (inter kws kw)
2819 (while (setq kws (pop kwds))
2820 (setq inter (pop kws) sep (member "|" kws)
2821 kws0 (delete "|" (copy-sequence kws))
2822 kwsa nil
2823 kws1 (mapcar
2824 (lambda (x)
2825 ;; 1 2
2826 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2827 (progn
2828 (setq kw (match-string 1 x)
2829 key (and (match-end 2) (match-string 2 x))
2830 log (org-extract-log-state-settings x))
2831 (push (cons kw (and key (string-to-char key))) kwsa)
2832 (and log (push log org-todo-log-states))
2834 (error "Invalid TODO keyword %s" x)))
2835 kws0)
2836 kwsa (if kwsa (append '((:startgroup))
2837 (nreverse kwsa)
2838 '((:endgroup))))
2839 hw (car kws1)
2840 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2841 tail (list inter hw (car dws) (org-last dws)))
2842 (add-to-list 'org-todo-heads hw 'append)
2843 (push kws1 org-todo-sets)
2844 (setq org-done-keywords (append org-done-keywords dws nil))
2845 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2846 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2847 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2848 (setq org-todo-sets (nreverse org-todo-sets)
2849 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2850 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2851 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2852 ;; Process the constants
2853 (when const
2854 (let (e cst)
2855 (while (setq e (pop const))
2856 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2857 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2858 (setq org-table-formula-constants-local cst)))
2860 ;; Process the tags.
2861 (when tags
2862 (let (e tgs)
2863 (while (setq e (pop tags))
2864 (cond
2865 ((equal e "{") (push '(:startgroup) tgs))
2866 ((equal e "}") (push '(:endgroup) tgs))
2867 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2868 (push (cons (match-string 1 e)
2869 (string-to-char (match-string 2 e)))
2870 tgs))
2871 (t (push (list e) tgs))))
2872 (org-set-local 'org-tag-alist nil)
2873 (while (setq e (pop tgs))
2874 (or (and (stringp (car e))
2875 (assoc (car e) org-tag-alist))
2876 (push e org-tag-alist))))))
2878 ;; Compute the regular expressions and other local variables
2879 (if (not org-done-keywords)
2880 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2881 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2882 (length org-scheduled-string)
2883 (length org-clock-string)
2884 (length org-closed-string)))
2885 org-drawer-regexp
2886 (concat "^[ \t]*:\\("
2887 (mapconcat 'regexp-quote org-drawers "\\|")
2888 "\\):[ \t]*$")
2889 org-not-done-keywords
2890 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2891 org-todo-regexp
2892 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2893 "\\|") "\\)\\>")
2894 org-not-done-regexp
2895 (concat "\\<\\("
2896 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2897 "\\)\\>")
2898 org-todo-line-regexp
2899 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2900 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2901 "\\)\\>\\)?[ \t]*\\(.*\\)")
2902 org-complex-heading-regexp
2903 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2904 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2905 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2906 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2907 org-nl-done-regexp
2908 (concat "\n\\*+[ \t]+"
2909 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2910 "\\)" "\\>")
2911 org-todo-line-tags-regexp
2912 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2913 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2914 (org-re
2915 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2916 org-looking-at-done-regexp
2917 (concat "^" "\\(?:"
2918 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2919 "\\>")
2920 org-deadline-regexp (concat "\\<" org-deadline-string)
2921 org-deadline-time-regexp
2922 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2923 org-deadline-line-regexp
2924 (concat "\\<\\(" org-deadline-string "\\).*")
2925 org-scheduled-regexp
2926 (concat "\\<" org-scheduled-string)
2927 org-scheduled-time-regexp
2928 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2929 org-closed-time-regexp
2930 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2931 org-keyword-time-regexp
2932 (concat "\\<\\(" org-scheduled-string
2933 "\\|" org-deadline-string
2934 "\\|" org-closed-string
2935 "\\|" org-clock-string "\\)"
2936 " *[[<]\\([^]>]+\\)[]>]")
2937 org-keyword-time-not-clock-regexp
2938 (concat "\\<\\(" org-scheduled-string
2939 "\\|" org-deadline-string
2940 "\\|" org-closed-string
2941 "\\)"
2942 " *[[<]\\([^]>]+\\)[]>]")
2943 org-maybe-keyword-time-regexp
2944 (concat "\\(\\<\\(" org-scheduled-string
2945 "\\|" org-deadline-string
2946 "\\|" org-closed-string
2947 "\\|" org-clock-string "\\)\\)?"
2948 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2949 org-planning-or-clock-line-re
2950 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2951 "\\|" org-deadline-string
2952 "\\|" org-closed-string "\\|" org-clock-string
2953 "\\)\\>\\)")
2955 (org-compute-latex-and-specials-regexp)
2956 (org-set-font-lock-defaults)))
2958 (defun org-file-contents (file &optional noerror)
2959 "Return the contents of FILE, as a string."
2960 (if (or (not file)
2961 (not (file-readable-p file)))
2962 (if noerror
2963 (progn
2964 (message "Cannot read file %s" file)
2965 (ding) (sit-for 2)
2967 (error "Cannot read file %s" file))
2968 (with-temp-buffer
2969 (insert-file-contents file)
2970 (buffer-string))))
2972 (defun org-extract-log-state-settings (x)
2973 "Extract the log state setting from a TODO keyword string.
2974 This will extract info from a string like \"WAIT(w@/!)\"."
2975 (let (kw key log1 log2)
2976 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2977 (setq kw (match-string 1 x)
2978 key (and (match-end 2) (match-string 2 x))
2979 log1 (and (match-end 3) (match-string 3 x))
2980 log2 (and (match-end 4) (match-string 4 x)))
2981 (and (or log1 log2)
2982 (list kw
2983 (and log1 (if (equal log1 "!") 'time 'note))
2984 (and log2 (if (equal log2 "!") 'time 'note)))))))
2986 (defun org-remove-keyword-keys (list)
2987 "Remove a pair of parenthesis at the end of each string in LIST."
2988 (mapcar (lambda (x)
2989 (if (string-match "(.*)$" x)
2990 (substring x 0 (match-beginning 0))
2992 list))
2994 ;; FIXME: this could be done much better, using second characters etc.
2995 (defun org-assign-fast-keys (alist)
2996 "Assign fast keys to a keyword-key alist.
2997 Respect keys that are already there."
2998 (let (new e k c c1 c2 (char ?a))
2999 (while (setq e (pop alist))
3000 (cond
3001 ((equal e '(:startgroup)) (push e new))
3002 ((equal e '(:endgroup)) (push e new))
3004 (setq k (car e) c2 nil)
3005 (if (cdr e)
3006 (setq c (cdr e))
3007 ;; automatically assign a character.
3008 (setq c1 (string-to-char
3009 (downcase (substring
3010 k (if (= (string-to-char k) ?@) 1 0)))))
3011 (if (or (rassoc c1 new) (rassoc c1 alist))
3012 (while (or (rassoc char new) (rassoc char alist))
3013 (setq char (1+ char)))
3014 (setq c2 c1))
3015 (setq c (or c2 char)))
3016 (push (cons k c) new))))
3017 (nreverse new)))
3019 ;;; Some variables used in various places
3021 (defvar org-window-configuration nil
3022 "Used in various places to store a window configuration.")
3023 (defvar org-finish-function nil
3024 "Function to be called when `C-c C-c' is used.
3025 This is for getting out of special buffers like remember.")
3028 ;; FIXME: Occasionally check by commenting these, to make sure
3029 ;; no other functions uses these, forgetting to let-bind them.
3030 (defvar entry)
3031 (defvar state)
3032 (defvar last-state)
3033 (defvar date)
3034 (defvar description)
3036 ;; Defined somewhere in this file, but used before definition.
3037 (defvar org-html-entities)
3038 (defvar org-struct-menu)
3039 (defvar org-org-menu)
3040 (defvar org-tbl-menu)
3041 (defvar org-agenda-keymap)
3043 ;;;; Define the Org-mode
3045 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3046 (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."))
3049 ;; We use a before-change function to check if a table might need
3050 ;; an update.
3051 (defvar org-table-may-need-update t
3052 "Indicates that a table might need an update.
3053 This variable is set by `org-before-change-function'.
3054 `org-table-align' sets it back to nil.")
3055 (defun org-before-change-function (beg end)
3056 "Every change indicates that a table might need an update."
3057 (setq org-table-may-need-update t))
3058 (defvar org-mode-map)
3059 (defvar org-mode-hook nil)
3060 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3061 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3062 (defvar org-table-buffer-is-an nil)
3063 (defconst org-outline-regexp "\\*+ ")
3065 ;;;###autoload
3066 (define-derived-mode org-mode outline-mode "Org"
3067 "Outline-based notes management and organizer, alias
3068 \"Carsten's outline-mode for keeping track of everything.\"
3070 Org-mode develops organizational tasks around a NOTES file which
3071 contains information about projects as plain text. Org-mode is
3072 implemented on top of outline-mode, which is ideal to keep the content
3073 of large files well structured. It supports ToDo items, deadlines and
3074 time stamps, which magically appear in the diary listing of the Emacs
3075 calendar. Tables are easily created with a built-in table editor.
3076 Plain text URL-like links connect to websites, emails (VM), Usenet
3077 messages (Gnus), BBDB entries, and any files related to the project.
3078 For printing and sharing of notes, an Org-mode file (or a part of it)
3079 can be exported as a structured ASCII or HTML file.
3081 The following commands are available:
3083 \\{org-mode-map}"
3085 ;; Get rid of Outline menus, they are not needed
3086 ;; Need to do this here because define-derived-mode sets up
3087 ;; the keymap so late. Still, it is a waste to call this each time
3088 ;; we switch another buffer into org-mode.
3089 (if (featurep 'xemacs)
3090 (when (boundp 'outline-mode-menu-heading)
3091 ;; Assume this is Greg's port, it used easymenu
3092 (easy-menu-remove outline-mode-menu-heading)
3093 (easy-menu-remove outline-mode-menu-show)
3094 (easy-menu-remove outline-mode-menu-hide))
3095 (define-key org-mode-map [menu-bar headings] 'undefined)
3096 (define-key org-mode-map [menu-bar hide] 'undefined)
3097 (define-key org-mode-map [menu-bar show] 'undefined))
3099 (org-load-modules-maybe)
3100 (easy-menu-add org-org-menu)
3101 (easy-menu-add org-tbl-menu)
3102 (org-install-agenda-files-menu)
3103 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3104 (org-add-to-invisibility-spec '(org-cwidth))
3105 (when (featurep 'xemacs)
3106 (org-set-local 'line-move-ignore-invisible t))
3107 (org-set-local 'outline-regexp org-outline-regexp)
3108 (org-set-local 'outline-level 'org-outline-level)
3109 (when (and org-ellipsis
3110 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3111 (fboundp 'make-glyph-code))
3112 (unless org-display-table
3113 (setq org-display-table (make-display-table)))
3114 (set-display-table-slot
3115 org-display-table 4
3116 (vconcat (mapcar
3117 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3118 org-ellipsis)))
3119 (if (stringp org-ellipsis) org-ellipsis "..."))))
3120 (setq buffer-display-table org-display-table))
3121 (org-set-regexps-and-options)
3122 ;; Calc embedded
3123 (org-set-local 'calc-embedded-open-mode "# ")
3124 (modify-syntax-entry ?# "<")
3125 (modify-syntax-entry ?@ "w")
3126 (if org-startup-truncated (setq truncate-lines t))
3127 (org-set-local 'font-lock-unfontify-region-function
3128 'org-unfontify-region)
3129 ;; Activate before-change-function
3130 (org-set-local 'org-table-may-need-update t)
3131 (org-add-hook 'before-change-functions 'org-before-change-function nil
3132 'local)
3133 ;; Check for running clock before killing a buffer
3134 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3135 ;; Paragraphs and auto-filling
3136 (org-set-autofill-regexps)
3137 (setq indent-line-function 'org-indent-line-function)
3138 (org-update-radio-target-regexp)
3140 ;; Comment characters
3141 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3142 (org-set-local 'comment-padding " ")
3144 ;; Align options lines
3145 (org-set-local
3146 'align-mode-rules-list
3147 '((org-in-buffer-settings
3148 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3149 (modes . '(org-mode)))))
3151 ;; Imenu
3152 (org-set-local 'imenu-create-index-function
3153 'org-imenu-get-tree)
3155 ;; Make isearch reveal context
3156 (if (or (featurep 'xemacs)
3157 (not (boundp 'outline-isearch-open-invisible-function)))
3158 ;; Emacs 21 and XEmacs make use of the hook
3159 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3160 ;; Emacs 22 deals with this through a special variable
3161 (org-set-local 'outline-isearch-open-invisible-function
3162 (lambda (&rest ignore) (org-show-context 'isearch))))
3164 ;; If empty file that did not turn on org-mode automatically, make it to.
3165 (if (and org-insert-mode-line-in-empty-file
3166 (interactive-p)
3167 (= (point-min) (point-max)))
3168 (insert "# -*- mode: org -*-\n\n"))
3170 (unless org-inhibit-startup
3171 (when org-startup-align-all-tables
3172 (let ((bmp (buffer-modified-p)))
3173 (org-table-map-tables 'org-table-align)
3174 (set-buffer-modified-p bmp)))
3175 (org-set-startup-visibility)))
3177 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3179 (defun org-current-time ()
3180 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3181 (if (> (car org-time-stamp-rounding-minutes) 1)
3182 (let ((r (car org-time-stamp-rounding-minutes))
3183 (time (decode-time)))
3184 (apply 'encode-time
3185 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3186 (nthcdr 2 time))))
3187 (current-time)))
3189 ;;;; Font-Lock stuff, including the activators
3191 (defvar org-mouse-map (make-sparse-keymap))
3192 (org-defkey org-mouse-map
3193 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3194 (org-defkey org-mouse-map
3195 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3196 (when org-mouse-1-follows-link
3197 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3198 (when org-tab-follows-link
3199 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3200 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3201 (when org-return-follows-link
3202 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3203 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3205 (require 'font-lock)
3207 (defconst org-non-link-chars "]\t\n\r<>")
3208 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3209 "shell" "elisp"))
3210 (defvar org-link-types-re nil
3211 "Matches a link that has a url-like prefix like \"http:\"")
3212 (defvar org-link-re-with-space nil
3213 "Matches a link with spaces, optional angular brackets around it.")
3214 (defvar org-link-re-with-space2 nil
3215 "Matches a link with spaces, optional angular brackets around it.")
3216 (defvar org-angle-link-re nil
3217 "Matches link with angular brackets, spaces are allowed.")
3218 (defvar org-plain-link-re nil
3219 "Matches plain link, without spaces.")
3220 (defvar org-bracket-link-regexp nil
3221 "Matches a link in double brackets.")
3222 (defvar org-bracket-link-analytic-regexp nil
3223 "Regular expression used to analyze links.
3224 Here is what the match groups contain after a match:
3225 1: http:
3226 2: http
3227 3: path
3228 4: [desc]
3229 5: desc")
3230 (defvar org-any-link-re nil
3231 "Regular expression matching any link.")
3233 (defun org-make-link-regexps ()
3234 "Update the link regular expressions.
3235 This should be called after the variable `org-link-types' has changed."
3236 (setq org-link-types-re
3237 (concat
3238 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3239 org-link-re-with-space
3240 (concat
3241 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3242 "\\([^" org-non-link-chars " ]"
3243 "[^" org-non-link-chars "]*"
3244 "[^" org-non-link-chars " ]\\)>?")
3245 org-link-re-with-space2
3246 (concat
3247 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3248 "\\([^" org-non-link-chars " ]"
3249 "[^]\t\n\r]*"
3250 "[^" org-non-link-chars " ]\\)>?")
3251 org-angle-link-re
3252 (concat
3253 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3254 "\\([^" org-non-link-chars " ]"
3255 "[^" org-non-link-chars "]*"
3256 "\\)>")
3257 org-plain-link-re
3258 (concat
3259 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3260 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3261 org-bracket-link-regexp
3262 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3263 org-bracket-link-analytic-regexp
3264 (concat
3265 "\\[\\["
3266 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3267 "\\([^]]+\\)"
3268 "\\]"
3269 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3270 "\\]")
3271 org-any-link-re
3272 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3273 org-angle-link-re "\\)\\|\\("
3274 org-plain-link-re "\\)")))
3276 (org-make-link-regexps)
3278 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3279 "Regular expression for fast time stamp matching.")
3280 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3281 "Regular expression for fast time stamp matching.")
3282 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3283 "Regular expression matching time strings for analysis.
3284 This one does not require the space after the date, so it can be used
3285 on a string that terminates immediately after the date.")
3286 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3287 "Regular expression matching time strings for analysis.")
3288 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3289 "Regular expression matching time stamps, with groups.")
3290 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3291 "Regular expression matching time stamps (also [..]), with groups.")
3292 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3293 "Regular expression matching a time stamp range.")
3294 (defconst org-tr-regexp-both
3295 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3296 "Regular expression matching a time stamp range.")
3297 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3298 org-ts-regexp "\\)?")
3299 "Regular expression matching a time stamp or time stamp range.")
3300 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3301 org-ts-regexp-both "\\)?")
3302 "Regular expression matching a time stamp or time stamp range.
3303 The time stamps may be either active or inactive.")
3305 (defvar org-emph-face nil)
3307 (defun org-do-emphasis-faces (limit)
3308 "Run through the buffer and add overlays to links."
3309 (let (rtn)
3310 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3311 (if (not (= (char-after (match-beginning 3))
3312 (char-after (match-beginning 4))))
3313 (progn
3314 (setq rtn t)
3315 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3316 'face
3317 (nth 1 (assoc (match-string 3)
3318 org-emphasis-alist)))
3319 (add-text-properties (match-beginning 2) (match-end 2)
3320 '(font-lock-multiline t))
3321 (when org-hide-emphasis-markers
3322 (add-text-properties (match-end 4) (match-beginning 5)
3323 '(invisible org-link))
3324 (add-text-properties (match-beginning 3) (match-end 3)
3325 '(invisible org-link)))))
3326 (backward-char 1))
3327 rtn))
3329 (defun org-emphasize (&optional char)
3330 "Insert or change an emphasis, i.e. a font like bold or italic.
3331 If there is an active region, change that region to a new emphasis.
3332 If there is no region, just insert the marker characters and position
3333 the cursor between them.
3334 CHAR should be either the marker character, or the first character of the
3335 HTML tag associated with that emphasis. If CHAR is a space, the means
3336 to remove the emphasis of the selected region.
3337 If char is not given (for example in an interactive call) it
3338 will be prompted for."
3339 (interactive)
3340 (let ((eal org-emphasis-alist) e det
3341 (erc org-emphasis-regexp-components)
3342 (prompt "")
3343 (string "") beg end move tag c s)
3344 (if (org-region-active-p)
3345 (setq beg (region-beginning) end (region-end)
3346 string (buffer-substring beg end))
3347 (setq move t))
3349 (while (setq e (pop eal))
3350 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3351 c (aref tag 0))
3352 (push (cons c (string-to-char (car e))) det)
3353 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3354 (substring tag 1)))))
3355 (unless char
3356 (message "%s" (concat "Emphasis marker or tag:" prompt))
3357 (setq char (read-char-exclusive)))
3358 (setq char (or (cdr (assoc char det)) char))
3359 (if (equal char ?\ )
3360 (setq s "" move nil)
3361 (unless (assoc (char-to-string char) org-emphasis-alist)
3362 (error "No such emphasis marker: \"%c\"" char))
3363 (setq s (char-to-string char)))
3364 (while (and (> (length string) 1)
3365 (equal (substring string 0 1) (substring string -1))
3366 (assoc (substring string 0 1) org-emphasis-alist))
3367 (setq string (substring string 1 -1)))
3368 (setq string (concat s string s))
3369 (if beg (delete-region beg end))
3370 (unless (or (bolp)
3371 (string-match (concat "[" (nth 0 erc) "\n]")
3372 (char-to-string (char-before (point)))))
3373 (insert " "))
3374 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3375 (char-to-string (char-after (point))))
3376 (insert " ") (backward-char 1))
3377 (insert string)
3378 (and move (backward-char 1))))
3380 (defconst org-nonsticky-props
3381 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3384 (defun org-activate-plain-links (limit)
3385 "Run through the buffer and add overlays to links."
3386 (catch 'exit
3387 (let (f)
3388 (while (re-search-forward org-plain-link-re limit t)
3389 (setq f (get-text-property (match-beginning 0) 'face))
3390 (if (or (eq f 'org-tag)
3391 (and (listp f) (memq 'org-tag f)))
3393 (add-text-properties (match-beginning 0) (match-end 0)
3394 (list 'mouse-face 'highlight
3395 'rear-nonsticky org-nonsticky-props
3396 'keymap org-mouse-map
3398 (throw 'exit t))))))
3400 (defun org-activate-code (limit)
3401 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3402 (unless (get-text-property (match-beginning 1) 'face)
3403 (remove-text-properties (match-beginning 0) (match-end 0)
3404 '(display t invisible t intangible t))
3405 t)))
3407 (defun org-activate-angle-links (limit)
3408 "Run through the buffer and add overlays to links."
3409 (if (re-search-forward org-angle-link-re limit t)
3410 (progn
3411 (add-text-properties (match-beginning 0) (match-end 0)
3412 (list 'mouse-face 'highlight
3413 'rear-nonsticky org-nonsticky-props
3414 'keymap org-mouse-map
3416 t)))
3418 (defun org-activate-bracket-links (limit)
3419 "Run through the buffer and add overlays to bracketed links."
3420 (if (re-search-forward org-bracket-link-regexp limit t)
3421 (let* ((help (concat "LINK: "
3422 (org-match-string-no-properties 1)))
3423 ;; FIXME: above we should remove the escapes.
3424 ;; but that requires another match, protecting match data,
3425 ;; a lot of overhead for font-lock.
3426 (ip (org-maybe-intangible
3427 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3428 'keymap org-mouse-map 'mouse-face 'highlight
3429 'font-lock-multiline t 'help-echo help)))
3430 (vp (list 'rear-nonsticky org-nonsticky-props
3431 'keymap org-mouse-map 'mouse-face 'highlight
3432 ' font-lock-multiline t 'help-echo help)))
3433 ;; We need to remove the invisible property here. Table narrowing
3434 ;; may have made some of this invisible.
3435 (remove-text-properties (match-beginning 0) (match-end 0)
3436 '(invisible nil))
3437 (if (match-end 3)
3438 (progn
3439 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3440 (add-text-properties (match-beginning 3) (match-end 3) vp)
3441 (add-text-properties (match-end 3) (match-end 0) ip))
3442 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3443 (add-text-properties (match-beginning 1) (match-end 1) vp)
3444 (add-text-properties (match-end 1) (match-end 0) ip))
3445 t)))
3447 (defun org-activate-dates (limit)
3448 "Run through the buffer and add overlays to dates."
3449 (if (re-search-forward org-tsr-regexp-both limit t)
3450 (progn
3451 (add-text-properties (match-beginning 0) (match-end 0)
3452 (list 'mouse-face 'highlight
3453 'rear-nonsticky org-nonsticky-props
3454 'keymap org-mouse-map))
3455 (when org-display-custom-times
3456 (if (match-end 3)
3457 (org-display-custom-time (match-beginning 3) (match-end 3)))
3458 (org-display-custom-time (match-beginning 1) (match-end 1)))
3459 t)))
3461 (defvar org-target-link-regexp nil
3462 "Regular expression matching radio targets in plain text.")
3463 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3464 "Regular expression matching a link target.")
3465 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3466 "Regular expression matching a radio target.")
3467 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3468 "Regular expression matching any target.")
3470 (defun org-activate-target-links (limit)
3471 "Run through the buffer and add overlays to target matches."
3472 (when org-target-link-regexp
3473 (let ((case-fold-search t))
3474 (if (re-search-forward org-target-link-regexp limit t)
3475 (progn
3476 (add-text-properties (match-beginning 0) (match-end 0)
3477 (list 'mouse-face 'highlight
3478 'rear-nonsticky org-nonsticky-props
3479 'keymap org-mouse-map
3480 'help-echo "Radio target link"
3481 'org-linked-text t))
3482 t)))))
3484 (defun org-update-radio-target-regexp ()
3485 "Find all radio targets in this file and update the regular expression."
3486 (interactive)
3487 (when (memq 'radio org-activate-links)
3488 (setq org-target-link-regexp
3489 (org-make-target-link-regexp (org-all-targets 'radio)))
3490 (org-restart-font-lock)))
3492 (defun org-hide-wide-columns (limit)
3493 (let (s e)
3494 (setq s (text-property-any (point) (or limit (point-max))
3495 'org-cwidth t))
3496 (when s
3497 (setq e (next-single-property-change s 'org-cwidth))
3498 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3499 (goto-char e)
3500 t)))
3502 (defvar org-latex-and-specials-regexp nil
3503 "Regular expression for highlighting export special stuff.")
3504 (defvar org-match-substring-regexp)
3505 (defvar org-match-substring-with-braces-regexp)
3506 (defvar org-export-html-special-string-regexps)
3508 (defun org-compute-latex-and-specials-regexp ()
3509 "Compute regular expression for stuff treated specially by exporters."
3510 (if (not org-highlight-latex-fragments-and-specials)
3511 (org-set-local 'org-latex-and-specials-regexp nil)
3512 (require 'org-exp)
3513 (let*
3514 ((matchers (plist-get org-format-latex-options :matchers))
3515 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3516 org-latex-regexps)))
3517 (options (org-combine-plists (org-default-export-plist)
3518 (org-infile-export-plist)))
3519 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3520 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3521 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3522 (org-export-html-expand (plist-get options :expand-quoted-html))
3523 (org-export-with-special-strings (plist-get options :special-strings))
3524 (re-sub
3525 (cond
3526 ((equal org-export-with-sub-superscripts '{})
3527 (list org-match-substring-with-braces-regexp))
3528 (org-export-with-sub-superscripts
3529 (list org-match-substring-regexp))
3530 (t nil)))
3531 (re-latex
3532 (if org-export-with-LaTeX-fragments
3533 (mapcar (lambda (x) (nth 1 x)) latexs)))
3534 (re-macros
3535 (if org-export-with-TeX-macros
3536 (list (concat "\\\\"
3537 (regexp-opt
3538 (append (mapcar 'car org-html-entities)
3539 (if (boundp 'org-latex-entities)
3540 org-latex-entities nil))
3541 'words))) ; FIXME
3543 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3544 (re-special (if org-export-with-special-strings
3545 (mapcar (lambda (x) (car x))
3546 org-export-html-special-string-regexps)))
3547 (re-rest
3548 (delq nil
3549 (list
3550 (if org-export-html-expand "@<[^>\n]+>")
3551 ))))
3552 (org-set-local
3553 'org-latex-and-specials-regexp
3554 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3555 re-rest) "\\|")))))
3557 (defun org-do-latex-and-special-faces (limit)
3558 "Run through the buffer and add overlays to links."
3559 (when org-latex-and-specials-regexp
3560 (let (rtn d)
3561 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3562 limit t))
3563 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3564 'face))
3565 '(org-code org-verbatim underline)))
3566 (progn
3567 (setq rtn t
3568 d (cond ((member (char-after (1+ (match-beginning 0)))
3569 '(?_ ?^)) 1)
3570 (t 0)))
3571 (font-lock-prepend-text-property
3572 (+ d (match-beginning 0)) (match-end 0)
3573 'face 'org-latex-and-export-specials)
3574 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3575 '(font-lock-multiline t)))))
3576 rtn)))
3578 (defun org-restart-font-lock ()
3579 "Restart font-lock-mode, to force refontification."
3580 (when (and (boundp 'font-lock-mode) font-lock-mode)
3581 (font-lock-mode -1)
3582 (font-lock-mode 1)))
3584 (defun org-all-targets (&optional radio)
3585 "Return a list of all targets in this file.
3586 With optional argument RADIO, only find radio targets."
3587 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3588 rtn)
3589 (save-excursion
3590 (goto-char (point-min))
3591 (while (re-search-forward re nil t)
3592 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3593 rtn)))
3595 (defun org-make-target-link-regexp (targets)
3596 "Make regular expression matching all strings in TARGETS.
3597 The regular expression finds the targets also if there is a line break
3598 between words."
3599 (and targets
3600 (concat
3601 "\\<\\("
3602 (mapconcat
3603 (lambda (x)
3604 (while (string-match " +" x)
3605 (setq x (replace-match "\\s-+" t t x)))
3607 targets
3608 "\\|")
3609 "\\)\\>")))
3611 (defun org-activate-tags (limit)
3612 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3613 (progn
3614 (add-text-properties (match-beginning 1) (match-end 1)
3615 (list 'mouse-face 'highlight
3616 'rear-nonsticky org-nonsticky-props
3617 'keymap org-mouse-map))
3618 t)))
3620 (defun org-outline-level ()
3621 (save-excursion
3622 (looking-at outline-regexp)
3623 (if (match-beginning 1)
3624 (+ (org-get-string-indentation (match-string 1)) 1000)
3625 (1- (- (match-end 0) (match-beginning 0))))))
3627 (defvar org-font-lock-keywords nil)
3629 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3630 "Regular expression matching a property line.")
3632 (defvar org-font-lock-hook nil
3633 "Functions to be called for special font lock stuff.")
3635 (defun org-font-lock-hook (limit)
3636 (run-hook-with-args 'org-font-lock-hook limit))
3638 (defun org-set-font-lock-defaults ()
3639 (let* ((em org-fontify-emphasized-text)
3640 (lk org-activate-links)
3641 (org-font-lock-extra-keywords
3642 (list
3643 ;; Call the hook
3644 '(org-font-lock-hook)
3645 ;; Headlines
3646 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3647 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3648 ;; Table lines
3649 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3650 (1 'org-table t))
3651 ;; Table internals
3652 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3653 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3654 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3655 ;; Drawers
3656 (list org-drawer-regexp '(0 'org-special-keyword t))
3657 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3658 ;; Properties
3659 (list org-property-re
3660 '(1 'org-special-keyword t)
3661 '(3 'org-property-value t))
3662 (if org-format-transports-properties-p
3663 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3664 ;; Links
3665 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3666 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3667 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3668 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3669 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3670 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3671 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3672 '(org-hide-wide-columns (0 nil append))
3673 ;; TODO lines
3674 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3675 '(1 (org-get-todo-face 1) t))
3676 ;; DONE
3677 (if org-fontify-done-headline
3678 (list (concat "^[*]+ +\\<\\("
3679 (mapconcat 'regexp-quote org-done-keywords "\\|")
3680 "\\)\\(.*\\)")
3681 '(2 'org-headline-done t))
3682 nil)
3683 ;; Priorities
3684 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3685 ;; Special keywords
3686 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3687 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3688 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3689 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3690 ;; Emphasis
3691 (if em
3692 (if (featurep 'xemacs)
3693 '(org-do-emphasis-faces (0 nil append))
3694 '(org-do-emphasis-faces)))
3695 ;; Checkboxes
3696 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3697 2 'bold prepend)
3698 (if org-provide-checkbox-statistics
3699 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3700 (0 (org-get-checkbox-statistics-face) t)))
3701 ;; Description list items
3702 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3703 2 'bold prepend)
3704 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3705 '(1 'org-archived prepend))
3706 ;; Specials
3707 '(org-do-latex-and-special-faces)
3708 ;; Code
3709 '(org-activate-code (1 'org-code t))
3710 ;; COMMENT
3711 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3712 "\\|" org-quote-string "\\)\\>")
3713 '(1 'org-special-keyword t))
3714 '("^#.*" (0 'font-lock-comment-face t))
3716 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3717 ;; Now set the full font-lock-keywords
3718 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3719 (org-set-local 'font-lock-defaults
3720 '(org-font-lock-keywords t nil nil backward-paragraph))
3721 (kill-local-variable 'font-lock-keywords) nil))
3723 (defvar org-m nil)
3724 (defvar org-l nil)
3725 (defvar org-f nil)
3726 (defun org-get-level-face (n)
3727 "Get the right face for match N in font-lock matching of healdines."
3728 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3729 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3730 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3731 (cond
3732 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3733 ((eq n 2) org-f)
3734 (t (if org-level-color-stars-only nil org-f))))
3736 (defun org-get-todo-face (kwd)
3737 "Get the right face for a TODO keyword KWD.
3738 If KWD is a number, get the corresponding match group."
3739 (if (numberp kwd) (setq kwd (match-string kwd)))
3740 (or (cdr (assoc kwd org-todo-keyword-faces))
3741 (and (member kwd org-done-keywords) 'org-done)
3742 'org-todo))
3744 (defun org-unfontify-region (beg end &optional maybe_loudly)
3745 "Remove fontification and activation overlays from links."
3746 (font-lock-default-unfontify-region beg end)
3747 (let* ((buffer-undo-list t)
3748 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3749 (inhibit-modification-hooks t)
3750 deactivate-mark buffer-file-name buffer-file-truename)
3751 (remove-text-properties beg end
3752 '(mouse-face t keymap t org-linked-text t
3753 invisible t intangible t))))
3755 ;;;; Visibility cycling, including org-goto and indirect buffer
3757 ;;; Cycling
3759 (defvar org-cycle-global-status nil)
3760 (make-variable-buffer-local 'org-cycle-global-status)
3761 (defvar org-cycle-subtree-status nil)
3762 (make-variable-buffer-local 'org-cycle-subtree-status)
3764 ;;;###autoload
3765 (defun org-cycle (&optional arg)
3766 "Visibility cycling for Org-mode.
3768 - When this function is called with a prefix argument, rotate the entire
3769 buffer through 3 states (global cycling)
3770 1. OVERVIEW: Show only top-level headlines.
3771 2. CONTENTS: Show all headlines of all levels, but no body text.
3772 3. SHOW ALL: Show everything.
3773 When called with two C-c C-u prefixes, switch to the startup visibility,
3774 determined by the variable `org-startup-folded', and by any VISIBILITY
3775 properties in the buffer.
3777 - When point is at the beginning of a headline, rotate the subtree started
3778 by this line through 3 different states (local cycling)
3779 1. FOLDED: Only the main headline is shown.
3780 2. CHILDREN: The main headline and the direct children are shown.
3781 From this state, you can move to one of the children
3782 and zoom in further.
3783 3. SUBTREE: Show the entire subtree, including body text.
3785 - When there is a numeric prefix, go up to a heading with level ARG, do
3786 a `show-subtree' and return to the previous cursor position. If ARG
3787 is negative, go up that many levels.
3789 - When point is not at the beginning of a headline, execute the global
3790 binding for TAB, which is re-indenting the line. See the option
3791 `org-cycle-emulate-tab' for details.
3793 - Special case: if point is at the beginning of the buffer and there is
3794 no headline in line 1, this function will act as if called with prefix arg.
3795 But only if also the variable `org-cycle-global-at-bob' is t."
3796 (interactive "P")
3797 (org-load-modules-maybe)
3798 (let* ((outline-regexp
3799 (if (and (org-mode-p) org-cycle-include-plain-lists)
3800 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3801 outline-regexp))
3802 (bob-special (and org-cycle-global-at-bob (bobp)
3803 (not (looking-at outline-regexp))))
3804 (org-cycle-hook
3805 (if bob-special
3806 (delq 'org-optimize-window-after-visibility-change
3807 (copy-sequence org-cycle-hook))
3808 org-cycle-hook))
3809 (pos (point)))
3811 (if (or bob-special (equal arg '(4)))
3812 ;; special case: use global cycling
3813 (setq arg t))
3815 (cond
3817 ((equal arg '(16))
3818 (org-set-startup-visibility)
3819 (message "Startup visibility, plus VISIBILITY properties."))
3821 ((org-at-table-p 'any)
3822 ;; Enter the table or move to the next field in the table
3823 (or (org-table-recognize-table.el)
3824 (progn
3825 (if arg (org-table-edit-field t)
3826 (org-table-justify-field-maybe)
3827 (call-interactively 'org-table-next-field)))))
3829 ((eq arg t) ;; Global cycling
3831 (cond
3832 ((and (eq last-command this-command)
3833 (eq org-cycle-global-status 'overview))
3834 ;; We just created the overview - now do table of contents
3835 ;; This can be slow in very large buffers, so indicate action
3836 (message "CONTENTS...")
3837 (org-content)
3838 (message "CONTENTS...done")
3839 (setq org-cycle-global-status 'contents)
3840 (run-hook-with-args 'org-cycle-hook 'contents))
3842 ((and (eq last-command this-command)
3843 (eq org-cycle-global-status 'contents))
3844 ;; We just showed the table of contents - now show everything
3845 (show-all)
3846 (message "SHOW ALL")
3847 (setq org-cycle-global-status 'all)
3848 (run-hook-with-args 'org-cycle-hook 'all))
3851 ;; Default action: go to overview
3852 (org-overview)
3853 (message "OVERVIEW")
3854 (setq org-cycle-global-status 'overview)
3855 (run-hook-with-args 'org-cycle-hook 'overview))))
3857 ((and org-drawers org-drawer-regexp
3858 (save-excursion
3859 (beginning-of-line 1)
3860 (looking-at org-drawer-regexp)))
3861 ;; Toggle block visibility
3862 (org-flag-drawer
3863 (not (get-char-property (match-end 0) 'invisible))))
3865 ((integerp arg)
3866 ;; Show-subtree, ARG levels up from here.
3867 (save-excursion
3868 (org-back-to-heading)
3869 (outline-up-heading (if (< arg 0) (- arg)
3870 (- (funcall outline-level) arg)))
3871 (org-show-subtree)))
3873 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3874 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3875 ;; At a heading: rotate between three different views
3876 (org-back-to-heading)
3877 (let ((goal-column 0) eoh eol eos)
3878 ;; First, some boundaries
3879 (save-excursion
3880 (org-back-to-heading)
3881 (save-excursion
3882 (beginning-of-line 2)
3883 (while (and (not (eobp)) ;; this is like `next-line'
3884 (get-char-property (1- (point)) 'invisible))
3885 (beginning-of-line 2)) (setq eol (point)))
3886 (outline-end-of-heading) (setq eoh (point))
3887 (org-end-of-subtree t)
3888 (unless (eobp)
3889 (skip-chars-forward " \t\n")
3890 (beginning-of-line 1) ; in case this is an item
3892 (setq eos (1- (point))))
3893 ;; Find out what to do next and set `this-command'
3894 (cond
3895 ((= eos eoh)
3896 ;; Nothing is hidden behind this heading
3897 (message "EMPTY ENTRY")
3898 (setq org-cycle-subtree-status nil)
3899 (save-excursion
3900 (goto-char eos)
3901 (outline-next-heading)
3902 (if (org-invisible-p) (org-flag-heading nil))))
3903 ((or (>= eol eos)
3904 (not (string-match "\\S-" (buffer-substring eol eos))))
3905 ;; Entire subtree is hidden in one line: open it
3906 (org-show-entry)
3907 (show-children)
3908 (message "CHILDREN")
3909 (save-excursion
3910 (goto-char eos)
3911 (outline-next-heading)
3912 (if (org-invisible-p) (org-flag-heading nil)))
3913 (setq org-cycle-subtree-status 'children)
3914 (run-hook-with-args 'org-cycle-hook 'children))
3915 ((and (eq last-command this-command)
3916 (eq org-cycle-subtree-status 'children))
3917 ;; We just showed the children, now show everything.
3918 (org-show-subtree)
3919 (message "SUBTREE")
3920 (setq org-cycle-subtree-status 'subtree)
3921 (run-hook-with-args 'org-cycle-hook 'subtree))
3923 ;; Default action: hide the subtree.
3924 (hide-subtree)
3925 (message "FOLDED")
3926 (setq org-cycle-subtree-status 'folded)
3927 (run-hook-with-args 'org-cycle-hook 'folded)))))
3929 ;; TAB emulation and template completion
3930 (buffer-read-only (org-back-to-heading))
3932 ((org-try-structure-completion))
3934 ((org-try-cdlatex-tab))
3936 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3937 (or (not (bolp))
3938 (not (looking-at outline-regexp))))
3939 (call-interactively (global-key-binding "\t")))
3941 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3942 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3943 (or (and (eq org-cycle-emulate-tab 'white)
3944 (= (match-end 0) (point-at-eol)))
3945 (and (eq org-cycle-emulate-tab 'whitestart)
3946 (>= (match-end 0) pos))))
3948 (eq org-cycle-emulate-tab t))
3949 (call-interactively (global-key-binding "\t")))
3951 (t (save-excursion
3952 (org-back-to-heading)
3953 (org-cycle))))))
3955 ;;;###autoload
3956 (defun org-global-cycle (&optional arg)
3957 "Cycle the global visibility. For details see `org-cycle'.
3958 With C-u prefix arg, switch to startup visibility.
3959 With a numeric prefix, show all headlines up to that level."
3960 (interactive "P")
3961 (let ((org-cycle-include-plain-lists
3962 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3963 (cond
3964 ((integerp arg)
3965 (show-all)
3966 (hide-sublevels arg)
3967 (setq org-cycle-global-status 'contents))
3968 ((equal arg '(4))
3969 (org-set-startup-visibility)
3970 (message "Startup visibility, plus VISIBILITY properties."))
3972 (org-cycle '(4))))))
3974 (defun org-set-startup-visibility ()
3975 "Set the visibility required by startup options and properties."
3976 (cond
3977 ((eq org-startup-folded t)
3978 (org-cycle '(4)))
3979 ((eq org-startup-folded 'content)
3980 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3981 (org-cycle '(4)) (org-cycle '(4)))))
3982 (org-set-visibility-according-to-property 'no-cleanup)
3983 (org-cycle-hide-archived-subtrees 'all)
3984 (org-cycle-hide-drawers 'all)
3985 (org-cycle-show-empty-lines 'all))
3987 (defun org-set-visibility-according-to-property (&optional no-cleanup)
3988 "Switch subtree visibilities according to :VISIBILITY: property."
3989 (interactive)
3990 (let (state)
3991 (save-excursion
3992 (goto-char (point-min))
3993 (while (re-search-forward
3994 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
3995 nil t)
3996 (setq state (match-string 1))
3997 (save-excursion
3998 (org-back-to-heading t)
3999 (hide-subtree)
4000 (org-reveal)
4001 (cond
4002 ((equal state '("fold" "folded"))
4003 (hide-subtree))
4004 ((equal state "children")
4005 (org-show-hidden-entry)
4006 (show-children))
4007 ((equal state "content")
4008 (save-excursion
4009 (save-restriction
4010 (org-narrow-to-subtree)
4011 (org-content))))
4012 ((member state '("all" "showall"))
4013 (show-subtree)))))
4014 (unless no-cleanup
4015 (org-cycle-hide-archived-subtrees 'all)
4016 (org-cycle-hide-drawers 'all)
4017 (org-cycle-show-empty-lines 'all)))))
4019 (defun org-overview ()
4020 "Switch to overview mode, shoing only top-level headlines.
4021 Really, this shows all headlines with level equal or greater than the level
4022 of the first headline in the buffer. This is important, because if the
4023 first headline is not level one, then (hide-sublevels 1) gives confusing
4024 results."
4025 (interactive)
4026 (let ((level (save-excursion
4027 (goto-char (point-min))
4028 (if (re-search-forward (concat "^" outline-regexp) nil t)
4029 (progn
4030 (goto-char (match-beginning 0))
4031 (funcall outline-level))))))
4032 (and level (hide-sublevels level))))
4034 (defun org-content (&optional arg)
4035 "Show all headlines in the buffer, like a table of contents.
4036 With numerical argument N, show content up to level N."
4037 (interactive "P")
4038 (save-excursion
4039 ;; Visit all headings and show their offspring
4040 (and (integerp arg) (org-overview))
4041 (goto-char (point-max))
4042 (catch 'exit
4043 (while (and (progn (condition-case nil
4044 (outline-previous-visible-heading 1)
4045 (error (goto-char (point-min))))
4047 (looking-at outline-regexp))
4048 (if (integerp arg)
4049 (show-children (1- arg))
4050 (show-branches))
4051 (if (bobp) (throw 'exit nil))))))
4054 (defun org-optimize-window-after-visibility-change (state)
4055 "Adjust the window after a change in outline visibility.
4056 This function is the default value of the hook `org-cycle-hook'."
4057 (when (get-buffer-window (current-buffer))
4058 (cond
4059 ; ((eq state 'overview) (org-first-headline-recenter 1))
4060 ; ((eq state 'overview) (org-beginning-of-line))
4061 ((eq state 'content) nil)
4062 ((eq state 'all) nil)
4063 ((eq state 'folded) nil)
4064 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4065 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4067 (defun org-compact-display-after-subtree-move ()
4068 (let (beg end)
4069 (save-excursion
4070 (if (org-up-heading-safe)
4071 (progn
4072 (hide-subtree)
4073 (show-entry)
4074 (show-children)
4075 (org-cycle-show-empty-lines 'children)
4076 (org-cycle-hide-drawers 'children))
4077 (org-overview)))))
4079 (defun org-cycle-show-empty-lines (state)
4080 "Show empty lines above all visible headlines.
4081 The region to be covered depends on STATE when called through
4082 `org-cycle-hook'. Lisp program can use t for STATE to get the
4083 entire buffer covered. Note that an empty line is only shown if there
4084 are at least `org-cycle-separator-lines' empty lines before the headeline."
4085 (when (> org-cycle-separator-lines 0)
4086 (save-excursion
4087 (let* ((n org-cycle-separator-lines)
4088 (re (cond
4089 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4090 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4091 (t (let ((ns (number-to-string (- n 2))))
4092 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4093 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4094 beg end)
4095 (cond
4096 ((memq state '(overview contents t))
4097 (setq beg (point-min) end (point-max)))
4098 ((memq state '(children folded))
4099 (setq beg (point) end (progn (org-end-of-subtree t t)
4100 (beginning-of-line 2)
4101 (point)))))
4102 (when beg
4103 (goto-char beg)
4104 (while (re-search-forward re end t)
4105 (if (not (get-char-property (match-end 1) 'invisible))
4106 (outline-flag-region
4107 (match-beginning 1) (match-end 1) nil)))))))
4108 ;; Never hide empty lines at the end of the file.
4109 (save-excursion
4110 (goto-char (point-max))
4111 (outline-previous-heading)
4112 (outline-end-of-heading)
4113 (if (and (looking-at "[ \t\n]+")
4114 (= (match-end 0) (point-max)))
4115 (outline-flag-region (point) (match-end 0) nil))))
4117 (defun org-cycle-hide-drawers (state)
4118 "Re-hide all drawers after a visibility state change."
4119 (when (and (org-mode-p)
4120 (not (memq state '(overview folded))))
4121 (save-excursion
4122 (let* ((globalp (memq state '(contents all)))
4123 (beg (if globalp (point-min) (point)))
4124 (end (if globalp (point-max) (org-end-of-subtree t))))
4125 (goto-char beg)
4126 (while (re-search-forward org-drawer-regexp end t)
4127 (org-flag-drawer t))))))
4129 (defun org-flag-drawer (flag)
4130 (save-excursion
4131 (beginning-of-line 1)
4132 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4133 (let ((b (match-end 0))
4134 (outline-regexp org-outline-regexp))
4135 (if (re-search-forward
4136 "^[ \t]*:END:"
4137 (save-excursion (outline-next-heading) (point)) t)
4138 (outline-flag-region b (point-at-eol) flag)
4139 (error ":END: line missing"))))))
4141 (defun org-subtree-end-visible-p ()
4142 "Is the end of the current subtree visible?"
4143 (pos-visible-in-window-p
4144 (save-excursion (org-end-of-subtree t) (point))))
4146 (defun org-first-headline-recenter (&optional N)
4147 "Move cursor to the first headline and recenter the headline.
4148 Optional argument N means, put the headline into the Nth line of the window."
4149 (goto-char (point-min))
4150 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4151 (beginning-of-line)
4152 (recenter (prefix-numeric-value N))))
4154 ;;; Org-goto
4156 (defvar org-goto-window-configuration nil)
4157 (defvar org-goto-marker nil)
4158 (defvar org-goto-map
4159 (let ((map (make-sparse-keymap)))
4160 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4161 (while (setq cmd (pop cmds))
4162 (substitute-key-definition cmd cmd map global-map)))
4163 (suppress-keymap map)
4164 (org-defkey map "\C-m" 'org-goto-ret)
4165 (org-defkey map [(return)] 'org-goto-ret)
4166 (org-defkey map [(left)] 'org-goto-left)
4167 (org-defkey map [(right)] 'org-goto-right)
4168 (org-defkey map [(control ?g)] 'org-goto-quit)
4169 (org-defkey map "\C-i" 'org-cycle)
4170 (org-defkey map [(tab)] 'org-cycle)
4171 (org-defkey map [(down)] 'outline-next-visible-heading)
4172 (org-defkey map [(up)] 'outline-previous-visible-heading)
4173 (if org-goto-auto-isearch
4174 (if (fboundp 'define-key-after)
4175 (define-key-after map [t] 'org-goto-local-auto-isearch)
4176 nil)
4177 (org-defkey map "q" 'org-goto-quit)
4178 (org-defkey map "n" 'outline-next-visible-heading)
4179 (org-defkey map "p" 'outline-previous-visible-heading)
4180 (org-defkey map "f" 'outline-forward-same-level)
4181 (org-defkey map "b" 'outline-backward-same-level)
4182 (org-defkey map "u" 'outline-up-heading))
4183 (org-defkey map "/" 'org-occur)
4184 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4185 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4186 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4187 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4188 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4189 map))
4191 (defconst org-goto-help
4192 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4193 RET=jump to location [Q]uit and return to previous location
4194 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4196 (defvar org-goto-start-pos) ; dynamically scoped parameter
4198 (defun org-goto (&optional alternative-interface)
4199 "Look up a different location in the current file, keeping current visibility.
4201 When you want look-up or go to a different location in a document, the
4202 fastest way is often to fold the entire buffer and then dive into the tree.
4203 This method has the disadvantage, that the previous location will be folded,
4204 which may not be what you want.
4206 This command works around this by showing a copy of the current buffer
4207 in an indirect buffer, in overview mode. You can dive into the tree in
4208 that copy, use org-occur and incremental search to find a location.
4209 When pressing RET or `Q', the command returns to the original buffer in
4210 which the visibility is still unchanged. After RET is will also jump to
4211 the location selected in the indirect buffer and expose the
4212 the headline hierarchy above."
4213 (interactive "P")
4214 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4215 (org-refile-use-outline-path t)
4216 (interface
4217 (if (not alternative-interface)
4218 org-goto-interface
4219 (if (eq org-goto-interface 'outline)
4220 'outline-path-completion
4221 'outline)))
4222 (org-goto-start-pos (point))
4223 (selected-point
4224 (if (eq interface 'outline)
4225 (car (org-get-location (current-buffer) org-goto-help))
4226 (nth 3 (org-refile-get-location "Goto: ")))))
4227 (if selected-point
4228 (progn
4229 (org-mark-ring-push org-goto-start-pos)
4230 (goto-char selected-point)
4231 (if (or (org-invisible-p) (org-invisible-p2))
4232 (org-show-context 'org-goto)))
4233 (message "Quit"))))
4235 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4236 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4237 (defvar org-goto-local-auto-isearch-map) ; defined below
4239 (defun org-get-location (buf help)
4240 "Let the user select a location in the Org-mode buffer BUF.
4241 This function uses a recursive edit. It returns the selected position
4242 or nil."
4243 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4244 (isearch-hide-immediately nil)
4245 (isearch-search-fun-function
4246 (lambda () 'org-goto-local-search-forward-headings))
4247 (org-goto-selected-point org-goto-exit-command))
4248 (save-excursion
4249 (save-window-excursion
4250 (delete-other-windows)
4251 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4252 (switch-to-buffer
4253 (condition-case nil
4254 (make-indirect-buffer (current-buffer) "*org-goto*")
4255 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4256 (with-output-to-temp-buffer "*Help*"
4257 (princ help))
4258 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4259 (setq buffer-read-only nil)
4260 (let ((org-startup-truncated t)
4261 (org-startup-folded nil)
4262 (org-startup-align-all-tables nil))
4263 (org-mode)
4264 (org-overview))
4265 (setq buffer-read-only t)
4266 (if (and (boundp 'org-goto-start-pos)
4267 (integer-or-marker-p org-goto-start-pos))
4268 (let ((org-show-hierarchy-above t)
4269 (org-show-siblings t)
4270 (org-show-following-heading t))
4271 (goto-char org-goto-start-pos)
4272 (and (org-invisible-p) (org-show-context)))
4273 (goto-char (point-min)))
4274 (org-beginning-of-line)
4275 (message "Select location and press RET")
4276 (use-local-map org-goto-map)
4277 (recursive-edit)
4279 (kill-buffer "*org-goto*")
4280 (cons org-goto-selected-point org-goto-exit-command)))
4282 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4283 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4284 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4285 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4287 (defun org-goto-local-search-forward-headings (string bound noerror)
4288 "Search and make sure that anu matches are in headlines."
4289 (catch 'return
4290 (while (search-forward string bound noerror)
4291 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4292 (and (member :headline context)
4293 (not (member :tags context))))
4294 (throw 'return (point))))))
4296 (defun org-goto-local-auto-isearch ()
4297 "Start isearch."
4298 (interactive)
4299 (goto-char (point-min))
4300 (let ((keys (this-command-keys)))
4301 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4302 (isearch-mode t)
4303 (isearch-process-search-char (string-to-char keys)))))
4305 (defun org-goto-ret (&optional arg)
4306 "Finish `org-goto' by going to the new location."
4307 (interactive "P")
4308 (setq org-goto-selected-point (point)
4309 org-goto-exit-command 'return)
4310 (throw 'exit nil))
4312 (defun org-goto-left ()
4313 "Finish `org-goto' by going to the new location."
4314 (interactive)
4315 (if (org-on-heading-p)
4316 (progn
4317 (beginning-of-line 1)
4318 (setq org-goto-selected-point (point)
4319 org-goto-exit-command 'left)
4320 (throw 'exit nil))
4321 (error "Not on a heading")))
4323 (defun org-goto-right ()
4324 "Finish `org-goto' by going to the new location."
4325 (interactive)
4326 (if (org-on-heading-p)
4327 (progn
4328 (setq org-goto-selected-point (point)
4329 org-goto-exit-command 'right)
4330 (throw 'exit nil))
4331 (error "Not on a heading")))
4333 (defun org-goto-quit ()
4334 "Finish `org-goto' without cursor motion."
4335 (interactive)
4336 (setq org-goto-selected-point nil)
4337 (setq org-goto-exit-command 'quit)
4338 (throw 'exit nil))
4340 ;;; Indirect buffer display of subtrees
4342 (defvar org-indirect-dedicated-frame nil
4343 "This is the frame being used for indirect tree display.")
4344 (defvar org-last-indirect-buffer nil)
4346 (defun org-tree-to-indirect-buffer (&optional arg)
4347 "Create indirect buffer and narrow it to current subtree.
4348 With numerical prefix ARG, go up to this level and then take that tree.
4349 If ARG is negative, go up that many levels.
4350 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4351 indirect buffer previously made with this command, to avoid proliferation of
4352 indirect buffers. However, when you call the command with a `C-u' prefix, or
4353 when `org-indirect-buffer-display' is `new-frame', the last buffer
4354 is kept so that you can work with several indirect buffers at the same time.
4355 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4356 requests that a new frame be made for the new buffer, so that the dedicated
4357 frame is not changed."
4358 (interactive "P")
4359 (let ((cbuf (current-buffer))
4360 (cwin (selected-window))
4361 (pos (point))
4362 beg end level heading ibuf)
4363 (save-excursion
4364 (org-back-to-heading t)
4365 (when (numberp arg)
4366 (setq level (org-outline-level))
4367 (if (< arg 0) (setq arg (+ level arg)))
4368 (while (> (setq level (org-outline-level)) arg)
4369 (outline-up-heading 1 t)))
4370 (setq beg (point)
4371 heading (org-get-heading))
4372 (org-end-of-subtree t) (setq end (point)))
4373 (if (and (buffer-live-p org-last-indirect-buffer)
4374 (not (eq org-indirect-buffer-display 'new-frame))
4375 (not arg))
4376 (kill-buffer org-last-indirect-buffer))
4377 (setq ibuf (org-get-indirect-buffer cbuf)
4378 org-last-indirect-buffer ibuf)
4379 (cond
4380 ((or (eq org-indirect-buffer-display 'new-frame)
4381 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4382 (select-frame (make-frame))
4383 (delete-other-windows)
4384 (switch-to-buffer ibuf)
4385 (org-set-frame-title heading))
4386 ((eq org-indirect-buffer-display 'dedicated-frame)
4387 (raise-frame
4388 (select-frame (or (and org-indirect-dedicated-frame
4389 (frame-live-p org-indirect-dedicated-frame)
4390 org-indirect-dedicated-frame)
4391 (setq org-indirect-dedicated-frame (make-frame)))))
4392 (delete-other-windows)
4393 (switch-to-buffer ibuf)
4394 (org-set-frame-title (concat "Indirect: " heading)))
4395 ((eq org-indirect-buffer-display 'current-window)
4396 (switch-to-buffer ibuf))
4397 ((eq org-indirect-buffer-display 'other-window)
4398 (pop-to-buffer ibuf))
4399 (t (error "Invalid value.")))
4400 (if (featurep 'xemacs)
4401 (save-excursion (org-mode) (turn-on-font-lock)))
4402 (narrow-to-region beg end)
4403 (show-all)
4404 (goto-char pos)
4405 (and (window-live-p cwin) (select-window cwin))))
4407 (defun org-get-indirect-buffer (&optional buffer)
4408 (setq buffer (or buffer (current-buffer)))
4409 (let ((n 1) (base (buffer-name buffer)) bname)
4410 (while (buffer-live-p
4411 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4412 (setq n (1+ n)))
4413 (condition-case nil
4414 (make-indirect-buffer buffer bname 'clone)
4415 (error (make-indirect-buffer buffer bname)))))
4417 (defun org-set-frame-title (title)
4418 "Set the title of the current frame to the string TITLE."
4419 ;; FIXME: how to name a single frame in XEmacs???
4420 (unless (featurep 'xemacs)
4421 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4423 ;;;; Structure editing
4425 ;;; Inserting headlines
4427 (defun org-insert-heading (&optional force-heading)
4428 "Insert a new heading or item with same depth at point.
4429 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4430 If point is at the beginning of a headline, insert a sibling before the
4431 current headline. If point is not at the beginning, do not split the line,
4432 but create the new hedline after the current line."
4433 (interactive "P")
4434 (if (= (buffer-size) 0)
4435 (insert "\n* ")
4436 (when (or force-heading (not (org-insert-item)))
4437 (let* ((head (save-excursion
4438 (condition-case nil
4439 (progn
4440 (org-back-to-heading)
4441 (match-string 0))
4442 (error "*"))))
4443 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4444 pos)
4445 (cond
4446 ((and (org-on-heading-p) (bolp)
4447 (or (bobp)
4448 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4449 ;; insert before the current line
4450 (open-line (if blank 2 1)))
4451 ((and (bolp)
4452 (or (bobp)
4453 (save-excursion
4454 (backward-char 1) (not (org-invisible-p)))))
4455 ;; insert right here
4456 nil)
4458 ;; in the middle of the line
4459 (org-show-entry)
4460 (let ((split
4461 (org-get-alist-option org-M-RET-may-split-line 'headline))
4462 tags pos)
4463 (if (org-on-heading-p)
4464 (progn
4465 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4466 (setq tags (and (match-end 2) (match-string 2)))
4467 (and (match-end 1)
4468 (delete-region (match-beginning 1) (match-end 1)))
4469 (setq pos (point-at-bol))
4470 (or split (end-of-line 1))
4471 (delete-horizontal-space)
4472 (newline (if blank 2 1))
4473 (when tags
4474 (save-excursion
4475 (goto-char pos)
4476 (end-of-line 1)
4477 (insert " " tags)
4478 (org-set-tags nil 'align))))
4479 (or split (end-of-line 1))
4480 (newline (if blank 2 1))))))
4481 (insert head) (just-one-space)
4482 (setq pos (point))
4483 (end-of-line 1)
4484 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4485 (run-hooks 'org-insert-heading-hook)))))
4487 (defun org-get-heading (&optional no-tags)
4488 "Return the heading of the current entry, without the stars."
4489 (save-excursion
4490 (org-back-to-heading t)
4491 (if (looking-at
4492 (if no-tags
4493 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4494 "\\*+[ \t]+\\([^\r\n]*\\)"))
4495 (match-string 1) "")))
4497 (defun org-insert-heading-after-current ()
4498 "Insert a new heading with same level as current, after current subtree."
4499 (interactive)
4500 (org-back-to-heading)
4501 (org-insert-heading)
4502 (org-move-subtree-down)
4503 (end-of-line 1))
4505 (defun org-insert-todo-heading (arg)
4506 "Insert a new heading with the same level and TODO state as current heading.
4507 If the heading has no TODO state, or if the state is DONE, use the first
4508 state (TODO by default). Also with prefix arg, force first state."
4509 (interactive "P")
4510 (when (not (org-insert-item 'checkbox))
4511 (org-insert-heading)
4512 (save-excursion
4513 (org-back-to-heading)
4514 (outline-previous-heading)
4515 (looking-at org-todo-line-regexp))
4516 (if (or arg
4517 (not (match-beginning 2))
4518 (member (match-string 2) org-done-keywords))
4519 (insert (car org-todo-keywords-1) " ")
4520 (insert (match-string 2) " "))))
4522 (defun org-insert-subheading (arg)
4523 "Insert a new subheading and demote it.
4524 Works for outline headings and for plain lists alike."
4525 (interactive "P")
4526 (org-insert-heading arg)
4527 (cond
4528 ((org-on-heading-p) (org-do-demote))
4529 ((org-at-item-p) (org-indent-item 1))))
4531 (defun org-insert-todo-subheading (arg)
4532 "Insert a new subheading with TODO keyword or checkbox and demote it.
4533 Works for outline headings and for plain lists alike."
4534 (interactive "P")
4535 (org-insert-todo-heading arg)
4536 (cond
4537 ((org-on-heading-p) (org-do-demote))
4538 ((org-at-item-p) (org-indent-item 1))))
4540 ;;; Promotion and Demotion
4542 (defun org-promote-subtree ()
4543 "Promote the entire subtree.
4544 See also `org-promote'."
4545 (interactive)
4546 (save-excursion
4547 (org-map-tree 'org-promote))
4548 (org-fix-position-after-promote))
4550 (defun org-demote-subtree ()
4551 "Demote the entire subtree. See `org-demote'.
4552 See also `org-promote'."
4553 (interactive)
4554 (save-excursion
4555 (org-map-tree 'org-demote))
4556 (org-fix-position-after-promote))
4559 (defun org-do-promote ()
4560 "Promote the current heading higher up the tree.
4561 If the region is active in `transient-mark-mode', promote all headings
4562 in the region."
4563 (interactive)
4564 (save-excursion
4565 (if (org-region-active-p)
4566 (org-map-region 'org-promote (region-beginning) (region-end))
4567 (org-promote)))
4568 (org-fix-position-after-promote))
4570 (defun org-do-demote ()
4571 "Demote the current heading lower down the tree.
4572 If the region is active in `transient-mark-mode', demote all headings
4573 in the region."
4574 (interactive)
4575 (save-excursion
4576 (if (org-region-active-p)
4577 (org-map-region 'org-demote (region-beginning) (region-end))
4578 (org-demote)))
4579 (org-fix-position-after-promote))
4581 (defun org-fix-position-after-promote ()
4582 "Make sure that after pro/demotion cursor position is right."
4583 (let ((pos (point)))
4584 (when (save-excursion
4585 (beginning-of-line 1)
4586 (looking-at org-todo-line-regexp)
4587 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4588 (cond ((eobp) (insert " "))
4589 ((eolp) (insert " "))
4590 ((equal (char-after) ?\ ) (forward-char 1))))))
4592 (defun org-reduced-level (l)
4593 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4595 (defun org-get-valid-level (level &optional change)
4596 "Rectify a level change under the influence of `org-odd-levels-only'
4597 LEVEL is a current level, CHANGE is by how much the level should be
4598 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4599 even level numbers will become the next higher odd number."
4600 (if org-odd-levels-only
4601 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4602 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4603 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4604 (max 1 (+ level change))))
4606 (if (boundp 'define-obsolete-function-alias)
4607 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4608 (define-obsolete-function-alias 'org-get-legal-level
4609 'org-get-valid-level)
4610 (define-obsolete-function-alias 'org-get-legal-level
4611 'org-get-valid-level "23.1")))
4613 (defun org-promote ()
4614 "Promote the current heading higher up the tree.
4615 If the region is active in `transient-mark-mode', promote all headings
4616 in the region."
4617 (org-back-to-heading t)
4618 (let* ((level (save-match-data (funcall outline-level)))
4619 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4620 (diff (abs (- level (length up-head) -1))))
4621 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4622 (replace-match up-head nil t)
4623 ;; Fixup tag positioning
4624 (and org-auto-align-tags (org-set-tags nil t))
4625 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4627 (defun org-demote ()
4628 "Demote the current heading lower down the tree.
4629 If the region is active in `transient-mark-mode', demote all headings
4630 in the region."
4631 (org-back-to-heading t)
4632 (let* ((level (save-match-data (funcall outline-level)))
4633 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4634 (diff (abs (- level (length down-head) -1))))
4635 (replace-match down-head nil t)
4636 ;; Fixup tag positioning
4637 (and org-auto-align-tags (org-set-tags nil t))
4638 (if org-adapt-indentation (org-fixup-indentation diff))))
4640 (defun org-map-tree (fun)
4641 "Call FUN for every heading underneath the current one."
4642 (org-back-to-heading)
4643 (let ((level (funcall outline-level)))
4644 (save-excursion
4645 (funcall fun)
4646 (while (and (progn
4647 (outline-next-heading)
4648 (> (funcall outline-level) level))
4649 (not (eobp)))
4650 (funcall fun)))))
4652 (defun org-map-region (fun beg end)
4653 "Call FUN for every heading between BEG and END."
4654 (let ((org-ignore-region t))
4655 (save-excursion
4656 (setq end (copy-marker end))
4657 (goto-char beg)
4658 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4659 (< (point) end))
4660 (funcall fun))
4661 (while (and (progn
4662 (outline-next-heading)
4663 (< (point) end))
4664 (not (eobp)))
4665 (funcall fun)))))
4667 (defun org-fixup-indentation (diff)
4668 "Change the indentation in the current entry by DIFF
4669 However, if any line in the current entry has no indentation, or if it
4670 would end up with no indentation after the change, nothing at all is done."
4671 (save-excursion
4672 (let ((end (save-excursion (outline-next-heading)
4673 (point-marker)))
4674 (prohibit (if (> diff 0)
4675 "^\\S-"
4676 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4677 col)
4678 (unless (save-excursion (end-of-line 1)
4679 (re-search-forward prohibit end t))
4680 (while (and (< (point) end)
4681 (re-search-forward "^[ \t]+" end t))
4682 (goto-char (match-end 0))
4683 (setq col (current-column))
4684 (if (< diff 0) (replace-match ""))
4685 (indent-to (+ diff col))))
4686 (move-marker end nil))))
4688 (defun org-convert-to-odd-levels ()
4689 "Convert an org-mode file with all levels allowed to one with odd levels.
4690 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4691 level 5 etc."
4692 (interactive)
4693 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4694 (let ((org-odd-levels-only nil) n)
4695 (save-excursion
4696 (goto-char (point-min))
4697 (while (re-search-forward "^\\*\\*+ " nil t)
4698 (setq n (- (length (match-string 0)) 2))
4699 (while (>= (setq n (1- n)) 0)
4700 (org-demote))
4701 (end-of-line 1))))))
4704 (defun org-convert-to-oddeven-levels ()
4705 "Convert an org-mode file with only odd levels to one with odd and even levels.
4706 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4707 section with an even level, conversion would destroy the structure of the file. An error
4708 is signaled in this case."
4709 (interactive)
4710 (goto-char (point-min))
4711 ;; First check if there are no even levels
4712 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4713 (org-show-context t)
4714 (error "Not all levels are odd in this file. Conversion not possible."))
4715 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4716 (let ((org-odd-levels-only nil) n)
4717 (save-excursion
4718 (goto-char (point-min))
4719 (while (re-search-forward "^\\*\\*+ " nil t)
4720 (setq n (/ (1- (length (match-string 0))) 2))
4721 (while (>= (setq n (1- n)) 0)
4722 (org-promote))
4723 (end-of-line 1))))))
4725 (defun org-tr-level (n)
4726 "Make N odd if required."
4727 (if org-odd-levels-only (1+ (/ n 2)) n))
4729 ;;; Vertical tree motion, cutting and pasting of subtrees
4731 (defun org-move-subtree-up (&optional arg)
4732 "Move the current subtree up past ARG headlines of the same level."
4733 (interactive "p")
4734 (org-move-subtree-down (- (prefix-numeric-value arg))))
4736 (defun org-move-subtree-down (&optional arg)
4737 "Move the current subtree down past ARG headlines of the same level."
4738 (interactive "p")
4739 (setq arg (prefix-numeric-value arg))
4740 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4741 'outline-get-last-sibling))
4742 (ins-point (make-marker))
4743 (cnt (abs arg))
4744 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4745 ;; Select the tree
4746 (org-back-to-heading)
4747 (setq beg0 (point))
4748 (save-excursion
4749 (setq ne-beg (org-back-over-empty-lines))
4750 (setq beg (point)))
4751 (save-match-data
4752 (save-excursion (outline-end-of-heading)
4753 (setq folded (org-invisible-p)))
4754 (outline-end-of-subtree))
4755 (outline-next-heading)
4756 (setq ne-end (org-back-over-empty-lines))
4757 (setq end (point))
4758 (goto-char beg0)
4759 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4760 ;; include less whitespace
4761 (save-excursion
4762 (goto-char beg)
4763 (forward-line (- ne-beg ne-end))
4764 (setq beg (point))))
4765 ;; Find insertion point, with error handling
4766 (while (> cnt 0)
4767 (or (and (funcall movfunc) (looking-at outline-regexp))
4768 (progn (goto-char beg0)
4769 (error "Cannot move past superior level or buffer limit")))
4770 (setq cnt (1- cnt)))
4771 (if (> arg 0)
4772 ;; Moving forward - still need to move over subtree
4773 (progn (org-end-of-subtree t t)
4774 (save-excursion
4775 (org-back-over-empty-lines)
4776 (or (bolp) (newline)))))
4777 (setq ne-ins (org-back-over-empty-lines))
4778 (move-marker ins-point (point))
4779 (setq txt (buffer-substring beg end))
4780 (org-save-markers-in-region beg end)
4781 (delete-region beg end)
4782 (outline-flag-region (1- beg) beg nil)
4783 (outline-flag-region (1- (point)) (point) nil)
4784 (let ((bbb (point)))
4785 (insert-before-markers txt)
4786 (org-reinstall-markers-in-region bbb)
4787 (move-marker ins-point bbb))
4788 (or (bolp) (insert "\n"))
4789 (setq ins-end (point))
4790 (goto-char ins-point)
4791 (org-skip-whitespace)
4792 (when (and (< arg 0)
4793 (org-first-sibling-p)
4794 (> ne-ins ne-beg))
4795 ;; Move whitespace back to beginning
4796 (save-excursion
4797 (goto-char ins-end)
4798 (let ((kill-whole-line t))
4799 (kill-line (- ne-ins ne-beg)) (point)))
4800 (insert (make-string (- ne-ins ne-beg) ?\n)))
4801 (move-marker ins-point nil)
4802 (org-compact-display-after-subtree-move)
4803 (unless folded
4804 (org-show-entry)
4805 (show-children)
4806 (org-cycle-hide-drawers 'children))))
4808 (defvar org-subtree-clip ""
4809 "Clipboard for cut and paste of subtrees.
4810 This is actually only a copy of the kill, because we use the normal kill
4811 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4813 (defvar org-subtree-clip-folded nil
4814 "Was the last copied subtree folded?
4815 This is used to fold the tree back after pasting.")
4817 (defun org-cut-subtree (&optional n)
4818 "Cut the current subtree into the clipboard.
4819 With prefix arg N, cut this many sequential subtrees.
4820 This is a short-hand for marking the subtree and then cutting it."
4821 (interactive "p")
4822 (org-copy-subtree n 'cut))
4824 (defun org-copy-subtree (&optional n cut force-store-markers)
4825 "Cut the current subtree into the clipboard.
4826 With prefix arg N, cut this many sequential subtrees.
4827 This is a short-hand for marking the subtree and then copying it.
4828 If CUT is non-nil, actually cut the subtree.
4829 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4830 of some markers in the region, even if CUT is non-nil. This is
4831 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4832 (interactive "p")
4833 (let (beg end folded (beg0 (point)))
4834 (if (interactive-p)
4835 (org-back-to-heading nil) ; take what looks like a subtree
4836 (org-back-to-heading t)) ; take what is really there
4837 (org-back-over-empty-lines)
4838 (setq beg (point))
4839 (skip-chars-forward " \t\r\n")
4840 (save-match-data
4841 (save-excursion (outline-end-of-heading)
4842 (setq folded (org-invisible-p)))
4843 (condition-case nil
4844 (outline-forward-same-level (1- n))
4845 (error nil))
4846 (org-end-of-subtree t t))
4847 (org-back-over-empty-lines)
4848 (setq end (point))
4849 (goto-char beg0)
4850 (when (> end beg)
4851 (setq org-subtree-clip-folded folded)
4852 (when (or cut force-store-markers)
4853 (org-save-markers-in-region beg end))
4854 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4855 (setq org-subtree-clip (current-kill 0))
4856 (message "%s: Subtree(s) with %d characters"
4857 (if cut "Cut" "Copied")
4858 (length org-subtree-clip)))))
4860 (defun org-paste-subtree (&optional level tree)
4861 "Paste the clipboard as a subtree, with modification of headline level.
4862 The entire subtree is promoted or demoted in order to match a new headline
4863 level. By default, the new level is derived from the visible headings
4864 before and after the insertion point, and taken to be the inferior headline
4865 level of the two. So if the previous visible heading is level 3 and the
4866 next is level 4 (or vice versa), level 4 will be used for insertion.
4867 This makes sure that the subtree remains an independent subtree and does
4868 not swallow low level entries.
4870 You can also force a different level, either by using a numeric prefix
4871 argument, or by inserting the heading marker by hand. For example, if the
4872 cursor is after \"*****\", then the tree will be shifted to level 5.
4874 If you want to insert the tree as is, just use \\[yank].
4876 If optional TREE is given, use this text instead of the kill ring."
4877 (interactive "P")
4878 (unless (org-kill-is-subtree-p tree)
4879 (error "%s"
4880 (substitute-command-keys
4881 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4882 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4883 (^re (concat "^\\(" outline-regexp "\\)"))
4884 (re (concat "\\(" outline-regexp "\\)"))
4885 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4887 (old-level (if (string-match ^re txt)
4888 (- (match-end 0) (match-beginning 0) 1)
4889 -1))
4890 (force-level (cond (level (prefix-numeric-value level))
4891 ((string-match
4892 ^re_ (buffer-substring (point-at-bol) (point)))
4893 (- (match-end 1) (match-beginning 1)))
4894 (t nil)))
4895 (previous-level (save-excursion
4896 (condition-case nil
4897 (progn
4898 (outline-previous-visible-heading 1)
4899 (if (looking-at re)
4900 (- (match-end 0) (match-beginning 0) 1)
4902 (error 1))))
4903 (next-level (save-excursion
4904 (condition-case nil
4905 (progn
4906 (or (looking-at outline-regexp)
4907 (outline-next-visible-heading 1))
4908 (if (looking-at re)
4909 (- (match-end 0) (match-beginning 0) 1)
4911 (error 1))))
4912 (new-level (or force-level (max previous-level next-level)))
4913 (shift (if (or (= old-level -1)
4914 (= new-level -1)
4915 (= old-level new-level))
4917 (- new-level old-level)))
4918 (delta (if (> shift 0) -1 1))
4919 (func (if (> shift 0) 'org-demote 'org-promote))
4920 (org-odd-levels-only nil)
4921 beg end)
4922 ;; Remove the forced level indicator
4923 (if force-level
4924 (delete-region (point-at-bol) (point)))
4925 ;; Paste
4926 (beginning-of-line 1)
4927 (org-back-over-empty-lines)
4928 (setq beg (point))
4929 (insert-before-markers txt)
4930 (unless (string-match "\n\\'" txt) (insert "\n"))
4931 (org-reinstall-markers-in-region beg)
4932 (setq end (point))
4933 (goto-char beg)
4934 (skip-chars-forward " \t\n\r")
4935 (setq beg (point))
4936 ;; Shift if necessary
4937 (unless (= shift 0)
4938 (save-restriction
4939 (narrow-to-region beg end)
4940 (while (not (= shift 0))
4941 (org-map-region func (point-min) (point-max))
4942 (setq shift (+ delta shift)))
4943 (goto-char (point-min))))
4944 (when (interactive-p)
4945 (message "Clipboard pasted as level %d subtree" new-level))
4946 (if (and kill-ring
4947 (eq org-subtree-clip (current-kill 0))
4948 org-subtree-clip-folded)
4949 ;; The tree was folded before it was killed/copied
4950 (hide-subtree))))
4952 (defun org-kill-is-subtree-p (&optional txt)
4953 "Check if the current kill is an outline subtree, or a set of trees.
4954 Returns nil if kill does not start with a headline, or if the first
4955 headline level is not the largest headline level in the tree.
4956 So this will actually accept several entries of equal levels as well,
4957 which is OK for `org-paste-subtree'.
4958 If optional TXT is given, check this string instead of the current kill."
4959 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4960 (start-level (and kill
4961 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4962 org-outline-regexp "\\)")
4963 kill)
4964 (- (match-end 2) (match-beginning 2) 1)))
4965 (re (concat "^" org-outline-regexp))
4966 (start (1+ (match-beginning 2))))
4967 (if (not start-level)
4968 (progn
4969 nil) ;; does not even start with a heading
4970 (catch 'exit
4971 (while (setq start (string-match re kill (1+ start)))
4972 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4973 (throw 'exit nil)))
4974 t))))
4976 (defvar org-markers-to-move nil
4977 "Markers that should be moved with a cut-and-paste operation.
4978 Those markers are stored together with their positions relative to
4979 the start of the region.")
4981 (defun org-save-markers-in-region (beg end)
4982 "Check markers in region.
4983 If these markers are between BEG and END, record their position relative
4984 to BEG, so that after moving the block of text, we can put the markers back
4985 into place.
4986 This function gets called just before an entry or tree gets cut from the
4987 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4988 called immediately, to move the markers with the entries."
4989 (setq org-markers-to-move nil)
4990 (when (featurep 'org-clock)
4991 (org-clock-save-markers-for-cut-and-paste beg end))
4992 (when (featurep 'org-agenda)
4993 (org-agenda-save-markers-for-cut-and-paste beg end)))
4995 (defun org-check-and-save-marker (marker beg end)
4996 "Check if MARKER is between BEG and END.
4997 If yes, remember the marker and the distance to BEG."
4998 (when (and (marker-buffer marker)
4999 (equal (marker-buffer marker) (current-buffer)))
5000 (if (and (>= marker beg) (< marker end))
5001 (push (cons marker (- marker beg)) org-markers-to-move))))
5003 (defun org-reinstall-markers-in-region (beg)
5004 "Move all remembered markers to their position relative to BEG."
5005 (mapc (lambda (x)
5006 (move-marker (car x) (+ beg (cdr x))))
5007 org-markers-to-move)
5008 (setq org-markers-to-move nil))
5010 (defun org-narrow-to-subtree ()
5011 "Narrow buffer to the current subtree."
5012 (interactive)
5013 (save-excursion
5014 (save-match-data
5015 (narrow-to-region
5016 (progn (org-back-to-heading) (point))
5017 (progn (org-end-of-subtree t t) (point))))))
5020 ;;; Outline Sorting
5022 (defun org-sort (with-case)
5023 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5024 Optional argument WITH-CASE means sort case-sensitively."
5025 (interactive "P")
5026 (if (org-at-table-p)
5027 (org-call-with-arg 'org-table-sort-lines with-case)
5028 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5030 (defun org-sort-remove-invisible (s)
5031 (remove-text-properties 0 (length s) org-rm-props s)
5032 (while (string-match org-bracket-link-regexp s)
5033 (setq s (replace-match (if (match-end 2)
5034 (match-string 3 s)
5035 (match-string 1 s)) t t s)))
5038 (defvar org-priority-regexp) ; defined later in the file
5040 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5041 "Sort entries on a certain level of an outline tree.
5042 If there is an active region, the entries in the region are sorted.
5043 Else, if the cursor is before the first entry, sort the top-level items.
5044 Else, the children of the entry at point are sorted.
5046 Sorting can be alphabetically, numerically, and by date/time as given by
5047 the first time stamp in the entry. The command prompts for the sorting
5048 type unless it has been given to the function through the SORTING-TYPE
5049 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5050 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5051 called with point at the beginning of the record. It must return either
5052 a string or a number that should serve as the sorting key for that record.
5054 Comparing entries ignores case by default. However, with an optional argument
5055 WITH-CASE, the sorting considers case as well."
5056 (interactive "P")
5057 (let ((case-func (if with-case 'identity 'downcase))
5058 start beg end stars re re2
5059 txt what tmp plain-list-p)
5060 ;; Find beginning and end of region to sort
5061 (cond
5062 ((org-region-active-p)
5063 ;; we will sort the region
5064 (setq end (region-end)
5065 what "region")
5066 (goto-char (region-beginning))
5067 (if (not (org-on-heading-p)) (outline-next-heading))
5068 (setq start (point)))
5069 ((org-at-item-p)
5070 ;; we will sort this plain list
5071 (org-beginning-of-item-list) (setq start (point))
5072 (org-end-of-item-list) (setq end (point))
5073 (goto-char start)
5074 (setq plain-list-p t
5075 what "plain list"))
5076 ((or (org-on-heading-p)
5077 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5078 ;; we will sort the children of the current headline
5079 (org-back-to-heading)
5080 (setq start (point)
5081 end (progn (org-end-of-subtree t t)
5082 (org-back-over-empty-lines)
5083 (point))
5084 what "children")
5085 (goto-char start)
5086 (show-subtree)
5087 (outline-next-heading))
5089 ;; we will sort the top-level entries in this file
5090 (goto-char (point-min))
5091 (or (org-on-heading-p) (outline-next-heading))
5092 (setq start (point) end (point-max) what "top-level")
5093 (goto-char start)
5094 (show-all)))
5096 (setq beg (point))
5097 (if (>= beg end) (error "Nothing to sort"))
5099 (unless plain-list-p
5100 (looking-at "\\(\\*+\\)")
5101 (setq stars (match-string 1)
5102 re (concat "^" (regexp-quote stars) " +")
5103 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5104 txt (buffer-substring beg end))
5105 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5106 (if (and (not (equal stars "*")) (string-match re2 txt))
5107 (error "Region to sort contains a level above the first entry")))
5109 (unless sorting-type
5110 (message
5111 (if plain-list-p
5112 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5113 "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:")
5114 what)
5115 (setq sorting-type (read-char-exclusive))
5117 (and (= (downcase sorting-type) ?f)
5118 (setq getkey-func
5119 (completing-read "Sort using function: "
5120 obarray 'fboundp t nil nil))
5121 (setq getkey-func (intern getkey-func)))
5123 (and (= (downcase sorting-type) ?r)
5124 (setq property
5125 (completing-read "Property: "
5126 (mapcar 'list (org-buffer-property-keys t))
5127 nil t))))
5129 (message "Sorting entries...")
5131 (save-restriction
5132 (narrow-to-region start end)
5134 (let ((dcst (downcase sorting-type))
5135 (now (current-time)))
5136 (sort-subr
5137 (/= dcst sorting-type)
5138 ;; This function moves to the beginning character of the "record" to
5139 ;; be sorted.
5140 (if plain-list-p
5141 (lambda nil
5142 (if (org-at-item-p) t (goto-char (point-max))))
5143 (lambda nil
5144 (if (re-search-forward re nil t)
5145 (goto-char (match-beginning 0))
5146 (goto-char (point-max)))))
5147 ;; This function moves to the last character of the "record" being
5148 ;; sorted.
5149 (if plain-list-p
5150 'org-end-of-item
5151 (lambda nil
5152 (save-match-data
5153 (condition-case nil
5154 (outline-forward-same-level 1)
5155 (error
5156 (goto-char (point-max)))))))
5158 ;; This function returns the value that gets sorted against.
5159 (if plain-list-p
5160 (lambda nil
5161 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5162 (cond
5163 ((= dcst ?n)
5164 (string-to-number (buffer-substring (match-end 0)
5165 (point-at-eol))))
5166 ((= dcst ?a)
5167 (buffer-substring (match-end 0) (point-at-eol)))
5168 ((= dcst ?t)
5169 (if (re-search-forward org-ts-regexp
5170 (point-at-eol) t)
5171 (org-time-string-to-time (match-string 0))
5172 now))
5173 ((= dcst ?f)
5174 (if getkey-func
5175 (progn
5176 (setq tmp (funcall getkey-func))
5177 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5178 tmp)
5179 (error "Invalid key function `%s'" getkey-func)))
5180 (t (error "Invalid sorting type `%c'" sorting-type)))))
5181 (lambda nil
5182 (cond
5183 ((= dcst ?n)
5184 (if (looking-at outline-regexp)
5185 (string-to-number (buffer-substring (match-end 0)
5186 (point-at-eol)))
5187 nil))
5188 ((= dcst ?a)
5189 (funcall case-func (buffer-substring (point-at-bol)
5190 (point-at-eol))))
5191 ((= dcst ?t)
5192 (if (re-search-forward org-ts-regexp
5193 (save-excursion
5194 (forward-line 2)
5195 (point)) t)
5196 (org-time-string-to-time (match-string 0))
5197 now))
5198 ((= dcst ?p)
5199 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5200 (string-to-char (match-string 2))
5201 org-default-priority))
5202 ((= dcst ?r)
5203 (or (org-entry-get nil property) ""))
5204 ((= dcst ?o)
5205 (if (looking-at org-complex-heading-regexp)
5206 (- 9999 (length (member (match-string 2)
5207 org-todo-keywords-1)))))
5208 ((= dcst ?f)
5209 (if getkey-func
5210 (progn
5211 (setq tmp (funcall getkey-func))
5212 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5213 tmp)
5214 (error "Invalid key function `%s'" getkey-func)))
5215 (t (error "Invalid sorting type `%c'" sorting-type)))))
5217 (cond
5218 ((= dcst ?a) 'string<)
5219 ((= dcst ?t) 'time-less-p)
5220 (t nil)))))
5221 (message "Sorting entries...done")))
5223 (defun org-do-sort (table what &optional with-case sorting-type)
5224 "Sort TABLE of WHAT according to SORTING-TYPE.
5225 The user will be prompted for the SORTING-TYPE if the call to this
5226 function does not specify it. WHAT is only for the prompt, to indicate
5227 what is being sorted. The sorting key will be extracted from
5228 the car of the elements of the table.
5229 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5230 (unless sorting-type
5231 (message
5232 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5233 what)
5234 (setq sorting-type (read-char-exclusive)))
5235 (let ((dcst (downcase sorting-type))
5236 extractfun comparefun)
5237 ;; Define the appropriate functions
5238 (cond
5239 ((= dcst ?n)
5240 (setq extractfun 'string-to-number
5241 comparefun (if (= dcst sorting-type) '< '>)))
5242 ((= dcst ?a)
5243 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5244 (lambda(x) (downcase (org-sort-remove-invisible x))))
5245 comparefun (if (= dcst sorting-type)
5246 'string<
5247 (lambda (a b) (and (not (string< a b))
5248 (not (string= a b)))))))
5249 ((= dcst ?t)
5250 (setq extractfun
5251 (lambda (x)
5252 (if (string-match org-ts-regexp x)
5253 (time-to-seconds
5254 (org-time-string-to-time (match-string 0 x)))
5256 comparefun (if (= dcst sorting-type) '< '>)))
5257 (t (error "Invalid sorting type `%c'" sorting-type)))
5259 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5260 table)
5261 (lambda (a b) (funcall comparefun (car a) (car b))))))
5263 ;;;; Plain list items, including checkboxes
5265 ;;; Plain list items
5267 (defun org-at-item-p ()
5268 "Is point in a line starting a hand-formatted item?"
5269 (let ((llt org-plain-list-ordered-item-terminator))
5270 (save-excursion
5271 (goto-char (point-at-bol))
5272 (looking-at
5273 (cond
5274 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5275 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5276 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5277 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5279 (defun org-in-item-p ()
5280 "It the cursor inside a plain list item.
5281 Does not have to be the first line."
5282 (save-excursion
5283 (condition-case nil
5284 (progn
5285 (org-beginning-of-item)
5286 (org-at-item-p)
5288 (error nil))))
5290 (defun org-insert-item (&optional checkbox)
5291 "Insert a new item at the current level.
5292 Return t when things worked, nil when we are not in an item."
5293 (when (save-excursion
5294 (condition-case nil
5295 (progn
5296 (org-beginning-of-item)
5297 (org-at-item-p)
5298 (if (org-invisible-p) (error "Invisible item"))
5300 (error nil)))
5301 (let* ((bul (match-string 0))
5302 (descp (save-excursion (goto-char (match-beginning 0))
5303 (beginning-of-line 1)
5304 (save-match-data
5305 (looking-at "[ \t]*.*? ::"))))
5306 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5307 (match-end 0)))
5308 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5309 pos)
5310 (if descp (setq checkbox nil))
5311 (cond
5312 ((and (org-at-item-p) (<= (point) eow))
5313 ;; before the bullet
5314 (beginning-of-line 1)
5315 (open-line (if blank 2 1)))
5316 ((<= (point) eow)
5317 (beginning-of-line 1))
5319 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5320 (end-of-line 1)
5321 (delete-horizontal-space))
5322 (newline (if blank 2 1))))
5323 (insert bul
5324 (if checkbox "[ ]" "")
5325 (if descp (concat (if checkbox " " "")
5326 (read-string "Term: ") " :: ") ""))
5327 (just-one-space)
5328 (setq pos (point))
5329 (end-of-line 1)
5330 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5331 (org-maybe-renumber-ordered-list)
5332 (and checkbox (org-update-checkbox-count-maybe))
5335 ;;; Checkboxes
5337 (defun org-at-item-checkbox-p ()
5338 "Is point at a line starting a plain-list item with a checklet?"
5339 (and (org-at-item-p)
5340 (save-excursion
5341 (goto-char (match-end 0))
5342 (skip-chars-forward " \t")
5343 (looking-at "\\[[- X]\\]"))))
5345 (defun org-toggle-checkbox (&optional arg)
5346 "Toggle the checkbox in the current line."
5347 (interactive "P")
5348 (catch 'exit
5349 (let (beg end status (firstnew 'unknown))
5350 (cond
5351 ((org-region-active-p)
5352 (setq beg (region-beginning) end (region-end)))
5353 ((org-on-heading-p)
5354 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5355 ((org-at-item-checkbox-p)
5356 (let ((pos (point)))
5357 (replace-match
5358 (cond (arg "[-]")
5359 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5360 (t "[ ]"))
5361 t t)
5362 (goto-char pos))
5363 (throw 'exit t))
5364 (t (error "Not at a checkbox or heading, and no active region")))
5365 (save-excursion
5366 (goto-char beg)
5367 (while (< (point) end)
5368 (when (org-at-item-checkbox-p)
5369 (setq status (equal (match-string 0) "[X]"))
5370 (when (eq firstnew 'unknown)
5371 (setq firstnew (not status)))
5372 (replace-match
5373 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5374 (beginning-of-line 2)))))
5375 (org-update-checkbox-count-maybe))
5377 (defun org-update-checkbox-count-maybe ()
5378 "Update checkbox statistics unless turned off by user."
5379 (when org-provide-checkbox-statistics
5380 (org-update-checkbox-count)))
5382 (defun org-update-checkbox-count (&optional all)
5383 "Update the checkbox statistics in the current section.
5384 This will find all statistic cookies like [57%] and [6/12] and update them
5385 with the current numbers. With optional prefix argument ALL, do this for
5386 the whole buffer."
5387 (interactive "P")
5388 (save-excursion
5389 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5390 (beg (condition-case nil
5391 (progn (outline-back-to-heading) (point))
5392 (error (point-min))))
5393 (end (move-marker (make-marker)
5394 (progn (outline-next-heading) (point))))
5395 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5396 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5397 (re-find (concat re "\\|" re-box))
5398 beg-cookie end-cookie is-percent c-on c-off lim
5399 eline curr-ind next-ind continue-from startsearch
5400 (cstat 0)
5402 (when all
5403 (goto-char (point-min))
5404 (outline-next-heading)
5405 (setq beg (point) end (point-max)))
5406 (goto-char end)
5407 ;; find each statistic cookie
5408 (while (re-search-backward re-find beg t)
5409 (setq beg-cookie (match-beginning 1)
5410 end-cookie (match-end 1)
5411 cstat (+ cstat (if end-cookie 1 0))
5412 startsearch (point-at-eol)
5413 continue-from (point-at-bol)
5414 is-percent (match-beginning 2)
5415 lim (cond
5416 ((org-on-heading-p) (outline-next-heading) (point))
5417 ((org-at-item-p) (org-end-of-item) (point))
5418 (t nil))
5419 c-on 0
5420 c-off 0)
5421 (when lim
5422 ;; find first checkbox for this cookie and gather
5423 ;; statistics from all that are at this indentation level
5424 (goto-char startsearch)
5425 (if (re-search-forward re-box lim t)
5426 (progn
5427 (org-beginning-of-item)
5428 (setq curr-ind (org-get-indentation))
5429 (setq next-ind curr-ind)
5430 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5431 (save-excursion (end-of-line) (setq eline (point)))
5432 (if (re-search-forward re-box eline t)
5433 (if (member (match-string 2) '("[ ]" "[-]"))
5434 (setq c-off (1+ c-off))
5435 (setq c-on (1+ c-on))
5438 (org-end-of-item)
5439 (setq next-ind (org-get-indentation))
5441 (goto-char continue-from)
5442 ;; update cookie
5443 (when end-cookie
5444 (delete-region beg-cookie end-cookie)
5445 (goto-char beg-cookie)
5446 (insert
5447 (if is-percent
5448 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5449 (format "[%d/%d]" c-on (+ c-on c-off)))))
5450 ;; update items checkbox if it has one
5451 (when (org-at-item-p)
5452 (org-beginning-of-item)
5453 (when (and (> (+ c-on c-off) 0)
5454 (re-search-forward re-box (point-at-eol) t))
5455 (setq beg-cookie (match-beginning 2)
5456 end-cookie (match-end 2))
5457 (delete-region beg-cookie end-cookie)
5458 (goto-char beg-cookie)
5459 (cond ((= c-off 0) (insert "[X]"))
5460 ((= c-on 0) (insert "[ ]"))
5461 (t (insert "[-]")))
5463 (goto-char continue-from))
5464 (when (interactive-p)
5465 (message "Checkbox satistics updated %s (%d places)"
5466 (if all "in entire file" "in current outline entry") cstat)))))
5468 (defun org-get-checkbox-statistics-face ()
5469 "Select the face for checkbox statistics.
5470 The face will be `org-done' when all relevant boxes are checked. Otherwise
5471 it will be `org-todo'."
5472 (if (match-end 1)
5473 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5474 (if (and (> (match-end 2) (match-beginning 2))
5475 (equal (match-string 2) (match-string 3)))
5476 'org-done
5477 'org-todo)))
5479 (defun org-get-indentation (&optional line)
5480 "Get the indentation of the current line, interpreting tabs.
5481 When LINE is given, assume it represents a line and compute its indentation."
5482 (if line
5483 (if (string-match "^ *" (org-remove-tabs line))
5484 (match-end 0))
5485 (save-excursion
5486 (beginning-of-line 1)
5487 (skip-chars-forward " \t")
5488 (current-column))))
5490 (defun org-remove-tabs (s &optional width)
5491 "Replace tabulators in S with spaces.
5492 Assumes that s is a single line, starting in column 0."
5493 (setq width (or width tab-width))
5494 (while (string-match "\t" s)
5495 (setq s (replace-match
5496 (make-string
5497 (- (* width (/ (+ (match-beginning 0) width) width))
5498 (match-beginning 0)) ?\ )
5499 t t s)))
5502 (defun org-fix-indentation (line ind)
5503 "Fix indentation in LINE.
5504 IND is a cons cell with target and minimum indentation.
5505 If the current indenation in LINE is smaller than the minimum,
5506 leave it alone. If it is larger than ind, set it to the target."
5507 (let* ((l (org-remove-tabs line))
5508 (i (org-get-indentation l))
5509 (i1 (car ind)) (i2 (cdr ind)))
5510 (if (>= i i2) (setq l (substring line i2)))
5511 (if (> i1 0)
5512 (concat (make-string i1 ?\ ) l)
5513 l)))
5515 (defun org-beginning-of-item ()
5516 "Go to the beginning of the current hand-formatted item.
5517 If the cursor is not in an item, throw an error."
5518 (interactive)
5519 (let ((pos (point))
5520 (limit (save-excursion
5521 (condition-case nil
5522 (progn
5523 (org-back-to-heading)
5524 (beginning-of-line 2) (point))
5525 (error (point-min)))))
5526 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5527 ind ind1)
5528 (if (org-at-item-p)
5529 (beginning-of-line 1)
5530 (beginning-of-line 1)
5531 (skip-chars-forward " \t")
5532 (setq ind (current-column))
5533 (if (catch 'exit
5534 (while t
5535 (beginning-of-line 0)
5536 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5538 (if (looking-at "[ \t]*$")
5539 (setq ind1 ind-empty)
5540 (skip-chars-forward " \t")
5541 (setq ind1 (current-column)))
5542 (if (< ind1 ind)
5543 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5545 (goto-char pos)
5546 (error "Not in an item")))))
5548 (defun org-end-of-item ()
5549 "Go to the end of the current hand-formatted item.
5550 If the cursor is not in an item, throw an error."
5551 (interactive)
5552 (let* ((pos (point))
5553 ind1
5554 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5555 (limit (save-excursion (outline-next-heading) (point)))
5556 (ind (save-excursion
5557 (org-beginning-of-item)
5558 (skip-chars-forward " \t")
5559 (current-column)))
5560 (end (catch 'exit
5561 (while t
5562 (beginning-of-line 2)
5563 (if (eobp) (throw 'exit (point)))
5564 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5565 (if (looking-at "[ \t]*$")
5566 (setq ind1 ind-empty)
5567 (skip-chars-forward " \t")
5568 (setq ind1 (current-column)))
5569 (if (<= ind1 ind)
5570 (throw 'exit (point-at-bol)))))))
5571 (if end
5572 (goto-char end)
5573 (goto-char pos)
5574 (error "Not in an item"))))
5576 (defun org-next-item ()
5577 "Move to the beginning of the next item in the current plain list.
5578 Error if not at a plain list, or if this is the last item in the list."
5579 (interactive)
5580 (let (ind ind1 (pos (point)))
5581 (org-beginning-of-item)
5582 (setq ind (org-get-indentation))
5583 (org-end-of-item)
5584 (setq ind1 (org-get-indentation))
5585 (unless (and (org-at-item-p) (= ind ind1))
5586 (goto-char pos)
5587 (error "On last item"))))
5589 (defun org-previous-item ()
5590 "Move to the beginning of the previous item in the current plain list.
5591 Error if not at a plain list, or if this is the first item in the list."
5592 (interactive)
5593 (let (beg ind ind1 (pos (point)))
5594 (org-beginning-of-item)
5595 (setq beg (point))
5596 (setq ind (org-get-indentation))
5597 (goto-char beg)
5598 (catch 'exit
5599 (while t
5600 (beginning-of-line 0)
5601 (if (looking-at "[ \t]*$")
5603 (if (<= (setq ind1 (org-get-indentation)) ind)
5604 (throw 'exit t)))))
5605 (condition-case nil
5606 (if (or (not (org-at-item-p))
5607 (< ind1 (1- ind)))
5608 (error "")
5609 (org-beginning-of-item))
5610 (error (goto-char pos)
5611 (error "On first item")))))
5613 (defun org-first-list-item-p ()
5614 "Is this heading the item in a plain list?"
5615 (unless (org-at-item-p)
5616 (error "Not at a plain list item"))
5617 (org-beginning-of-item)
5618 (= (point) (save-excursion (org-beginning-of-item-list))))
5620 (defun org-move-item-down ()
5621 "Move the plain list item at point down, i.e. swap with following item.
5622 Subitems (items with larger indentation) are considered part of the item,
5623 so this really moves item trees."
5624 (interactive)
5625 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5626 (org-beginning-of-item)
5627 (setq beg0 (point))
5628 (save-excursion
5629 (setq ne-beg (org-back-over-empty-lines))
5630 (setq beg (point)))
5631 (goto-char beg0)
5632 (setq ind (org-get-indentation))
5633 (org-end-of-item)
5634 (setq end0 (point))
5635 (setq ind1 (org-get-indentation))
5636 (setq ne-end (org-back-over-empty-lines))
5637 (setq end (point))
5638 (goto-char beg0)
5639 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5640 ;; include less whitespace
5641 (save-excursion
5642 (goto-char beg)
5643 (forward-line (- ne-beg ne-end))
5644 (setq beg (point))))
5645 (goto-char end0)
5646 (if (and (org-at-item-p) (= ind ind1))
5647 (progn
5648 (org-end-of-item)
5649 (org-back-over-empty-lines)
5650 (setq txt (buffer-substring beg end))
5651 (save-excursion
5652 (delete-region beg end))
5653 (setq pos (point))
5654 (insert txt)
5655 (goto-char pos) (org-skip-whitespace)
5656 (org-maybe-renumber-ordered-list))
5657 (goto-char pos)
5658 (error "Cannot move this item further down"))))
5660 (defun org-move-item-up (arg)
5661 "Move the plain list item at point up, i.e. swap with previous item.
5662 Subitems (items with larger indentation) are considered part of the item,
5663 so this really moves item trees."
5664 (interactive "p")
5665 (let (beg beg0 end ind ind1 (pos (point)) txt
5666 ne-beg ne-ins ins-end)
5667 (org-beginning-of-item)
5668 (setq beg0 (point))
5669 (setq ind (org-get-indentation))
5670 (save-excursion
5671 (setq ne-beg (org-back-over-empty-lines))
5672 (setq beg (point)))
5673 (goto-char beg0)
5674 (org-end-of-item)
5675 (setq end (point))
5676 (goto-char beg0)
5677 (catch 'exit
5678 (while t
5679 (beginning-of-line 0)
5680 (if (looking-at "[ \t]*$")
5681 (if org-empty-line-terminates-plain-lists
5682 (progn
5683 (goto-char pos)
5684 (error "Cannot move this item further up"))
5685 nil)
5686 (if (<= (setq ind1 (org-get-indentation)) ind)
5687 (throw 'exit t)))))
5688 (condition-case nil
5689 (org-beginning-of-item)
5690 (error (goto-char beg)
5691 (error "Cannot move this item further up")))
5692 (setq ind1 (org-get-indentation))
5693 (if (and (org-at-item-p) (= ind ind1))
5694 (progn
5695 (setq ne-ins (org-back-over-empty-lines))
5696 (setq txt (buffer-substring beg end))
5697 (save-excursion
5698 (delete-region beg end))
5699 (setq pos (point))
5700 (insert txt)
5701 (setq ins-end (point))
5702 (goto-char pos) (org-skip-whitespace)
5704 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5705 ;; Move whitespace back to beginning
5706 (save-excursion
5707 (goto-char ins-end)
5708 (let ((kill-whole-line t))
5709 (kill-line (- ne-ins ne-beg)) (point)))
5710 (insert (make-string (- ne-ins ne-beg) ?\n)))
5712 (org-maybe-renumber-ordered-list))
5713 (goto-char pos)
5714 (error "Cannot move this item further up"))))
5716 (defun org-maybe-renumber-ordered-list ()
5717 "Renumber the ordered list at point if setup allows it.
5718 This tests the user option `org-auto-renumber-ordered-lists' before
5719 doing the renumbering."
5720 (interactive)
5721 (when (and org-auto-renumber-ordered-lists
5722 (org-at-item-p))
5723 (if (match-beginning 3)
5724 (org-renumber-ordered-list 1)
5725 (org-fix-bullet-type))))
5727 (defun org-maybe-renumber-ordered-list-safe ()
5728 (condition-case nil
5729 (save-excursion
5730 (org-maybe-renumber-ordered-list))
5731 (error nil)))
5733 (defun org-cycle-list-bullet (&optional which)
5734 "Cycle through the different itemize/enumerate bullets.
5735 This cycle the entire list level through the sequence:
5737 `-' -> `+' -> `*' -> `1.' -> `1)'
5739 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5740 0 meand `-', 1 means `+' etc."
5741 (interactive "P")
5742 (org-preserve-lc
5743 (org-beginning-of-item-list)
5744 (org-at-item-p)
5745 (beginning-of-line 1)
5746 (let ((current (match-string 0))
5747 (prevp (eq which 'previous))
5748 new)
5749 (setq new (cond
5750 ((and (numberp which)
5751 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5752 ((string-match "-" current) (if prevp "1)" "+"))
5753 ((string-match "\\+" current)
5754 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5755 ((string-match "\\*" current) (if prevp "+" "1."))
5756 ((string-match "\\." current) (if prevp "*" "1)"))
5757 ((string-match ")" current) (if prevp "1." "-"))
5758 (t (error "This should not happen"))))
5759 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5760 (org-fix-bullet-type)
5761 (org-maybe-renumber-ordered-list))))
5763 (defun org-get-string-indentation (s)
5764 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5765 (let ((n -1) (i 0) (w tab-width) c)
5766 (catch 'exit
5767 (while (< (setq n (1+ n)) (length s))
5768 (setq c (aref s n))
5769 (cond ((= c ?\ ) (setq i (1+ i)))
5770 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5771 (t (throw 'exit t)))))
5774 (defun org-renumber-ordered-list (arg)
5775 "Renumber an ordered plain list.
5776 Cursor needs to be in the first line of an item, the line that starts
5777 with something like \"1.\" or \"2)\"."
5778 (interactive "p")
5779 (unless (and (org-at-item-p)
5780 (match-beginning 3))
5781 (error "This is not an ordered list"))
5782 (let ((line (org-current-line))
5783 (col (current-column))
5784 (ind (org-get-string-indentation
5785 (buffer-substring (point-at-bol) (match-beginning 3))))
5786 ;; (term (substring (match-string 3) -1))
5787 ind1 (n (1- arg))
5788 fmt)
5789 ;; find where this list begins
5790 (org-beginning-of-item-list)
5791 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5792 (setq fmt (concat "%d" (match-string 1)))
5793 (beginning-of-line 0)
5794 ;; walk forward and replace these numbers
5795 (catch 'exit
5796 (while t
5797 (catch 'next
5798 (beginning-of-line 2)
5799 (if (eobp) (throw 'exit nil))
5800 (if (looking-at "[ \t]*$") (throw 'next nil))
5801 (skip-chars-forward " \t") (setq ind1 (current-column))
5802 (if (> ind1 ind) (throw 'next t))
5803 (if (< ind1 ind) (throw 'exit t))
5804 (if (not (org-at-item-p)) (throw 'exit nil))
5805 (delete-region (match-beginning 2) (match-end 2))
5806 (goto-char (match-beginning 2))
5807 (insert (format fmt (setq n (1+ n)))))))
5808 (goto-line line)
5809 (org-move-to-column col)))
5811 (defun org-fix-bullet-type ()
5812 "Make sure all items in this list have the same bullet as the firsst item."
5813 (interactive)
5814 (unless (org-at-item-p) (error "This is not a list"))
5815 (let ((line (org-current-line))
5816 (col (current-column))
5817 (ind (current-indentation))
5818 ind1 bullet)
5819 ;; find where this list begins
5820 (org-beginning-of-item-list)
5821 (beginning-of-line 1)
5822 ;; find out what the bullet type is
5823 (looking-at "[ \t]*\\(\\S-+\\)")
5824 (setq bullet (match-string 1))
5825 ;; walk forward and replace these numbers
5826 (beginning-of-line 0)
5827 (catch 'exit
5828 (while t
5829 (catch 'next
5830 (beginning-of-line 2)
5831 (if (eobp) (throw 'exit nil))
5832 (if (looking-at "[ \t]*$") (throw 'next nil))
5833 (skip-chars-forward " \t") (setq ind1 (current-column))
5834 (if (> ind1 ind) (throw 'next t))
5835 (if (< ind1 ind) (throw 'exit t))
5836 (if (not (org-at-item-p)) (throw 'exit nil))
5837 (skip-chars-forward " \t")
5838 (looking-at "\\S-+")
5839 (replace-match bullet))))
5840 (goto-line line)
5841 (org-move-to-column col)
5842 (if (string-match "[0-9]" bullet)
5843 (org-renumber-ordered-list 1))))
5845 (defun org-beginning-of-item-list ()
5846 "Go to the beginning of the current item list.
5847 I.e. to the first item in this list."
5848 (interactive)
5849 (org-beginning-of-item)
5850 (let ((pos (point-at-bol))
5851 (ind (org-get-indentation))
5852 ind1)
5853 ;; find where this list begins
5854 (catch 'exit
5855 (while t
5856 (catch 'next
5857 (beginning-of-line 0)
5858 (if (looking-at "[ \t]*$")
5859 (throw (if (bobp) 'exit 'next) t))
5860 (skip-chars-forward " \t") (setq ind1 (current-column))
5861 (if (or (< ind1 ind)
5862 (and (= ind1 ind)
5863 (not (org-at-item-p)))
5864 (bobp))
5865 (throw 'exit t)
5866 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5867 (goto-char pos)))
5870 (defun org-end-of-item-list ()
5871 "Go to the end of the current item list.
5872 I.e. to the text after the last item."
5873 (interactive)
5874 (org-beginning-of-item)
5875 (let ((pos (point-at-bol))
5876 (ind (org-get-indentation))
5877 ind1)
5878 ;; find where this list begins
5879 (catch 'exit
5880 (while t
5881 (catch 'next
5882 (beginning-of-line 2)
5883 (if (looking-at "[ \t]*$")
5884 (throw (if (eobp) 'exit 'next) t))
5885 (skip-chars-forward " \t") (setq ind1 (current-column))
5886 (if (or (< ind1 ind)
5887 (and (= ind1 ind)
5888 (not (org-at-item-p)))
5889 (eobp))
5890 (progn
5891 (setq pos (point-at-bol))
5892 (throw 'exit t))))))
5893 (goto-char pos)))
5896 (defvar org-last-indent-begin-marker (make-marker))
5897 (defvar org-last-indent-end-marker (make-marker))
5899 (defun org-outdent-item (arg)
5900 "Outdent a local list item."
5901 (interactive "p")
5902 (org-indent-item (- arg)))
5904 (defun org-indent-item (arg)
5905 "Indent a local list item."
5906 (interactive "p")
5907 (unless (org-at-item-p)
5908 (error "Not on an item"))
5909 (save-excursion
5910 (let (beg end ind ind1 tmp delta ind-down ind-up)
5911 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5912 (setq beg org-last-indent-begin-marker
5913 end org-last-indent-end-marker)
5914 (org-beginning-of-item)
5915 (setq beg (move-marker org-last-indent-begin-marker (point)))
5916 (org-end-of-item)
5917 (setq end (move-marker org-last-indent-end-marker (point))))
5918 (goto-char beg)
5919 (setq tmp (org-item-indent-positions)
5920 ind (car tmp)
5921 ind-down (nth 2 tmp)
5922 ind-up (nth 1 tmp)
5923 delta (if (> arg 0)
5924 (if ind-down (- ind-down ind) 2)
5925 (if ind-up (- ind-up ind) -2)))
5926 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5927 (while (< (point) end)
5928 (beginning-of-line 1)
5929 (skip-chars-forward " \t") (setq ind1 (current-column))
5930 (delete-region (point-at-bol) (point))
5931 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5932 (beginning-of-line 2))))
5933 (org-fix-bullet-type)
5934 (org-maybe-renumber-ordered-list-safe)
5935 (save-excursion
5936 (beginning-of-line 0)
5937 (condition-case nil (org-beginning-of-item) (error nil))
5938 (org-maybe-renumber-ordered-list-safe)))
5940 (defun org-item-indent-positions ()
5941 "Return indentation for plain list items.
5942 This returns a list with three values: The current indentation, the
5943 parent indentation and the indentation a child should habe.
5944 Assumes cursor in item line."
5945 (let* ((bolpos (point-at-bol))
5946 (ind (org-get-indentation))
5947 ind-down ind-up pos)
5948 (save-excursion
5949 (org-beginning-of-item-list)
5950 (skip-chars-backward "\n\r \t")
5951 (when (org-in-item-p)
5952 (org-beginning-of-item)
5953 (setq ind-up (org-get-indentation))))
5954 (setq pos (point))
5955 (save-excursion
5956 (cond
5957 ((and (condition-case nil (progn (org-previous-item) t)
5958 (error nil))
5959 (or (forward-char 1) t)
5960 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5961 (setq ind-down (org-get-indentation)))
5962 ((and (goto-char pos)
5963 (org-at-item-p))
5964 (goto-char (match-end 0))
5965 (skip-chars-forward " \t")
5966 (setq ind-down (current-column)))))
5967 (list ind ind-up ind-down)))
5969 ;;; The orgstruct minor mode
5971 ;; Define a minor mode which can be used in other modes in order to
5972 ;; integrate the org-mode structure editing commands.
5974 ;; This is really a hack, because the org-mode structure commands use
5975 ;; keys which normally belong to the major mode. Here is how it
5976 ;; works: The minor mode defines all the keys necessary to operate the
5977 ;; structure commands, but wraps the commands into a function which
5978 ;; tests if the cursor is currently at a headline or a plain list
5979 ;; item. If that is the case, the structure command is used,
5980 ;; temporarily setting many Org-mode variables like regular
5981 ;; expressions for filling etc. However, when any of those keys is
5982 ;; used at a different location, function uses `key-binding' to look
5983 ;; up if the key has an associated command in another currently active
5984 ;; keymap (minor modes, major mode, global), and executes that
5985 ;; command. There might be problems if any of the keys is otherwise
5986 ;; used as a prefix key.
5988 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5989 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5990 ;; addresses this by checking explicitly for both bindings.
5992 (defvar orgstruct-mode-map (make-sparse-keymap)
5993 "Keymap for the minor `orgstruct-mode'.")
5995 (defvar org-local-vars nil
5996 "List of local variables, for use by `orgstruct-mode'")
5998 ;;;###autoload
5999 (define-minor-mode orgstruct-mode
6000 "Toggle the minor more `orgstruct-mode'.
6001 This mode is for using Org-mode structure commands in other modes.
6002 The following key behave as if Org-mode was active, if the cursor
6003 is on a headline, or on a plain list item (both in the definition
6004 of Org-mode).
6006 M-up Move entry/item up
6007 M-down Move entry/item down
6008 M-left Promote
6009 M-right Demote
6010 M-S-up Move entry/item up
6011 M-S-down Move entry/item down
6012 M-S-left Promote subtree
6013 M-S-right Demote subtree
6014 M-q Fill paragraph and items like in Org-mode
6015 C-c ^ Sort entries
6016 C-c - Cycle list bullet
6017 TAB Cycle item visibility
6018 M-RET Insert new heading/item
6019 S-M-RET Insert new TODO heading / Chekbox item
6020 C-c C-c Set tags / toggle checkbox"
6021 nil " OrgStruct" nil
6022 (org-load-modules-maybe)
6023 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6025 ;;;###autoload
6026 (defun turn-on-orgstruct ()
6027 "Unconditionally turn on `orgstruct-mode'."
6028 (orgstruct-mode 1))
6030 ;;;###autoload
6031 (defun turn-on-orgstruct++ ()
6032 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6033 In addition to setting orgstruct-mode, this also exports all indentation and
6034 autofilling variables from org-mode into the buffer. Note that turning
6035 off orgstruct-mode will *not* remove these additional settings."
6036 (orgstruct-mode 1)
6037 (let (var val)
6038 (mapc
6039 (lambda (x)
6040 (when (string-match
6041 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6042 (symbol-name (car x)))
6043 (setq var (car x) val (nth 1 x))
6044 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6045 org-local-vars)))
6047 (defun orgstruct-error ()
6048 "Error when there is no default binding for a structure key."
6049 (interactive)
6050 (error "This key has no function outside structure elements"))
6052 (defun orgstruct-setup ()
6053 "Setup orgstruct keymaps."
6054 (let ((nfunc 0)
6055 (bindings
6056 (list
6057 '([(meta up)] org-metaup)
6058 '([(meta down)] org-metadown)
6059 '([(meta left)] org-metaleft)
6060 '([(meta right)] org-metaright)
6061 '([(meta shift up)] org-shiftmetaup)
6062 '([(meta shift down)] org-shiftmetadown)
6063 '([(meta shift left)] org-shiftmetaleft)
6064 '([(meta shift right)] org-shiftmetaright)
6065 '([(shift up)] org-shiftup)
6066 '([(shift down)] org-shiftdown)
6067 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6068 '("\M-q" fill-paragraph)
6069 '("\C-c^" org-sort)
6070 '("\C-c-" org-cycle-list-bullet)))
6071 elt key fun cmd)
6072 (while (setq elt (pop bindings))
6073 (setq nfunc (1+ nfunc))
6074 (setq key (org-key (car elt))
6075 fun (nth 1 elt)
6076 cmd (orgstruct-make-binding fun nfunc key))
6077 (org-defkey orgstruct-mode-map key cmd))
6079 ;; Special treatment needed for TAB and RET
6080 (org-defkey orgstruct-mode-map [(tab)]
6081 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6082 (org-defkey orgstruct-mode-map "\C-i"
6083 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6085 (org-defkey orgstruct-mode-map "\M-\C-m"
6086 (orgstruct-make-binding 'org-insert-heading 105
6087 "\M-\C-m" [(meta return)]))
6088 (org-defkey orgstruct-mode-map [(meta return)]
6089 (orgstruct-make-binding 'org-insert-heading 106
6090 [(meta return)] "\M-\C-m"))
6092 (org-defkey orgstruct-mode-map [(shift meta return)]
6093 (orgstruct-make-binding 'org-insert-todo-heading 107
6094 [(meta return)] "\M-\C-m"))
6096 (unless org-local-vars
6097 (setq org-local-vars (org-get-local-variables)))
6101 (defun orgstruct-make-binding (fun n &rest keys)
6102 "Create a function for binding in the structure minor mode.
6103 FUN is the command to call inside a table. N is used to create a unique
6104 command name. KEYS are keys that should be checked in for a command
6105 to execute outside of tables."
6106 (eval
6107 (list 'defun
6108 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6109 '(arg)
6110 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6111 "Outside of structure, run the binding of `"
6112 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6113 "'.")
6114 '(interactive "p")
6115 (list 'if
6116 '(org-context-p 'headline 'item)
6117 (list 'org-run-like-in-org-mode (list 'quote fun))
6118 (list 'let '(orgstruct-mode)
6119 (list 'call-interactively
6120 (append '(or)
6121 (mapcar (lambda (k)
6122 (list 'key-binding k))
6123 keys)
6124 '('orgstruct-error))))))))
6126 (defun org-context-p (&rest contexts)
6127 "Check if local context is and of CONTEXTS.
6128 Possible values in the list of contexts are `table', `headline', and `item'."
6129 (let ((pos (point)))
6130 (goto-char (point-at-bol))
6131 (prog1 (or (and (memq 'table contexts)
6132 (looking-at "[ \t]*|"))
6133 (and (memq 'headline contexts)
6134 (looking-at "\\*+"))
6135 (and (memq 'item contexts)
6136 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6137 (goto-char pos))))
6139 (defun org-get-local-variables ()
6140 "Return a list of all local variables in an org-mode buffer."
6141 (let (varlist)
6142 (with-current-buffer (get-buffer-create "*Org tmp*")
6143 (erase-buffer)
6144 (org-mode)
6145 (setq varlist (buffer-local-variables)))
6146 (kill-buffer "*Org tmp*")
6147 (delq nil
6148 (mapcar
6149 (lambda (x)
6150 (setq x
6151 (if (symbolp x)
6152 (list x)
6153 (list (car x) (list 'quote (cdr x)))))
6154 (if (string-match
6155 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6156 (symbol-name (car x)))
6157 x nil))
6158 varlist))))
6160 ;;;###autoload
6161 (defun org-run-like-in-org-mode (cmd)
6162 (org-load-modules-maybe)
6163 (unless org-local-vars
6164 (setq org-local-vars (org-get-local-variables)))
6165 (eval (list 'let org-local-vars
6166 (list 'call-interactively (list 'quote cmd)))))
6168 ;;;; Archiving
6170 (defun org-get-category (&optional pos)
6171 "Get the category applying to position POS."
6172 (get-text-property (or pos (point)) 'org-category))
6174 (defun org-refresh-category-properties ()
6175 "Refresh category text properties in the buffer."
6176 (let ((def-cat (cond
6177 ((null org-category)
6178 (if buffer-file-name
6179 (file-name-sans-extension
6180 (file-name-nondirectory buffer-file-name))
6181 "???"))
6182 ((symbolp org-category) (symbol-name org-category))
6183 (t org-category)))
6184 beg end cat pos optionp)
6185 (org-unmodified
6186 (save-excursion
6187 (save-restriction
6188 (widen)
6189 (goto-char (point-min))
6190 (put-text-property (point) (point-max) 'org-category def-cat)
6191 (while (re-search-forward
6192 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6193 (setq pos (match-end 0)
6194 optionp (equal (char-after (match-beginning 0)) ?#)
6195 cat (org-trim (match-string 2)))
6196 (if optionp
6197 (setq beg (point-at-bol) end (point-max))
6198 (org-back-to-heading t)
6199 (setq beg (point) end (org-end-of-subtree t t)))
6200 (put-text-property beg end 'org-category cat)
6201 (goto-char pos)))))))
6204 ;;;; Link Stuff
6206 ;;; Link abbreviations
6208 (defun org-link-expand-abbrev (link)
6209 "Apply replacements as defined in `org-link-abbrev-alist."
6210 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6211 (let* ((key (match-string 1 link))
6212 (as (or (assoc key org-link-abbrev-alist-local)
6213 (assoc key org-link-abbrev-alist)))
6214 (tag (and (match-end 2) (match-string 3 link)))
6215 rpl)
6216 (if (not as)
6217 link
6218 (setq rpl (cdr as))
6219 (cond
6220 ((symbolp rpl) (funcall rpl tag))
6221 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6222 (t (concat rpl tag)))))
6223 link))
6225 ;;; Storing and inserting links
6227 (defvar org-insert-link-history nil
6228 "Minibuffer history for links inserted with `org-insert-link'.")
6230 (defvar org-stored-links nil
6231 "Contains the links stored with `org-store-link'.")
6233 (defvar org-store-link-plist nil
6234 "Plist with info about the most recently link created with `org-store-link'.")
6236 (defvar org-link-protocols nil
6237 "Link protocols added to Org-mode using `org-add-link-type'.")
6239 (defvar org-store-link-functions nil
6240 "List of functions that are called to create and store a link.
6241 Each function will be called in turn until one returns a non-nil
6242 value. Each function should check if it is responsible for creating
6243 this link (for example by looking at the major mode).
6244 If not, it must exit and return nil.
6245 If yes, it should return a non-nil value after a calling
6246 `org-store-link-props' with a list of properties and values.
6247 Special properties are:
6249 :type The link prefix. like \"http\". This must be given.
6250 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6251 This is obligatory as well.
6252 :description Optional default description for the second pair
6253 of brackets in an Org-mode link. The user can still change
6254 this when inserting this link into an Org-mode buffer.
6256 In addition to these, any additional properties can be specified
6257 and then used in remember templates.")
6259 (defun org-add-link-type (type &optional follow export)
6260 "Add TYPE to the list of `org-link-types'.
6261 Re-compute all regular expressions depending on `org-link-types'
6263 FOLLOW and EXPORT are two functions.
6265 FOLLOW should take the link path as the single argument and do whatever
6266 is necessary to follow the link, for example find a file or display
6267 a mail message.
6269 EXPORT should format the link path for export to one of the export formats.
6270 It should be a function accepting three arguments:
6272 path the path of the link, the text after the prefix (like \"http:\")
6273 desc the description of the link, if any, nil if there was no descripton
6274 format the export format, a symbol like `html' or `latex'.
6276 The function may use the FORMAT information to return different values
6277 depending on the format. The return value will be put literally into
6278 the exported file.
6279 Org-mode has a built-in default for exporting links. If you are happy with
6280 this default, there is no need to define an export function for the link
6281 type. For a simple example of an export function, see `org-bbdb.el'."
6282 (add-to-list 'org-link-types type t)
6283 (org-make-link-regexps)
6284 (if (assoc type org-link-protocols)
6285 (setcdr (assoc type org-link-protocols) (list follow export))
6286 (push (list type follow export) org-link-protocols)))
6289 ;;;###autoload
6290 (defun org-store-link (arg)
6291 "\\<org-mode-map>Store an org-link to the current location.
6292 This link is added to `org-stored-links' and can later be inserted
6293 into an org-buffer with \\[org-insert-link].
6295 For some link types, a prefix arg is interpreted:
6296 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6297 For file links, arg negates `org-context-in-file-links'."
6298 (interactive "P")
6299 (org-load-modules-maybe)
6300 (setq org-store-link-plist nil) ; reset
6301 (let (link cpltxt desc description search txt)
6302 (cond
6304 ((run-hook-with-args-until-success 'org-store-link-functions)
6305 (setq link (plist-get org-store-link-plist :link)
6306 desc (or (plist-get org-store-link-plist :description) link)))
6308 ((eq major-mode 'calendar-mode)
6309 (let ((cd (calendar-cursor-to-date)))
6310 (setq link
6311 (format-time-string
6312 (car org-time-stamp-formats)
6313 (apply 'encode-time
6314 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6315 nil nil nil))))
6316 (org-store-link-props :type "calendar" :date cd)))
6318 ((eq major-mode 'w3-mode)
6319 (setq cpltxt (url-view-url t)
6320 link (org-make-link cpltxt))
6321 (org-store-link-props :type "w3" :url (url-view-url t)))
6323 ((eq major-mode 'w3m-mode)
6324 (setq cpltxt (or w3m-current-title w3m-current-url)
6325 link (org-make-link w3m-current-url))
6326 (org-store-link-props :type "w3m" :url (url-view-url t)))
6328 ((setq search (run-hook-with-args-until-success
6329 'org-create-file-search-functions))
6330 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6331 "::" search))
6332 (setq cpltxt (or description link)))
6334 ((eq major-mode 'image-mode)
6335 (setq cpltxt (concat "file:"
6336 (abbreviate-file-name buffer-file-name))
6337 link (org-make-link cpltxt))
6338 (org-store-link-props :type "image" :file buffer-file-name))
6340 ((eq major-mode 'dired-mode)
6341 ;; link to the file in the current line
6342 (setq cpltxt (concat "file:"
6343 (abbreviate-file-name
6344 (expand-file-name
6345 (dired-get-filename nil t))))
6346 link (org-make-link cpltxt)))
6348 ((and buffer-file-name (org-mode-p))
6349 ;; Just link to current headline
6350 (setq cpltxt (concat "file:"
6351 (abbreviate-file-name buffer-file-name)))
6352 ;; Add a context search string
6353 (when (org-xor org-context-in-file-links arg)
6354 ;; Check if we are on a target
6355 (if (org-in-regexp "<<\\(.*?\\)>>")
6356 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6357 (setq txt (cond
6358 ((org-on-heading-p) nil)
6359 ((org-region-active-p)
6360 (buffer-substring (region-beginning) (region-end)))
6361 (t nil)))
6362 (when (or (null txt) (string-match "\\S-" txt))
6363 (setq cpltxt
6364 (concat cpltxt "::"
6365 (condition-case nil
6366 (org-make-org-heading-search-string txt)
6367 (error "")))
6368 desc "NONE"))))
6369 (if (string-match "::\\'" cpltxt)
6370 (setq cpltxt (substring cpltxt 0 -2)))
6371 (setq link (org-make-link cpltxt)))
6373 ((buffer-file-name (buffer-base-buffer))
6374 ;; Just link to this file here.
6375 (setq cpltxt (concat "file:"
6376 (abbreviate-file-name
6377 (buffer-file-name (buffer-base-buffer)))))
6378 ;; Add a context string
6379 (when (org-xor org-context-in-file-links arg)
6380 (setq txt (if (org-region-active-p)
6381 (buffer-substring (region-beginning) (region-end))
6382 (buffer-substring (point-at-bol) (point-at-eol))))
6383 ;; Only use search option if there is some text.
6384 (when (string-match "\\S-" txt)
6385 (setq cpltxt
6386 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6387 desc "NONE")))
6388 (setq link (org-make-link cpltxt)))
6390 ((interactive-p)
6391 (error "Cannot link to a buffer which is not visiting a file"))
6393 (t (setq link nil)))
6395 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6396 (setq link (or link cpltxt)
6397 desc (or desc cpltxt))
6398 (if (equal desc "NONE") (setq desc nil))
6400 (if (and (interactive-p) link)
6401 (progn
6402 (setq org-stored-links
6403 (cons (list link desc) org-stored-links))
6404 (message "Stored: %s" (or desc link)))
6405 (and link (org-make-link-string link desc)))))
6407 (defun org-store-link-props (&rest plist)
6408 "Store link properties, extract names and addresses."
6409 (let (x adr)
6410 (when (setq x (plist-get plist :from))
6411 (setq adr (mail-extract-address-components x))
6412 (plist-put plist :fromname (car adr))
6413 (plist-put plist :fromaddress (nth 1 adr)))
6414 (when (setq x (plist-get plist :to))
6415 (setq adr (mail-extract-address-components x))
6416 (plist-put plist :toname (car adr))
6417 (plist-put plist :toaddress (nth 1 adr))))
6418 (let ((from (plist-get plist :from))
6419 (to (plist-get plist :to)))
6420 (when (and from to org-from-is-user-regexp)
6421 (plist-put plist :fromto
6422 (if (string-match org-from-is-user-regexp from)
6423 (concat "to %t")
6424 (concat "from %f")))))
6425 (setq org-store-link-plist plist))
6427 (defun org-add-link-props (&rest plist)
6428 "Add these properties to the link property list."
6429 (let (key value)
6430 (while plist
6431 (setq key (pop plist) value (pop plist))
6432 (setq org-store-link-plist
6433 (plist-put org-store-link-plist key value)))))
6435 (defun org-email-link-description (&optional fmt)
6436 "Return the description part of an email link.
6437 This takes information from `org-store-link-plist' and formats it
6438 according to FMT (default from `org-email-link-description-format')."
6439 (setq fmt (or fmt org-email-link-description-format))
6440 (let* ((p org-store-link-plist)
6441 (to (plist-get p :toaddress))
6442 (from (plist-get p :fromaddress))
6443 (table
6444 (list
6445 (cons "%c" (plist-get p :fromto))
6446 (cons "%F" (plist-get p :from))
6447 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6448 (cons "%T" (plist-get p :to))
6449 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6450 (cons "%s" (plist-get p :subject))
6451 (cons "%m" (plist-get p :message-id)))))
6452 (when (string-match "%c" fmt)
6453 ;; Check if the user wrote this message
6454 (if (and org-from-is-user-regexp from to
6455 (save-match-data (string-match org-from-is-user-regexp from)))
6456 (setq fmt (replace-match "to %t" t t fmt))
6457 (setq fmt (replace-match "from %f" t t fmt))))
6458 (org-replace-escapes fmt table)))
6460 (defun org-make-org-heading-search-string (&optional string heading)
6461 "Make search string for STRING or current headline."
6462 (interactive)
6463 (let ((s (or string (org-get-heading))))
6464 (unless (and string (not heading))
6465 ;; We are using a headline, clean up garbage in there.
6466 (if (string-match org-todo-regexp s)
6467 (setq s (replace-match "" t t s)))
6468 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6469 (setq s (replace-match "" t t s)))
6470 (setq s (org-trim s))
6471 (if (string-match (concat "^\\(" org-quote-string "\\|"
6472 org-comment-string "\\)") s)
6473 (setq s (replace-match "" t t s)))
6474 (while (string-match org-ts-regexp s)
6475 (setq s (replace-match "" t t s))))
6476 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6477 (setq s (replace-match " " t t s)))
6478 (or string (setq s (concat "*" s))) ; Add * for headlines
6479 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6481 (defun org-make-link (&rest strings)
6482 "Concatenate STRINGS."
6483 (apply 'concat strings))
6485 (defun org-make-link-string (link &optional description)
6486 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6487 (unless (string-match "\\S-" link)
6488 (error "Empty link"))
6489 (when (stringp description)
6490 ;; Remove brackets from the description, they are fatal.
6491 (while (string-match "\\[" description)
6492 (setq description (replace-match "{" t t description)))
6493 (while (string-match "\\]" description)
6494 (setq description (replace-match "}" t t description))))
6495 (when (equal (org-link-escape link) description)
6496 ;; No description needed, it is identical
6497 (setq description nil))
6498 (when (and (not description)
6499 (not (equal link (org-link-escape link))))
6500 (setq description link))
6501 (concat "[[" (org-link-escape link) "]"
6502 (if description (concat "[" description "]") "")
6503 "]"))
6505 (defconst org-link-escape-chars
6506 '((?\ . "%20")
6507 (?\[ . "%5B")
6508 (?\] . "%5D")
6509 (?\340 . "%E0") ; `a
6510 (?\342 . "%E2") ; ^a
6511 (?\347 . "%E7") ; ,c
6512 (?\350 . "%E8") ; `e
6513 (?\351 . "%E9") ; 'e
6514 (?\352 . "%EA") ; ^e
6515 (?\356 . "%EE") ; ^i
6516 (?\364 . "%F4") ; ^o
6517 (?\371 . "%F9") ; `u
6518 (?\373 . "%FB") ; ^u
6519 (?\; . "%3B")
6520 (?? . "%3F")
6521 (?= . "%3D")
6522 (?+ . "%2B")
6524 "Association list of escapes for some characters problematic in links.
6525 This is the list that is used for internal purposes.")
6527 (defconst org-link-escape-chars-browser
6528 '((?\ . "%20")) ; 32 for the SPC char
6529 "Association list of escapes for some characters problematic in links.
6530 This is the list that is used before handing over to the browser.")
6532 (defun org-link-escape (text &optional table)
6533 "Escape charaters in TEXT that are problematic for links."
6534 (setq table (or table org-link-escape-chars))
6535 (when text
6536 (let ((re (mapconcat (lambda (x) (regexp-quote
6537 (char-to-string (car x))))
6538 table "\\|")))
6539 (while (string-match re text)
6540 (setq text
6541 (replace-match
6542 (cdr (assoc (string-to-char (match-string 0 text))
6543 table))
6544 t t text)))
6545 text)))
6547 (defun org-link-unescape (text &optional table)
6548 "Reverse the action of `org-link-escape'."
6549 (setq table (or table org-link-escape-chars))
6550 (when text
6551 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6552 table "\\|")))
6553 (while (string-match re text)
6554 (setq text
6555 (replace-match
6556 (char-to-string (car (rassoc (match-string 0 text) table)))
6557 t t text)))
6558 text)))
6560 (defun org-xor (a b)
6561 "Exclusive or."
6562 (if a (not b) b))
6564 (defun org-get-header (header)
6565 "Find a header field in the current buffer."
6566 (save-excursion
6567 (goto-char (point-min))
6568 (let ((case-fold-search t) s)
6569 (cond
6570 ((eq header 'from)
6571 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6572 (setq s (match-string 1)))
6573 (while (string-match "\"" s)
6574 (setq s (replace-match "" t t s)))
6575 (if (string-match "[<(].*" s)
6576 (setq s (replace-match "" t t s))))
6577 ((eq header 'message-id)
6578 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6579 (setq s (match-string 1))))
6580 ((eq header 'subject)
6581 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6582 (setq s (match-string 1)))))
6583 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6584 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6585 s)))
6588 (defun org-fixup-message-id-for-http (s)
6589 "Replace special characters in a message id, so it can be used in an http query."
6590 (while (string-match "<" s)
6591 (setq s (replace-match "%3C" t t s)))
6592 (while (string-match ">" s)
6593 (setq s (replace-match "%3E" t t s)))
6594 (while (string-match "@" s)
6595 (setq s (replace-match "%40" t t s)))
6598 ;;;###autoload
6599 (defun org-insert-link-global ()
6600 "Insert a link like Org-mode does.
6601 This command can be called in any mode to insert a link in Org-mode syntax."
6602 (interactive)
6603 (org-load-modules-maybe)
6604 (org-run-like-in-org-mode 'org-insert-link))
6606 (defun org-insert-link (&optional complete-file link-location)
6607 "Insert a link. At the prompt, enter the link.
6609 Completion can be used to select a link previously stored with
6610 `org-store-link'. When the empty string is entered (i.e. if you just
6611 press RET at the prompt), the link defaults to the most recently
6612 stored link. As SPC triggers completion in the minibuffer, you need to
6613 use M-SPC or C-q SPC to force the insertion of a space character.
6615 You will also be prompted for a description, and if one is given, it will
6616 be displayed in the buffer instead of the link.
6618 If there is already a link at point, this command will allow you to edit link
6619 and description parts.
6621 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6622 be selected using completion. The path to the file will be relative to the
6623 current directory if the file is in the current directory or a subdirectory.
6624 Otherwise, the link will be the absolute path as completed in the minibuffer
6625 \(i.e. normally ~/path/to/file).
6627 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6628 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6629 of `org-keep-stored-link-after-insertion'.
6631 If `org-make-link-description-function' is non-nil, this function will be
6632 called with the link target, and the result will be the default
6633 link description.
6635 If the LINK-LOCATION parameter is non-nil, this value will be
6636 used as the link location instead of reading one interactively."
6637 (interactive "P")
6638 (let* ((wcf (current-window-configuration))
6639 (region (if (org-region-active-p)
6640 (buffer-substring (region-beginning) (region-end))))
6641 (remove (and region (list (region-beginning) (region-end))))
6642 (desc region)
6643 tmphist ; byte-compile incorrectly complains about this
6644 (link link-location)
6645 entry file)
6646 (cond
6647 (link-location) ; specified by arg, just use it.
6648 ((org-in-regexp org-bracket-link-regexp 1)
6649 ;; We do have a link at point, and we are going to edit it.
6650 (setq remove (list (match-beginning 0) (match-end 0)))
6651 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6652 (setq link (read-string "Link: "
6653 (org-link-unescape
6654 (org-match-string-no-properties 1)))))
6655 ((or (org-in-regexp org-angle-link-re)
6656 (org-in-regexp org-plain-link-re))
6657 ;; Convert to bracket link
6658 (setq remove (list (match-beginning 0) (match-end 0))
6659 link (read-string "Link: "
6660 (org-remove-angle-brackets (match-string 0)))))
6661 ((equal complete-file '(4))
6662 ;; Completing read for file names.
6663 (setq file (read-file-name "File: "))
6664 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6665 (pwd1 (file-name-as-directory (abbreviate-file-name
6666 (expand-file-name ".")))))
6667 (cond
6668 ((equal complete-file '(16))
6669 (setq link (org-make-link
6670 "file:"
6671 (abbreviate-file-name (expand-file-name file)))))
6672 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6673 (setq link (org-make-link "file:" (match-string 1 file))))
6674 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6675 (expand-file-name file))
6676 (setq link (org-make-link
6677 "file:" (match-string 1 (expand-file-name file)))))
6678 (t (setq link (org-make-link "file:" file))))))
6680 ;; Read link, with completion for stored links.
6681 (with-output-to-temp-buffer "*Org Links*"
6682 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6683 (when org-stored-links
6684 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6685 (princ (mapconcat
6686 (lambda (x)
6687 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6688 (reverse org-stored-links) "\n"))))
6689 (let ((cw (selected-window)))
6690 (select-window (get-buffer-window "*Org Links*"))
6691 (shrink-window-if-larger-than-buffer)
6692 (setq truncate-lines t)
6693 (select-window cw))
6694 ;; Fake a link history, containing the stored links.
6695 (setq tmphist (append (mapcar 'car org-stored-links)
6696 org-insert-link-history))
6697 (unwind-protect
6698 (setq link (org-completing-read
6699 "Link: "
6700 (append
6701 (mapcar (lambda (x) (list (concat (car x) ":")))
6702 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6703 (mapcar (lambda (x) (list (concat x ":")))
6704 org-link-types))
6705 nil nil nil
6706 'tmphist
6707 (or (car (car org-stored-links)))))
6708 (set-window-configuration wcf)
6709 (kill-buffer "*Org Links*"))
6710 (setq entry (assoc link org-stored-links))
6711 (or entry (push link org-insert-link-history))
6712 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6713 (not org-keep-stored-link-after-insertion))
6714 (setq org-stored-links (delq (assoc link org-stored-links)
6715 org-stored-links)))
6716 (setq desc (or desc (nth 1 entry)))))
6718 (if (string-match org-plain-link-re link)
6719 ;; URL-like link, normalize the use of angular brackets.
6720 (setq link (org-make-link (org-remove-angle-brackets link))))
6722 ;; Check if we are linking to the current file with a search option
6723 ;; If yes, simplify the link by using only the search option.
6724 (when (and buffer-file-name
6725 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6726 (let* ((path (match-string 1 link))
6727 (case-fold-search nil)
6728 (search (match-string 2 link)))
6729 (save-match-data
6730 (if (equal (file-truename buffer-file-name) (file-truename path))
6731 ;; We are linking to this same file, with a search option
6732 (setq link search)))))
6734 ;; Check if we can/should use a relative path. If yes, simplify the link
6735 (when (string-match "\\<file:\\(.*\\)" link)
6736 (let* ((path (match-string 1 link))
6737 (origpath path)
6738 (case-fold-search nil))
6739 (cond
6740 ((eq org-link-file-path-type 'absolute)
6741 (setq path (abbreviate-file-name (expand-file-name path))))
6742 ((eq org-link-file-path-type 'noabbrev)
6743 (setq path (expand-file-name path)))
6744 ((eq org-link-file-path-type 'relative)
6745 (setq path (file-relative-name path)))
6747 (save-match-data
6748 (if (string-match (concat "^" (regexp-quote
6749 (file-name-as-directory
6750 (expand-file-name "."))))
6751 (expand-file-name path))
6752 ;; We are linking a file with relative path name.
6753 (setq path (substring (expand-file-name path)
6754 (match-end 0)))))))
6755 (setq link (concat "file:" path))
6756 (if (equal desc origpath)
6757 (setq desc path))))
6759 (if org-make-link-description-function
6760 (setq desc (funcall org-make-link-description-function link desc)))
6762 (setq desc (read-string "Description: " desc))
6763 (unless (string-match "\\S-" desc) (setq desc nil))
6764 (if remove (apply 'delete-region remove))
6765 (insert (org-make-link-string link desc))))
6767 (defun org-completing-read (&rest args)
6768 (let ((minibuffer-local-completion-map
6769 (copy-keymap minibuffer-local-completion-map)))
6770 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6771 (apply 'completing-read args)))
6773 ;;; Opening/following a link
6775 (defvar org-link-search-failed nil)
6777 (defun org-next-link ()
6778 "Move forward to the next link.
6779 If the link is in hidden text, expose it."
6780 (interactive)
6781 (when (and org-link-search-failed (eq this-command last-command))
6782 (goto-char (point-min))
6783 (message "Link search wrapped back to beginning of buffer"))
6784 (setq org-link-search-failed nil)
6785 (let* ((pos (point))
6786 (ct (org-context))
6787 (a (assoc :link ct)))
6788 (if a (goto-char (nth 2 a)))
6789 (if (re-search-forward org-any-link-re nil t)
6790 (progn
6791 (goto-char (match-beginning 0))
6792 (if (org-invisible-p) (org-show-context)))
6793 (goto-char pos)
6794 (setq org-link-search-failed t)
6795 (error "No further link found"))))
6797 (defun org-previous-link ()
6798 "Move backward to the previous link.
6799 If the link is in hidden text, expose it."
6800 (interactive)
6801 (when (and org-link-search-failed (eq this-command last-command))
6802 (goto-char (point-max))
6803 (message "Link search wrapped back to end of buffer"))
6804 (setq org-link-search-failed nil)
6805 (let* ((pos (point))
6806 (ct (org-context))
6807 (a (assoc :link ct)))
6808 (if a (goto-char (nth 1 a)))
6809 (if (re-search-backward org-any-link-re nil t)
6810 (progn
6811 (goto-char (match-beginning 0))
6812 (if (org-invisible-p) (org-show-context)))
6813 (goto-char pos)
6814 (setq org-link-search-failed t)
6815 (error "No further link found"))))
6817 (defun org-find-file-at-mouse (ev)
6818 "Open file link or URL at mouse."
6819 (interactive "e")
6820 (mouse-set-point ev)
6821 (org-open-at-point 'in-emacs))
6823 (defun org-open-at-mouse (ev)
6824 "Open file link or URL at mouse."
6825 (interactive "e")
6826 (mouse-set-point ev)
6827 (org-open-at-point))
6829 (defvar org-window-config-before-follow-link nil
6830 "The window configuration before following a link.
6831 This is saved in case the need arises to restore it.")
6833 (defvar org-open-link-marker (make-marker)
6834 "Marker pointing to the location where `org-open-at-point; was called.")
6836 ;;;###autoload
6837 (defun org-open-at-point-global ()
6838 "Follow a link like Org-mode does.
6839 This command can be called in any mode to follow a link that has
6840 Org-mode syntax."
6841 (interactive)
6842 (org-run-like-in-org-mode 'org-open-at-point))
6844 ;;;###autoload
6845 (defun org-open-link-from-string (s &optional arg)
6846 "Open a link in the string S, as if it was in Org-mode."
6847 (interactive "sLink: \nP")
6848 (with-temp-buffer
6849 (let ((org-inhibit-startup t))
6850 (org-mode)
6851 (insert s)
6852 (goto-char (point-min))
6853 (org-open-at-point arg))))
6855 (defun org-open-at-point (&optional in-emacs)
6856 "Open link at or after point.
6857 If there is no link at point, this function will search forward up to
6858 the end of the current subtree.
6859 Normally, files will be opened by an appropriate application. If the
6860 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6861 (interactive "P")
6862 (org-load-modules-maybe)
6863 (move-marker org-open-link-marker (point))
6864 (setq org-window-config-before-follow-link (current-window-configuration))
6865 (org-remove-occur-highlights nil nil t)
6866 (if (org-at-timestamp-p t)
6867 (org-follow-timestamp-link)
6868 (let (type path link line search (pos (point)))
6869 (catch 'match
6870 (save-excursion
6871 (skip-chars-forward "^]\n\r")
6872 (when (org-in-regexp org-bracket-link-regexp)
6873 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6874 (while (string-match " *\n *" link)
6875 (setq link (replace-match " " t t link)))
6876 (setq link (org-link-expand-abbrev link))
6877 (if (string-match org-link-re-with-space2 link)
6878 (setq type (match-string 1 link) path (match-string 2 link))
6879 (setq type "thisfile" path link))
6880 (throw 'match t)))
6882 (when (get-text-property (point) 'org-linked-text)
6883 (setq type "thisfile"
6884 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6885 (1+ (point)) (point))
6886 path (buffer-substring
6887 (previous-single-property-change pos 'org-linked-text)
6888 (next-single-property-change pos 'org-linked-text)))
6889 (throw 'match t))
6891 (save-excursion
6892 (when (or (org-in-regexp org-angle-link-re)
6893 (org-in-regexp org-plain-link-re))
6894 (setq type (match-string 1) path (match-string 2))
6895 (throw 'match t)))
6896 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6897 (setq type "tree-match"
6898 path (match-string 1))
6899 (throw 'match t))
6900 (save-excursion
6901 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6902 (setq type "tags"
6903 path (match-string 1))
6904 (while (string-match ":" path)
6905 (setq path (replace-match "+" t t path)))
6906 (throw 'match t))))
6907 (unless path
6908 (error "No link found"))
6909 ;; Remove any trailing spaces in path
6910 (if (string-match " +\\'" path)
6911 (setq path (replace-match "" t t path)))
6913 (cond
6915 ((assoc type org-link-protocols)
6916 (funcall (nth 1 (assoc type org-link-protocols)) path))
6918 ((equal type "mailto")
6919 (let ((cmd (car org-link-mailto-program))
6920 (args (cdr org-link-mailto-program)) args1
6921 (address path) (subject "") a)
6922 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6923 (setq address (match-string 1 path)
6924 subject (org-link-escape (match-string 2 path))))
6925 (while args
6926 (cond
6927 ((not (stringp (car args))) (push (pop args) args1))
6928 (t (setq a (pop args))
6929 (if (string-match "%a" a)
6930 (setq a (replace-match address t t a)))
6931 (if (string-match "%s" a)
6932 (setq a (replace-match subject t t a)))
6933 (push a args1))))
6934 (apply cmd (nreverse args1))))
6936 ((member type '("http" "https" "ftp" "news"))
6937 (browse-url (concat type ":" (org-link-escape
6938 path org-link-escape-chars-browser))))
6940 ((member type '("message"))
6941 (browse-url (concat type ":" path)))
6943 ((string= type "tags")
6944 (org-tags-view in-emacs path))
6945 ((string= type "thisfile")
6946 (if in-emacs
6947 (switch-to-buffer-other-window
6948 (org-get-buffer-for-internal-link (current-buffer)))
6949 (org-mark-ring-push))
6950 (let ((cmd `(org-link-search
6951 ,path
6952 ,(cond ((equal in-emacs '(4)) 'occur)
6953 ((equal in-emacs '(16)) 'org-occur)
6954 (t nil))
6955 ,pos)))
6956 (condition-case nil (eval cmd)
6957 (error (progn (widen) (eval cmd))))))
6959 ((string= type "tree-match")
6960 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6962 ((string= type "file")
6963 (if (string-match "::\\([0-9]+\\)\\'" path)
6964 (setq line (string-to-number (match-string 1 path))
6965 path (substring path 0 (match-beginning 0)))
6966 (if (string-match "::\\(.+\\)\\'" path)
6967 (setq search (match-string 1 path)
6968 path (substring path 0 (match-beginning 0)))))
6969 (if (string-match "[*?{]" (file-name-nondirectory path))
6970 (dired path)
6971 (org-open-file path in-emacs line search)))
6973 ((string= type "news")
6974 (require 'org-gnus)
6975 (org-gnus-follow-link path))
6977 ((string= type "shell")
6978 (let ((cmd path))
6979 (if (or (not org-confirm-shell-link-function)
6980 (funcall org-confirm-shell-link-function
6981 (format "Execute \"%s\" in shell? "
6982 (org-add-props cmd nil
6983 'face 'org-warning))))
6984 (progn
6985 (message "Executing %s" cmd)
6986 (shell-command cmd))
6987 (error "Abort"))))
6989 ((string= type "elisp")
6990 (let ((cmd path))
6991 (if (or (not org-confirm-elisp-link-function)
6992 (funcall org-confirm-elisp-link-function
6993 (format "Execute \"%s\" as elisp? "
6994 (org-add-props cmd nil
6995 'face 'org-warning))))
6996 (message "%s => %s" cmd (eval (read cmd)))
6997 (error "Abort"))))
7000 (browse-url-at-point)))))
7001 (move-marker org-open-link-marker nil)
7002 (run-hook-with-args 'org-follow-link-hook))
7004 ;;;; Time estimates
7006 (defun org-get-effort (&optional pom)
7007 "Get the effort estimate for the current entry."
7008 (org-entry-get pom org-effort-property))
7010 ;;; File search
7012 (defvar org-create-file-search-functions nil
7013 "List of functions to construct the right search string for a file link.
7014 These functions are called in turn with point at the location to
7015 which the link should point.
7017 A function in the hook should first test if it would like to
7018 handle this file type, for example by checking the major-mode or
7019 the file extension. If it decides not to handle this file, it
7020 should just return nil to give other functions a chance. If it
7021 does handle the file, it must return the search string to be used
7022 when following the link. The search string will be part of the
7023 file link, given after a double colon, and `org-open-at-point'
7024 will automatically search for it. If special measures must be
7025 taken to make the search successful, another function should be
7026 added to the companion hook `org-execute-file-search-functions',
7027 which see.
7029 A function in this hook may also use `setq' to set the variable
7030 `description' to provide a suggestion for the descriptive text to
7031 be used for this link when it gets inserted into an Org-mode
7032 buffer with \\[org-insert-link].")
7034 (defvar org-execute-file-search-functions nil
7035 "List of functions to execute a file search triggered by a link.
7037 Functions added to this hook must accept a single argument, the
7038 search string that was part of the file link, the part after the
7039 double colon. The function must first check if it would like to
7040 handle this search, for example by checking the major-mode or the
7041 file extension. If it decides not to handle this search, it
7042 should just return nil to give other functions a chance. If it
7043 does handle the search, it must return a non-nil value to keep
7044 other functions from trying.
7046 Each function can access the current prefix argument through the
7047 variable `current-prefix-argument'. Note that a single prefix is
7048 used to force opening a link in Emacs, so it may be good to only
7049 use a numeric or double prefix to guide the search function.
7051 In case this is needed, a function in this hook can also restore
7052 the window configuration before `org-open-at-point' was called using:
7054 (set-window-configuration org-window-config-before-follow-link)")
7056 (defun org-link-search (s &optional type avoid-pos)
7057 "Search for a link search option.
7058 If S is surrounded by forward slashes, it is interpreted as a
7059 regular expression. In org-mode files, this will create an `org-occur'
7060 sparse tree. In ordinary files, `occur' will be used to list matches.
7061 If the current buffer is in `dired-mode', grep will be used to search
7062 in all files. If AVOID-POS is given, ignore matches near that position."
7063 (let ((case-fold-search t)
7064 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7065 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7066 (append '(("") (" ") ("\t") ("\n"))
7067 org-emphasis-alist)
7068 "\\|") "\\)"))
7069 (pos (point))
7070 (pre nil) (post nil)
7071 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7072 (cond
7073 ;; First check if there are any special
7074 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7075 ;; Now try the builtin stuff
7076 ((save-excursion
7077 (goto-char (point-min))
7078 (and
7079 (re-search-forward
7080 (concat "<<" (regexp-quote s0) ">>") nil t)
7081 (setq type 'dedicated
7082 pos (match-beginning 0))))
7083 ;; There is an exact target for this
7084 (goto-char pos))
7085 ((string-match "^/\\(.*\\)/$" s)
7086 ;; A regular expression
7087 (cond
7088 ((org-mode-p)
7089 (org-occur (match-string 1 s)))
7090 ;;((eq major-mode 'dired-mode)
7091 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7092 (t (org-do-occur (match-string 1 s)))))
7094 ;; A normal search strings
7095 (when (equal (string-to-char s) ?*)
7096 ;; Anchor on headlines, post may include tags.
7097 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7098 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7099 s (substring s 1)))
7100 (remove-text-properties
7101 0 (length s)
7102 '(face nil mouse-face nil keymap nil fontified nil) s)
7103 ;; Make a series of regular expressions to find a match
7104 (setq words (org-split-string s "[ \n\r\t]+")
7106 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7107 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7108 "\\)" markers)
7109 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7110 re2a (concat "[ \t\r\n]" re2a_)
7111 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7112 re4 (concat "[^a-zA-Z_]" re4_)
7114 re1 (concat pre re2 post)
7115 re3 (concat pre (if pre re4_ re4) post)
7116 re5 (concat pre ".*" re4)
7117 re2 (concat pre re2)
7118 re2a (concat pre (if pre re2a_ re2a))
7119 re4 (concat pre (if pre re4_ re4))
7120 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7121 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7122 re5 "\\)"
7124 (cond
7125 ((eq type 'org-occur) (org-occur reall))
7126 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7127 (t (goto-char (point-min))
7128 (setq type 'fuzzy)
7129 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7130 (org-search-not-self 1 re1 nil t)
7131 (org-search-not-self 1 re2 nil t)
7132 (org-search-not-self 1 re2a nil t)
7133 (org-search-not-self 1 re3 nil t)
7134 (org-search-not-self 1 re4 nil t)
7135 (org-search-not-self 1 re5 nil t)
7137 (goto-char (match-beginning 1))
7138 (goto-char pos)
7139 (error "No match")))))
7141 ;; Normal string-search
7142 (goto-char (point-min))
7143 (if (search-forward s nil t)
7144 (goto-char (match-beginning 0))
7145 (error "No match"))))
7146 (and (org-mode-p) (org-show-context 'link-search))
7147 type))
7149 (defun org-search-not-self (group &rest args)
7150 "Execute `re-search-forward', but only accept matches that do not
7151 enclose the position of `org-open-link-marker'."
7152 (let ((m org-open-link-marker))
7153 (catch 'exit
7154 (while (apply 're-search-forward args)
7155 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7156 (goto-char (match-end group))
7157 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7158 (> (match-beginning 0) (marker-position m))
7159 (< (match-end 0) (marker-position m)))
7160 (save-match-data
7161 (or (not (org-in-regexp
7162 org-bracket-link-analytic-regexp 1))
7163 (not (match-end 4)) ; no description
7164 (and (<= (match-beginning 4) (point))
7165 (>= (match-end 4) (point))))))
7166 (throw 'exit (point))))))))
7168 (defun org-get-buffer-for-internal-link (buffer)
7169 "Return a buffer to be used for displaying the link target of internal links."
7170 (cond
7171 ((not org-display-internal-link-with-indirect-buffer)
7172 buffer)
7173 ((string-match "(Clone)$" (buffer-name buffer))
7174 (message "Buffer is already a clone, not making another one")
7175 ;; we also do not modify visibility in this case
7176 buffer)
7177 (t ; make a new indirect buffer for displaying the link
7178 (let* ((bn (buffer-name buffer))
7179 (ibn (concat bn "(Clone)"))
7180 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7181 (with-current-buffer ib (org-overview))
7182 ib))))
7184 (defun org-do-occur (regexp &optional cleanup)
7185 "Call the Emacs command `occur'.
7186 If CLEANUP is non-nil, remove the printout of the regular expression
7187 in the *Occur* buffer. This is useful if the regex is long and not useful
7188 to read."
7189 (occur regexp)
7190 (when cleanup
7191 (let ((cwin (selected-window)) win beg end)
7192 (when (setq win (get-buffer-window "*Occur*"))
7193 (select-window win))
7194 (goto-char (point-min))
7195 (when (re-search-forward "match[a-z]+" nil t)
7196 (setq beg (match-end 0))
7197 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7198 (setq end (1- (match-beginning 0)))))
7199 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7200 (goto-char (point-min))
7201 (select-window cwin))))
7203 ;;; The mark ring for links jumps
7205 (defvar org-mark-ring nil
7206 "Mark ring for positions before jumps in Org-mode.")
7207 (defvar org-mark-ring-last-goto nil
7208 "Last position in the mark ring used to go back.")
7209 ;; Fill and close the ring
7210 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7211 (loop for i from 1 to org-mark-ring-length do
7212 (push (make-marker) org-mark-ring))
7213 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7214 org-mark-ring)
7216 (defun org-mark-ring-push (&optional pos buffer)
7217 "Put the current position or POS into the mark ring and rotate it."
7218 (interactive)
7219 (setq pos (or pos (point)))
7220 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7221 (move-marker (car org-mark-ring)
7222 (or pos (point))
7223 (or buffer (current-buffer)))
7224 (message "%s"
7225 (substitute-command-keys
7226 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7228 (defun org-mark-ring-goto (&optional n)
7229 "Jump to the previous position in the mark ring.
7230 With prefix arg N, jump back that many stored positions. When
7231 called several times in succession, walk through the entire ring.
7232 Org-mode commands jumping to a different position in the current file,
7233 or to another Org-mode file, automatically push the old position
7234 onto the ring."
7235 (interactive "p")
7236 (let (p m)
7237 (if (eq last-command this-command)
7238 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7239 (setq p org-mark-ring))
7240 (setq org-mark-ring-last-goto p)
7241 (setq m (car p))
7242 (switch-to-buffer (marker-buffer m))
7243 (goto-char m)
7244 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7246 (defun org-remove-angle-brackets (s)
7247 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7248 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7250 (defun org-add-angle-brackets (s)
7251 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7252 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7254 (defun org-remove-double-quotes (s)
7255 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7256 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7259 ;;; Following specific links
7261 (defun org-follow-timestamp-link ()
7262 (cond
7263 ((org-at-date-range-p t)
7264 (let ((org-agenda-start-on-weekday)
7265 (t1 (match-string 1))
7266 (t2 (match-string 2)))
7267 (setq t1 (time-to-days (org-time-string-to-time t1))
7268 t2 (time-to-days (org-time-string-to-time t2)))
7269 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7270 ((org-at-timestamp-p t)
7271 (org-agenda-list nil (time-to-days (org-time-string-to-time
7272 (substring (match-string 1) 0 10)))
7274 (t (error "This should not happen"))))
7277 ;;; Following file links
7278 (defvar org-wait nil)
7279 (defun org-open-file (path &optional in-emacs line search)
7280 "Open the file at PATH.
7281 First, this expands any special file name abbreviations. Then the
7282 configuration variable `org-file-apps' is checked if it contains an
7283 entry for this file type, and if yes, the corresponding command is launched.
7284 If no application is found, Emacs simply visits the file.
7285 With optional argument IN-EMACS, Emacs will visit the file.
7286 Optional LINE specifies a line to go to, optional SEARCH a string to
7287 search for. If LINE or SEARCH is given, the file will always be
7288 opened in Emacs.
7289 If the file does not exist, an error is thrown."
7290 (setq in-emacs (or in-emacs line search))
7291 (let* ((file (if (equal path "")
7292 buffer-file-name
7293 (substitute-in-file-name (expand-file-name path))))
7294 (apps (append org-file-apps (org-default-apps)))
7295 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7296 (dirp (if remp nil (file-directory-p file)))
7297 (dfile (downcase file))
7298 (old-buffer (current-buffer))
7299 (old-pos (point))
7300 (old-mode major-mode)
7301 ext cmd)
7302 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7303 (setq ext (match-string 1 dfile))
7304 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7305 (setq ext (match-string 1 dfile))))
7306 (if in-emacs
7307 (setq cmd 'emacs)
7308 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7309 (and dirp (cdr (assoc 'directory apps)))
7310 (cdr (assoc ext apps))
7311 (cdr (assoc t apps)))))
7312 (when (eq cmd 'mailcap)
7313 (require 'mailcap)
7314 (mailcap-parse-mailcaps)
7315 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7316 (command (mailcap-mime-info mime-type)))
7317 (if (stringp command)
7318 (setq cmd command)
7319 (setq cmd 'emacs))))
7320 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7321 (not (file-exists-p file))
7322 (not org-open-non-existing-files))
7323 (error "No such file: %s" file))
7324 (cond
7325 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7326 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7327 (while (string-match "['\"]%s['\"]" cmd)
7328 (setq cmd (replace-match "%s" t t cmd)))
7329 (while (string-match "%s" cmd)
7330 (setq cmd (replace-match
7331 (save-match-data (shell-quote-argument file))
7332 t t cmd)))
7333 (save-window-excursion
7334 (start-process-shell-command cmd nil cmd)
7335 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7337 ((or (stringp cmd)
7338 (eq cmd 'emacs))
7339 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7340 (widen)
7341 (if line (goto-line line)
7342 (if search (org-link-search search))))
7343 ((consp cmd)
7344 (eval cmd))
7345 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7346 (and (org-mode-p) (eq old-mode 'org-mode)
7347 (or (not (equal old-buffer (current-buffer)))
7348 (not (equal old-pos (point))))
7349 (org-mark-ring-push old-pos old-buffer))))
7351 (defun org-default-apps ()
7352 "Return the default applications for this operating system."
7353 (cond
7354 ((eq system-type 'darwin)
7355 org-file-apps-defaults-macosx)
7356 ((eq system-type 'windows-nt)
7357 org-file-apps-defaults-windowsnt)
7358 (t org-file-apps-defaults-gnu)))
7360 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7361 (defun org-file-remote-p (file)
7362 "Test whether FILE specifies a location on a remote system.
7363 Return non-nil if the location is indeed remote.
7365 For example, the filename \"/user@host:/foo\" specifies a location
7366 on the system \"/user@host:\"."
7367 (cond ((fboundp 'file-remote-p)
7368 (file-remote-p file))
7369 ((fboundp 'tramp-handle-file-remote-p)
7370 (tramp-handle-file-remote-p file))
7371 ((and (boundp 'ange-ftp-name-format)
7372 (string-match (car ange-ftp-name-format) file))
7374 (t nil)))
7377 ;;;; Refiling
7379 (defun org-get-org-file ()
7380 "Read a filename, with default directory `org-directory'."
7381 (let ((default (or org-default-notes-file remember-data-file)))
7382 (read-file-name (format "File name [%s]: " default)
7383 (file-name-as-directory org-directory)
7384 default)))
7386 (defun org-notes-order-reversed-p ()
7387 "Check if the current file should receive notes in reversed order."
7388 (cond
7389 ((not org-reverse-note-order) nil)
7390 ((eq t org-reverse-note-order) t)
7391 ((not (listp org-reverse-note-order)) nil)
7392 (t (catch 'exit
7393 (let ((all org-reverse-note-order)
7394 entry)
7395 (while (setq entry (pop all))
7396 (if (string-match (car entry) buffer-file-name)
7397 (throw 'exit (cdr entry))))
7398 nil)))))
7400 (defvar org-refile-target-table nil
7401 "The list of refile targets, created by `org-refile'.")
7403 (defvar org-agenda-new-buffers nil
7404 "Buffers created to visit agenda files.")
7406 (defun org-get-refile-targets (&optional default-buffer)
7407 "Produce a table with refile targets."
7408 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7409 targets txt re files f desc descre)
7410 (with-current-buffer (or default-buffer (current-buffer))
7411 (while (setq entry (pop entries))
7412 (setq files (car entry) desc (cdr entry))
7413 (cond
7414 ((null files) (setq files (list (current-buffer))))
7415 ((eq files 'org-agenda-files)
7416 (setq files (org-agenda-files 'unrestricted)))
7417 ((and (symbolp files) (fboundp files))
7418 (setq files (funcall files)))
7419 ((and (symbolp files) (boundp files))
7420 (setq files (symbol-value files))))
7421 (if (stringp files) (setq files (list files)))
7422 (cond
7423 ((eq (car desc) :tag)
7424 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7425 ((eq (car desc) :todo)
7426 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7427 ((eq (car desc) :regexp)
7428 (setq descre (cdr desc)))
7429 ((eq (car desc) :level)
7430 (setq descre (concat "^\\*\\{" (number-to-string
7431 (if org-odd-levels-only
7432 (1- (* 2 (cdr desc)))
7433 (cdr desc)))
7434 "\\}[ \t]")))
7435 ((eq (car desc) :maxlevel)
7436 (setq descre (concat "^\\*\\{1," (number-to-string
7437 (if org-odd-levels-only
7438 (1- (* 2 (cdr desc)))
7439 (cdr desc)))
7440 "\\}[ \t]")))
7441 (t (error "Bad refiling target description %s" desc)))
7442 (while (setq f (pop files))
7443 (save-excursion
7444 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7445 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7446 (save-excursion
7447 (save-restriction
7448 (widen)
7449 (goto-char (point-min))
7450 (while (re-search-forward descre nil t)
7451 (goto-char (point-at-bol))
7452 (when (looking-at org-complex-heading-regexp)
7453 (setq txt (match-string 4)
7454 re (concat "^" (regexp-quote
7455 (buffer-substring (match-beginning 1)
7456 (match-end 4)))))
7457 (if (match-end 5) (setq re (concat re "[ \t]+"
7458 (regexp-quote
7459 (match-string 5)))))
7460 (setq re (concat re "[ \t]*$"))
7461 (when org-refile-use-outline-path
7462 (setq txt (mapconcat 'identity
7463 (append
7464 (if (eq org-refile-use-outline-path 'file)
7465 (list (file-name-nondirectory
7466 (buffer-file-name (buffer-base-buffer))))
7467 (if (eq org-refile-use-outline-path 'full-file-path)
7468 (list (buffer-file-name (buffer-base-buffer)))))
7469 (org-get-outline-path)
7470 (list txt))
7471 "/")))
7472 (push (list txt f re (point)) targets))
7473 (goto-char (point-at-eol))))))))
7474 (nreverse targets))))
7476 (defun org-get-outline-path ()
7477 "Return the outline path to the current entry, as a list."
7478 (let (rtn)
7479 (save-excursion
7480 (while (org-up-heading-safe)
7481 (when (looking-at org-complex-heading-regexp)
7482 (push (org-match-string-no-properties 4) rtn)))
7483 rtn)))
7485 (defvar org-refile-history nil
7486 "History for refiling operations.")
7488 (defun org-refile (&optional goto default-buffer)
7489 "Move the entry at point to another heading.
7490 The list of target headings is compiled using the information in
7491 `org-refile-targets', which see. This list is created before each use
7492 and will therefore always be up-to-date.
7494 At the target location, the entry is filed as a subitem of the target heading.
7495 Depending on `org-reverse-note-order', the new subitem will either be the
7496 first of the last subitem.
7498 With prefix arg GOTO, the command will only visit the target location,
7499 not actually move anything.
7500 With a double prefix `C-c C-c', go to the location where the last refiling
7501 operation has put the subtree."
7502 (interactive "P")
7503 (let* ((cbuf (current-buffer))
7504 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7505 pos it nbuf file re level reversed)
7506 (if (equal goto '(16))
7507 (org-refile-goto-last-stored)
7508 (when (setq it (org-refile-get-location
7509 (if goto "Goto: " "Refile to: ") default-buffer))
7510 (setq file (nth 1 it)
7511 re (nth 2 it)
7512 pos (nth 3 it))
7513 (setq nbuf (or (find-buffer-visiting file)
7514 (find-file-noselect file)))
7515 (if goto
7516 (progn
7517 (switch-to-buffer nbuf)
7518 (goto-char pos)
7519 (org-show-context 'org-goto))
7520 (org-copy-subtree 1 nil t)
7521 (save-excursion
7522 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7523 (find-file-noselect file))))
7524 (setq reversed (org-notes-order-reversed-p))
7525 (save-excursion
7526 (save-restriction
7527 (widen)
7528 (goto-char pos)
7529 (looking-at outline-regexp)
7530 (setq level (org-get-valid-level (funcall outline-level) 1))
7531 (goto-char
7532 (if reversed
7533 (outline-next-heading)
7534 (or (save-excursion (outline-get-next-sibling))
7535 (org-end-of-subtree t t)
7536 (point-max))))
7537 (bookmark-set "org-refile-last-stored")
7538 (org-paste-subtree level))))
7539 (org-cut-subtree)
7540 (setq org-markers-to-move nil)
7541 (message "Entry refiled to \"%s\"" (car it)))))))
7543 (defun org-refile-goto-last-stored ()
7544 "Go to the location where the last refile was stored."
7545 (interactive)
7546 (bookmark-jump "org-refile-last-stored")
7547 (message "This is the location of the last refile"))
7549 (defun org-refile-get-location (&optional prompt default-buffer)
7550 "Prompt the user for a refile location, using PROMPT."
7551 (let ((org-refile-targets org-refile-targets)
7552 (org-refile-use-outline-path org-refile-use-outline-path))
7553 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7554 (unless org-refile-target-table
7555 (error "No refile targets"))
7556 (let* ((cbuf (current-buffer))
7557 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7558 (fname (and filename (file-truename filename)))
7559 (tbl (mapcar
7560 (lambda (x)
7561 (if (not (equal fname (file-truename (nth 1 x))))
7562 (cons (concat (car x) " (" (file-name-nondirectory
7563 (nth 1 x)) ")")
7564 (cdr x))
7566 org-refile-target-table))
7567 (completion-ignore-case t))
7568 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7569 tbl)))
7571 ;;;; Dynamic blocks
7573 (defun org-find-dblock (name)
7574 "Find the first dynamic block with name NAME in the buffer.
7575 If not found, stay at current position and return nil."
7576 (let (pos)
7577 (save-excursion
7578 (goto-char (point-min))
7579 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7580 nil t)
7581 (match-beginning 0))))
7582 (if pos (goto-char pos))
7583 pos))
7585 (defconst org-dblock-start-re
7586 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7587 "Matches the startline of a dynamic block, with parameters.")
7589 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7590 "Matches the end of a dyhamic block.")
7592 (defun org-create-dblock (plist)
7593 "Create a dynamic block section, with parameters taken from PLIST.
7594 PLIST must containe a :name entry which is used as name of the block."
7595 (unless (bolp) (newline))
7596 (let ((name (plist-get plist :name)))
7597 (insert "#+BEGIN: " name)
7598 (while plist
7599 (if (eq (car plist) :name)
7600 (setq plist (cddr plist))
7601 (insert " " (prin1-to-string (pop plist)))))
7602 (insert "\n\n#+END:\n")
7603 (beginning-of-line -2)))
7605 (defun org-prepare-dblock ()
7606 "Prepare dynamic block for refresh.
7607 This empties the block, puts the cursor at the insert position and returns
7608 the property list including an extra property :name with the block name."
7609 (unless (looking-at org-dblock-start-re)
7610 (error "Not at a dynamic block"))
7611 (let* ((begdel (1+ (match-end 0)))
7612 (name (org-no-properties (match-string 1)))
7613 (params (append (list :name name)
7614 (read (concat "(" (match-string 3) ")")))))
7615 (unless (re-search-forward org-dblock-end-re nil t)
7616 (error "Dynamic block not terminated"))
7617 (setq params
7618 (append params
7619 (list :content (buffer-substring
7620 begdel (match-beginning 0)))))
7621 (delete-region begdel (match-beginning 0))
7622 (goto-char begdel)
7623 (open-line 1)
7624 params))
7626 (defun org-map-dblocks (&optional command)
7627 "Apply COMMAND to all dynamic blocks in the current buffer.
7628 If COMMAND is not given, use `org-update-dblock'."
7629 (let ((cmd (or command 'org-update-dblock))
7630 pos)
7631 (save-excursion
7632 (goto-char (point-min))
7633 (while (re-search-forward org-dblock-start-re nil t)
7634 (goto-char (setq pos (match-beginning 0)))
7635 (condition-case nil
7636 (funcall cmd)
7637 (error (message "Error during update of dynamic block")))
7638 (goto-char pos)
7639 (unless (re-search-forward org-dblock-end-re nil t)
7640 (error "Dynamic block not terminated"))))))
7642 (defun org-dblock-update (&optional arg)
7643 "User command for updating dynamic blocks.
7644 Update the dynamic block at point. With prefix ARG, update all dynamic
7645 blocks in the buffer."
7646 (interactive "P")
7647 (if arg
7648 (org-update-all-dblocks)
7649 (or (looking-at org-dblock-start-re)
7650 (org-beginning-of-dblock))
7651 (org-update-dblock)))
7653 (defun org-update-dblock ()
7654 "Update the dynamic block at point
7655 This means to empty the block, parse for parameters and then call
7656 the correct writing function."
7657 (save-window-excursion
7658 (let* ((pos (point))
7659 (line (org-current-line))
7660 (params (org-prepare-dblock))
7661 (name (plist-get params :name))
7662 (cmd (intern (concat "org-dblock-write:" name))))
7663 (message "Updating dynamic block `%s' at line %d..." name line)
7664 (funcall cmd params)
7665 (message "Updating dynamic block `%s' at line %d...done" name line)
7666 (goto-char pos))))
7668 (defun org-beginning-of-dblock ()
7669 "Find the beginning of the dynamic block at point.
7670 Error if there is no scuh block at point."
7671 (let ((pos (point))
7672 beg)
7673 (end-of-line 1)
7674 (if (and (re-search-backward org-dblock-start-re nil t)
7675 (setq beg (match-beginning 0))
7676 (re-search-forward org-dblock-end-re nil t)
7677 (> (match-end 0) pos))
7678 (goto-char beg)
7679 (goto-char pos)
7680 (error "Not in a dynamic block"))))
7682 (defun org-update-all-dblocks ()
7683 "Update all dynamic blocks in the buffer.
7684 This function can be used in a hook."
7685 (when (org-mode-p)
7686 (org-map-dblocks 'org-update-dblock)))
7689 ;;;; Completion
7691 (defconst org-additional-option-like-keywords
7692 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7693 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7694 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7696 (defcustom org-structure-template-alist
7698 ("s" "#+begin_src ?\n\n#+end_src"
7699 "<src lang=\"?\">\n\n</src>")
7700 ("e" "#+begin_example\n?\n#+end_example"
7701 "<example>\n?\n</example>")
7702 ("q" "#+begin_quote\n?\n#+end_quote"
7703 "<quote>\n?\n</quote>")
7704 ("v" "#+begin_verse\n?\n#+end_verse"
7705 "<verse>\n?\n/verse>")
7706 ("l" "#+begin_latex\n?\n#+end_latex"
7707 "<literal style=\"latex\">\n?\n</literal>")
7708 ("L" "#+latex: "
7709 "<literal style=\"latex\">?</literal>")
7710 ("h" "#+begin_html\n?\n#+end_html"
7711 "<literal style=\"html\">\n?\n</literal>")
7712 ("H" "#+html: "
7713 "<literal style=\"html\">?</literal>")
7714 ("a" "#+begin_ascii\n?\n#+end_ascii")
7715 ("A" "#+ascii: ")
7716 ("i" "#+include %file ?"
7717 "<include file=%file markup=\"?\">")
7719 "Structure completion elements.
7720 This is a list of abbreviation keys and values. The value gets inserted
7721 it you type @samp{.} followed by the key and then the completion key,
7722 usually `M-TAB'. %file will be replaced by a file name after prompting
7723 for the file uning completion.
7724 There are two templates for each key, the first uses the original Org syntax,
7725 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7726 the default when the /org-mtags.el/ module has been loaded. See also the
7727 variable `org-mtags-prefere-muse-templates'.
7728 This is an experimental feature, it is undecided if it is going to stay in."
7729 :group 'org-completion
7730 :type '(repeat
7731 (string :tag "Key")
7732 (string :tag "Template")
7733 (string :tag "Muse Template")))
7735 (defun org-try-structure-completion ()
7736 "Try to complete a structure template before point.
7737 This looks for strings like \"<e\" on an otherwise empty line and
7738 expands them."
7739 (let ((l (buffer-substring (point-at-bol) (point)))
7741 (when (and (looking-at "[ \t]*$")
7742 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7743 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7744 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7745 (match-beginning 1)) a)
7746 t)))
7748 (defun org-complete-expand-structure-template (start cell)
7749 "Expand a structure template."
7750 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7751 (rpl (nth (if musep 2 1) cell)))
7752 (delete-region start (point))
7753 (when (string-match "\\`#\\+" rpl)
7754 (cond
7755 ((bolp))
7756 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7757 (delete-region (point-at-bol) (point)))
7758 (t (newline))))
7759 (setq start (point))
7760 (if (string-match "%file" rpl)
7761 (setq rpl (replace-match
7762 (concat
7763 "\""
7764 (save-match-data
7765 (abbreviate-file-name (read-file-name "Include file: ")))
7766 "\"")
7767 t t rpl)))
7768 (insert rpl)
7769 (if (re-search-backward "\\?" start t) (delete-char 1))))
7772 (defun org-complete (&optional arg)
7773 "Perform completion on word at point.
7774 At the beginning of a headline, this completes TODO keywords as given in
7775 `org-todo-keywords'.
7776 If the current word is preceded by a backslash, completes the TeX symbols
7777 that are supported for HTML support.
7778 If the current word is preceded by \"#+\", completes special words for
7779 setting file options.
7780 In the line after \"#+STARTUP:, complete valid keywords.\"
7781 At all other locations, this simply calls the value of
7782 `org-completion-fallback-command'."
7783 (interactive "P")
7784 (org-without-partial-completion
7785 (catch 'exit
7786 (let* ((a nil)
7787 (end (point))
7788 (beg1 (save-excursion
7789 (skip-chars-backward (org-re "[:alnum:]_@"))
7790 (point)))
7791 (beg (save-excursion
7792 (skip-chars-backward "a-zA-Z0-9_:$")
7793 (point)))
7794 (confirm (lambda (x) (stringp (car x))))
7795 (searchhead (equal (char-before beg) ?*))
7796 (struct
7797 (when (and (member (char-before beg1) '(?. ?<))
7798 (setq a (assoc (buffer-substring beg1 (point))
7799 org-structure-template-alist)))
7800 (org-complete-expand-structure-template (1- beg1) a)
7801 (throw 'exit t)))
7802 (tag (and (equal (char-before beg1) ?:)
7803 (equal (char-after (point-at-bol)) ?*)))
7804 (prop (and (equal (char-before beg1) ?:)
7805 (not (equal (char-after (point-at-bol)) ?*))))
7806 (texp (equal (char-before beg) ?\\))
7807 (link (equal (char-before beg) ?\[))
7808 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7809 beg)
7810 "#+"))
7811 (startup (string-match "^#\\+STARTUP:.*"
7812 (buffer-substring (point-at-bol) (point))))
7813 (completion-ignore-case opt)
7814 (type nil)
7815 (tbl nil)
7816 (table (cond
7817 (opt
7818 (setq type :opt)
7819 (require 'org-exp)
7820 (append
7821 (mapcar
7822 (lambda (x)
7823 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7824 (cons (match-string 2 x) (match-string 1 x)))
7825 (org-split-string (org-get-current-options) "\n"))
7826 (mapcar 'list org-additional-option-like-keywords)))
7827 (startup
7828 (setq type :startup)
7829 org-startup-options)
7830 (link (append org-link-abbrev-alist-local
7831 org-link-abbrev-alist))
7832 (texp
7833 (setq type :tex)
7834 org-html-entities)
7835 ((string-match "\\`\\*+[ \t]+\\'"
7836 (buffer-substring (point-at-bol) beg))
7837 (setq type :todo)
7838 (mapcar 'list org-todo-keywords-1))
7839 (searchhead
7840 (setq type :searchhead)
7841 (save-excursion
7842 (goto-char (point-min))
7843 (while (re-search-forward org-todo-line-regexp nil t)
7844 (push (list
7845 (org-make-org-heading-search-string
7846 (match-string 3) t))
7847 tbl)))
7848 tbl)
7849 (tag (setq type :tag beg beg1)
7850 (or org-tag-alist (org-get-buffer-tags)))
7851 (prop (setq type :prop beg beg1)
7852 (mapcar 'list (org-buffer-property-keys nil t t)))
7853 (t (progn
7854 (call-interactively org-completion-fallback-command)
7855 (throw 'exit nil)))))
7856 (pattern (buffer-substring-no-properties beg end))
7857 (completion (try-completion pattern table confirm)))
7858 (cond ((eq completion t)
7859 (if (not (assoc (upcase pattern) table))
7860 (message "Already complete")
7861 (if (and (equal type :opt)
7862 (not (member (car (assoc (upcase pattern) table))
7863 org-additional-option-like-keywords)))
7864 (insert (substring (cdr (assoc (upcase pattern) table))
7865 (length pattern)))
7866 (if (memq type '(:tag :prop)) (insert ":")))))
7867 ((null completion)
7868 (message "Can't find completion for \"%s\"" pattern)
7869 (ding))
7870 ((not (string= pattern completion))
7871 (delete-region beg end)
7872 (if (string-match " +$" completion)
7873 (setq completion (replace-match "" t t completion)))
7874 (insert completion)
7875 (if (get-buffer-window "*Completions*")
7876 (delete-window (get-buffer-window "*Completions*")))
7877 (if (assoc completion table)
7878 (if (eq type :todo) (insert " ")
7879 (if (memq type '(:tag :prop)) (insert ":"))))
7880 (if (and (equal type :opt) (assoc completion table))
7881 (message "%s" (substitute-command-keys
7882 "Press \\[org-complete] again to insert example settings"))))
7884 (message "Making completion list...")
7885 (let ((list (sort (all-completions pattern table confirm)
7886 'string<)))
7887 (with-output-to-temp-buffer "*Completions*"
7888 (condition-case nil
7889 ;; Protection needed for XEmacs and emacs 21
7890 (display-completion-list list pattern)
7891 (error (display-completion-list list)))))
7892 (message "Making completion list...%s" "done")))))))
7894 ;;;; TODO, DEADLINE, Comments
7896 (defun org-toggle-comment ()
7897 "Change the COMMENT state of an entry."
7898 (interactive)
7899 (save-excursion
7900 (org-back-to-heading)
7901 (let (case-fold-search)
7902 (if (looking-at (concat outline-regexp
7903 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7904 (replace-match "" t t nil 1)
7905 (if (looking-at outline-regexp)
7906 (progn
7907 (goto-char (match-end 0))
7908 (insert org-comment-string " ")))))))
7910 (defvar org-last-todo-state-is-todo nil
7911 "This is non-nil when the last TODO state change led to a TODO state.
7912 If the last change removed the TODO tag or switched to DONE, then
7913 this is nil.")
7915 (defvar org-setting-tags nil) ; dynamically skiped
7917 (defun org-parse-local-options (string var)
7918 "Parse STRING for startup setting relevant for variable VAR."
7919 (let ((rtn (symbol-value var))
7920 e opts)
7921 (save-match-data
7922 (if (or (not string) (not (string-match "\\S-" string)))
7924 (setq opts (delq nil (mapcar (lambda (x)
7925 (setq e (assoc x org-startup-options))
7926 (if (eq (nth 1 e) var) e nil))
7927 (org-split-string string "[ \t]+"))))
7928 (if (not opts)
7930 (setq rtn nil)
7931 (while (setq e (pop opts))
7932 (if (not (nth 3 e))
7933 (setq rtn (nth 2 e))
7934 (if (not (listp rtn)) (setq rtn nil))
7935 (push (nth 2 e) rtn)))
7936 rtn)))))
7938 (defvar org-blocker-hook nil
7939 "Hook for functions that are allowed to block a state change.
7941 Each function gets as its single argument a property list, see
7942 `org-trigger-hook' for more information about this list.
7944 If any of the functions in this hook returns nil, the state change
7945 is blocked.")
7947 (defvar org-trigger-hook nil
7948 "Hook for functions that are triggered by a state change.
7950 Each function gets as its single argument a property list with at least
7951 the following elements:
7953 (:type type-of-change :position pos-at-entry-start
7954 :from old-state :to new-state)
7956 Depending on the type, more properties may be present.
7958 This mechanism is currently implemented for:
7960 TODO state changes
7961 ------------------
7962 :type todo-state-change
7963 :from previous state (keyword as a string), or nil
7964 :to new state (keyword as a string), or nil")
7967 (defun org-todo (&optional arg)
7968 "Change the TODO state of an item.
7969 The state of an item is given by a keyword at the start of the heading,
7970 like
7971 *** TODO Write paper
7972 *** DONE Call mom
7974 The different keywords are specified in the variable `org-todo-keywords'.
7975 By default the available states are \"TODO\" and \"DONE\".
7976 So for this example: when the item starts with TODO, it is changed to DONE.
7977 When it starts with DONE, the DONE is removed. And when neither TODO nor
7978 DONE are present, add TODO at the beginning of the heading.
7980 With C-u prefix arg, use completion to determine the new state.
7981 With numeric prefix arg, switch to that state.
7983 For calling through lisp, arg is also interpreted in the following way:
7984 'none -> empty state
7985 \"\"(empty string) -> switch to empty state
7986 'done -> switch to DONE
7987 'nextset -> switch to the next set of keywords
7988 'previousset -> switch to the previous set of keywords
7989 \"WAITING\" -> switch to the specified keyword, but only if it
7990 really is a member of `org-todo-keywords'."
7991 (interactive "P")
7992 (save-excursion
7993 (catch 'exit
7994 (org-back-to-heading)
7995 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7996 (or (looking-at (concat " +" org-todo-regexp " *"))
7997 (looking-at " *"))
7998 (let* ((match-data (match-data))
7999 (startpos (point-at-bol))
8000 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8001 (org-log-done org-log-done)
8002 (org-log-repeat org-log-repeat)
8003 (org-todo-log-states org-todo-log-states)
8004 (this (match-string 1))
8005 (hl-pos (match-beginning 0))
8006 (head (org-get-todo-sequence-head this))
8007 (ass (assoc head org-todo-kwd-alist))
8008 (interpret (nth 1 ass))
8009 (done-word (nth 3 ass))
8010 (final-done-word (nth 4 ass))
8011 (last-state (or this ""))
8012 (completion-ignore-case t)
8013 (member (member this org-todo-keywords-1))
8014 (tail (cdr member))
8015 (state (cond
8016 ((and org-todo-key-trigger
8017 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8018 (and (not arg) org-use-fast-todo-selection
8019 (not (eq org-use-fast-todo-selection 'prefix)))))
8020 ;; Use fast selection
8021 (org-fast-todo-selection))
8022 ((and (equal arg '(4))
8023 (or (not org-use-fast-todo-selection)
8024 (not org-todo-key-trigger)))
8025 ;; Read a state with completion
8026 (completing-read "State: " (mapcar (lambda(x) (list x))
8027 org-todo-keywords-1)
8028 nil t))
8029 ((eq arg 'right)
8030 (if this
8031 (if tail (car tail) nil)
8032 (car org-todo-keywords-1)))
8033 ((eq arg 'left)
8034 (if (equal member org-todo-keywords-1)
8036 (if this
8037 (nth (- (length org-todo-keywords-1) (length tail) 2)
8038 org-todo-keywords-1)
8039 (org-last org-todo-keywords-1))))
8040 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8041 (setq arg nil))) ; hack to fall back to cycling
8042 (arg
8043 ;; user or caller requests a specific state
8044 (cond
8045 ((equal arg "") nil)
8046 ((eq arg 'none) nil)
8047 ((eq arg 'done) (or done-word (car org-done-keywords)))
8048 ((eq arg 'nextset)
8049 (or (car (cdr (member head org-todo-heads)))
8050 (car org-todo-heads)))
8051 ((eq arg 'previousset)
8052 (let ((org-todo-heads (reverse org-todo-heads)))
8053 (or (car (cdr (member head org-todo-heads)))
8054 (car org-todo-heads))))
8055 ((car (member arg org-todo-keywords-1)))
8056 ((nth (1- (prefix-numeric-value arg))
8057 org-todo-keywords-1))))
8058 ((null member) (or head (car org-todo-keywords-1)))
8059 ((equal this final-done-word) nil) ;; -> make empty
8060 ((null tail) nil) ;; -> first entry
8061 ((eq interpret 'sequence)
8062 (car tail))
8063 ((memq interpret '(type priority))
8064 (if (eq this-command last-command)
8065 (car tail)
8066 (if (> (length tail) 0)
8067 (or done-word (car org-done-keywords))
8068 nil)))
8069 (t nil)))
8070 (next (if state (concat " " state " ") " "))
8071 (change-plist (list :type 'todo-state-change :from this :to state
8072 :position startpos))
8073 dolog now-done-p)
8074 (when org-blocker-hook
8075 (unless (save-excursion
8076 (save-match-data
8077 (run-hook-with-args-until-failure
8078 'org-blocker-hook change-plist)))
8079 (if (interactive-p)
8080 (error "TODO state change from %s to %s blocked" this state)
8081 ;; fail silently
8082 (message "TODO state change from %s to %s blocked" this state)
8083 (throw 'exit nil))))
8084 (store-match-data match-data)
8085 (replace-match next t t)
8086 (unless (pos-visible-in-window-p hl-pos)
8087 (message "TODO state changed to %s" (org-trim next)))
8088 (unless head
8089 (setq head (org-get-todo-sequence-head state)
8090 ass (assoc head org-todo-kwd-alist)
8091 interpret (nth 1 ass)
8092 done-word (nth 3 ass)
8093 final-done-word (nth 4 ass)))
8094 (when (memq arg '(nextset previousset))
8095 (message "Keyword-Set %d/%d: %s"
8096 (- (length org-todo-sets) -1
8097 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8098 (length org-todo-sets)
8099 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8100 (setq org-last-todo-state-is-todo
8101 (not (member state org-done-keywords)))
8102 (setq now-done-p (and (member state org-done-keywords)
8103 (not (member this org-done-keywords))))
8104 (and logging (org-local-logging logging))
8105 (when (and (or org-todo-log-states org-log-done)
8106 (not (memq arg '(nextset previousset))))
8107 ;; we need to look at recording a time and note
8108 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8109 (nth 2 (assoc this org-todo-log-states))))
8110 (when (and state
8111 (member state org-not-done-keywords)
8112 (not (member this org-not-done-keywords)))
8113 ;; This is now a todo state and was not one before
8114 ;; If there was a CLOSED time stamp, get rid of it.
8115 (org-add-planning-info nil nil 'closed))
8116 (when (and now-done-p org-log-done)
8117 ;; It is now done, and it was not done before
8118 (org-add-planning-info 'closed (org-current-time))
8119 (if (and (not dolog) (eq 'note org-log-done))
8120 (org-add-log-setup 'done state 'findpos 'note)))
8121 (when (and state dolog)
8122 ;; This is a non-nil state, and we need to log it
8123 (org-add-log-setup 'state state 'findpos dolog)))
8124 ;; Fixup tag positioning
8125 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8126 (run-hooks 'org-after-todo-state-change-hook)
8127 (if (and arg (not (member state org-done-keywords)))
8128 (setq head (org-get-todo-sequence-head state)))
8129 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8130 ;; Do we need to trigger a repeat?
8131 (when now-done-p (org-auto-repeat-maybe state))
8132 ;; Fixup cursor location if close to the keyword
8133 (if (and (outline-on-heading-p)
8134 (not (bolp))
8135 (save-excursion (beginning-of-line 1)
8136 (looking-at org-todo-line-regexp))
8137 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8138 (progn
8139 (goto-char (or (match-end 2) (match-end 1)))
8140 (just-one-space)))
8141 (when org-trigger-hook
8142 (save-excursion
8143 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8145 (defun org-local-logging (value)
8146 "Get logging settings from a property VALUE."
8147 (let* (words w a)
8148 ;; directly set the variables, they are already local.
8149 (setq org-log-done nil
8150 org-log-repeat nil
8151 org-todo-log-states nil)
8152 (setq words (org-split-string value))
8153 (while (setq w (pop words))
8154 (cond
8155 ((setq a (assoc w org-startup-options))
8156 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8157 (set (nth 1 a) (nth 2 a))))
8158 ((setq a (org-extract-log-state-settings w))
8159 (and (member (car a) org-todo-keywords-1)
8160 (push a org-todo-log-states)))))))
8162 (defun org-get-todo-sequence-head (kwd)
8163 "Return the head of the TODO sequence to which KWD belongs.
8164 If KWD is not set, check if there is a text property remembering the
8165 right sequence."
8166 (let (p)
8167 (cond
8168 ((not kwd)
8169 (or (get-text-property (point-at-bol) 'org-todo-head)
8170 (progn
8171 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8172 nil (point-at-eol)))
8173 (get-text-property p 'org-todo-head))))
8174 ((not (member kwd org-todo-keywords-1))
8175 (car org-todo-keywords-1))
8176 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8178 (defun org-fast-todo-selection ()
8179 "Fast TODO keyword selection with single keys.
8180 Returns the new TODO keyword, or nil if no state change should occur."
8181 (let* ((fulltable org-todo-key-alist)
8182 (done-keywords org-done-keywords) ;; needed for the faces.
8183 (maxlen (apply 'max (mapcar
8184 (lambda (x)
8185 (if (stringp (car x)) (string-width (car x)) 0))
8186 fulltable)))
8187 (expert nil)
8188 (fwidth (+ maxlen 3 1 3))
8189 (ncol (/ (- (window-width) 4) fwidth))
8190 tg cnt e c tbl
8191 groups ingroup)
8192 (save-window-excursion
8193 (if expert
8194 (set-buffer (get-buffer-create " *Org todo*"))
8195 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8196 (erase-buffer)
8197 (org-set-local 'org-done-keywords done-keywords)
8198 (setq tbl fulltable cnt 0)
8199 (while (setq e (pop tbl))
8200 (cond
8201 ((equal e '(:startgroup))
8202 (push '() groups) (setq ingroup t)
8203 (when (not (= cnt 0))
8204 (setq cnt 0)
8205 (insert "\n"))
8206 (insert "{ "))
8207 ((equal e '(:endgroup))
8208 (setq ingroup nil cnt 0)
8209 (insert "}\n"))
8211 (setq tg (car e) c (cdr e))
8212 (if ingroup (push tg (car groups)))
8213 (setq tg (org-add-props tg nil 'face
8214 (org-get-todo-face tg)))
8215 (if (and (= cnt 0) (not ingroup)) (insert " "))
8216 (insert "[" c "] " tg (make-string
8217 (- fwidth 4 (length tg)) ?\ ))
8218 (when (= (setq cnt (1+ cnt)) ncol)
8219 (insert "\n")
8220 (if ingroup (insert " "))
8221 (setq cnt 0)))))
8222 (insert "\n")
8223 (goto-char (point-min))
8224 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8225 (fit-window-to-buffer))
8226 (message "[a-z..]:Set [SPC]:clear")
8227 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8228 (cond
8229 ((or (= c ?\C-g)
8230 (and (= c ?q) (not (rassoc c fulltable))))
8231 (setq quit-flag t))
8232 ((= c ?\ ) nil)
8233 ((setq e (rassoc c fulltable) tg (car e))
8235 (t (setq quit-flag t))))))
8237 (defun org-entry-is-todo-p ()
8238 (member (org-get-todo-state) org-not-done-keywords))
8240 (defun org-entry-is-done-p ()
8241 (member (org-get-todo-state) org-done-keywords))
8243 (defun org-get-todo-state ()
8244 (save-excursion
8245 (org-back-to-heading t)
8246 (and (looking-at org-todo-line-regexp)
8247 (match-end 2)
8248 (match-string 2))))
8250 (defun org-at-date-range-p (&optional inactive-ok)
8251 "Is the cursor inside a date range?"
8252 (interactive)
8253 (save-excursion
8254 (catch 'exit
8255 (let ((pos (point)))
8256 (skip-chars-backward "^[<\r\n")
8257 (skip-chars-backward "<[")
8258 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8259 (>= (match-end 0) pos)
8260 (throw 'exit t))
8261 (skip-chars-backward "^<[\r\n")
8262 (skip-chars-backward "<[")
8263 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8264 (>= (match-end 0) pos)
8265 (throw 'exit t)))
8266 nil)))
8268 (defun org-get-repeat ()
8269 "Check if tere is a deadline/schedule with repeater in this entry."
8270 (save-match-data
8271 (save-excursion
8272 (org-back-to-heading t)
8273 (if (re-search-forward
8274 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8275 (match-string 1)))))
8277 (defvar org-last-changed-timestamp)
8278 (defvar org-log-post-message)
8279 (defvar org-log-note-purpose)
8280 (defvar org-log-note-how)
8281 (defun org-auto-repeat-maybe (done-word)
8282 "Check if the current headline contains a repeated deadline/schedule.
8283 If yes, set TODO state back to what it was and change the base date
8284 of repeating deadline/scheduled time stamps to new date.
8285 This function is run automatically after each state change to a DONE state."
8286 ;; last-state is dynamically scoped into this function
8287 (let* ((repeat (org-get-repeat))
8288 (aa (assoc last-state org-todo-kwd-alist))
8289 (interpret (nth 1 aa))
8290 (head (nth 2 aa))
8291 (whata '(("d" . day) ("m" . month) ("y" . year)))
8292 (msg "Entry repeats: ")
8293 (org-log-done nil)
8294 (org-todo-log-states nil)
8295 (nshiftmax 10) (nshift 0)
8296 re type n what ts mb0 time)
8297 (when repeat
8298 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8299 (org-todo (if (eq interpret 'type) last-state head))
8300 (when org-log-repeat
8301 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8302 (memq 'org-add-log-note post-command-hook))
8303 ;; OK, we are already setup for some record
8304 (if (eq org-log-repeat 'note)
8305 ;; make sure we take a note, not only a time stamp
8306 (setq org-log-note-how 'note))
8307 ;; Set up for taking a record
8308 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8309 'findpos org-log-repeat)))
8310 (org-back-to-heading t)
8311 (org-add-planning-info nil nil 'closed)
8312 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8313 org-deadline-time-regexp "\\)\\|\\("
8314 org-ts-regexp "\\)"))
8315 (while (re-search-forward
8316 re (save-excursion (outline-next-heading) (point)) t)
8317 (setq type (if (match-end 1) org-scheduled-string
8318 (if (match-end 3) org-deadline-string "Plain:"))
8319 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8320 mb0 (match-beginning 0))
8321 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8322 (setq n (string-to-number (match-string 2 ts))
8323 what (match-string 3 ts))
8324 (if (equal what "w") (setq n (* n 7) what "d"))
8325 ;; Preparation, see if we need to modify the start date for the change
8326 (when (match-end 1)
8327 (setq time (save-match-data (org-time-string-to-time ts)))
8328 (cond
8329 ((equal (match-string 1 ts) ".")
8330 ;; Shift starting date to today
8331 (org-timestamp-change
8332 (- (time-to-days (current-time)) (time-to-days time))
8333 'day))
8334 ((equal (match-string 1 ts) "+")
8335 (while (or (= nshift 0)
8336 (<= (time-to-days time) (time-to-days (current-time))))
8337 (when (= (incf nshift) nshiftmax)
8338 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8339 (error "Abort")))
8340 (org-timestamp-change n (cdr (assoc what whata)))
8341 (org-at-timestamp-p t)
8342 (setq ts (match-string 1))
8343 (setq time (save-match-data (org-time-string-to-time ts))))
8344 (org-timestamp-change (- n) (cdr (assoc what whata)))
8345 ;; rematch, so that we have everything in place for the real shift
8346 (org-at-timestamp-p t)
8347 (setq ts (match-string 1))
8348 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8349 (org-timestamp-change n (cdr (assoc what whata)))
8350 (setq msg (concat msg type org-last-changed-timestamp " "))))
8351 (setq org-log-post-message msg)
8352 (message "%s" msg))))
8354 (defun org-show-todo-tree (arg)
8355 "Make a compact tree which shows all headlines marked with TODO.
8356 The tree will show the lines where the regexp matches, and all higher
8357 headlines above the match.
8358 With a \\[universal-argument] prefix, also show the DONE entries.
8359 With a numeric prefix N, construct a sparse tree for the Nth element
8360 of `org-todo-keywords-1'."
8361 (interactive "P")
8362 (let ((case-fold-search nil)
8363 (kwd-re
8364 (cond ((null arg) org-not-done-regexp)
8365 ((equal arg '(4))
8366 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8367 (mapcar 'list org-todo-keywords-1))))
8368 (concat "\\("
8369 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8370 "\\)\\>")))
8371 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8372 (regexp-quote (nth (1- (prefix-numeric-value arg))
8373 org-todo-keywords-1)))
8374 (t (error "Invalid prefix argument: %s" arg)))))
8375 (message "%d TODO entries found"
8376 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8378 (defun org-deadline (&optional remove)
8379 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8380 With argument REMOVE, remove any deadline from the item."
8381 (interactive "P")
8382 (if remove
8383 (progn
8384 (org-remove-timestamp-with-keyword org-deadline-string)
8385 (message "Item no longer has a deadline."))
8386 (org-add-planning-info 'deadline nil 'closed)))
8388 (defun org-schedule (&optional remove)
8389 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8390 With argument REMOVE, remove any scheduling date from the item."
8391 (interactive "P")
8392 (if remove
8393 (progn
8394 (org-remove-timestamp-with-keyword org-scheduled-string)
8395 (message "Item is no longer scheduled."))
8396 (org-add-planning-info 'scheduled nil 'closed)))
8398 (defun org-remove-timestamp-with-keyword (keyword)
8399 "Remove all time stamps with KEYWORD in the current entry."
8400 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8401 beg)
8402 (save-excursion
8403 (org-back-to-heading t)
8404 (setq beg (point))
8405 (org-end-of-subtree t t)
8406 (while (re-search-backward re beg t)
8407 (replace-match "")
8408 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8409 (equal (char-before) ?\ ))
8410 (backward-delete-char 1)
8411 (if (string-match "^[ \t]*$" (buffer-substring
8412 (point-at-bol) (point-at-eol)))
8413 (delete-region (point-at-bol)
8414 (min (point-max) (1+ (point-at-eol))))))))))
8416 (defun org-add-planning-info (what &optional time &rest remove)
8417 "Insert new timestamp with keyword in the line directly after the headline.
8418 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8419 If non is given, the user is prompted for a date.
8420 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8421 be removed."
8422 (interactive)
8423 (let (org-time-was-given org-end-time-was-given ts
8424 end default-time default-input)
8426 (when (and (not time) (memq what '(scheduled deadline)))
8427 ;; Try to get a default date/time from existing timestamp
8428 (save-excursion
8429 (org-back-to-heading t)
8430 (setq end (save-excursion (outline-next-heading) (point)))
8431 (when (re-search-forward (if (eq what 'scheduled)
8432 org-scheduled-time-regexp
8433 org-deadline-time-regexp)
8434 end t)
8435 (setq ts (match-string 1)
8436 default-time
8437 (apply 'encode-time (org-parse-time-string ts))
8438 default-input (and ts (org-get-compact-tod ts))))))
8439 (when what
8440 ;; If necessary, get the time from the user
8441 (setq time (or time (org-read-date nil 'to-time nil nil
8442 default-time default-input))))
8444 (when (and org-insert-labeled-timestamps-at-point
8445 (member what '(scheduled deadline)))
8446 (insert
8447 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8448 (org-insert-time-stamp time org-time-was-given
8449 nil nil nil (list org-end-time-was-given))
8450 (setq what nil))
8451 (save-excursion
8452 (save-restriction
8453 (let (col list elt ts buffer-invisibility-spec)
8454 (org-back-to-heading t)
8455 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8456 (goto-char (match-end 1))
8457 (setq col (current-column))
8458 (goto-char (match-end 0))
8459 (if (eobp) (insert "\n") (forward-char 1))
8460 (if (and (not (looking-at outline-regexp))
8461 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8462 "[^\r\n]*"))
8463 (not (equal (match-string 1) org-clock-string)))
8464 (narrow-to-region (match-beginning 0) (match-end 0))
8465 (insert-before-markers "\n")
8466 (backward-char 1)
8467 (narrow-to-region (point) (point))
8468 (org-indent-to-column col))
8469 ;; Check if we have to remove something.
8470 (setq list (cons what remove))
8471 (while list
8472 (setq elt (pop list))
8473 (goto-char (point-min))
8474 (when (or (and (eq elt 'scheduled)
8475 (re-search-forward org-scheduled-time-regexp nil t))
8476 (and (eq elt 'deadline)
8477 (re-search-forward org-deadline-time-regexp nil t))
8478 (and (eq elt 'closed)
8479 (re-search-forward org-closed-time-regexp nil t)))
8480 (replace-match "")
8481 (if (looking-at "--+<[^>]+>") (replace-match ""))
8482 (if (looking-at " +") (replace-match ""))))
8483 (goto-char (point-max))
8484 (when what
8485 (insert
8486 (if (not (equal (char-before) ?\ )) " " "")
8487 (cond ((eq what 'scheduled) org-scheduled-string)
8488 ((eq what 'deadline) org-deadline-string)
8489 ((eq what 'closed) org-closed-string))
8490 " ")
8491 (setq ts (org-insert-time-stamp
8492 time
8493 (or org-time-was-given
8494 (and (eq what 'closed) org-log-done-with-time))
8495 (eq what 'closed)
8496 nil nil (list org-end-time-was-given)))
8497 (end-of-line 1))
8498 (goto-char (point-min))
8499 (widen)
8500 (if (and (looking-at "[ \t]+\n")
8501 (equal (char-before) ?\n))
8502 (delete-region (1- (point)) (point-at-eol)))
8503 ts)))))
8505 (defvar org-log-note-marker (make-marker))
8506 (defvar org-log-note-purpose nil)
8507 (defvar org-log-note-state nil)
8508 (defvar org-log-note-how nil)
8509 (defvar org-log-note-window-configuration nil)
8510 (defvar org-log-note-return-to (make-marker))
8511 (defvar org-log-post-message nil
8512 "Message to be displayed after a log note has been stored.
8513 The auto-repeater uses this.")
8515 (defun org-add-note ()
8516 "Add a note to the current entry.
8517 This is done in the same way as adding a state change note."
8518 (interactive)
8519 (org-add-log-setup 'note nil t nil))
8521 (defun org-add-log-setup (&optional purpose state findpos how)
8522 "Set up the post command hook to take a note.
8523 If this is about to TODO state change, the new state is expected in STATE.
8524 When FINDPOS is non-nil, find the correct position for the note in
8525 the current entry. If not, assume that it can be inserted at point."
8526 (save-excursion
8527 (when findpos
8528 (org-back-to-heading t)
8529 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8530 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8531 "[^\r\n]*\\)?"))
8532 (goto-char (match-end 0))
8533 (unless org-log-states-order-reversed
8534 (and (= (char-after) ?\n) (forward-char 1))
8535 (org-skip-over-state-notes)
8536 (skip-chars-backward " \t\n\r")))
8537 (move-marker org-log-note-marker (point))
8538 (setq org-log-note-purpose purpose
8539 org-log-note-state state
8540 org-log-note-how how)
8541 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8543 (defun org-skip-over-state-notes ()
8544 "Skip past the list of State notes in an entry."
8545 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8546 (while (looking-at "[ \t]*- State")
8547 (condition-case nil
8548 (org-next-item)
8549 (error (org-end-of-item)))))
8551 (defun org-add-log-note (&optional purpose)
8552 "Pop up a window for taking a note, and add this note later at point."
8553 (remove-hook 'post-command-hook 'org-add-log-note)
8554 (setq org-log-note-window-configuration (current-window-configuration))
8555 (delete-other-windows)
8556 (move-marker org-log-note-return-to (point))
8557 (switch-to-buffer (marker-buffer org-log-note-marker))
8558 (goto-char org-log-note-marker)
8559 (org-switch-to-buffer-other-window "*Org Note*")
8560 (erase-buffer)
8561 (if (memq org-log-note-how '(time state))
8562 (org-store-log-note)
8563 (let ((org-inhibit-startup t)) (org-mode))
8564 (insert (format "# Insert note for %s.
8565 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8566 (cond
8567 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8568 ((eq org-log-note-purpose 'done) "closed todo item")
8569 ((eq org-log-note-purpose 'state)
8570 (format "state change to \"%s\"" org-log-note-state))
8571 ((eq org-log-note-purpose 'note)
8572 "this entry")
8573 (t (error "This should not happen")))))
8574 (org-set-local 'org-finish-function 'org-store-log-note)))
8576 (defvar org-note-abort nil) ; dynamically scoped
8577 (defun org-store-log-note ()
8578 "Finish taking a log note, and insert it to where it belongs."
8579 (let ((txt (buffer-string))
8580 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8581 lines ind)
8582 (kill-buffer (current-buffer))
8583 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8584 (setq txt (replace-match "" t t txt)))
8585 (if (string-match "\\s-+\\'" txt)
8586 (setq txt (replace-match "" t t txt)))
8587 (setq lines (org-split-string txt "\n"))
8588 (when (and note (string-match "\\S-" note))
8589 (setq note
8590 (org-replace-escapes
8591 note
8592 (list (cons "%u" (user-login-name))
8593 (cons "%U" user-full-name)
8594 (cons "%t" (format-time-string
8595 (org-time-stamp-format 'long 'inactive)
8596 (current-time)))
8597 (cons "%s" (if org-log-note-state
8598 (concat "\"" org-log-note-state "\"")
8599 "")))))
8600 (if lines (setq note (concat note " \\\\")))
8601 (push note lines))
8602 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8603 (when lines
8604 (save-excursion
8605 (set-buffer (marker-buffer org-log-note-marker))
8606 (save-excursion
8607 (goto-char org-log-note-marker)
8608 (move-marker org-log-note-marker nil)
8609 (end-of-line 1)
8610 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8611 (indent-relative nil)
8612 (insert "- " (pop lines))
8613 (org-indent-line-function)
8614 (beginning-of-line 1)
8615 (looking-at "[ \t]*")
8616 (setq ind (concat (match-string 0) " "))
8617 (end-of-line 1)
8618 (while lines (insert "\n" ind (pop lines)))))))
8619 (set-window-configuration org-log-note-window-configuration)
8620 (with-current-buffer (marker-buffer org-log-note-return-to)
8621 (goto-char org-log-note-return-to))
8622 (move-marker org-log-note-return-to nil)
8623 (and org-log-post-message (message "%s" org-log-post-message)))
8625 (defun org-sparse-tree (&optional arg)
8626 "Create a sparse tree, prompt for the details.
8627 This command can create sparse trees. You first need to select the type
8628 of match used to create the tree:
8630 t Show entries with a specific TODO keyword.
8631 T Show entries selected by a tags match.
8632 p Enter a property name and its value (both with completion on existing
8633 names/values) and show entries with that property.
8634 r Show entries matching a regular expression
8635 d Show deadlines due within `org-deadline-warning-days'."
8636 (interactive "P")
8637 (let (ans kwd value)
8638 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8639 (setq ans (read-char-exclusive))
8640 (cond
8641 ((equal ans ?d)
8642 (call-interactively 'org-check-deadlines))
8643 ((equal ans ?b)
8644 (call-interactively 'org-check-before-date))
8645 ((equal ans ?t)
8646 (org-show-todo-tree '(4)))
8647 ((equal ans ?T)
8648 (call-interactively 'org-tags-sparse-tree))
8649 ((member ans '(?p ?P))
8650 (setq kwd (completing-read "Property: "
8651 (mapcar 'list (org-buffer-property-keys))))
8652 (setq value (completing-read "Value: "
8653 (mapcar 'list (org-property-values kwd))))
8654 (unless (string-match "\\`{.*}\\'" value)
8655 (setq value (concat "\"" value "\"")))
8656 (org-tags-sparse-tree arg (concat kwd "=" value)))
8657 ((member ans '(?r ?R ?/))
8658 (call-interactively 'org-occur))
8659 (t (error "No such sparse tree command \"%c\"" ans)))))
8661 (defvar org-occur-highlights nil
8662 "List of overlays used for occur matches.")
8663 (make-variable-buffer-local 'org-occur-highlights)
8664 (defvar org-occur-parameters nil
8665 "Parameters of the active org-occur calls.
8666 This is a list, each call to org-occur pushes as cons cell,
8667 containing the regular expression and the callback, onto the list.
8668 The list can contain several entries if `org-occur' has been called
8669 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8670 will only contain one set of parameters. When the highlights are
8671 removed (for example with `C-c C-c', or with the next edit (depending
8672 on `org-remove-highlights-with-change'), this variable is emptied
8673 as well.")
8674 (make-variable-buffer-local 'org-occur-parameters)
8676 (defun org-occur (regexp &optional keep-previous callback)
8677 "Make a compact tree which shows all matches of REGEXP.
8678 The tree will show the lines where the regexp matches, and all higher
8679 headlines above the match. It will also show the heading after the match,
8680 to make sure editing the matching entry is easy.
8681 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8682 call to `org-occur' will be kept, to allow stacking of calls to this
8683 command.
8684 If CALLBACK is non-nil, it is a function which is called to confirm
8685 that the match should indeed be shown."
8686 (interactive "sRegexp: \nP")
8687 (unless keep-previous
8688 (org-remove-occur-highlights nil nil t))
8689 (push (cons regexp callback) org-occur-parameters)
8690 (let ((cnt 0))
8691 (save-excursion
8692 (goto-char (point-min))
8693 (if (or (not keep-previous) ; do not want to keep
8694 (not org-occur-highlights)) ; no previous matches
8695 ;; hide everything
8696 (org-overview))
8697 (while (re-search-forward regexp nil t)
8698 (when (or (not callback)
8699 (save-match-data (funcall callback)))
8700 (setq cnt (1+ cnt))
8701 (when org-highlight-sparse-tree-matches
8702 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8703 (org-show-context 'occur-tree))))
8704 (when org-remove-highlights-with-change
8705 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8706 nil 'local))
8707 (unless org-sparse-tree-open-archived-trees
8708 (org-hide-archived-subtrees (point-min) (point-max)))
8709 (run-hooks 'org-occur-hook)
8710 (if (interactive-p)
8711 (message "%d match(es) for regexp %s" cnt regexp))
8712 cnt))
8714 (defun org-show-context (&optional key)
8715 "Make sure point and context and visible.
8716 How much context is shown depends upon the variables
8717 `org-show-hierarchy-above', `org-show-following-heading'. and
8718 `org-show-siblings'."
8719 (let ((heading-p (org-on-heading-p t))
8720 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8721 (following-p (org-get-alist-option org-show-following-heading key))
8722 (entry-p (org-get-alist-option org-show-entry-below key))
8723 (siblings-p (org-get-alist-option org-show-siblings key)))
8724 (catch 'exit
8725 ;; Show heading or entry text
8726 (if (and heading-p (not entry-p))
8727 (org-flag-heading nil) ; only show the heading
8728 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8729 (org-show-hidden-entry))) ; show entire entry
8730 (when following-p
8731 ;; Show next sibling, or heading below text
8732 (save-excursion
8733 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8734 (org-flag-heading nil))))
8735 (when siblings-p (org-show-siblings))
8736 (when hierarchy-p
8737 ;; show all higher headings, possibly with siblings
8738 (save-excursion
8739 (while (and (condition-case nil
8740 (progn (org-up-heading-all 1) t)
8741 (error nil))
8742 (not (bobp)))
8743 (org-flag-heading nil)
8744 (when siblings-p (org-show-siblings))))))))
8746 (defun org-reveal (&optional siblings)
8747 "Show current entry, hierarchy above it, and the following headline.
8748 This can be used to show a consistent set of context around locations
8749 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8750 not t for the search context.
8752 With optional argument SIBLINGS, on each level of the hierarchy all
8753 siblings are shown. This repairs the tree structure to what it would
8754 look like when opened with hierarchical calls to `org-cycle'."
8755 (interactive "P")
8756 (let ((org-show-hierarchy-above t)
8757 (org-show-following-heading t)
8758 (org-show-siblings (if siblings t org-show-siblings)))
8759 (org-show-context nil)))
8761 (defun org-highlight-new-match (beg end)
8762 "Highlight from BEG to END and mark the highlight is an occur headline."
8763 (let ((ov (org-make-overlay beg end)))
8764 (org-overlay-put ov 'face 'secondary-selection)
8765 (push ov org-occur-highlights)))
8767 (defun org-remove-occur-highlights (&optional beg end noremove)
8768 "Remove the occur highlights from the buffer.
8769 BEG and END are ignored. If NOREMOVE is nil, remove this function
8770 from the `before-change-functions' in the current buffer."
8771 (interactive)
8772 (unless org-inhibit-highlight-removal
8773 (mapc 'org-delete-overlay org-occur-highlights)
8774 (setq org-occur-highlights nil)
8775 (setq org-occur-parameters nil)
8776 (unless noremove
8777 (remove-hook 'before-change-functions
8778 'org-remove-occur-highlights 'local))))
8780 ;;;; Priorities
8782 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8783 "Regular expression matching the priority indicator.")
8785 (defvar org-remove-priority-next-time nil)
8787 (defun org-priority-up ()
8788 "Increase the priority of the current item."
8789 (interactive)
8790 (org-priority 'up))
8792 (defun org-priority-down ()
8793 "Decrease the priority of the current item."
8794 (interactive)
8795 (org-priority 'down))
8797 (defun org-priority (&optional action)
8798 "Change the priority of an item by ARG.
8799 ACTION can be `set', `up', `down', or a character."
8800 (interactive)
8801 (setq action (or action 'set))
8802 (let (current new news have remove)
8803 (save-excursion
8804 (org-back-to-heading)
8805 (if (looking-at org-priority-regexp)
8806 (setq current (string-to-char (match-string 2))
8807 have t)
8808 (setq current org-default-priority))
8809 (cond
8810 ((or (eq action 'set)
8811 (if (featurep 'xemacs) (characterp action) (integerp action)))
8812 (if (not (eq action 'set))
8813 (setq new action)
8814 (message "Priority %c-%c, SPC to remove: "
8815 org-highest-priority org-lowest-priority)
8816 (setq new (read-char-exclusive)))
8817 (if (and (= (upcase org-highest-priority) org-highest-priority)
8818 (= (upcase org-lowest-priority) org-lowest-priority))
8819 (setq new (upcase new)))
8820 (cond ((equal new ?\ ) (setq remove t))
8821 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8822 (error "Priority must be between `%c' and `%c'"
8823 org-highest-priority org-lowest-priority))))
8824 ((eq action 'up)
8825 (if (and (not have) (eq last-command this-command))
8826 (setq new org-lowest-priority)
8827 (setq new (if (and org-priority-start-cycle-with-default (not have))
8828 org-default-priority (1- current)))))
8829 ((eq action 'down)
8830 (if (and (not have) (eq last-command this-command))
8831 (setq new org-highest-priority)
8832 (setq new (if (and org-priority-start-cycle-with-default (not have))
8833 org-default-priority (1+ current)))))
8834 (t (error "Invalid action")))
8835 (if (or (< (upcase new) org-highest-priority)
8836 (> (upcase new) org-lowest-priority))
8837 (setq remove t))
8838 (setq news (format "%c" new))
8839 (if have
8840 (if remove
8841 (replace-match "" t t nil 1)
8842 (replace-match news t t nil 2))
8843 (if remove
8844 (error "No priority cookie found in line")
8845 (looking-at org-todo-line-regexp)
8846 (if (match-end 2)
8847 (progn
8848 (goto-char (match-end 2))
8849 (insert " [#" news "]"))
8850 (goto-char (match-beginning 3))
8851 (insert "[#" news "] ")))))
8852 (org-preserve-lc (org-set-tags nil 'align))
8853 (if remove
8854 (message "Priority removed")
8855 (message "Priority of current item set to %s" news))))
8858 (defun org-get-priority (s)
8859 "Find priority cookie and return priority."
8860 (save-match-data
8861 (if (not (string-match org-priority-regexp s))
8862 (* 1000 (- org-lowest-priority org-default-priority))
8863 (* 1000 (- org-lowest-priority
8864 (string-to-char (match-string 2 s)))))))
8866 ;;;; Tags
8868 (defun org-scan-tags (action matcher &optional todo-only)
8869 "Scan headline tags with inheritance and produce output ACTION.
8870 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8871 evaluated, testing if a given set of tags qualifies a headline for
8872 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8873 are included in the output."
8874 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8875 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8876 (org-re
8877 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8878 (props (list 'face nil
8879 'done-face 'org-done
8880 'undone-face nil
8881 'mouse-face 'highlight
8882 'org-not-done-regexp org-not-done-regexp
8883 'org-todo-regexp org-todo-regexp
8884 'keymap org-agenda-keymap
8885 'help-echo
8886 (format "mouse-2 or RET jump to org file %s"
8887 (abbreviate-file-name
8888 (or (buffer-file-name (buffer-base-buffer))
8889 (buffer-name (buffer-base-buffer)))))))
8890 (case-fold-search nil)
8891 lspos
8892 tags tags-list tags-alist (llast 0) rtn level category i txt
8893 todo marker entry priority)
8894 (save-excursion
8895 (goto-char (point-min))
8896 (when (eq action 'sparse-tree)
8897 (org-overview)
8898 (org-remove-occur-highlights))
8899 (while (re-search-forward re nil t)
8900 (catch :skip
8901 (setq todo (if (match-end 1) (match-string 2))
8902 tags (if (match-end 4) (match-string 4)))
8903 (goto-char (setq lspos (1+ (match-beginning 0))))
8904 (setq level (org-reduced-level (funcall outline-level))
8905 category (org-get-category))
8906 (setq i llast llast level)
8907 ;; remove tag lists from same and sublevels
8908 (while (>= i level)
8909 (when (setq entry (assoc i tags-alist))
8910 (setq tags-alist (delete entry tags-alist)))
8911 (setq i (1- i)))
8912 ;; add the next tags
8913 (when tags
8914 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8915 tags-alist
8916 (cons (cons level tags) tags-alist)))
8917 ;; compile tags for current headline
8918 (setq tags-list
8919 (if org-use-tag-inheritance
8920 (apply 'append (mapcar 'cdr tags-alist))
8921 tags))
8922 (when (and tags org-use-tag-inheritance
8923 (not (eq t org-use-tag-inheritance)))
8924 ;; selective inheritance, remove uninherited ones
8925 (setcdr (car tags-alist)
8926 (org-remove-uniherited-tags (cdar tags-alist))))
8927 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8928 (eval matcher)
8929 (or (not org-agenda-skip-archived-trees)
8930 (not (member org-archive-tag tags-list))))
8931 (and (eq action 'agenda) (org-agenda-skip))
8932 ;; list this headline
8934 (if (eq action 'sparse-tree)
8935 (progn
8936 (and org-highlight-sparse-tree-matches
8937 (org-get-heading) (match-end 0)
8938 (org-highlight-new-match
8939 (match-beginning 0) (match-beginning 1)))
8940 (org-show-context 'tags-tree))
8941 (setq txt (org-format-agenda-item
8943 (concat
8944 (if org-tags-match-list-sublevels
8945 (make-string (1- level) ?.) "")
8946 (org-get-heading))
8947 category tags-list)
8948 priority (org-get-priority txt))
8949 (goto-char lspos)
8950 (setq marker (org-agenda-new-marker))
8951 (org-add-props txt props
8952 'org-marker marker 'org-hd-marker marker 'org-category category
8953 'priority priority 'type "tagsmatch")
8954 (push txt rtn))
8955 ;; if we are to skip sublevels, jump to end of subtree
8956 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8957 (when (and (eq action 'sparse-tree)
8958 (not org-sparse-tree-open-archived-trees))
8959 (org-hide-archived-subtrees (point-min) (point-max)))
8960 (nreverse rtn)))
8962 (defun org-remove-uniherited-tags (tags)
8963 "Remove all tags that are not inherited from the list TAGS."
8964 (cond
8965 ((eq org-use-tag-inheritance t) tags)
8966 ((not org-use-tag-inheritance) nil)
8967 ((stringp org-use-tag-inheritance)
8968 (delq nil (mapcar
8969 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8970 tags)))
8971 ((listp org-use-tag-inheritance)
8972 (org-delete-all org-use-tag-inheritance tags))))
8974 (defvar todo-only) ;; dynamically scoped
8976 (defun org-tags-sparse-tree (&optional todo-only match)
8977 "Create a sparse tree according to tags string MATCH.
8978 MATCH can contain positive and negative selection of tags, like
8979 \"+WORK+URGENT-WITHBOSS\".
8980 If optional argument TODO_ONLY is non-nil, only select lines that are
8981 also TODO lines."
8982 (interactive "P")
8983 (org-prepare-agenda-buffers (list (current-buffer)))
8984 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8986 (defvar org-cached-props nil)
8987 (defun org-cached-entry-get (pom property)
8988 (if (or (eq t org-use-property-inheritance)
8989 (and (stringp org-use-property-inheritance)
8990 (string-match org-use-property-inheritance property))
8991 (and (listp org-use-property-inheritance)
8992 (member property org-use-property-inheritance)))
8993 ;; Caching is not possible, check it directly
8994 (org-entry-get pom property 'inherit)
8995 ;; Get all properties, so that we can do complicated checks easily
8996 (cdr (assoc property (or org-cached-props
8997 (setq org-cached-props
8998 (org-entry-properties pom)))))))
9000 (defun org-global-tags-completion-table (&optional files)
9001 "Return the list of all tags in all agenda buffer/files."
9002 (save-excursion
9003 (org-uniquify
9004 (delq nil
9005 (apply 'append
9006 (mapcar
9007 (lambda (file)
9008 (set-buffer (find-file-noselect file))
9009 (append (org-get-buffer-tags)
9010 (mapcar (lambda (x) (if (stringp (car-safe x))
9011 (list (car-safe x)) nil))
9012 org-tag-alist)))
9013 (if (and files (car files))
9014 files
9015 (org-agenda-files))))))))
9017 (defun org-make-tags-matcher (match)
9018 "Create the TAGS//TODO matcher form for the selection string MATCH."
9019 ;; todo-only is scoped dynamically into this function, and the function
9020 ;; may change it it the matcher asksk for it.
9021 (unless match
9022 ;; Get a new match request, with completion
9023 (let ((org-last-tags-completion-table
9024 (org-global-tags-completion-table)))
9025 (setq match (completing-read
9026 "Match: " 'org-tags-completion-function nil nil nil
9027 'org-tags-history))))
9029 ;; Parse the string and create a lisp form
9030 (let ((match0 match)
9031 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9032 minus tag mm
9033 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9034 orterms term orlist re-p str-p level-p level-op
9035 prop-p pn pv po cat-p gv)
9036 (if (string-match "/+" match)
9037 ;; match contains also a todo-matching request
9038 (progn
9039 (setq tagsmatch (substring match 0 (match-beginning 0))
9040 todomatch (substring match (match-end 0)))
9041 (if (string-match "^!" todomatch)
9042 (setq todo-only t todomatch (substring todomatch 1)))
9043 (if (string-match "^\\s-*$" todomatch)
9044 (setq todomatch nil)))
9045 ;; only matching tags
9046 (setq tagsmatch match todomatch nil))
9048 ;; Make the tags matcher
9049 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9050 (setq tagsmatcher t)
9051 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9052 (while (setq term (pop orterms))
9053 (while (and (equal (substring term -1) "\\") orterms)
9054 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9055 (while (string-match re term)
9056 (setq minus (and (match-end 1)
9057 (equal (match-string 1 term) "-"))
9058 tag (match-string 2 term)
9059 re-p (equal (string-to-char tag) ?{)
9060 level-p (match-end 4)
9061 prop-p (match-end 5)
9062 mm (cond
9063 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9064 (level-p
9065 (setq level-op (org-op-to-function (match-string 3 term)))
9066 `(,level-op level ,(string-to-number
9067 (match-string 4 term))))
9068 (prop-p
9069 (setq pn (match-string 5 term)
9070 po (match-string 6 term)
9071 pv (match-string 7 term)
9072 cat-p (equal pn "CATEGORY")
9073 re-p (equal (string-to-char pv) ?{)
9074 str-p (equal (string-to-char pv) ?\")
9075 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9076 (setq po (org-op-to-function po str-p))
9077 (if (equal pn "CATEGORY")
9078 (setq gv '(get-text-property (point) 'org-category))
9079 (setq gv `(org-cached-entry-get nil ,pn)))
9080 (if re-p
9081 (if (eq po 'org<>)
9082 `(not (string-match ,pv (or ,gv "")))
9083 `(string-match ,pv (or ,gv "")))
9084 (if str-p
9085 `(,po (or ,gv "") ,pv)
9086 `(,po (string-to-number (or ,gv ""))
9087 ,(string-to-number pv) ))))
9088 (t `(member ,(downcase tag) tags-list)))
9089 mm (if minus (list 'not mm) mm)
9090 term (substring term (match-end 0)))
9091 (push mm tagsmatcher))
9092 (push (if (> (length tagsmatcher) 1)
9093 (cons 'and tagsmatcher)
9094 (car tagsmatcher))
9095 orlist)
9096 (setq tagsmatcher nil))
9097 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9098 (setq tagsmatcher
9099 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9100 ;; Make the todo matcher
9101 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9102 (setq todomatcher t)
9103 (setq orterms (org-split-string todomatch "|") orlist nil)
9104 (while (setq term (pop orterms))
9105 (while (string-match re term)
9106 (setq minus (and (match-end 1)
9107 (equal (match-string 1 term) "-"))
9108 kwd (match-string 2 term)
9109 re-p (equal (string-to-char kwd) ?{)
9110 term (substring term (match-end 0))
9111 mm (if re-p
9112 `(string-match ,(substring kwd 1 -1) todo)
9113 (list 'equal 'todo kwd))
9114 mm (if minus (list 'not mm) mm))
9115 (push mm todomatcher))
9116 (push (if (> (length todomatcher) 1)
9117 (cons 'and todomatcher)
9118 (car todomatcher))
9119 orlist)
9120 (setq todomatcher nil))
9121 (setq todomatcher (if (> (length orlist) 1)
9122 (cons 'or orlist) (car orlist))))
9124 ;; Return the string and lisp forms of the matcher
9125 (setq matcher (if todomatcher
9126 (list 'and tagsmatcher todomatcher)
9127 tagsmatcher))
9128 (cons match0 matcher)))
9130 (defun org-op-to-function (op &optional stringp)
9131 (setq op
9132 (cond
9133 ((equal op "<" ) '(< string< ))
9134 ((equal op ">" ) '(> org-string> ))
9135 ((member op '("<=" "=<")) '(<= org-string<= ))
9136 ((member op '(">=" "=>")) '(>= org-string>= ))
9137 ((member op '("=" "==")) '(= string= ))
9138 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9139 (nth (if stringp 1 0) op))
9141 (defun org<> (a b) (not (= a b)))
9142 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9143 (defun org-string>= (a b) (not (string< a b)))
9144 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9145 (defun org-string<> (a b) (not (string= a b)))
9147 (defun org-match-any-p (re list)
9148 "Does re match any element of list?"
9149 (setq list (mapcar (lambda (x) (string-match re x)) list))
9150 (delq nil list))
9152 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9153 (defvar org-tags-overlay (org-make-overlay 1 1))
9154 (org-detach-overlay org-tags-overlay)
9156 (defun org-get-tags-at (&optional pos)
9157 "Get a list of all headline tags applicable at POS.
9158 POS defaults to point. If tags are inherited, the list contains
9159 the targets in the same sequence as the headlines appear, i.e.
9160 sthe tags of the current headline come last."
9161 (interactive)
9162 (let (tags ltags lastpos parent)
9163 (save-excursion
9164 (save-restriction
9165 (widen)
9166 (goto-char (or pos (point)))
9167 (save-match-data
9168 (condition-case nil
9169 (progn
9170 (org-back-to-heading t)
9171 (while (not (equal lastpos (point)))
9172 (setq lastpos (point))
9173 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9174 (setq ltags (org-split-string
9175 (org-match-string-no-properties 1) ":"))
9176 (setq tags (append (org-remove-uniherited-tags ltags)
9177 tags)))
9178 (or org-use-tag-inheritance (error ""))
9179 (org-up-heading-all 1)
9180 (setq parent t)))
9181 (error nil))))
9182 tags)))
9184 (defun org-toggle-tag (tag &optional onoff)
9185 "Toggle the tag TAG for the current line.
9186 If ONOFF is `on' or `off', don't toggle but set to this state."
9187 (unless (org-on-heading-p t) (error "Not on headling"))
9188 (let (res current)
9189 (save-excursion
9190 (beginning-of-line)
9191 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9192 (point-at-eol) t)
9193 (progn
9194 (setq current (match-string 1))
9195 (replace-match ""))
9196 (setq current ""))
9197 (setq current (nreverse (org-split-string current ":")))
9198 (cond
9199 ((eq onoff 'on)
9200 (setq res t)
9201 (or (member tag current) (push tag current)))
9202 ((eq onoff 'off)
9203 (or (not (member tag current)) (setq current (delete tag current))))
9204 (t (if (member tag current)
9205 (setq current (delete tag current))
9206 (setq res t)
9207 (push tag current))))
9208 (end-of-line 1)
9209 (if current
9210 (progn
9211 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9212 (org-set-tags nil t))
9213 (delete-horizontal-space))
9214 (run-hooks 'org-after-tags-change-hook))
9215 res))
9217 (defun org-align-tags-here (to-col)
9218 ;; Assumes that this is a headline
9219 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9220 (beginning-of-line 1)
9221 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9222 (< pos (match-beginning 2)))
9223 (progn
9224 (setq tags-l (- (match-end 2) (match-beginning 2)))
9225 (goto-char (match-beginning 1))
9226 (insert " ")
9227 (delete-region (point) (1+ (match-beginning 2)))
9228 (setq ncol (max (1+ (current-column))
9229 (1+ col)
9230 (if (> to-col 0)
9231 to-col
9232 (- (abs to-col) tags-l))))
9233 (setq p (point))
9234 (insert (make-string (- ncol (current-column)) ?\ ))
9235 (setq ncol (current-column))
9236 (tabify p (point-at-eol))
9237 (org-move-to-column (min ncol col) t))
9238 (goto-char pos))))
9240 (defun org-set-tags (&optional arg just-align)
9241 "Set the tags for the current headline.
9242 With prefix ARG, realign all tags in headings in the current buffer."
9243 (interactive "P")
9244 (let* ((re (concat "^" outline-regexp))
9245 (current (org-get-tags-string))
9246 (col (current-column))
9247 (org-setting-tags t)
9248 table current-tags inherited-tags ; computed below when needed
9249 tags p0 c0 c1 rpl)
9250 (if arg
9251 (save-excursion
9252 (goto-char (point-min))
9253 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9254 (while (re-search-forward re nil t)
9255 (org-set-tags nil t)
9256 (end-of-line 1)))
9257 (message "All tags realigned to column %d" org-tags-column))
9258 (if just-align
9259 (setq tags current)
9260 ;; Get a new set of tags from the user
9261 (save-excursion
9262 (setq table (or org-tag-alist (org-get-buffer-tags))
9263 org-last-tags-completion-table table
9264 current-tags (org-split-string current ":")
9265 inherited-tags (nreverse
9266 (nthcdr (length current-tags)
9267 (nreverse (org-get-tags-at))))
9268 tags
9269 (if (or (eq t org-use-fast-tag-selection)
9270 (and org-use-fast-tag-selection
9271 (delq nil (mapcar 'cdr table))))
9272 (org-fast-tag-selection
9273 current-tags inherited-tags table
9274 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9275 (let ((org-add-colon-after-tag-completion t))
9276 (org-trim
9277 (org-without-partial-completion
9278 (completing-read "Tags: " 'org-tags-completion-function
9279 nil nil current 'org-tags-history)))))))
9280 (while (string-match "[-+&]+" tags)
9281 ;; No boolean logic, just a list
9282 (setq tags (replace-match ":" t t tags))))
9284 (if (string-match "\\`[\t ]*\\'" tags)
9285 (setq tags "")
9286 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9287 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9289 ;; Insert new tags at the correct column
9290 (beginning-of-line 1)
9291 (cond
9292 ((and (equal current "") (equal tags "")))
9293 ((re-search-forward
9294 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9295 (point-at-eol) t)
9296 (if (equal tags "")
9297 (setq rpl "")
9298 (goto-char (match-beginning 0))
9299 (setq c0 (current-column) p0 (point)
9300 c1 (max (1+ c0) (if (> org-tags-column 0)
9301 org-tags-column
9302 (- (- org-tags-column) (length tags))))
9303 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9304 (replace-match rpl t t)
9305 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9306 tags)
9307 (t (error "Tags alignment failed")))
9308 (org-move-to-column col)
9309 (unless just-align
9310 (run-hooks 'org-after-tags-change-hook)))))
9312 (defun org-change-tag-in-region (beg end tag off)
9313 "Add or remove TAG for each entry in the region.
9314 This works in the agenda, and also in an org-mode buffer."
9315 (interactive
9316 (list (region-beginning) (region-end)
9317 (let ((org-last-tags-completion-table
9318 (if (org-mode-p)
9319 (org-get-buffer-tags)
9320 (org-global-tags-completion-table))))
9321 (completing-read
9322 "Tag: " 'org-tags-completion-function nil nil nil
9323 'org-tags-history))
9324 (progn
9325 (message "[s]et or [r]emove? ")
9326 (equal (read-char-exclusive) ?r))))
9327 (if (fboundp 'deactivate-mark) (deactivate-mark))
9328 (let ((agendap (equal major-mode 'org-agenda-mode))
9329 l1 l2 m buf pos newhead (cnt 0))
9330 (goto-char end)
9331 (setq l2 (1- (org-current-line)))
9332 (goto-char beg)
9333 (setq l1 (org-current-line))
9334 (loop for l from l1 to l2 do
9335 (goto-line l)
9336 (setq m (get-text-property (point) 'org-hd-marker))
9337 (when (or (and (org-mode-p) (org-on-heading-p))
9338 (and agendap m))
9339 (setq buf (if agendap (marker-buffer m) (current-buffer))
9340 pos (if agendap m (point)))
9341 (with-current-buffer buf
9342 (save-excursion
9343 (save-restriction
9344 (goto-char pos)
9345 (setq cnt (1+ cnt))
9346 (org-toggle-tag tag (if off 'off 'on))
9347 (setq newhead (org-get-heading)))))
9348 (and agendap (org-agenda-change-all-lines newhead m))))
9349 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9351 (defun org-tags-completion-function (string predicate &optional flag)
9352 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9353 (confirm (lambda (x) (stringp (car x)))))
9354 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9355 (setq s1 (match-string 1 string)
9356 s2 (match-string 2 string))
9357 (setq s1 "" s2 string))
9358 (cond
9359 ((eq flag nil)
9360 ;; try completion
9361 (setq rtn (try-completion s2 ctable confirm))
9362 (if (stringp rtn)
9363 (setq rtn
9364 (concat s1 s2 (substring rtn (length s2))
9365 (if (and org-add-colon-after-tag-completion
9366 (assoc rtn ctable))
9367 ":" ""))))
9368 rtn)
9369 ((eq flag t)
9370 ;; all-completions
9371 (all-completions s2 ctable confirm)
9373 ((eq flag 'lambda)
9374 ;; exact match?
9375 (assoc s2 ctable)))
9378 (defun org-fast-tag-insert (kwd tags face &optional end)
9379 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9380 (insert (format "%-12s" (concat kwd ":"))
9381 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9382 (or end "")))
9384 (defun org-fast-tag-show-exit (flag)
9385 (save-excursion
9386 (goto-line 3)
9387 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9388 (replace-match ""))
9389 (when flag
9390 (end-of-line 1)
9391 (org-move-to-column (- (window-width) 19) t)
9392 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9394 (defun org-set-current-tags-overlay (current prefix)
9395 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9396 (if (featurep 'xemacs)
9397 (org-overlay-display org-tags-overlay (concat prefix s)
9398 'secondary-selection)
9399 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9400 (org-overlay-display org-tags-overlay (concat prefix s)))))
9402 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9403 "Fast tag selection with single keys.
9404 CURRENT is the current list of tags in the headline, INHERITED is the
9405 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9406 possibly with grouping information. TODO-TABLE is a similar table with
9407 TODO keywords, should these have keys assigned to them.
9408 If the keys are nil, a-z are automatically assigned.
9409 Returns the new tags string, or nil to not change the current settings."
9410 (let* ((fulltable (append table todo-table))
9411 (maxlen (apply 'max (mapcar
9412 (lambda (x)
9413 (if (stringp (car x)) (string-width (car x)) 0))
9414 fulltable)))
9415 (buf (current-buffer))
9416 (expert (eq org-fast-tag-selection-single-key 'expert))
9417 (buffer-tags nil)
9418 (fwidth (+ maxlen 3 1 3))
9419 (ncol (/ (- (window-width) 4) fwidth))
9420 (i-face 'org-done)
9421 (c-face 'org-todo)
9422 tg cnt e c char c1 c2 ntable tbl rtn
9423 ov-start ov-end ov-prefix
9424 (exit-after-next org-fast-tag-selection-single-key)
9425 (done-keywords org-done-keywords)
9426 groups ingroup)
9427 (save-excursion
9428 (beginning-of-line 1)
9429 (if (looking-at
9430 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9431 (setq ov-start (match-beginning 1)
9432 ov-end (match-end 1)
9433 ov-prefix "")
9434 (setq ov-start (1- (point-at-eol))
9435 ov-end (1+ ov-start))
9436 (skip-chars-forward "^\n\r")
9437 (setq ov-prefix
9438 (concat
9439 (buffer-substring (1- (point)) (point))
9440 (if (> (current-column) org-tags-column)
9442 (make-string (- org-tags-column (current-column)) ?\ ))))))
9443 (org-move-overlay org-tags-overlay ov-start ov-end)
9444 (save-window-excursion
9445 (if expert
9446 (set-buffer (get-buffer-create " *Org tags*"))
9447 (delete-other-windows)
9448 (split-window-vertically)
9449 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9450 (erase-buffer)
9451 (org-set-local 'org-done-keywords done-keywords)
9452 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9453 (org-fast-tag-insert "Current" current c-face "\n\n")
9454 (org-fast-tag-show-exit exit-after-next)
9455 (org-set-current-tags-overlay current ov-prefix)
9456 (setq tbl fulltable char ?a cnt 0)
9457 (while (setq e (pop tbl))
9458 (cond
9459 ((equal e '(:startgroup))
9460 (push '() groups) (setq ingroup t)
9461 (when (not (= cnt 0))
9462 (setq cnt 0)
9463 (insert "\n"))
9464 (insert "{ "))
9465 ((equal e '(:endgroup))
9466 (setq ingroup nil cnt 0)
9467 (insert "}\n"))
9469 (setq tg (car e) c2 nil)
9470 (if (cdr e)
9471 (setq c (cdr e))
9472 ;; automatically assign a character.
9473 (setq c1 (string-to-char
9474 (downcase (substring
9475 tg (if (= (string-to-char tg) ?@) 1 0)))))
9476 (if (or (rassoc c1 ntable) (rassoc c1 table))
9477 (while (or (rassoc char ntable) (rassoc char table))
9478 (setq char (1+ char)))
9479 (setq c2 c1))
9480 (setq c (or c2 char)))
9481 (if ingroup (push tg (car groups)))
9482 (setq tg (org-add-props tg nil 'face
9483 (cond
9484 ((not (assoc tg table))
9485 (org-get-todo-face tg))
9486 ((member tg current) c-face)
9487 ((member tg inherited) i-face)
9488 (t nil))))
9489 (if (and (= cnt 0) (not ingroup)) (insert " "))
9490 (insert "[" c "] " tg (make-string
9491 (- fwidth 4 (length tg)) ?\ ))
9492 (push (cons tg c) ntable)
9493 (when (= (setq cnt (1+ cnt)) ncol)
9494 (insert "\n")
9495 (if ingroup (insert " "))
9496 (setq cnt 0)))))
9497 (setq ntable (nreverse ntable))
9498 (insert "\n")
9499 (goto-char (point-min))
9500 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9501 (fit-window-to-buffer))
9502 (setq rtn
9503 (catch 'exit
9504 (while t
9505 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9506 (if groups " [!] no groups" " [!]groups")
9507 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9508 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9509 (cond
9510 ((= c ?\r) (throw 'exit t))
9511 ((= c ?!)
9512 (setq groups (not groups))
9513 (goto-char (point-min))
9514 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9515 ((= c ?\C-c)
9516 (if (not expert)
9517 (org-fast-tag-show-exit
9518 (setq exit-after-next (not exit-after-next)))
9519 (setq expert nil)
9520 (delete-other-windows)
9521 (split-window-vertically)
9522 (org-switch-to-buffer-other-window " *Org tags*")
9523 (and (fboundp 'fit-window-to-buffer)
9524 (fit-window-to-buffer))))
9525 ((or (= c ?\C-g)
9526 (and (= c ?q) (not (rassoc c ntable))))
9527 (org-detach-overlay org-tags-overlay)
9528 (setq quit-flag t))
9529 ((= c ?\ )
9530 (setq current nil)
9531 (if exit-after-next (setq exit-after-next 'now)))
9532 ((= c ?\t)
9533 (condition-case nil
9534 (setq tg (completing-read
9535 "Tag: "
9536 (or buffer-tags
9537 (with-current-buffer buf
9538 (org-get-buffer-tags)))))
9539 (quit (setq tg "")))
9540 (when (string-match "\\S-" tg)
9541 (add-to-list 'buffer-tags (list tg))
9542 (if (member tg current)
9543 (setq current (delete tg current))
9544 (push tg current)))
9545 (if exit-after-next (setq exit-after-next 'now)))
9546 ((setq e (rassoc c todo-table) tg (car e))
9547 (with-current-buffer buf
9548 (save-excursion (org-todo tg)))
9549 (if exit-after-next (setq exit-after-next 'now)))
9550 ((setq e (rassoc c ntable) tg (car e))
9551 (if (member tg current)
9552 (setq current (delete tg current))
9553 (loop for g in groups do
9554 (if (member tg g)
9555 (mapc (lambda (x)
9556 (setq current (delete x current)))
9557 g)))
9558 (push tg current))
9559 (if exit-after-next (setq exit-after-next 'now))))
9561 ;; Create a sorted list
9562 (setq current
9563 (sort current
9564 (lambda (a b)
9565 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9566 (if (eq exit-after-next 'now) (throw 'exit t))
9567 (goto-char (point-min))
9568 (beginning-of-line 2)
9569 (delete-region (point) (point-at-eol))
9570 (org-fast-tag-insert "Current" current c-face)
9571 (org-set-current-tags-overlay current ov-prefix)
9572 (while (re-search-forward
9573 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9574 (setq tg (match-string 1))
9575 (add-text-properties
9576 (match-beginning 1) (match-end 1)
9577 (list 'face
9578 (cond
9579 ((member tg current) c-face)
9580 ((member tg inherited) i-face)
9581 (t (get-text-property (match-beginning 1) 'face))))))
9582 (goto-char (point-min)))))
9583 (org-detach-overlay org-tags-overlay)
9584 (if rtn
9585 (mapconcat 'identity current ":")
9586 nil))))
9588 (defun org-get-tags-string ()
9589 "Get the TAGS string in the current headline."
9590 (unless (org-on-heading-p t)
9591 (error "Not on a heading"))
9592 (save-excursion
9593 (beginning-of-line 1)
9594 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9595 (org-match-string-no-properties 1)
9596 "")))
9598 (defun org-get-tags ()
9599 "Get the list of tags specified in the current headline."
9600 (org-split-string (org-get-tags-string) ":"))
9602 (defun org-get-buffer-tags ()
9603 "Get a table of all tags used in the buffer, for completion."
9604 (let (tags)
9605 (save-excursion
9606 (goto-char (point-min))
9607 (while (re-search-forward
9608 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9609 (when (equal (char-after (point-at-bol 0)) ?*)
9610 (mapc (lambda (x) (add-to-list 'tags x))
9611 (org-split-string (org-match-string-no-properties 1) ":")))))
9612 (mapcar 'list tags)))
9615 ;;;; Properties
9617 ;;; Setting and retrieving properties
9619 (defconst org-special-properties
9620 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9621 "TIMESTAMP" "TIMESTAMP_IA")
9622 "The special properties valid in Org-mode.
9624 These are properties that are not defined in the property drawer,
9625 but in some other way.")
9627 (defconst org-default-properties
9628 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9629 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9630 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE")
9631 "Some properties that are used by Org-mode for various purposes.
9632 Being in this list makes sure that they are offered for completion.")
9634 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9635 "Regular expression matching the first line of a property drawer.")
9637 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9638 "Regular expression matching the first line of a property drawer.")
9640 (defun org-property-action ()
9641 "Do an action on properties."
9642 (interactive)
9643 (let (c)
9644 (org-at-property-p)
9645 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9646 (setq c (read-char-exclusive))
9647 (cond
9648 ((equal c ?s)
9649 (call-interactively 'org-set-property))
9650 ((equal c ?d)
9651 (call-interactively 'org-delete-property))
9652 ((equal c ?D)
9653 (call-interactively 'org-delete-property-globally))
9654 ((equal c ?c)
9655 (call-interactively 'org-compute-property-at-point))
9656 (t (error "No such property action %c" c)))))
9658 (defun org-at-property-p ()
9659 "Is the cursor in a property line?"
9660 ;; FIXME: Does not check if we are actually in the drawer.
9661 ;; FIXME: also returns true on any drawers.....
9662 ;; This is used by C-c C-c for property action.
9663 (save-excursion
9664 (beginning-of-line 1)
9665 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9667 (defun org-get-property-block (&optional beg end force)
9668 "Return the (beg . end) range of the body of the property drawer.
9669 BEG and END can be beginning and end of subtree, if not given
9670 they will be found.
9671 If the drawer does not exist and FORCE is non-nil, create the drawer."
9672 (catch 'exit
9673 (save-excursion
9674 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9675 (end (or end (progn (outline-next-heading) (point)))))
9676 (goto-char beg)
9677 (if (re-search-forward org-property-start-re end t)
9678 (setq beg (1+ (match-end 0)))
9679 (if force
9680 (save-excursion
9681 (org-insert-property-drawer)
9682 (setq end (progn (outline-next-heading) (point))))
9683 (throw 'exit nil))
9684 (goto-char beg)
9685 (if (re-search-forward org-property-start-re end t)
9686 (setq beg (1+ (match-end 0)))))
9687 (if (re-search-forward org-property-end-re end t)
9688 (setq end (match-beginning 0))
9689 (or force (throw 'exit nil))
9690 (goto-char beg)
9691 (setq end beg)
9692 (org-indent-line-function)
9693 (insert ":END:\n"))
9694 (cons beg end)))))
9696 (defun org-entry-properties (&optional pom which)
9697 "Get all properties of the entry at point-or-marker POM.
9698 This includes the TODO keyword, the tags, time strings for deadline,
9699 scheduled, and clocking, and any additional properties defined in the
9700 entry. The return value is an alist, keys may occur multiple times
9701 if the property key was used several times.
9702 POM may also be nil, in which case the current entry is used.
9703 If WHICH is nil or `all', get all properties. If WHICH is
9704 `special' or `standard', only get that subclass."
9705 (setq which (or which 'all))
9706 (org-with-point-at pom
9707 (let ((clockstr (substring org-clock-string 0 -1))
9708 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9709 beg end range props sum-props key value string clocksum)
9710 (save-excursion
9711 (when (condition-case nil (org-back-to-heading t) (error nil))
9712 (setq beg (point))
9713 (setq sum-props (get-text-property (point) 'org-summaries))
9714 (setq clocksum (get-text-property (point) :org-clock-minutes))
9715 (outline-next-heading)
9716 (setq end (point))
9717 (when (memq which '(all special))
9718 ;; Get the special properties, like TODO and tags
9719 (goto-char beg)
9720 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9721 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9722 (when (looking-at org-priority-regexp)
9723 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9724 (when (and (setq value (org-get-tags-string))
9725 (string-match "\\S-" value))
9726 (push (cons "TAGS" value) props))
9727 (when (setq value (org-get-tags-at))
9728 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9729 props))
9730 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9731 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9732 string (if (equal key clockstr)
9733 (org-no-properties
9734 (org-trim
9735 (buffer-substring
9736 (match-beginning 3) (goto-char (point-at-eol)))))
9737 (substring (org-match-string-no-properties 3) 1 -1)))
9738 (unless key
9739 (if (= (char-after (match-beginning 3)) ?\[)
9740 (setq key "TIMESTAMP_IA")
9741 (setq key "TIMESTAMP")))
9742 (when (or (equal key clockstr) (not (assoc key props)))
9743 (push (cons key string) props)))
9747 (when (memq which '(all standard))
9748 ;; Get the standard properties, like :PORP: ...
9749 (setq range (org-get-property-block beg end))
9750 (when range
9751 (goto-char (car range))
9752 (while (re-search-forward
9753 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9754 (cdr range) t)
9755 (setq key (org-match-string-no-properties 1)
9756 value (org-trim (or (org-match-string-no-properties 2) "")))
9757 (unless (member key excluded)
9758 (push (cons key (or value "")) props)))))
9759 (if clocksum
9760 (push (cons "CLOCKSUM"
9761 (org-columns-number-to-string (/ (float clocksum) 60.)
9762 'add_times))
9763 props))
9764 (append sum-props (nreverse props)))))))
9766 (defun org-entry-get (pom property &optional inherit)
9767 "Get value of PROPERTY for entry at point-or-marker POM.
9768 If INHERIT is non-nil and the entry does not have the property,
9769 then also check higher levels of the hierarchy.
9770 If INHERIT is the symbol `selective', use inheritance only if the setting
9771 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9772 If the property is present but empty, the return value is the empty string.
9773 If the property is not present at all, nil is returned."
9774 (org-with-point-at pom
9775 (if (and inherit (if (eq inherit 'selective)
9776 (org-property-inherit-p property)
9778 (org-entry-get-with-inheritance property)
9779 (if (member property org-special-properties)
9780 ;; We need a special property. Use brute force, get all properties.
9781 (cdr (assoc property (org-entry-properties nil 'special)))
9782 (let ((range (org-get-property-block)))
9783 (if (and range
9784 (goto-char (car range))
9785 (re-search-forward
9786 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9787 (cdr range) t))
9788 ;; Found the property, return it.
9789 (if (match-end 1)
9790 (org-match-string-no-properties 1)
9791 "")))))))
9793 (defun org-property-or-variable-value (var &optional inherit)
9794 "Check if there is a property fixing the value of VAR.
9795 If yes, return this value. If not, return the current value of the variable."
9796 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9797 (if (and prop (stringp prop) (string-match "\\S-" prop))
9798 (read prop)
9799 (symbol-value var))))
9801 (defun org-entry-delete (pom property)
9802 "Delete the property PROPERTY from entry at point-or-marker POM."
9803 (org-with-point-at pom
9804 (if (member property org-special-properties)
9805 nil ; cannot delete these properties.
9806 (let ((range (org-get-property-block)))
9807 (if (and range
9808 (goto-char (car range))
9809 (re-search-forward
9810 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9811 (cdr range) t))
9812 (progn
9813 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9815 nil)))))
9817 ;; Multi-values properties are properties that contain multiple values
9818 ;; These values are assumed to be single words, separated by whitespace.
9819 (defun org-entry-add-to-multivalued-property (pom property value)
9820 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9821 (let* ((old (org-entry-get pom property))
9822 (values (and old (org-split-string old "[ \t]"))))
9823 (unless (member value values)
9824 (setq values (cons value values))
9825 (org-entry-put pom property
9826 (mapconcat 'identity values " ")))))
9828 (defun org-entry-remove-from-multivalued-property (pom property value)
9829 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9830 (let* ((old (org-entry-get pom property))
9831 (values (and old (org-split-string old "[ \t]"))))
9832 (when (member value values)
9833 (setq values (delete value values))
9834 (org-entry-put pom property
9835 (mapconcat 'identity values " ")))))
9837 (defun org-entry-member-in-multivalued-property (pom property value)
9838 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9839 (let* ((old (org-entry-get pom property))
9840 (values (and old (org-split-string old "[ \t]"))))
9841 (member value values)))
9843 (defvar org-entry-property-inherited-from (make-marker))
9845 (defun org-entry-get-with-inheritance (property)
9846 "Get entry property, and search higher levels if not present."
9847 (let (tmp)
9848 (save-excursion
9849 (save-restriction
9850 (widen)
9851 (catch 'ex
9852 (while t
9853 (when (setq tmp (org-entry-get nil property))
9854 (org-back-to-heading t)
9855 (move-marker org-entry-property-inherited-from (point))
9856 (throw 'ex tmp))
9857 (or (org-up-heading-safe) (throw 'ex nil)))))
9858 (or tmp
9859 (cdr (assoc property org-local-properties))
9860 (cdr (assoc property org-global-properties))
9861 (cdr (assoc property org-global-properties-fixed))))))
9863 (defun org-entry-put (pom property value)
9864 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9865 (org-with-point-at pom
9866 (org-back-to-heading t)
9867 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9868 range)
9869 (cond
9870 ((equal property "TODO")
9871 (when (and (stringp value) (string-match "\\S-" value)
9872 (not (member value org-todo-keywords-1)))
9873 (error "\"%s\" is not a valid TODO state" value))
9874 (if (or (not value)
9875 (not (string-match "\\S-" value)))
9876 (setq value 'none))
9877 (org-todo value)
9878 (org-set-tags nil 'align))
9879 ((equal property "PRIORITY")
9880 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9881 (string-to-char value) ?\ ))
9882 (org-set-tags nil 'align))
9883 ((equal property "SCHEDULED")
9884 (if (re-search-forward org-scheduled-time-regexp end t)
9885 (cond
9886 ((eq value 'earlier) (org-timestamp-change -1 'day))
9887 ((eq value 'later) (org-timestamp-change 1 'day))
9888 (t (call-interactively 'org-schedule)))
9889 (call-interactively 'org-schedule)))
9890 ((equal property "DEADLINE")
9891 (if (re-search-forward org-deadline-time-regexp end t)
9892 (cond
9893 ((eq value 'earlier) (org-timestamp-change -1 'day))
9894 ((eq value 'later) (org-timestamp-change 1 'day))
9895 (t (call-interactively 'org-deadline)))
9896 (call-interactively 'org-deadline)))
9897 ((member property org-special-properties)
9898 (error "The %s property can not yet be set with `org-entry-put'"
9899 property))
9900 (t ; a non-special property
9901 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9902 (setq range (org-get-property-block beg end 'force))
9903 (goto-char (car range))
9904 (if (re-search-forward
9905 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9906 (progn
9907 (delete-region (match-beginning 1) (match-end 1))
9908 (goto-char (match-beginning 1)))
9909 (goto-char (cdr range))
9910 (insert "\n")
9911 (backward-char 1)
9912 (org-indent-line-function)
9913 (insert ":" property ":"))
9914 (and value (insert " " value))
9915 (org-indent-line-function)))))))
9917 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9918 "Get all property keys in the current buffer.
9919 With INCLUDE-SPECIALS, also list the special properties that relect things
9920 like tags and TODO state.
9921 With INCLUDE-DEFAULTS, also include properties that has special meaning
9922 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9923 With INCLUDE-COLUMNS, also include property names given in COLUMN
9924 formats in the current buffer."
9925 (let (rtn range cfmt cols s p)
9926 (save-excursion
9927 (save-restriction
9928 (widen)
9929 (goto-char (point-min))
9930 (while (re-search-forward org-property-start-re nil t)
9931 (setq range (org-get-property-block))
9932 (goto-char (car range))
9933 (while (re-search-forward
9934 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9935 (cdr range) t)
9936 (add-to-list 'rtn (org-match-string-no-properties 1)))
9937 (outline-next-heading))))
9939 (when include-specials
9940 (setq rtn (append org-special-properties rtn)))
9942 (when include-defaults
9943 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9945 (when include-columns
9946 (save-excursion
9947 (save-restriction
9948 (widen)
9949 (goto-char (point-min))
9950 (while (re-search-forward
9951 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9952 nil t)
9953 (setq cfmt (match-string 2) s 0)
9954 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9955 cfmt s)
9956 (setq s (match-end 0)
9957 p (match-string 1 cfmt))
9958 (unless (or (equal p "ITEM")
9959 (member p org-special-properties))
9960 (add-to-list 'rtn (match-string 1 cfmt))))))))
9962 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9964 (defun org-property-values (key)
9965 "Return a list of all values of property KEY."
9966 (save-excursion
9967 (save-restriction
9968 (widen)
9969 (goto-char (point-min))
9970 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9971 values)
9972 (while (re-search-forward re nil t)
9973 (add-to-list 'values (org-trim (match-string 1))))
9974 (delete "" values)))))
9976 (defun org-insert-property-drawer ()
9977 "Insert a property drawer into the current entry."
9978 (interactive)
9979 (org-back-to-heading t)
9980 (looking-at outline-regexp)
9981 (let ((indent (- (match-end 0)(match-beginning 0)))
9982 (beg (point))
9983 (re (concat "^[ \t]*" org-keyword-time-regexp))
9984 end hiddenp)
9985 (outline-next-heading)
9986 (setq end (point))
9987 (goto-char beg)
9988 (while (re-search-forward re end t))
9989 (setq hiddenp (org-invisible-p))
9990 (end-of-line 1)
9991 (and (equal (char-after) ?\n) (forward-char 1))
9992 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9993 (beginning-of-line 2))
9994 (org-skip-over-state-notes)
9995 (skip-chars-backward " \t\n\r")
9996 (if (eq (char-before) ?*) (forward-char 1))
9997 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9998 (beginning-of-line 0)
9999 (org-indent-to-column indent)
10000 (beginning-of-line 2)
10001 (org-indent-to-column indent)
10002 (beginning-of-line 0)
10003 (if hiddenp
10004 (save-excursion
10005 (org-back-to-heading t)
10006 (hide-entry))
10007 (org-flag-drawer t))))
10009 (defun org-set-property (property value)
10010 "In the current entry, set PROPERTY to VALUE.
10011 When called interactively, this will prompt for a property name, offering
10012 completion on existing and default properties. And then it will prompt
10013 for a value, offering competion either on allowed values (via an inherited
10014 xxx_ALL property) or on existing values in other instances of this property
10015 in the current file."
10016 (interactive
10017 (let* ((completion-ignore-case t)
10018 (keys (org-buffer-property-keys nil t t))
10019 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10020 (prop (if (member prop0 keys)
10021 prop0
10022 (or (cdr (assoc (downcase prop0)
10023 (mapcar (lambda (x) (cons (downcase x) x))
10024 keys)))
10025 prop0)))
10026 (cur (org-entry-get nil prop))
10027 (allowed (org-property-get-allowed-values nil prop 'table))
10028 (existing (mapcar 'list (org-property-values prop)))
10029 (val (if allowed
10030 (org-completing-read "Value: " allowed nil 'req-match)
10031 (org-completing-read
10032 (concat "Value" (if (and cur (string-match "\\S-" cur))
10033 (concat "[" cur "]") "")
10034 ": ")
10035 existing nil nil "" nil cur))))
10036 (list prop (if (equal val "") cur val))))
10037 (unless (equal (org-entry-get nil property) value)
10038 (org-entry-put nil property value)))
10040 (defun org-delete-property (property)
10041 "In the current entry, delete PROPERTY."
10042 (interactive
10043 (let* ((completion-ignore-case t)
10044 (prop (completing-read
10045 "Property: " (org-entry-properties nil 'standard))))
10046 (list prop)))
10047 (message "Property %s %s" property
10048 (if (org-entry-delete nil property)
10049 "deleted"
10050 "was not present in the entry")))
10052 (defun org-delete-property-globally (property)
10053 "Remove PROPERTY globally, from all entries."
10054 (interactive
10055 (let* ((completion-ignore-case t)
10056 (prop (completing-read
10057 "Globally remove property: "
10058 (mapcar 'list (org-buffer-property-keys)))))
10059 (list prop)))
10060 (save-excursion
10061 (save-restriction
10062 (widen)
10063 (goto-char (point-min))
10064 (let ((cnt 0))
10065 (while (re-search-forward
10066 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10067 nil t)
10068 (setq cnt (1+ cnt))
10069 (replace-match ""))
10070 (message "Property \"%s\" removed from %d entries" property cnt)))))
10072 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10074 (defun org-compute-property-at-point ()
10075 "Compute the property at point.
10076 This looks for an enclosing column format, extracts the operator and
10077 then applies it to the proerty in the column format's scope."
10078 (interactive)
10079 (unless (org-at-property-p)
10080 (error "Not at a property"))
10081 (let ((prop (org-match-string-no-properties 2)))
10082 (org-columns-get-format-and-top-level)
10083 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10084 (error "No operator defined for property %s" prop))
10085 (org-columns-compute prop)))
10087 (defun org-property-get-allowed-values (pom property &optional table)
10088 "Get allowed values for the property PROPERTY.
10089 When TABLE is non-nil, return an alist that can directly be used for
10090 completion."
10091 (let (vals)
10092 (cond
10093 ((equal property "TODO")
10094 (setq vals (org-with-point-at pom
10095 (append org-todo-keywords-1 '("")))))
10096 ((equal property "PRIORITY")
10097 (let ((n org-lowest-priority))
10098 (while (>= n org-highest-priority)
10099 (push (char-to-string n) vals)
10100 (setq n (1- n)))))
10101 ((member property org-special-properties))
10103 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10105 (when (and vals (string-match "\\S-" vals))
10106 (setq vals (car (read-from-string (concat "(" vals ")"))))
10107 (setq vals (mapcar (lambda (x)
10108 (cond ((stringp x) x)
10109 ((numberp x) (number-to-string x))
10110 ((symbolp x) (symbol-name x))
10111 (t "???")))
10112 vals)))))
10113 (if table (mapcar 'list vals) vals)))
10115 (defun org-property-previous-allowed-value (&optional previous)
10116 "Switch to the next allowed value for this property."
10117 (interactive)
10118 (org-property-next-allowed-value t))
10120 (defun org-property-next-allowed-value (&optional previous)
10121 "Switch to the next allowed value for this property."
10122 (interactive)
10123 (unless (org-at-property-p)
10124 (error "Not at a property"))
10125 (let* ((key (match-string 2))
10126 (value (match-string 3))
10127 (allowed (or (org-property-get-allowed-values (point) key)
10128 (and (member value '("[ ]" "[-]" "[X]"))
10129 '("[ ]" "[X]"))))
10130 nval)
10131 (unless allowed
10132 (error "Allowed values for this property have not been defined"))
10133 (if previous (setq allowed (reverse allowed)))
10134 (if (member value allowed)
10135 (setq nval (car (cdr (member value allowed)))))
10136 (setq nval (or nval (car allowed)))
10137 (if (equal nval value)
10138 (error "Only one allowed value for this property"))
10139 (org-at-property-p)
10140 (replace-match (concat " :" key ": " nval) t t)
10141 (org-indent-line-function)
10142 (beginning-of-line 1)
10143 (skip-chars-forward " \t")))
10145 (defun org-find-entry-with-id (ident)
10146 "Locate the entry that contains the ID property with exact value IDENT.
10147 IDENT can be a string, a symbol or a number, this function will search for
10148 the string representation of it.
10149 Return the position where this entry starts, or nil if there is no such entry."
10150 (let ((id (cond
10151 ((stringp ident) ident)
10152 ((symbol-name ident) (symbol-name ident))
10153 ((numberp ident) (number-to-string ident))
10154 (t (error "IDENT %s must be a string, symbol or number" ident))))
10155 (case-fold-search nil))
10156 (save-excursion
10157 (save-restriction
10158 (widen)
10159 (goto-char (point-min))
10160 (when (re-search-forward
10161 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10162 nil t)
10163 (org-back-to-heading)
10164 (point))))))
10166 ;;;; Timestamps
10168 (defvar org-last-changed-timestamp nil)
10169 (defvar org-time-was-given) ; dynamically scoped parameter
10170 (defvar org-end-time-was-given) ; dynamically scoped parameter
10171 (defvar org-ts-what) ; dynamically scoped parameter
10173 (defun org-time-stamp (arg)
10174 "Prompt for a date/time and insert a time stamp.
10175 If the user specifies a time like HH:MM, or if this command is called
10176 with a prefix argument, the time stamp will contain date and time.
10177 Otherwise, only the date will be included. All parts of a date not
10178 specified by the user will be filled in from the current date/time.
10179 So if you press just return without typing anything, the time stamp
10180 will represent the current date/time. If there is already a timestamp
10181 at the cursor, it will be modified."
10182 (interactive "P")
10183 (let* ((ts nil)
10184 (default-time
10185 ;; Default time is either today, or, when entering a range,
10186 ;; the range start.
10187 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10188 (save-excursion
10189 (re-search-backward
10190 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10191 (- (point) 20) t)))
10192 (apply 'encode-time (org-parse-time-string (match-string 1)))
10193 (current-time)))
10194 (default-input (and ts (org-get-compact-tod ts)))
10195 org-time-was-given org-end-time-was-given time)
10196 (cond
10197 ((and (org-at-timestamp-p)
10198 (eq last-command 'org-time-stamp)
10199 (eq this-command 'org-time-stamp))
10200 (insert "--")
10201 (setq time (let ((this-command this-command))
10202 (org-read-date arg 'totime nil nil default-time default-input)))
10203 (org-insert-time-stamp time (or org-time-was-given arg)))
10204 ((org-at-timestamp-p)
10205 (setq time (let ((this-command this-command))
10206 (org-read-date arg 'totime nil nil default-time default-input)))
10207 (when (org-at-timestamp-p) ; just to get the match data
10208 (replace-match "")
10209 (setq org-last-changed-timestamp
10210 (org-insert-time-stamp
10211 time (or org-time-was-given arg)
10212 nil nil nil (list org-end-time-was-given))))
10213 (message "Timestamp updated"))
10215 (setq time (let ((this-command this-command))
10216 (org-read-date arg 'totime nil nil default-time default-input)))
10217 (org-insert-time-stamp time (or org-time-was-given arg)
10218 nil nil nil (list org-end-time-was-given))))))
10220 ;; FIXME: can we use this for something else, like computing time differences?
10221 (defun org-get-compact-tod (s)
10222 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10223 (let* ((t1 (match-string 1 s))
10224 (h1 (string-to-number (match-string 2 s)))
10225 (m1 (string-to-number (match-string 3 s)))
10226 (t2 (and (match-end 4) (match-string 5 s)))
10227 (h2 (and t2 (string-to-number (match-string 6 s))))
10228 (m2 (and t2 (string-to-number (match-string 7 s))))
10229 dh dm)
10230 (if (not t2)
10232 (setq dh (- h2 h1) dm (- m2 m1))
10233 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10234 (concat t1 "+" (number-to-string dh)
10235 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10237 (defun org-time-stamp-inactive (&optional arg)
10238 "Insert an inactive time stamp.
10239 An inactive time stamp is enclosed in square brackets instead of angle
10240 brackets. It is inactive in the sense that it does not trigger agenda entries,
10241 does not link to the calendar and cannot be changed with the S-cursor keys.
10242 So these are more for recording a certain time/date."
10243 (interactive "P")
10244 (let (org-time-was-given org-end-time-was-given time)
10245 (setq time (org-read-date arg 'totime))
10246 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10247 nil nil (list org-end-time-was-given))))
10249 (defvar org-date-ovl (org-make-overlay 1 1))
10250 (org-overlay-put org-date-ovl 'face 'org-warning)
10251 (org-detach-overlay org-date-ovl)
10253 (defvar org-ans1) ; dynamically scoped parameter
10254 (defvar org-ans2) ; dynamically scoped parameter
10256 (defvar org-plain-time-of-day-regexp) ; defined below
10258 (defvar org-read-date-overlay nil)
10259 (defvar org-dcst nil) ; dynamically scoped
10261 (defun org-read-date (&optional with-time to-time from-string prompt
10262 default-time default-input)
10263 "Read a date, possibly a time, and make things smooth for the user.
10264 The prompt will suggest to enter an ISO date, but you can also enter anything
10265 which will at least partially be understood by `parse-time-string'.
10266 Unrecognized parts of the date will default to the current day, month, year,
10267 hour and minute. If this command is called to replace a timestamp at point,
10268 of to enter the second timestamp of a range, the default time is taken from the
10269 existing stamp. For example,
10270 3-2-5 --> 2003-02-05
10271 feb 15 --> currentyear-02-15
10272 sep 12 9 --> 2009-09-12
10273 12:45 --> today 12:45
10274 22 sept 0:34 --> currentyear-09-22 0:34
10275 12 --> currentyear-currentmonth-12
10276 Fri --> nearest Friday (today or later)
10277 etc.
10279 Furthermore you can specify a relative date by giving, as the *first* thing
10280 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10281 change in days weeks, months, years.
10282 With a single plus or minus, the date is relative to today. With a double
10283 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10284 +4d --> four days from today
10285 +4 --> same as above
10286 +2w --> two weeks from today
10287 ++5 --> five days from default date
10289 The function understands only English month and weekday abbreviations,
10290 but this can be configured with the variables `parse-time-months' and
10291 `parse-time-weekdays'.
10293 While prompting, a calendar is popped up - you can also select the
10294 date with the mouse (button 1). The calendar shows a period of three
10295 months. To scroll it to other months, use the keys `>' and `<'.
10296 If you don't like the calendar, turn it off with
10297 \(setq org-read-date-popup-calendar nil)
10299 With optional argument TO-TIME, the date will immediately be converted
10300 to an internal time.
10301 With an optional argument WITH-TIME, the prompt will suggest to also
10302 insert a time. Note that when WITH-TIME is not set, you can still
10303 enter a time, and this function will inform the calling routine about
10304 this change. The calling routine may then choose to change the format
10305 used to insert the time stamp into the buffer to include the time.
10306 With optional argument FROM-STRING, read from this string instead from
10307 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10308 the time/date that is used for everything that is not specified by the
10309 user."
10310 (require 'parse-time)
10311 (let* ((org-time-stamp-rounding-minutes
10312 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10313 (org-dcst org-display-custom-times)
10314 (ct (org-current-time))
10315 (def (or default-time ct))
10316 (defdecode (decode-time def))
10317 (dummy (progn
10318 (when (< (nth 2 defdecode) org-extend-today-until)
10319 (setcar (nthcdr 2 defdecode) -1)
10320 (setcar (nthcdr 1 defdecode) 59)
10321 (setq def (apply 'encode-time defdecode)
10322 defdecode (decode-time def)))))
10323 (calendar-move-hook nil)
10324 (calendar-view-diary-initially-flag nil)
10325 (view-diary-entries-initially nil)
10326 (calendar-view-holidays-initially-flag nil)
10327 (view-calendar-holidays-initially nil)
10328 (timestr (format-time-string
10329 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10330 (prompt (concat (if prompt (concat prompt " ") "")
10331 (format "Date+time [%s]: " timestr)))
10332 ans (org-ans0 "") org-ans1 org-ans2 final)
10334 (cond
10335 (from-string (setq ans from-string))
10336 (org-read-date-popup-calendar
10337 (save-excursion
10338 (save-window-excursion
10339 (calendar)
10340 (calendar-forward-day (- (time-to-days def)
10341 (calendar-absolute-from-gregorian
10342 (calendar-current-date))))
10343 (org-eval-in-calendar nil t)
10344 (let* ((old-map (current-local-map))
10345 (map (copy-keymap calendar-mode-map))
10346 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10347 (org-defkey map (kbd "RET") 'org-calendar-select)
10348 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10349 'org-calendar-select-mouse)
10350 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10351 'org-calendar-select-mouse)
10352 (org-defkey minibuffer-local-map [(meta shift left)]
10353 (lambda () (interactive)
10354 (org-eval-in-calendar '(calendar-backward-month 1))))
10355 (org-defkey minibuffer-local-map [(meta shift right)]
10356 (lambda () (interactive)
10357 (org-eval-in-calendar '(calendar-forward-month 1))))
10358 (org-defkey minibuffer-local-map [(meta shift up)]
10359 (lambda () (interactive)
10360 (org-eval-in-calendar '(calendar-backward-year 1))))
10361 (org-defkey minibuffer-local-map [(meta shift down)]
10362 (lambda () (interactive)
10363 (org-eval-in-calendar '(calendar-forward-year 1))))
10364 (org-defkey minibuffer-local-map [(shift up)]
10365 (lambda () (interactive)
10366 (org-eval-in-calendar '(calendar-backward-week 1))))
10367 (org-defkey minibuffer-local-map [(shift down)]
10368 (lambda () (interactive)
10369 (org-eval-in-calendar '(calendar-forward-week 1))))
10370 (org-defkey minibuffer-local-map [(shift left)]
10371 (lambda () (interactive)
10372 (org-eval-in-calendar '(calendar-backward-day 1))))
10373 (org-defkey minibuffer-local-map [(shift right)]
10374 (lambda () (interactive)
10375 (org-eval-in-calendar '(calendar-forward-day 1))))
10376 (org-defkey minibuffer-local-map ">"
10377 (lambda () (interactive)
10378 (org-eval-in-calendar '(scroll-calendar-left 1))))
10379 (org-defkey minibuffer-local-map "<"
10380 (lambda () (interactive)
10381 (org-eval-in-calendar '(scroll-calendar-right 1))))
10382 (unwind-protect
10383 (progn
10384 (use-local-map map)
10385 (add-hook 'post-command-hook 'org-read-date-display)
10386 (setq org-ans0 (read-string prompt default-input nil nil))
10387 ;; org-ans0: from prompt
10388 ;; org-ans1: from mouse click
10389 ;; org-ans2: from calendar motion
10390 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10391 (remove-hook 'post-command-hook 'org-read-date-display)
10392 (use-local-map old-map)
10393 (when org-read-date-overlay
10394 (org-delete-overlay org-read-date-overlay)
10395 (setq org-read-date-overlay nil)))))))
10397 (t ; Naked prompt only
10398 (unwind-protect
10399 (setq ans (read-string prompt default-input nil timestr))
10400 (when org-read-date-overlay
10401 (org-delete-overlay org-read-date-overlay)
10402 (setq org-read-date-overlay nil)))))
10404 (setq final (org-read-date-analyze ans def defdecode))
10406 (if to-time
10407 (apply 'encode-time final)
10408 (if (and (boundp 'org-time-was-given) org-time-was-given)
10409 (format "%04d-%02d-%02d %02d:%02d"
10410 (nth 5 final) (nth 4 final) (nth 3 final)
10411 (nth 2 final) (nth 1 final))
10412 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10413 (defvar def)
10414 (defvar defdecode)
10415 (defvar with-time)
10416 (defun org-read-date-display ()
10417 "Display the currrent date prompt interpretation in the minibuffer."
10418 (when org-read-date-display-live
10419 (when org-read-date-overlay
10420 (org-delete-overlay org-read-date-overlay))
10421 (let ((p (point)))
10422 (end-of-line 1)
10423 (while (not (equal (buffer-substring
10424 (max (point-min) (- (point) 4)) (point))
10425 " "))
10426 (insert " "))
10427 (goto-char p))
10428 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10429 " " (or org-ans1 org-ans2)))
10430 (org-end-time-was-given nil)
10431 (f (org-read-date-analyze ans def defdecode))
10432 (fmts (if org-dcst
10433 org-time-stamp-custom-formats
10434 org-time-stamp-formats))
10435 (fmt (if (or with-time
10436 (and (boundp 'org-time-was-given) org-time-was-given))
10437 (cdr fmts)
10438 (car fmts)))
10439 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10440 (when (and org-end-time-was-given
10441 (string-match org-plain-time-of-day-regexp txt))
10442 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10443 org-end-time-was-given
10444 (substring txt (match-end 0)))))
10445 (setq org-read-date-overlay
10446 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10447 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10449 (defun org-read-date-analyze (ans def defdecode)
10450 "Analyze the combined answer of the date prompt."
10451 ;; FIXME: cleanup and comment
10452 (let (delta deltan deltaw deltadef year month day
10453 hour minute second wday pm h2 m2 tl wday1
10454 iso-year iso-weekday iso-week iso-year iso-date)
10456 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10457 (setq ans "+0"))
10459 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10460 (setq ans (replace-match "" t t ans)
10461 deltan (car delta)
10462 deltaw (nth 1 delta)
10463 deltadef (nth 2 delta)))
10465 ;; Check if there is an iso week date in there
10466 ;; If yes, sore the info and ostpone interpreting it until the rest
10467 ;; of the parsing is done
10468 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10469 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10470 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10471 iso-week (string-to-number (match-string 2 ans)))
10472 (setq ans (replace-match "" t t ans)))
10474 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10475 (when (string-match
10476 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10477 (setq year (if (match-end 2)
10478 (string-to-number (match-string 2 ans))
10479 (string-to-number (format-time-string "%Y")))
10480 month (string-to-number (match-string 3 ans))
10481 day (string-to-number (match-string 4 ans)))
10482 (if (< year 100) (setq year (+ 2000 year)))
10483 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10484 t nil ans)))
10485 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10486 ;; If there is a time with am/pm, and *no* time without it, we convert
10487 ;; so that matching will be successful.
10488 (loop for i from 1 to 2 do ; twice, for end time as well
10489 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10490 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10491 (setq hour (string-to-number (match-string 1 ans))
10492 minute (if (match-end 3)
10493 (string-to-number (match-string 3 ans))
10495 pm (equal ?p
10496 (string-to-char (downcase (match-string 4 ans)))))
10497 (if (and (= hour 12) (not pm))
10498 (setq hour 0)
10499 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10500 (setq ans (replace-match (format "%02d:%02d" hour minute)
10501 t t ans))))
10503 ;; Check if a time range is given as a duration
10504 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10505 (setq hour (string-to-number (match-string 1 ans))
10506 h2 (+ hour (string-to-number (match-string 3 ans)))
10507 minute (string-to-number (match-string 2 ans))
10508 m2 (+ minute (if (match-end 5) (string-to-number
10509 (match-string 5 ans))0)))
10510 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10511 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10512 t t ans)))
10514 ;; Check if there is a time range
10515 (when (boundp 'org-end-time-was-given)
10516 (setq org-time-was-given nil)
10517 (when (and (string-match org-plain-time-of-day-regexp ans)
10518 (match-end 8))
10519 (setq org-end-time-was-given (match-string 8 ans))
10520 (setq ans (concat (substring ans 0 (match-beginning 7))
10521 (substring ans (match-end 7))))))
10523 (setq tl (parse-time-string ans)
10524 day (or (nth 3 tl) (nth 3 defdecode))
10525 month (or (nth 4 tl)
10526 (if (and org-read-date-prefer-future
10527 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10528 (1+ (nth 4 defdecode))
10529 (nth 4 defdecode)))
10530 year (or (nth 5 tl)
10531 (if (and org-read-date-prefer-future
10532 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10533 (1+ (nth 5 defdecode))
10534 (nth 5 defdecode)))
10535 hour (or (nth 2 tl) (nth 2 defdecode))
10536 minute (or (nth 1 tl) (nth 1 defdecode))
10537 second (or (nth 0 tl) 0)
10538 wday (nth 6 tl))
10540 ;; Special date definitions below
10541 (cond
10542 (iso-week
10543 ;; There was an iso week
10544 (setq year (or iso-year year)
10545 day (or iso-weekday wday 1)
10546 wday nil ; to make sure that the trigger below does not match
10547 iso-date (calendar-gregorian-from-absolute
10548 (calendar-absolute-from-iso
10549 (list iso-week day year))))
10550 ; FIXME: Should we also push ISO weeks into the future?
10551 ; (when (and org-read-date-prefer-future
10552 ; (not iso-year)
10553 ; (< (calendar-absolute-from-gregorian iso-date)
10554 ; (time-to-days (current-time))))
10555 ; (setq year (1+ year)
10556 ; iso-date (calendar-gregorian-from-absolute
10557 ; (calendar-absolute-from-iso
10558 ; (list iso-week day year)))))
10559 (setq month (car iso-date)
10560 year (nth 2 iso-date)
10561 day (nth 1 iso-date)))
10562 (deltan
10563 (unless deltadef
10564 (let ((now (decode-time (current-time))))
10565 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10566 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10567 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10568 ((equal deltaw "m") (setq month (+ month deltan)))
10569 ((equal deltaw "y") (setq year (+ year deltan)))))
10570 ((and wday (not (nth 3 tl)))
10571 ;; Weekday was given, but no day, so pick that day in the week
10572 ;; on or after the derived date.
10573 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10574 (unless (equal wday wday1)
10575 (setq day (+ day (% (- wday wday1 -7) 7))))))
10576 (if (and (boundp 'org-time-was-given)
10577 (nth 2 tl))
10578 (setq org-time-was-given t))
10579 (if (< year 100) (setq year (+ 2000 year)))
10580 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10581 (list second minute hour day month year)))
10583 (defvar parse-time-weekdays)
10585 (defun org-read-date-get-relative (s today default)
10586 "Check string S for special relative date string.
10587 TODAY and DEFAULT are internal times, for today and for a default.
10588 Return shift list (N what def-flag)
10589 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10590 N is the number of WHATs to shift.
10591 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10592 the DEFAULT date rather than TODAY."
10593 (when (and
10594 (string-match
10595 (concat
10596 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10597 "\\([0-9]+\\)?"
10598 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10599 "\\([ \t]\\|$\\)") s)
10600 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10601 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10602 (string-to-char (substring (match-string 1 s) -1))
10603 ?+))
10604 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10605 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10606 (what (if (match-end 3) (match-string 3 s) "d"))
10607 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10608 (date (if rel default today))
10609 (wday (nth 6 (decode-time date)))
10610 delta)
10611 (if wday1
10612 (progn
10613 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10614 (if (= dir ?-) (setq delta (- delta 7)))
10615 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10616 (list delta "d" rel))
10617 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10619 (defun org-eval-in-calendar (form &optional keepdate)
10620 "Eval FORM in the calendar window and return to current window.
10621 Also, store the cursor date in variable org-ans2."
10622 (let ((sw (selected-window)))
10623 (select-window (get-buffer-window "*Calendar*"))
10624 (eval form)
10625 (when (and (not keepdate) (calendar-cursor-to-date))
10626 (let* ((date (calendar-cursor-to-date))
10627 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10628 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10629 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10630 (select-window sw)))
10632 ; ;; Update the prompt to show new default date
10633 ; (save-excursion
10634 ; (goto-char (point-min))
10635 ; (when (and org-ans2
10636 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10637 ; (get-text-property (match-end 0) 'field))
10638 ; (let ((inhibit-read-only t))
10639 ; (replace-match (concat "[" org-ans2 "]") t t)
10640 ; (add-text-properties (point-min) (1+ (match-end 0))
10641 ; (text-properties-at (1+ (point-min)))))))))
10643 (defun org-calendar-select ()
10644 "Return to `org-read-date' with the date currently selected.
10645 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10646 (interactive)
10647 (when (calendar-cursor-to-date)
10648 (let* ((date (calendar-cursor-to-date))
10649 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10650 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10651 (if (active-minibuffer-window) (exit-minibuffer))))
10653 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10654 "Insert a date stamp for the date given by the internal TIME.
10655 WITH-HM means, use the stamp format that includes the time of the day.
10656 INACTIVE means use square brackets instead of angular ones, so that the
10657 stamp will not contribute to the agenda.
10658 PRE and POST are optional strings to be inserted before and after the
10659 stamp.
10660 The command returns the inserted time stamp."
10661 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10662 stamp)
10663 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10664 (insert-before-markers (or pre ""))
10665 (insert-before-markers (setq stamp (format-time-string fmt time)))
10666 (when (listp extra)
10667 (setq extra (car extra))
10668 (if (and (stringp extra)
10669 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10670 (setq extra (format "-%02d:%02d"
10671 (string-to-number (match-string 1 extra))
10672 (string-to-number (match-string 2 extra))))
10673 (setq extra nil)))
10674 (when extra
10675 (backward-char 1)
10676 (insert-before-markers extra)
10677 (forward-char 1))
10678 (insert-before-markers (or post ""))
10679 stamp))
10681 (defun org-toggle-time-stamp-overlays ()
10682 "Toggle the use of custom time stamp formats."
10683 (interactive)
10684 (setq org-display-custom-times (not org-display-custom-times))
10685 (unless org-display-custom-times
10686 (let ((p (point-min)) (bmp (buffer-modified-p)))
10687 (while (setq p (next-single-property-change p 'display))
10688 (if (and (get-text-property p 'display)
10689 (eq (get-text-property p 'face) 'org-date))
10690 (remove-text-properties
10691 p (setq p (next-single-property-change p 'display))
10692 '(display t))))
10693 (set-buffer-modified-p bmp)))
10694 (if (featurep 'xemacs)
10695 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10696 (org-restart-font-lock)
10697 (setq org-table-may-need-update t)
10698 (if org-display-custom-times
10699 (message "Time stamps are overlayed with custom format")
10700 (message "Time stamp overlays removed")))
10702 (defun org-display-custom-time (beg end)
10703 "Overlay modified time stamp format over timestamp between BEG and END."
10704 (let* ((ts (buffer-substring beg end))
10705 t1 w1 with-hm tf time str w2 (off 0))
10706 (save-match-data
10707 (setq t1 (org-parse-time-string ts t))
10708 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10709 (setq off (- (match-end 0) (match-beginning 0)))))
10710 (setq end (- end off))
10711 (setq w1 (- end beg)
10712 with-hm (and (nth 1 t1) (nth 2 t1))
10713 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10714 time (org-fix-decoded-time t1)
10715 str (org-add-props
10716 (format-time-string
10717 (substring tf 1 -1) (apply 'encode-time time))
10718 nil 'mouse-face 'highlight)
10719 w2 (length str))
10720 (if (not (= w2 w1))
10721 (add-text-properties (1+ beg) (+ 2 beg)
10722 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10723 (if (featurep 'xemacs)
10724 (progn
10725 (put-text-property beg end 'invisible t)
10726 (put-text-property beg end 'end-glyph (make-glyph str)))
10727 (put-text-property beg end 'display str))))
10729 (defun org-translate-time (string)
10730 "Translate all timestamps in STRING to custom format.
10731 But do this only if the variable `org-display-custom-times' is set."
10732 (when org-display-custom-times
10733 (save-match-data
10734 (let* ((start 0)
10735 (re org-ts-regexp-both)
10736 t1 with-hm inactive tf time str beg end)
10737 (while (setq start (string-match re string start))
10738 (setq beg (match-beginning 0)
10739 end (match-end 0)
10740 t1 (save-match-data
10741 (org-parse-time-string (substring string beg end) t))
10742 with-hm (and (nth 1 t1) (nth 2 t1))
10743 inactive (equal (substring string beg (1+ beg)) "[")
10744 tf (funcall (if with-hm 'cdr 'car)
10745 org-time-stamp-custom-formats)
10746 time (org-fix-decoded-time t1)
10747 str (format-time-string
10748 (concat
10749 (if inactive "[" "<") (substring tf 1 -1)
10750 (if inactive "]" ">"))
10751 (apply 'encode-time time))
10752 string (replace-match str t t string)
10753 start (+ start (length str)))))))
10754 string)
10756 (defun org-fix-decoded-time (time)
10757 "Set 0 instead of nil for the first 6 elements of time.
10758 Don't touch the rest."
10759 (let ((n 0))
10760 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10762 (defun org-days-to-time (timestamp-string)
10763 "Difference between TIMESTAMP-STRING and now in days."
10764 (- (time-to-days (org-time-string-to-time timestamp-string))
10765 (time-to-days (current-time))))
10767 (defun org-deadline-close (timestamp-string &optional ndays)
10768 "Is the time in TIMESTAMP-STRING close to the current date?"
10769 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10770 (and (< (org-days-to-time timestamp-string) ndays)
10771 (not (org-entry-is-done-p))))
10773 (defun org-get-wdays (ts)
10774 "Get the deadline lead time appropriate for timestring TS."
10775 (cond
10776 ((<= org-deadline-warning-days 0)
10777 ;; 0 or negative, enforce this value no matter what
10778 (- org-deadline-warning-days))
10779 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10780 ;; lead time is specified.
10781 (floor (* (string-to-number (match-string 1 ts))
10782 (cdr (assoc (match-string 2 ts)
10783 '(("d" . 1) ("w" . 7)
10784 ("m" . 30.4) ("y" . 365.25)))))))
10785 ;; go for the default.
10786 (t org-deadline-warning-days)))
10788 (defun org-calendar-select-mouse (ev)
10789 "Return to `org-read-date' with the date currently selected.
10790 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10791 (interactive "e")
10792 (mouse-set-point ev)
10793 (when (calendar-cursor-to-date)
10794 (let* ((date (calendar-cursor-to-date))
10795 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10796 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10797 (if (active-minibuffer-window) (exit-minibuffer))))
10799 (defun org-check-deadlines (ndays)
10800 "Check if there are any deadlines due or past due.
10801 A deadline is considered due if it happens within `org-deadline-warning-days'
10802 days from today's date. If the deadline appears in an entry marked DONE,
10803 it is not shown. The prefix arg NDAYS can be used to test that many
10804 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10805 (interactive "P")
10806 (let* ((org-warn-days
10807 (cond
10808 ((equal ndays '(4)) 100000)
10809 (ndays (prefix-numeric-value ndays))
10810 (t (abs org-deadline-warning-days))))
10811 (case-fold-search nil)
10812 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10813 (callback
10814 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10816 (message "%d deadlines past-due or due within %d days"
10817 (org-occur regexp nil callback)
10818 org-warn-days)))
10820 (defun org-check-before-date (date)
10821 "Check if there are deadlines or scheduled entries before DATE."
10822 (interactive (list (org-read-date)))
10823 (let ((case-fold-search nil)
10824 (regexp (concat "\\<\\(" org-deadline-string
10825 "\\|" org-scheduled-string
10826 "\\) *<\\([^>]+\\)>"))
10827 (callback
10828 (lambda () (time-less-p
10829 (org-time-string-to-time (match-string 2))
10830 (org-time-string-to-time date)))))
10831 (message "%d entries before %s"
10832 (org-occur regexp nil callback) date)))
10834 (defun org-evaluate-time-range (&optional to-buffer)
10835 "Evaluate a time range by computing the difference between start and end.
10836 Normally the result is just printed in the echo area, but with prefix arg
10837 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10838 If the time range is actually in a table, the result is inserted into the
10839 next column.
10840 For time difference computation, a year is assumed to be exactly 365
10841 days in order to avoid rounding problems."
10842 (interactive "P")
10844 (org-clock-update-time-maybe)
10845 (save-excursion
10846 (unless (org-at-date-range-p t)
10847 (goto-char (point-at-bol))
10848 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10849 (if (not (org-at-date-range-p t))
10850 (error "Not at a time-stamp range, and none found in current line")))
10851 (let* ((ts1 (match-string 1))
10852 (ts2 (match-string 2))
10853 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10854 (match-end (match-end 0))
10855 (time1 (org-time-string-to-time ts1))
10856 (time2 (org-time-string-to-time ts2))
10857 (t1 (time-to-seconds time1))
10858 (t2 (time-to-seconds time2))
10859 (diff (abs (- t2 t1)))
10860 (negative (< (- t2 t1) 0))
10861 ;; (ys (floor (* 365 24 60 60)))
10862 (ds (* 24 60 60))
10863 (hs (* 60 60))
10864 (fy "%dy %dd %02d:%02d")
10865 (fy1 "%dy %dd")
10866 (fd "%dd %02d:%02d")
10867 (fd1 "%dd")
10868 (fh "%02d:%02d")
10869 y d h m align)
10870 (if havetime
10871 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10873 d (floor (/ diff ds)) diff (mod diff ds)
10874 h (floor (/ diff hs)) diff (mod diff hs)
10875 m (floor (/ diff 60)))
10876 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10878 d (floor (+ (/ diff ds) 0.5))
10879 h 0 m 0))
10880 (if (not to-buffer)
10881 (message "%s" (org-make-tdiff-string y d h m))
10882 (if (org-at-table-p)
10883 (progn
10884 (goto-char match-end)
10885 (setq align t)
10886 (and (looking-at " *|") (goto-char (match-end 0))))
10887 (goto-char match-end))
10888 (if (looking-at
10889 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10890 (replace-match ""))
10891 (if negative (insert " -"))
10892 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10893 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10894 (insert " " (format fh h m))))
10895 (if align (org-table-align))
10896 (message "Time difference inserted")))))
10898 (defun org-make-tdiff-string (y d h m)
10899 (let ((fmt "")
10900 (l nil))
10901 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10902 l (push y l)))
10903 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10904 l (push d l)))
10905 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10906 l (push h l)))
10907 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10908 l (push m l)))
10909 (apply 'format fmt (nreverse l))))
10911 (defun org-time-string-to-time (s)
10912 (apply 'encode-time (org-parse-time-string s)))
10914 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10915 "Convert a time stamp to an absolute day number.
10916 If there is a specifyer for a cyclic time stamp, get the closest date to
10917 DAYNR.
10918 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10919 (cond
10920 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10921 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10922 daynr
10923 (+ daynr 1000)))
10924 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10925 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10926 (time-to-days (current-time))) (match-string 0 s)
10927 prefer show-all))
10928 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10930 (defun org-days-to-iso-week (days)
10931 "Return the iso week number."
10932 (require 'cal-iso)
10933 (car (calendar-iso-from-absolute days)))
10935 (defun org-small-year-to-year (year)
10936 "Convert 2-digit years into 4-digit years.
10937 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10938 The year 2000 cannot be abbreviated. Any year lager than 99
10939 is retrned unchanged."
10940 (if (< year 38)
10941 (setq year (+ 2000 year))
10942 (if (< year 100)
10943 (setq year (+ 1900 year))))
10944 year)
10946 (defun org-time-from-absolute (d)
10947 "Return the time corresponding to date D.
10948 D may be an absolute day number, or a calendar-type list (month day year)."
10949 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10950 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10952 (defun org-calendar-holiday ()
10953 "List of holidays, for Diary display in Org-mode."
10954 (require 'holidays)
10955 (let ((hl (funcall
10956 (if (fboundp 'calendar-check-holidays)
10957 'calendar-check-holidays 'check-calendar-holidays) date)))
10958 (if hl (mapconcat 'identity hl "; "))))
10960 (defun org-diary-sexp-entry (sexp entry date)
10961 "Process a SEXP diary ENTRY for DATE."
10962 (require 'diary-lib)
10963 (let ((result (if calendar-debug-sexp
10964 (let ((stack-trace-on-error t))
10965 (eval (car (read-from-string sexp))))
10966 (condition-case nil
10967 (eval (car (read-from-string sexp)))
10968 (error
10969 (beep)
10970 (message "Bad sexp at line %d in %s: %s"
10971 (org-current-line)
10972 (buffer-file-name) sexp)
10973 (sleep-for 2))))))
10974 (cond ((stringp result) result)
10975 ((and (consp result)
10976 (stringp (cdr result))) (cdr result))
10977 (result entry)
10978 (t nil))))
10980 (defun org-diary-to-ical-string (frombuf)
10981 "Get iCalendar entries from diary entries in buffer FROMBUF.
10982 This uses the icalendar.el library."
10983 (let* ((tmpdir (if (featurep 'xemacs)
10984 (temp-directory)
10985 temporary-file-directory))
10986 (tmpfile (make-temp-name
10987 (expand-file-name "orgics" tmpdir)))
10988 buf rtn b e)
10989 (save-excursion
10990 (set-buffer frombuf)
10991 (icalendar-export-region (point-min) (point-max) tmpfile)
10992 (setq buf (find-buffer-visiting tmpfile))
10993 (set-buffer buf)
10994 (goto-char (point-min))
10995 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10996 (setq b (match-beginning 0)))
10997 (goto-char (point-max))
10998 (if (re-search-backward "^END:VEVENT" nil t)
10999 (setq e (match-end 0)))
11000 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11001 (kill-buffer buf)
11002 (kill-buffer frombuf)
11003 (delete-file tmpfile)
11004 rtn))
11006 (defun org-closest-date (start current change prefer show-all)
11007 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11008 When PREFER is `past' return a date that is either CURRENT or past.
11009 When PREFER is `future', return a date that is either CURRENT or future.
11010 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11011 ;; Make the proper lists from the dates
11012 (catch 'exit
11013 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11014 dn dw sday cday n1 n2
11015 d m y y1 y2 date1 date2 nmonths nm ny m2)
11017 (setq start (org-date-to-gregorian start)
11018 current (org-date-to-gregorian
11019 (if show-all
11020 current
11021 (time-to-days (current-time))))
11022 sday (calendar-absolute-from-gregorian start)
11023 cday (calendar-absolute-from-gregorian current))
11025 (if (<= cday sday) (throw 'exit sday))
11027 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11028 (setq dn (string-to-number (match-string 1 change))
11029 dw (cdr (assoc (match-string 2 change) a1)))
11030 (error "Invalid change specifyer: %s" change))
11031 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11032 (cond
11033 ((eq dw 'day)
11034 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11035 n2 (+ n1 dn)))
11036 ((eq dw 'year)
11037 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11038 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11039 (setq date1 (list m d y1)
11040 n1 (calendar-absolute-from-gregorian date1)
11041 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11042 n2 (calendar-absolute-from-gregorian date2)))
11043 ((eq dw 'month)
11044 ;; approx number of month between the tow dates
11045 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11046 ;; How often does dn fit in there?
11047 (setq d (nth 1 start) m (car start) y (nth 2 start)
11048 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11049 m (+ m nm)
11050 ny (floor (/ m 12))
11051 y (+ y ny)
11052 m (- m (* ny 12)))
11053 (while (> m 12) (setq m (- m 12) y (1+ y)))
11054 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11055 (setq m2 (+ m dn) y2 y)
11056 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11057 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11058 (while (< n2 cday)
11059 (setq n1 n2 m m2 y y2)
11060 (setq m2 (+ m dn) y2 y)
11061 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11062 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11064 (if show-all
11065 (cond
11066 ((eq prefer 'past) n1)
11067 ((eq prefer 'future) (if (= cday n1) n1 n2))
11068 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11069 (cond
11070 ((eq prefer 'past) n1)
11071 ((eq prefer 'future) (if (= cday n1) n1 n2))
11072 (t (if (= cday n1) n1 n2)))))))
11074 (defun org-date-to-gregorian (date)
11075 "Turn any specification of DATE into a gregorian date for the calendar."
11076 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11077 ((and (listp date) (= (length date) 3)) date)
11078 ((stringp date)
11079 (setq date (org-parse-time-string date))
11080 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11081 ((listp date)
11082 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11084 (defun org-parse-time-string (s &optional nodefault)
11085 "Parse the standard Org-mode time string.
11086 This should be a lot faster than the normal `parse-time-string'.
11087 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11088 hour and minute fields will be nil if not given."
11089 (if (string-match org-ts-regexp0 s)
11090 (list 0
11091 (if (or (match-beginning 8) (not nodefault))
11092 (string-to-number (or (match-string 8 s) "0")))
11093 (if (or (match-beginning 7) (not nodefault))
11094 (string-to-number (or (match-string 7 s) "0")))
11095 (string-to-number (match-string 4 s))
11096 (string-to-number (match-string 3 s))
11097 (string-to-number (match-string 2 s))
11098 nil nil nil)
11099 (make-list 9 0)))
11101 (defun org-timestamp-up (&optional arg)
11102 "Increase the date item at the cursor by one.
11103 If the cursor is on the year, change the year. If it is on the month or
11104 the day, change that.
11105 With prefix ARG, change by that many units."
11106 (interactive "p")
11107 (org-timestamp-change (prefix-numeric-value arg)))
11109 (defun org-timestamp-down (&optional arg)
11110 "Decrease the date item at the cursor by one.
11111 If the cursor is on the year, change the year. If it is on the month or
11112 the day, change that.
11113 With prefix ARG, change by that many units."
11114 (interactive "p")
11115 (org-timestamp-change (- (prefix-numeric-value arg))))
11117 (defun org-timestamp-up-day (&optional arg)
11118 "Increase the date in the time stamp by one day.
11119 With prefix ARG, change that many days."
11120 (interactive "p")
11121 (if (and (not (org-at-timestamp-p t))
11122 (org-on-heading-p))
11123 (org-todo 'up)
11124 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11126 (defun org-timestamp-down-day (&optional arg)
11127 "Decrease the date in the time stamp by one day.
11128 With prefix ARG, change that many days."
11129 (interactive "p")
11130 (if (and (not (org-at-timestamp-p t))
11131 (org-on-heading-p))
11132 (org-todo 'down)
11133 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11135 (defun org-at-timestamp-p (&optional inactive-ok)
11136 "Determine if the cursor is in or at a timestamp."
11137 (interactive)
11138 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11139 (pos (point))
11140 (ans (or (looking-at tsr)
11141 (save-excursion
11142 (skip-chars-backward "^[<\n\r\t")
11143 (if (> (point) (point-min)) (backward-char 1))
11144 (and (looking-at tsr)
11145 (> (- (match-end 0) pos) -1))))))
11146 (and ans
11147 (boundp 'org-ts-what)
11148 (setq org-ts-what
11149 (cond
11150 ((= pos (match-beginning 0)) 'bracket)
11151 ((= pos (1- (match-end 0))) 'bracket)
11152 ((org-pos-in-match-range pos 2) 'year)
11153 ((org-pos-in-match-range pos 3) 'month)
11154 ((org-pos-in-match-range pos 7) 'hour)
11155 ((org-pos-in-match-range pos 8) 'minute)
11156 ((or (org-pos-in-match-range pos 4)
11157 (org-pos-in-match-range pos 5)) 'day)
11158 ((and (> pos (or (match-end 8) (match-end 5)))
11159 (< pos (match-end 0)))
11160 (- pos (or (match-end 8) (match-end 5))))
11161 (t 'day))))
11162 ans))
11164 (defun org-toggle-timestamp-type ()
11165 "Toggle the type (<active> or [inactive]) of a time stamp."
11166 (interactive)
11167 (when (org-at-timestamp-p t)
11168 (save-excursion
11169 (goto-char (match-beginning 0))
11170 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11171 (goto-char (1- (match-end 0)))
11172 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11173 (message "Timestamp is now %sactive"
11174 (if (equal (char-before) ?>) "in" ""))))
11176 (defun org-timestamp-change (n &optional what)
11177 "Change the date in the time stamp at point.
11178 The date will be changed by N times WHAT. WHAT can be `day', `month',
11179 `year', `minute', `second'. If WHAT is not given, the cursor position
11180 in the timestamp determines what will be changed."
11181 (let ((pos (point))
11182 with-hm inactive
11183 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11184 org-ts-what
11185 extra rem
11186 ts time time0)
11187 (if (not (org-at-timestamp-p t))
11188 (error "Not at a timestamp"))
11189 (if (and (not what) (eq org-ts-what 'bracket))
11190 (org-toggle-timestamp-type)
11191 (if (and (not what) (not (eq org-ts-what 'day))
11192 org-display-custom-times
11193 (get-text-property (point) 'display)
11194 (not (get-text-property (1- (point)) 'display)))
11195 (setq org-ts-what 'day))
11196 (setq org-ts-what (or what org-ts-what)
11197 inactive (= (char-after (match-beginning 0)) ?\[)
11198 ts (match-string 0))
11199 (replace-match "")
11200 (if (string-match
11201 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11203 (setq extra (match-string 1 ts)))
11204 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11205 (setq with-hm t))
11206 (setq time0 (org-parse-time-string ts))
11207 (when (and (eq org-ts-what 'minute)
11208 (eq current-prefix-arg nil))
11209 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11210 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11211 (setcar (cdr time0) (+ (nth 1 time0)
11212 (if (> n 0) (- rem) (- dm rem))))))
11213 (setq time
11214 (encode-time (or (car time0) 0)
11215 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11216 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11217 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11218 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11219 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11220 (nthcdr 6 time0)))
11221 (when (integerp org-ts-what)
11222 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11223 (if (eq what 'calendar)
11224 (let ((cal-date (org-get-date-from-calendar)))
11225 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11226 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11227 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11228 (setcar time0 (or (car time0) 0))
11229 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11230 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11231 (setq time (apply 'encode-time time0))))
11232 (setq org-last-changed-timestamp
11233 (org-insert-time-stamp time with-hm inactive nil nil extra))
11234 (org-clock-update-time-maybe)
11235 (goto-char pos)
11236 ;; Try to recenter the calendar window, if any
11237 (if (and org-calendar-follow-timestamp-change
11238 (get-buffer-window "*Calendar*" t)
11239 (memq org-ts-what '(day month year)))
11240 (org-recenter-calendar (time-to-days time))))))
11242 (defun org-modify-ts-extra (s pos n dm)
11243 "Change the different parts of the lead-time and repeat fields in timestamp."
11244 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11245 ng h m new rem)
11246 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11247 (cond
11248 ((or (org-pos-in-match-range pos 2)
11249 (org-pos-in-match-range pos 3))
11250 (setq m (string-to-number (match-string 3 s))
11251 h (string-to-number (match-string 2 s)))
11252 (if (org-pos-in-match-range pos 2)
11253 (setq h (+ h n))
11254 (setq n (* dm (org-no-warnings (signum n))))
11255 (when (not (= 0 (setq rem (% m dm))))
11256 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11257 (setq m (+ m n)))
11258 (if (< m 0) (setq m (+ m 60) h (1- h)))
11259 (if (> m 59) (setq m (- m 60) h (1+ h)))
11260 (setq h (min 24 (max 0 h)))
11261 (setq ng 1 new (format "-%02d:%02d" h m)))
11262 ((org-pos-in-match-range pos 6)
11263 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11264 ((org-pos-in-match-range pos 5)
11265 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11267 ((org-pos-in-match-range pos 9)
11268 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11269 ((org-pos-in-match-range pos 8)
11270 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11272 (when ng
11273 (setq s (concat
11274 (substring s 0 (match-beginning ng))
11276 (substring s (match-end ng))))))
11279 (defun org-recenter-calendar (date)
11280 "If the calendar is visible, recenter it to DATE."
11281 (let* ((win (selected-window))
11282 (cwin (get-buffer-window "*Calendar*" t))
11283 (calendar-move-hook nil))
11284 (when cwin
11285 (select-window cwin)
11286 (calendar-goto-date (if (listp date) date
11287 (calendar-gregorian-from-absolute date)))
11288 (select-window win))))
11290 (defun org-goto-calendar (&optional arg)
11291 "Go to the Emacs calendar at the current date.
11292 If there is a time stamp in the current line, go to that date.
11293 A prefix ARG can be used to force the current date."
11294 (interactive "P")
11295 (let ((tsr org-ts-regexp) diff
11296 (calendar-move-hook nil)
11297 (calendar-view-holidays-initially-flag nil)
11298 (view-calendar-holidays-initially nil)
11299 (calendar-view-diary-initially-flag nil)
11300 (view-diary-entries-initially nil))
11301 (if (or (org-at-timestamp-p)
11302 (save-excursion
11303 (beginning-of-line 1)
11304 (looking-at (concat ".*" tsr))))
11305 (let ((d1 (time-to-days (current-time)))
11306 (d2 (time-to-days
11307 (org-time-string-to-time (match-string 1)))))
11308 (setq diff (- d2 d1))))
11309 (calendar)
11310 (calendar-goto-today)
11311 (if (and diff (not arg)) (calendar-forward-day diff))))
11313 (defun org-get-date-from-calendar ()
11314 "Return a list (month day year) of date at point in calendar."
11315 (with-current-buffer "*Calendar*"
11316 (save-match-data
11317 (calendar-cursor-to-date))))
11319 (defun org-date-from-calendar ()
11320 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11321 If there is already a time stamp at the cursor position, update it."
11322 (interactive)
11323 (if (org-at-timestamp-p t)
11324 (org-timestamp-change 0 'calendar)
11325 (let ((cal-date (org-get-date-from-calendar)))
11326 (org-insert-time-stamp
11327 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11329 (defun org-minutes-to-hh:mm-string (m)
11330 "Compute H:MM from a number of minutes."
11331 (let ((h (/ m 60)))
11332 (setq m (- m (* 60 h)))
11333 (format "%d:%02d" h m)))
11335 (defun org-hh:mm-string-to-minutes (s)
11336 "Convert a string H:MM to a number of minutes."
11337 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11338 (+ (* (string-to-number (match-string 1 s)) 60)
11339 (string-to-number (match-string 2 s)))
11342 ;;;; Agenda files
11344 ;;;###autoload
11345 (defun org-iswitchb (&optional arg)
11346 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11347 With a prefix argument, restrict available to files.
11348 With two prefix arguments, restrict available buffers to agenda files.
11350 Due to some yet unresolved reason, global function
11351 `iswitchb-mode' needs to be active for this function to work."
11352 (interactive "P")
11353 (require 'iswitchb)
11354 (let ((enabled iswitchb-mode) blist)
11355 (or enabled (iswitchb-mode 1))
11356 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11357 ((equal arg '(16)) (org-buffer-list 'agenda))
11358 (t (org-buffer-list))))
11359 (unwind-protect
11360 (let ((iswitchb-make-buflist-hook
11361 (lambda ()
11362 (setq iswitchb-temp-buflist
11363 (mapcar 'buffer-name blist)))))
11364 (switch-to-buffer
11365 (iswitchb-read-buffer
11366 "Switch-to: " nil t))
11367 (or enabled (iswitchb-mode -1))))))
11369 (defun org-buffer-list (&optional predicate tmp)
11370 "Return a list of Org buffers.
11371 PREDICATE can be either 'export, 'files or 'agenda.
11373 'export restrict the list to Export buffers.
11374 'files restrict the list to buffers visiting Org files.
11375 'agenda restrict the list to buffers visiting agenda files.
11377 If TMP is non-nil, don't include temporary buffers."
11378 (let (filter blist)
11379 (setq filter
11380 (cond ((eq predicate 'files) "\.org$")
11381 ((eq predicate 'export) "\*Org .*Export")
11382 (t "\*Org \\|\.org$")))
11383 (setq blist
11384 (mapcar
11385 (lambda(b)
11386 (let ((bname (buffer-name b))
11387 (bfile (buffer-file-name b)))
11388 (if (and (string-match filter bname)
11389 (if (eq predicate 'agenda)
11390 (member bfile
11391 (mapcar (lambda(f) (file-truename f))
11392 org-agenda-files)) t)
11393 (if tmp (not (string-match "tmp" bname)) t)) b)))
11394 (buffer-list)))
11395 (delete nil blist)))
11397 (defun org-agenda-files (&optional unrestricted ext)
11398 "Get the list of agenda files.
11399 Optional UNRESTRICTED means return the full list even if a restriction
11400 is currently in place.
11401 When EXT is non-nil, try to add all files that are created by adding EXT
11402 to the file nemes. Basically, this is a way to add the archive files
11403 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11404 a string, \"_archive\" will be used."
11405 (let ((files
11406 (cond
11407 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11408 ((stringp org-agenda-files) (org-read-agenda-file-list))
11409 ((listp org-agenda-files) org-agenda-files)
11410 (t (error "Invalid value of `org-agenda-files'")))))
11411 (setq files (apply 'append
11412 (mapcar (lambda (f)
11413 (if (file-directory-p f)
11414 (directory-files
11415 f t org-agenda-file-regexp)
11416 (list f)))
11417 files)))
11418 (when org-agenda-skip-unavailable-files
11419 (setq files (delq nil
11420 (mapcar (function
11421 (lambda (file)
11422 (and (file-readable-p file) file)))
11423 files))))
11424 (when ext
11425 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11426 ext "_archive"))
11427 (setq files (apply 'append
11428 (mapcar
11429 (lambda (f)
11430 (if (file-exists-p (concat f ext))
11431 (list f (concat f ext))
11432 (list f)))
11433 files))))
11434 files))
11436 (defun org-edit-agenda-file-list ()
11437 "Edit the list of agenda files.
11438 Depending on setup, this either uses customize to edit the variable
11439 `org-agenda-files', or it visits the file that is holding the list. In the
11440 latter case, the buffer is set up in a way that saving it automatically kills
11441 the buffer and restores the previous window configuration."
11442 (interactive)
11443 (if (stringp org-agenda-files)
11444 (let ((cw (current-window-configuration)))
11445 (find-file org-agenda-files)
11446 (org-set-local 'org-window-configuration cw)
11447 (org-add-hook 'after-save-hook
11448 (lambda ()
11449 (set-window-configuration
11450 (prog1 org-window-configuration
11451 (kill-buffer (current-buffer))))
11452 (org-install-agenda-files-menu)
11453 (message "New agenda file list installed"))
11454 nil 'local)
11455 (message "%s" (substitute-command-keys
11456 "Edit list and finish with \\[save-buffer]")))
11457 (customize-variable 'org-agenda-files)))
11459 (defun org-store-new-agenda-file-list (list)
11460 "Set new value for the agenda file list and save it correcly."
11461 (if (stringp org-agenda-files)
11462 (let ((f org-agenda-files) b)
11463 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11464 (with-temp-file f
11465 (insert (mapconcat 'identity list "\n") "\n")))
11466 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11467 (setq org-agenda-files list)
11468 (customize-save-variable 'org-agenda-files org-agenda-files))))
11470 (defun org-read-agenda-file-list ()
11471 "Read the list of agenda files from a file."
11472 (when (file-directory-p org-agenda-files)
11473 (error "`org-agenda-files' cannot be a single directory"))
11474 (when (stringp org-agenda-files)
11475 (with-temp-buffer
11476 (insert-file-contents org-agenda-files)
11477 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11480 ;;;###autoload
11481 (defun org-cycle-agenda-files ()
11482 "Cycle through the files in `org-agenda-files'.
11483 If the current buffer visits an agenda file, find the next one in the list.
11484 If the current buffer does not, find the first agenda file."
11485 (interactive)
11486 (let* ((fs (org-agenda-files t))
11487 (files (append fs (list (car fs))))
11488 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11489 file)
11490 (unless files (error "No agenda files"))
11491 (catch 'exit
11492 (while (setq file (pop files))
11493 (if (equal (file-truename file) tcf)
11494 (when (car files)
11495 (find-file (car files))
11496 (throw 'exit t))))
11497 (find-file (car fs)))
11498 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11500 (defun org-agenda-file-to-front (&optional to-end)
11501 "Move/add the current file to the top of the agenda file list.
11502 If the file is not present in the list, it is added to the front. If it is
11503 present, it is moved there. With optional argument TO-END, add/move to the
11504 end of the list."
11505 (interactive "P")
11506 (let ((org-agenda-skip-unavailable-files nil)
11507 (file-alist (mapcar (lambda (x)
11508 (cons (file-truename x) x))
11509 (org-agenda-files t)))
11510 (ctf (file-truename buffer-file-name))
11511 x had)
11512 (setq x (assoc ctf file-alist) had x)
11514 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11515 (if to-end
11516 (setq file-alist (append (delq x file-alist) (list x)))
11517 (setq file-alist (cons x (delq x file-alist))))
11518 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11519 (org-install-agenda-files-menu)
11520 (message "File %s to %s of agenda file list"
11521 (if had "moved" "added") (if to-end "end" "front"))))
11523 (defun org-remove-file (&optional file)
11524 "Remove current file from the list of files in variable `org-agenda-files'.
11525 These are the files which are being checked for agenda entries.
11526 Optional argument FILE means, use this file instead of the current."
11527 (interactive)
11528 (let* ((org-agenda-skip-unavailable-files nil)
11529 (file (or file buffer-file-name))
11530 (true-file (file-truename file))
11531 (afile (abbreviate-file-name file))
11532 (files (delq nil (mapcar
11533 (lambda (x)
11534 (if (equal true-file
11535 (file-truename x))
11536 nil x))
11537 (org-agenda-files t)))))
11538 (if (not (= (length files) (length (org-agenda-files t))))
11539 (progn
11540 (org-store-new-agenda-file-list files)
11541 (org-install-agenda-files-menu)
11542 (message "Removed file: %s" afile))
11543 (message "File was not in list: %s (not removed)" afile))))
11545 (defun org-file-menu-entry (file)
11546 (vector file (list 'find-file file) t))
11548 (defun org-check-agenda-file (file)
11549 "Make sure FILE exists. If not, ask user what to do."
11550 (when (not (file-exists-p file))
11551 (message "non-existent file %s. [R]emove from list or [A]bort?"
11552 (abbreviate-file-name file))
11553 (let ((r (downcase (read-char-exclusive))))
11554 (cond
11555 ((equal r ?r)
11556 (org-remove-file file)
11557 (throw 'nextfile t))
11558 (t (error "Abort"))))))
11560 (defun org-get-agenda-file-buffer (file)
11561 "Get a buffer visiting FILE. If the buffer needs to be created, add
11562 it to the list of buffers which might be released later."
11563 (let ((buf (org-find-base-buffer-visiting file)))
11564 (if buf
11565 buf ; just return it
11566 ;; Make a new buffer and remember it
11567 (setq buf (find-file-noselect file))
11568 (if buf (push buf org-agenda-new-buffers))
11569 buf)))
11571 (defun org-release-buffers (blist)
11572 "Release all buffers in list, asking the user for confirmation when needed.
11573 When a buffer is unmodified, it is just killed. When modified, it is saved
11574 \(if the user agrees) and then killed."
11575 (let (buf file)
11576 (while (setq buf (pop blist))
11577 (setq file (buffer-file-name buf))
11578 (when (and (buffer-modified-p buf)
11579 file
11580 (y-or-n-p (format "Save file %s? " file)))
11581 (with-current-buffer buf (save-buffer)))
11582 (kill-buffer buf))))
11584 (defun org-prepare-agenda-buffers (files)
11585 "Create buffers for all agenda files, protect archived trees and comments."
11586 (interactive)
11587 (let ((pa '(:org-archived t))
11588 (pc '(:org-comment t))
11589 (pall '(:org-archived t :org-comment t))
11590 (inhibit-read-only t)
11591 (rea (concat ":" org-archive-tag ":"))
11592 bmp file re)
11593 (save-excursion
11594 (save-restriction
11595 (while (setq file (pop files))
11596 (if (bufferp file)
11597 (set-buffer file)
11598 (org-check-agenda-file file)
11599 (set-buffer (org-get-agenda-file-buffer file)))
11600 (widen)
11601 (setq bmp (buffer-modified-p))
11602 (org-refresh-category-properties)
11603 (setq org-todo-keywords-for-agenda
11604 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11605 (setq org-done-keywords-for-agenda
11606 (append org-done-keywords-for-agenda org-done-keywords))
11607 (save-excursion
11608 (remove-text-properties (point-min) (point-max) pall)
11609 (when org-agenda-skip-archived-trees
11610 (goto-char (point-min))
11611 (while (re-search-forward rea nil t)
11612 (if (org-on-heading-p t)
11613 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11614 (goto-char (point-min))
11615 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11616 (while (re-search-forward re nil t)
11617 (add-text-properties
11618 (match-beginning 0) (org-end-of-subtree t) pc)))
11619 (set-buffer-modified-p bmp))))))
11621 ;;;; Embedded LaTeX
11623 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11624 "Keymap for the minor `org-cdlatex-mode'.")
11626 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11627 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11628 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11629 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11630 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11632 (defvar org-cdlatex-texmathp-advice-is-done nil
11633 "Flag remembering if we have applied the advice to texmathp already.")
11635 (define-minor-mode org-cdlatex-mode
11636 "Toggle the minor `org-cdlatex-mode'.
11637 This mode supports entering LaTeX environment and math in LaTeX fragments
11638 in Org-mode.
11639 \\{org-cdlatex-mode-map}"
11640 nil " OCDL" nil
11641 (when org-cdlatex-mode (require 'cdlatex))
11642 (unless org-cdlatex-texmathp-advice-is-done
11643 (setq org-cdlatex-texmathp-advice-is-done t)
11644 (defadvice texmathp (around org-math-always-on activate)
11645 "Always return t in org-mode buffers.
11646 This is because we want to insert math symbols without dollars even outside
11647 the LaTeX math segments. If Orgmode thinks that point is actually inside
11648 en embedded LaTeX fragement, let texmathp do its job.
11649 \\[org-cdlatex-mode-map]"
11650 (interactive)
11651 (let (p)
11652 (cond
11653 ((not (org-mode-p)) ad-do-it)
11654 ((eq this-command 'cdlatex-math-symbol)
11655 (setq ad-return-value t
11656 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11658 (let ((p (org-inside-LaTeX-fragment-p)))
11659 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11660 (setq ad-return-value t
11661 texmathp-why '("Org-mode embedded math" . 0))
11662 (if p ad-do-it)))))))))
11664 (defun turn-on-org-cdlatex ()
11665 "Unconditionally turn on `org-cdlatex-mode'."
11666 (org-cdlatex-mode 1))
11668 (defun org-inside-LaTeX-fragment-p ()
11669 "Test if point is inside a LaTeX fragment.
11670 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11671 sequence appearing also before point.
11672 Even though the matchers for math are configurable, this function assumes
11673 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11674 delimiters are skipped when they have been removed by customization.
11675 The return value is nil, or a cons cell with the delimiter and
11676 and the position of this delimiter.
11678 This function does a reasonably good job, but can locally be fooled by
11679 for example currency specifications. For example it will assume being in
11680 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11681 fragments that are properly closed, but during editing, we have to live
11682 with the uncertainty caused by missing closing delimiters. This function
11683 looks only before point, not after."
11684 (catch 'exit
11685 (let ((pos (point))
11686 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11687 (lim (progn
11688 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11689 (point)))
11690 dd-on str (start 0) m re)
11691 (goto-char pos)
11692 (when dodollar
11693 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11694 re (nth 1 (assoc "$" org-latex-regexps)))
11695 (while (string-match re str start)
11696 (cond
11697 ((= (match-end 0) (length str))
11698 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11699 ((= (match-end 0) (- (length str) 5))
11700 (throw 'exit nil))
11701 (t (setq start (match-end 0))))))
11702 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11703 (goto-char pos)
11704 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11705 (and (match-beginning 2) (throw 'exit nil))
11706 ;; count $$
11707 (while (re-search-backward "\\$\\$" lim t)
11708 (setq dd-on (not dd-on)))
11709 (goto-char pos)
11710 (if dd-on (cons "$$" m))))))
11713 (defun org-try-cdlatex-tab ()
11714 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11715 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11716 - inside a LaTeX fragment, or
11717 - after the first word in a line, where an abbreviation expansion could
11718 insert a LaTeX environment."
11719 (when org-cdlatex-mode
11720 (cond
11721 ((save-excursion
11722 (skip-chars-backward "a-zA-Z0-9*")
11723 (skip-chars-backward " \t")
11724 (bolp))
11725 (cdlatex-tab) t)
11726 ((org-inside-LaTeX-fragment-p)
11727 (cdlatex-tab) t)
11728 (t nil))))
11730 (defun org-cdlatex-underscore-caret (&optional arg)
11731 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11732 Revert to the normal definition outside of these fragments."
11733 (interactive "P")
11734 (if (org-inside-LaTeX-fragment-p)
11735 (call-interactively 'cdlatex-sub-superscript)
11736 (let (org-cdlatex-mode)
11737 (call-interactively (key-binding (vector last-input-event))))))
11739 (defun org-cdlatex-math-modify (&optional arg)
11740 "Execute `cdlatex-math-modify' in LaTeX fragments.
11741 Revert to the normal definition outside of these fragments."
11742 (interactive "P")
11743 (if (org-inside-LaTeX-fragment-p)
11744 (call-interactively 'cdlatex-math-modify)
11745 (let (org-cdlatex-mode)
11746 (call-interactively (key-binding (vector last-input-event))))))
11748 (defvar org-latex-fragment-image-overlays nil
11749 "List of overlays carrying the images of latex fragments.")
11750 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11752 (defun org-remove-latex-fragment-image-overlays ()
11753 "Remove all overlays with LaTeX fragment images in current buffer."
11754 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11755 (setq org-latex-fragment-image-overlays nil))
11757 (defun org-preview-latex-fragment (&optional subtree)
11758 "Preview the LaTeX fragment at point, or all locally or globally.
11759 If the cursor is in a LaTeX fragment, create the image and overlay
11760 it over the source code. If there is no fragment at point, display
11761 all fragments in the current text, from one headline to the next. With
11762 prefix SUBTREE, display all fragments in the current subtree. With a
11763 double prefix `C-u C-u', or when the cursor is before the first headline,
11764 display all fragments in the buffer.
11765 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11766 (interactive "P")
11767 (org-remove-latex-fragment-image-overlays)
11768 (save-excursion
11769 (save-restriction
11770 (let (beg end at msg)
11771 (cond
11772 ((or (equal subtree '(16))
11773 (not (save-excursion
11774 (re-search-backward (concat "^" outline-regexp) nil t))))
11775 (setq beg (point-min) end (point-max)
11776 msg "Creating images for buffer...%s"))
11777 ((equal subtree '(4))
11778 (org-back-to-heading)
11779 (setq beg (point) end (org-end-of-subtree t)
11780 msg "Creating images for subtree...%s"))
11782 (if (setq at (org-inside-LaTeX-fragment-p))
11783 (goto-char (max (point-min) (- (cdr at) 2)))
11784 (org-back-to-heading))
11785 (setq beg (point) end (progn (outline-next-heading) (point))
11786 msg (if at "Creating image...%s"
11787 "Creating images for entry...%s"))))
11788 (message msg "")
11789 (narrow-to-region beg end)
11790 (goto-char beg)
11791 (org-format-latex
11792 (concat "ltxpng/" (file-name-sans-extension
11793 (file-name-nondirectory
11794 buffer-file-name)))
11795 default-directory 'overlays msg at 'forbuffer)
11796 (message msg "done. Use `C-c C-c' to remove images.")))))
11798 (defvar org-latex-regexps
11799 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11800 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11801 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11802 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11803 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11804 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11805 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11806 "Regular expressions for matching embedded LaTeX.")
11808 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11809 "Replace LaTeX fragments with links to an image, and produce images."
11810 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11811 (let* ((prefixnodir (file-name-nondirectory prefix))
11812 (absprefix (expand-file-name prefix dir))
11813 (todir (file-name-directory absprefix))
11814 (opt org-format-latex-options)
11815 (matchers (plist-get opt :matchers))
11816 (re-list org-latex-regexps)
11817 (cnt 0) txt link beg end re e checkdir
11818 m n block linkfile movefile ov)
11819 ;; Check if there are old images files with this prefix, and remove them
11820 (when (file-directory-p todir)
11821 (mapc 'delete-file
11822 (directory-files
11823 todir 'full
11824 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11825 ;; Check the different regular expressions
11826 (while (setq e (pop re-list))
11827 (setq m (car e) re (nth 1 e) n (nth 2 e)
11828 block (if (nth 3 e) "\n\n" ""))
11829 (when (member m matchers)
11830 (goto-char (point-min))
11831 (while (re-search-forward re nil t)
11832 (when (or (not at) (equal (cdr at) (match-beginning n)))
11833 (setq txt (match-string n)
11834 beg (match-beginning n) end (match-end n)
11835 cnt (1+ cnt)
11836 linkfile (format "%s_%04d.png" prefix cnt)
11837 movefile (format "%s_%04d.png" absprefix cnt)
11838 link (concat block "[[file:" linkfile "]]" block))
11839 (if msg (message msg cnt))
11840 (goto-char beg)
11841 (unless checkdir ; make sure the directory exists
11842 (setq checkdir t)
11843 (or (file-directory-p todir) (make-directory todir)))
11844 (org-create-formula-image
11845 txt movefile opt forbuffer)
11846 (if overlays
11847 (progn
11848 (setq ov (org-make-overlay beg end))
11849 (if (featurep 'xemacs)
11850 (progn
11851 (org-overlay-put ov 'invisible t)
11852 (org-overlay-put
11853 ov 'end-glyph
11854 (make-glyph (vector 'png :file movefile))))
11855 (org-overlay-put
11856 ov 'display
11857 (list 'image :type 'png :file movefile :ascent 'center)))
11858 (push ov org-latex-fragment-image-overlays)
11859 (goto-char end))
11860 (delete-region beg end)
11861 (insert link))))))))
11863 ;; This function borrows from Ganesh Swami's latex2png.el
11864 (defun org-create-formula-image (string tofile options buffer)
11865 (let* ((tmpdir (if (featurep 'xemacs)
11866 (temp-directory)
11867 temporary-file-directory))
11868 (texfilebase (make-temp-name
11869 (expand-file-name "orgtex" tmpdir)))
11870 (texfile (concat texfilebase ".tex"))
11871 (dvifile (concat texfilebase ".dvi"))
11872 (pngfile (concat texfilebase ".png"))
11873 (fnh (if (featurep 'xemacs)
11874 (font-height (get-face-font 'default))
11875 (face-attribute 'default :height nil)))
11876 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11877 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11878 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11879 "Black"))
11880 (bg (or (plist-get options (if buffer :background :html-background))
11881 "Transparent")))
11882 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11883 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11884 (with-temp-file texfile
11885 (insert org-format-latex-header
11886 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11887 (let ((dir default-directory))
11888 (condition-case nil
11889 (progn
11890 (cd tmpdir)
11891 (call-process "latex" nil nil nil texfile))
11892 (error nil))
11893 (cd dir))
11894 (if (not (file-exists-p dvifile))
11895 (progn (message "Failed to create dvi file from %s" texfile) nil)
11896 (call-process "dvipng" nil nil nil
11897 "-E" "-fg" fg "-bg" bg
11898 "-D" dpi
11899 ;;"-x" scale "-y" scale
11900 "-T" "tight"
11901 "-o" pngfile
11902 dvifile)
11903 (if (not (file-exists-p pngfile))
11904 (progn (message "Failed to create png file from %s" texfile) nil)
11905 ;; Use the requested file name and clean up
11906 (copy-file pngfile tofile 'replace)
11907 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11908 (delete-file (concat texfilebase e)))
11909 pngfile))))
11911 (defun org-dvipng-color (attr)
11912 "Return an rgb color specification for dvipng."
11913 (apply 'format "rgb %s %s %s"
11914 (mapcar 'org-normalize-color
11915 (color-values (face-attribute 'default attr nil)))))
11917 (defun org-normalize-color (value)
11918 "Return string to be used as color value for an RGB component."
11919 (format "%g" (/ value 65535.0)))
11922 ;;;; Key bindings
11924 ;; Make `C-c C-x' a prefix key
11925 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11927 ;; TAB key with modifiers
11928 (org-defkey org-mode-map "\C-i" 'org-cycle)
11929 (org-defkey org-mode-map [(tab)] 'org-cycle)
11930 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11931 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11932 (org-defkey org-mode-map "\M-\t" 'org-complete)
11933 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11934 ;; The following line is necessary under Suse GNU/Linux
11935 (unless (featurep 'xemacs)
11936 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11937 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11938 (define-key org-mode-map [backtab] 'org-shifttab)
11940 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11941 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11942 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11944 ;; Cursor keys with modifiers
11945 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11946 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11947 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11948 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11950 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11951 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11952 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11953 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11955 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11956 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11957 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11958 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11960 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11961 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11963 ;;; Extra keys for tty access.
11964 ;; We only set them when really needed because otherwise the
11965 ;; menus don't show the simple keys
11967 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11968 (not window-system))
11969 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11970 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11971 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11972 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11973 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11974 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11975 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11976 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11977 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11978 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11979 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11980 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11981 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11982 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11983 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11984 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11985 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11986 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11987 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11988 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11989 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11990 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11992 ;; All the other keys
11994 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11995 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11996 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11997 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11998 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11999 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12000 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12001 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12002 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12003 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12004 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12005 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12006 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12007 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12008 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12009 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12010 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12011 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12012 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12013 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12014 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12015 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12016 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12017 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12018 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12019 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12020 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12021 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12022 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12023 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12024 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12025 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12026 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12027 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12028 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12029 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12030 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12031 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12032 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12033 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12034 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12035 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12036 (org-defkey org-mode-map "\C-c^" 'org-sort)
12037 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12038 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12039 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12040 (org-defkey org-mode-map "\C-m" 'org-return)
12041 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12042 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12043 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12044 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12045 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12046 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
12047 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12048 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12049 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12050 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12051 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12052 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12053 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12054 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12055 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12056 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12058 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12059 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12060 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12061 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12063 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12064 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12065 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12066 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12067 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12068 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12069 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12070 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12071 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12072 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12073 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12074 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12076 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12078 (when (featurep 'xemacs)
12079 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12081 (defvar org-table-auto-blank-field) ; defined in org-table.el
12082 (defun org-self-insert-command (N)
12083 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12084 If the cursor is in a table looking at whitespace, the whitespace is
12085 overwritten, and the table is not marked as requiring realignment."
12086 (interactive "p")
12087 (if (and (org-table-p)
12088 (progn
12089 ;; check if we blank the field, and if that triggers align
12090 (and (featurep 'org-table) org-table-auto-blank-field
12091 (member last-command
12092 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12093 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12094 ;; got extra space, this field does not determine column width
12095 (let (org-table-may-need-update) (org-table-blank-field))
12096 ;; no extra space, this field may determine column width
12097 (org-table-blank-field)))
12099 (eq N 1)
12100 (looking-at "[^|\n]* |"))
12101 (let (org-table-may-need-update)
12102 (goto-char (1- (match-end 0)))
12103 (delete-backward-char 1)
12104 (goto-char (match-beginning 0))
12105 (self-insert-command N))
12106 (setq org-table-may-need-update t)
12107 (self-insert-command N)
12108 (org-fix-tags-on-the-fly)))
12110 (defun org-fix-tags-on-the-fly ()
12111 (when (and (equal (char-after (point-at-bol)) ?*)
12112 (org-on-heading-p))
12113 (org-align-tags-here org-tags-column)))
12115 (defun org-delete-backward-char (N)
12116 "Like `delete-backward-char', insert whitespace at field end in tables.
12117 When deleting backwards, in tables this function will insert whitespace in
12118 front of the next \"|\" separator, to keep the table aligned. The table will
12119 still be marked for re-alignment if the field did fill the entire column,
12120 because, in this case the deletion might narrow the column."
12121 (interactive "p")
12122 (if (and (org-table-p)
12123 (eq N 1)
12124 (string-match "|" (buffer-substring (point-at-bol) (point)))
12125 (looking-at ".*?|"))
12126 (let ((pos (point))
12127 (noalign (looking-at "[^|\n\r]* |"))
12128 (c org-table-may-need-update))
12129 (backward-delete-char N)
12130 (skip-chars-forward "^|")
12131 (insert " ")
12132 (goto-char (1- pos))
12133 ;; noalign: if there were two spaces at the end, this field
12134 ;; does not determine the width of the column.
12135 (if noalign (setq org-table-may-need-update c)))
12136 (backward-delete-char N)
12137 (org-fix-tags-on-the-fly)))
12139 (defun org-delete-char (N)
12140 "Like `delete-char', but insert whitespace at field end in tables.
12141 When deleting characters, in tables this function will insert whitespace in
12142 front of the next \"|\" separator, to keep the table aligned. The table will
12143 still be marked for re-alignment if the field did fill the entire column,
12144 because, in this case the deletion might narrow the column."
12145 (interactive "p")
12146 (if (and (org-table-p)
12147 (not (bolp))
12148 (not (= (char-after) ?|))
12149 (eq N 1))
12150 (if (looking-at ".*?|")
12151 (let ((pos (point))
12152 (noalign (looking-at "[^|\n\r]* |"))
12153 (c org-table-may-need-update))
12154 (replace-match (concat
12155 (substring (match-string 0) 1 -1)
12156 " |"))
12157 (goto-char pos)
12158 ;; noalign: if there were two spaces at the end, this field
12159 ;; does not determine the width of the column.
12160 (if noalign (setq org-table-may-need-update c)))
12161 (delete-char N))
12162 (delete-char N)
12163 (org-fix-tags-on-the-fly)))
12165 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12166 (put 'org-self-insert-command 'delete-selection t)
12167 (put 'orgtbl-self-insert-command 'delete-selection t)
12168 (put 'org-delete-char 'delete-selection 'supersede)
12169 (put 'org-delete-backward-char 'delete-selection 'supersede)
12171 ;; Make `flyspell-mode' delay after some commands
12172 (put 'org-self-insert-command 'flyspell-delayed t)
12173 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12174 (put 'org-delete-char 'flyspell-delayed t)
12175 (put 'org-delete-backward-char 'flyspell-delayed t)
12177 ;; Make pabbrev-mode expand after org-mode commands
12178 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12179 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12181 ;; How to do this: Measure non-white length of current string
12182 ;; If equal to column width, we should realign.
12184 (defun org-remap (map &rest commands)
12185 "In MAP, remap the functions given in COMMANDS.
12186 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12187 (let (new old)
12188 (while commands
12189 (setq old (pop commands) new (pop commands))
12190 (if (fboundp 'command-remapping)
12191 (org-defkey map (vector 'remap old) new)
12192 (substitute-key-definition old new map global-map)))))
12194 (when (eq org-enable-table-editor 'optimized)
12195 ;; If the user wants maximum table support, we need to hijack
12196 ;; some standard editing functions
12197 (org-remap org-mode-map
12198 'self-insert-command 'org-self-insert-command
12199 'delete-char 'org-delete-char
12200 'delete-backward-char 'org-delete-backward-char)
12201 (org-defkey org-mode-map "|" 'org-force-self-insert))
12203 (defun org-shiftcursor-error ()
12204 "Throw an error because Shift-Cursor command was applied in wrong context."
12205 (error "This command is active in special context like tables, headlines or timestamps"))
12207 (defun org-shifttab (&optional arg)
12208 "Global visibility cycling or move to previous table field.
12209 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12210 on context.
12211 See the individual commands for more information."
12212 (interactive "P")
12213 (cond
12214 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12215 ((integerp arg)
12216 (message "Content view to level: %d" arg)
12217 (org-content (prefix-numeric-value arg))
12218 (setq org-cycle-global-status 'overview))
12219 (t (call-interactively 'org-global-cycle))))
12221 (defun org-shiftmetaleft ()
12222 "Promote subtree or delete table column.
12223 Calls `org-promote-subtree', `org-outdent-item',
12224 or `org-table-delete-column', depending on context.
12225 See the individual commands for more information."
12226 (interactive)
12227 (cond
12228 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12229 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12230 ((org-at-item-p) (call-interactively 'org-outdent-item))
12231 (t (org-shiftcursor-error))))
12233 (defun org-shiftmetaright ()
12234 "Demote subtree or insert table column.
12235 Calls `org-demote-subtree', `org-indent-item',
12236 or `org-table-insert-column', depending on context.
12237 See the individual commands for more information."
12238 (interactive)
12239 (cond
12240 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12241 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12242 ((org-at-item-p) (call-interactively 'org-indent-item))
12243 (t (org-shiftcursor-error))))
12245 (defun org-shiftmetaup (&optional arg)
12246 "Move subtree up or kill table row.
12247 Calls `org-move-subtree-up' or `org-table-kill-row' or
12248 `org-move-item-up' depending on context. See the individual commands
12249 for more information."
12250 (interactive "P")
12251 (cond
12252 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12253 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12254 ((org-at-item-p) (call-interactively 'org-move-item-up))
12255 (t (org-shiftcursor-error))))
12256 (defun org-shiftmetadown (&optional arg)
12257 "Move subtree down or insert table row.
12258 Calls `org-move-subtree-down' or `org-table-insert-row' or
12259 `org-move-item-down', depending on context. See the individual
12260 commands for more information."
12261 (interactive "P")
12262 (cond
12263 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12264 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12265 ((org-at-item-p) (call-interactively 'org-move-item-down))
12266 (t (org-shiftcursor-error))))
12268 (defun org-metaleft (&optional arg)
12269 "Promote heading or move table column to left.
12270 Calls `org-do-promote' or `org-table-move-column', depending on context.
12271 With no specific context, calls the Emacs default `backward-word'.
12272 See the individual commands for more information."
12273 (interactive "P")
12274 (cond
12275 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12276 ((or (org-on-heading-p) (org-region-active-p))
12277 (call-interactively 'org-do-promote))
12278 ((org-at-item-p) (call-interactively 'org-outdent-item))
12279 (t (call-interactively 'backward-word))))
12281 (defun org-metaright (&optional arg)
12282 "Demote subtree or move table column to right.
12283 Calls `org-do-demote' or `org-table-move-column', depending on context.
12284 With no specific context, calls the Emacs default `forward-word'.
12285 See the individual commands for more information."
12286 (interactive "P")
12287 (cond
12288 ((org-at-table-p) (call-interactively 'org-table-move-column))
12289 ((or (org-on-heading-p) (org-region-active-p))
12290 (call-interactively 'org-do-demote))
12291 ((org-at-item-p) (call-interactively 'org-indent-item))
12292 (t (call-interactively 'forward-word))))
12294 (defun org-metaup (&optional arg)
12295 "Move subtree up or move table row up.
12296 Calls `org-move-subtree-up' or `org-table-move-row' or
12297 `org-move-item-up', depending on context. See the individual commands
12298 for more information."
12299 (interactive "P")
12300 (cond
12301 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12302 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12303 ((org-at-item-p) (call-interactively 'org-move-item-up))
12304 (t (transpose-lines 1) (beginning-of-line -1))))
12306 (defun org-metadown (&optional arg)
12307 "Move subtree down or move table row down.
12308 Calls `org-move-subtree-down' or `org-table-move-row' or
12309 `org-move-item-down', depending on context. See the individual
12310 commands for more information."
12311 (interactive "P")
12312 (cond
12313 ((org-at-table-p) (call-interactively 'org-table-move-row))
12314 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12315 ((org-at-item-p) (call-interactively 'org-move-item-down))
12316 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12318 (defun org-shiftup (&optional arg)
12319 "Increase item in timestamp or increase priority of current headline.
12320 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12321 depending on context. See the individual commands for more information."
12322 (interactive "P")
12323 (cond
12324 ((org-at-timestamp-p t)
12325 (call-interactively (if org-edit-timestamp-down-means-later
12326 'org-timestamp-down 'org-timestamp-up)))
12327 ((org-on-heading-p) (call-interactively 'org-priority-up))
12328 ((org-at-item-p) (call-interactively 'org-previous-item))
12329 ((org-clocktable-try-shift 'up arg))
12330 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12332 (defun org-shiftdown (&optional arg)
12333 "Decrease item in timestamp or decrease priority of current headline.
12334 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12335 depending on context. See the individual commands for more information."
12336 (interactive "P")
12337 (cond
12338 ((org-at-timestamp-p t)
12339 (call-interactively (if org-edit-timestamp-down-means-later
12340 'org-timestamp-up 'org-timestamp-down)))
12341 ((org-on-heading-p) (call-interactively 'org-priority-down))
12342 ((org-clocktable-try-shift 'down arg))
12343 (t (call-interactively 'org-next-item))))
12345 (defun org-shiftright (&optional arg)
12346 "Next TODO keyword or timestamp one day later, depending on context."
12347 (interactive "P")
12348 (cond
12349 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12350 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12351 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12352 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12353 ((org-clocktable-try-shift 'right arg))
12354 (t (org-shiftcursor-error))))
12356 (defun org-shiftleft (&optional arg)
12357 "Previous TODO keyword or timestamp one day earlier, depending on context."
12358 (interactive "P")
12359 (cond
12360 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12361 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12362 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12363 ((org-at-property-p)
12364 (call-interactively 'org-property-previous-allowed-value))
12365 ((org-clocktable-try-shift 'left arg))
12366 (t (org-shiftcursor-error))))
12368 (defun org-shiftcontrolright ()
12369 "Switch to next TODO set."
12370 (interactive)
12371 (cond
12372 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12373 (t (org-shiftcursor-error))))
12375 (defun org-shiftcontrolleft ()
12376 "Switch to previous TODO set."
12377 (interactive)
12378 (cond
12379 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12380 (t (org-shiftcursor-error))))
12382 (defun org-ctrl-c-ret ()
12383 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12384 (interactive)
12385 (cond
12386 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12387 (t (call-interactively 'org-insert-heading))))
12389 (defun org-copy-special ()
12390 "Copy region in table or copy current subtree.
12391 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12392 See the individual commands for more information."
12393 (interactive)
12394 (call-interactively
12395 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12397 (defun org-cut-special ()
12398 "Cut region in table or cut current subtree.
12399 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12400 See the individual commands for more information."
12401 (interactive)
12402 (call-interactively
12403 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12405 (defun org-paste-special (arg)
12406 "Paste rectangular region into table, or past subtree relative to level.
12407 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12408 See the individual commands for more information."
12409 (interactive "P")
12410 (if (org-at-table-p)
12411 (org-table-paste-rectangle)
12412 (org-paste-subtree arg)))
12414 (defun org-ctrl-c-ctrl-c (&optional arg)
12415 "Set tags in headline, or update according to changed information at point.
12417 This command does many different things, depending on context:
12419 - If the cursor is in a headline, prompt for tags and insert them
12420 into the current line, aligned to `org-tags-column'. When called
12421 with prefix arg, realign all tags in the current buffer.
12423 - If the cursor is in one of the special #+KEYWORD lines, this
12424 triggers scanning the buffer for these lines and updating the
12425 information.
12427 - If the cursor is inside a table, realign the table. This command
12428 works even if the automatic table editor has been turned off.
12430 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12431 the entire table.
12433 - If the cursor is a the beginning of a dynamic block, update it.
12435 - If the cursor is inside a table created by the table.el package,
12436 activate that table.
12438 - If the current buffer is a remember buffer, close note and file it.
12439 with a prefix argument, file it without further interaction to the default
12440 location.
12442 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12443 links in this buffer.
12445 - If the cursor is on a numbered item in a plain list, renumber the
12446 ordered list.
12448 - If the cursor is on a checkbox, toggle it."
12449 (interactive "P")
12450 (let ((org-enable-table-editor t))
12451 (cond
12452 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12453 org-occur-highlights
12454 org-latex-fragment-image-overlays)
12455 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12456 (org-remove-occur-highlights)
12457 (org-remove-latex-fragment-image-overlays)
12458 (message "Temporary highlights/overlays removed from current buffer"))
12459 ((and (local-variable-p 'org-finish-function (current-buffer))
12460 (fboundp org-finish-function))
12461 (funcall org-finish-function))
12462 ((org-at-property-p)
12463 (call-interactively 'org-property-action))
12464 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12465 ((org-on-heading-p) (call-interactively 'org-set-tags))
12466 ((org-at-table.el-p)
12467 (require 'table)
12468 (beginning-of-line 1)
12469 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12470 (call-interactively 'table-recognize-table))
12471 ((org-at-table-p)
12472 (org-table-maybe-eval-formula)
12473 (if arg
12474 (call-interactively 'org-table-recalculate)
12475 (org-table-maybe-recalculate-line))
12476 (call-interactively 'org-table-align))
12477 ((org-at-item-checkbox-p)
12478 (call-interactively 'org-toggle-checkbox))
12479 ((org-at-item-p)
12480 (call-interactively 'org-maybe-renumber-ordered-list))
12481 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12482 ;; Dynamic block
12483 (beginning-of-line 1)
12484 (org-update-dblock))
12485 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12486 (cond
12487 ((equal (match-string 1) "TBLFM")
12488 ;; Recalculate the table before this line
12489 (save-excursion
12490 (beginning-of-line 1)
12491 (skip-chars-backward " \r\n\t")
12492 (if (org-at-table-p)
12493 (org-call-with-arg 'org-table-recalculate t))))
12495 ; (org-set-regexps-and-options)
12496 ; (org-restart-font-lock)
12497 (let ((org-inhibit-startup t)) (org-mode-restart))
12498 (message "Local setup has been refreshed"))))
12499 (t (error "C-c C-c can do nothing useful at this location.")))))
12501 (defun org-mode-restart ()
12502 "Restart Org-mode, to scan again for special lines.
12503 Also updates the keyword regular expressions."
12504 (interactive)
12505 (org-mode)
12506 (message "Org-mode restarted"))
12508 (defun org-kill-note-or-show-branches ()
12509 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12510 (interactive)
12511 (if (not org-finish-function)
12512 (call-interactively 'show-branches)
12513 (let ((org-note-abort t))
12514 (funcall org-finish-function))))
12516 (defun org-return (&optional indent)
12517 "Goto next table row or insert a newline.
12518 Calls `org-table-next-row' or `newline', depending on context.
12519 See the individual commands for more information."
12520 (interactive)
12521 (cond
12522 ((bobp) (if indent (newline-and-indent) (newline)))
12523 ((and (org-at-heading-p)
12524 (looking-at
12525 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12526 (org-show-entry)
12527 (end-of-line 1)
12528 (newline))
12529 ((org-at-table-p)
12530 (org-table-justify-field-maybe)
12531 (call-interactively 'org-table-next-row))
12532 (t (if indent (newline-and-indent) (newline)))))
12534 (defun org-return-indent ()
12535 "Goto next table row or insert a newline and indent.
12536 Calls `org-table-next-row' or `newline-and-indent', depending on
12537 context. See the individual commands for more information."
12538 (interactive)
12539 (org-return t))
12541 (defun org-ctrl-c-star ()
12542 "Compute table, or change heading status of lines.
12543 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12544 depending on context. This will also turn a plain list item or a normal
12545 line into a subheading."
12546 (interactive)
12547 (cond
12548 ((org-at-table-p)
12549 (call-interactively 'org-table-recalculate))
12550 ((org-region-active-p)
12551 ;; Convert all lines in region to list items
12552 (call-interactively 'org-toggle-region-headings))
12553 ((org-on-heading-p)
12554 (org-toggle-region-headings (point-at-bol)
12555 (min (1+ (point-at-eol)) (point-max))))
12556 ((org-at-item-p)
12557 ;; Convert to heading
12558 (let ((level (save-match-data
12559 (save-excursion
12560 (condition-case nil
12561 (progn
12562 (org-back-to-heading t)
12563 (funcall outline-level))
12564 (error 0))))))
12565 (replace-match
12566 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12567 (t (org-toggle-region-headings (point-at-bol)
12568 (min (1+ (point-at-eol)) (point-max))))))
12570 (defun org-ctrl-c-minus ()
12571 "Insert separator line in table or modify bullet status of line.
12572 Also turns a plain line or a region of lines into list items.
12573 Calls `org-table-insert-hline', `org-toggle-region-items', or
12574 `org-cycle-list-bullet', depending on context."
12575 (interactive)
12576 (cond
12577 ((org-at-table-p)
12578 (call-interactively 'org-table-insert-hline))
12579 ((org-on-heading-p)
12580 ;; Convert to item
12581 (save-excursion
12582 (beginning-of-line 1)
12583 (if (looking-at "\\*+ ")
12584 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12585 ((org-region-active-p)
12586 ;; Convert all lines in region to list items
12587 (call-interactively 'org-toggle-region-items))
12588 ((org-in-item-p)
12589 (call-interactively 'org-cycle-list-bullet))
12590 (t (org-toggle-region-items (point-at-bol)
12591 (min (1+ (point-at-eol)) (point-max))))))
12593 (defun org-toggle-region-items (beg end)
12594 "Convert all lines in region to list items.
12595 If the first line is already an item, convert all list items in the region
12596 to normal lines."
12597 (interactive "r")
12598 (let (l2 l)
12599 (save-excursion
12600 (goto-char end)
12601 (setq l2 (org-current-line))
12602 (goto-char beg)
12603 (beginning-of-line 1)
12604 (setq l (1- (org-current-line)))
12605 (if (org-at-item-p)
12606 ;; We already have items, de-itemize
12607 (while (< (setq l (1+ l)) l2)
12608 (when (org-at-item-p)
12609 (goto-char (match-beginning 2))
12610 (delete-region (match-beginning 2) (match-end 2))
12611 (and (looking-at "[ \t]+") (replace-match "")))
12612 (beginning-of-line 2))
12613 (while (< (setq l (1+ l)) l2)
12614 (unless (org-at-item-p)
12615 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12616 (replace-match "\\1- \\2")))
12617 (beginning-of-line 2))))))
12619 (defun org-toggle-region-headings (beg end)
12620 "Convert all lines in region to list items.
12621 If the first line is already an item, convert all list items in the region
12622 to normal lines."
12623 (interactive "r")
12624 (let (l2 l)
12625 (save-excursion
12626 (goto-char end)
12627 (setq l2 (org-current-line))
12628 (goto-char beg)
12629 (beginning-of-line 1)
12630 (setq l (1- (org-current-line)))
12631 (if (org-on-heading-p)
12632 ;; We already have headlines, de-star them
12633 (while (< (setq l (1+ l)) l2)
12634 (when (org-on-heading-p t)
12635 (and (looking-at outline-regexp) (replace-match "")))
12636 (beginning-of-line 2))
12637 (let* ((stars (save-excursion
12638 (re-search-backward org-complex-heading-regexp nil t)
12639 (or (match-string 1) "*")))
12640 (add-stars (if org-odd-levels-only "**" "*"))
12641 (rpl (concat stars add-stars " \\2")))
12642 (while (< (setq l (1+ l)) l2)
12643 (unless (org-on-heading-p)
12644 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12645 (replace-match rpl)))
12646 (beginning-of-line 2)))))))
12648 (defun org-meta-return (&optional arg)
12649 "Insert a new heading or wrap a region in a table.
12650 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12651 See the individual commands for more information."
12652 (interactive "P")
12653 (cond
12654 ((org-at-table-p)
12655 (call-interactively 'org-table-wrap-region))
12656 (t (call-interactively 'org-insert-heading))))
12658 ;;; Menu entries
12660 ;; Define the Org-mode menus
12661 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12662 '("Tbl"
12663 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12664 ["Next Field" org-cycle (org-at-table-p)]
12665 ["Previous Field" org-shifttab (org-at-table-p)]
12666 ["Next Row" org-return (org-at-table-p)]
12667 "--"
12668 ["Blank Field" org-table-blank-field (org-at-table-p)]
12669 ["Edit Field" org-table-edit-field (org-at-table-p)]
12670 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12671 "--"
12672 ("Column"
12673 ["Move Column Left" org-metaleft (org-at-table-p)]
12674 ["Move Column Right" org-metaright (org-at-table-p)]
12675 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12676 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12677 ("Row"
12678 ["Move Row Up" org-metaup (org-at-table-p)]
12679 ["Move Row Down" org-metadown (org-at-table-p)]
12680 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12681 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12682 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12683 "--"
12684 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12685 ("Rectangle"
12686 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12687 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12688 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12689 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12690 "--"
12691 ("Calculate"
12692 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12693 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12694 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12695 "--"
12696 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12697 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12698 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12699 "--"
12700 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12701 "--"
12702 ["Sum Column/Rectangle" org-table-sum
12703 (or (org-at-table-p) (org-region-active-p))]
12704 ["Which Column?" org-table-current-column (org-at-table-p)])
12705 ["Debug Formulas"
12706 org-table-toggle-formula-debugger
12707 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12708 ["Show Col/Row Numbers"
12709 org-table-toggle-coordinate-overlays
12710 :style toggle
12711 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12712 "--"
12713 ["Create" org-table-create (and (not (org-at-table-p))
12714 org-enable-table-editor)]
12715 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12716 ["Import from File" org-table-import (not (org-at-table-p))]
12717 ["Export to File" org-table-export (org-at-table-p)]
12718 "--"
12719 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12721 (easy-menu-define org-org-menu org-mode-map "Org menu"
12722 '("Org"
12723 ("Show/Hide"
12724 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12725 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12726 ["Sparse Tree..." org-sparse-tree t]
12727 ["Reveal Context" org-reveal t]
12728 ["Show All" show-all t]
12729 "--"
12730 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12731 "--"
12732 ["New Heading" org-insert-heading t]
12733 ("Navigate Headings"
12734 ["Up" outline-up-heading t]
12735 ["Next" outline-next-visible-heading t]
12736 ["Previous" outline-previous-visible-heading t]
12737 ["Next Same Level" outline-forward-same-level t]
12738 ["Previous Same Level" outline-backward-same-level t]
12739 "--"
12740 ["Jump" org-goto t])
12741 ("Edit Structure"
12742 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12743 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12744 "--"
12745 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12746 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12747 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12748 "--"
12749 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12750 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12751 ["Demote Heading" org-metaright (not (org-at-table-p))]
12752 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12753 "--"
12754 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12755 "--"
12756 ["Convert to odd levels" org-convert-to-odd-levels t]
12757 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12758 ("Editing"
12759 ["Emphasis..." org-emphasize t])
12760 ("Archive"
12761 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12762 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12763 ; :active t :keys "C-u C-c C-x C-a"]
12764 ["Sparse trees open ARCHIVE trees"
12765 (setq org-sparse-tree-open-archived-trees
12766 (not org-sparse-tree-open-archived-trees))
12767 :style toggle :selected org-sparse-tree-open-archived-trees]
12768 ["Cycling opens ARCHIVE trees"
12769 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12770 :style toggle :selected org-cycle-open-archived-trees]
12771 ["Agenda includes ARCHIVE trees"
12772 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12773 :style toggle :selected (not org-agenda-skip-archived-trees)]
12774 "--"
12775 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12776 ; ["Check and Move Children" (org-archive-subtree '(4))
12777 ; :active t :keys "C-u C-c C-x C-s"]
12779 "--"
12780 ("TODO Lists"
12781 ["TODO/DONE/-" org-todo t]
12782 ("Select keyword"
12783 ["Next keyword" org-shiftright (org-on-heading-p)]
12784 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12785 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12786 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12787 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12788 ["Show TODO Tree" org-show-todo-tree t]
12789 ["Global TODO list" org-todo-list t]
12790 "--"
12791 ["Set Priority" org-priority t]
12792 ["Priority Up" org-shiftup t]
12793 ["Priority Down" org-shiftdown t])
12794 ("TAGS and Properties"
12795 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12796 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12797 "--"
12798 ["Set property" 'org-set-property t]
12799 ["Column view of properties" org-columns t]
12800 ["Insert Column View DBlock" org-insert-columns-dblock t])
12801 ("Dates and Scheduling"
12802 ["Timestamp" org-time-stamp t]
12803 ["Timestamp (inactive)" org-time-stamp-inactive t]
12804 ("Change Date"
12805 ["1 Day Later" org-shiftright t]
12806 ["1 Day Earlier" org-shiftleft t]
12807 ["1 ... Later" org-shiftup t]
12808 ["1 ... Earlier" org-shiftdown t])
12809 ["Compute Time Range" org-evaluate-time-range t]
12810 ["Schedule Item" org-schedule t]
12811 ["Deadline" org-deadline t]
12812 "--"
12813 ["Custom time format" org-toggle-time-stamp-overlays
12814 :style radio :selected org-display-custom-times]
12815 "--"
12816 ["Goto Calendar" org-goto-calendar t]
12817 ["Date from Calendar" org-date-from-calendar t])
12818 ("Logging work"
12819 ["Clock in" org-clock-in t]
12820 ["Clock out" org-clock-out t]
12821 ["Clock cancel" org-clock-cancel t]
12822 ["Goto running clock" org-clock-goto t]
12823 ["Display times" org-clock-display t]
12824 ["Create clock table" org-clock-report t]
12825 "--"
12826 ["Record DONE time"
12827 (progn (setq org-log-done (not org-log-done))
12828 (message "Switching to %s will %s record a timestamp"
12829 (car org-done-keywords)
12830 (if org-log-done "automatically" "not")))
12831 :style toggle :selected org-log-done])
12832 "--"
12833 ["Agenda Command..." org-agenda t]
12834 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12835 ("File List for Agenda")
12836 ("Special views current file"
12837 ["TODO Tree" org-show-todo-tree t]
12838 ["Check Deadlines" org-check-deadlines t]
12839 ["Timeline" org-timeline t]
12840 ["Tags Tree" org-tags-sparse-tree t])
12841 "--"
12842 ("Hyperlinks"
12843 ["Store Link (Global)" org-store-link t]
12844 ["Insert Link" org-insert-link t]
12845 ["Follow Link" org-open-at-point t]
12846 "--"
12847 ["Next link" org-next-link t]
12848 ["Previous link" org-previous-link t]
12849 "--"
12850 ["Descriptive Links"
12851 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12852 :style radio
12853 :selected (member '(org-link) buffer-invisibility-spec)]
12854 ["Literal Links"
12855 (progn
12856 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12857 :style radio
12858 :selected (not (member '(org-link) buffer-invisibility-spec))])
12859 "--"
12860 ["Export/Publish..." org-export t]
12861 ("LaTeX"
12862 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12863 :selected org-cdlatex-mode]
12864 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12865 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12866 ["Modify math symbol" org-cdlatex-math-modify
12867 (org-inside-LaTeX-fragment-p)]
12868 ["Export LaTeX fragments as images"
12869 (if (featurep 'org-exp)
12870 (setq org-export-with-LaTeX-fragments
12871 (not org-export-with-LaTeX-fragments))
12872 (require 'org-exp))
12873 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12874 org-export-with-LaTeX-fragments)])
12875 "--"
12876 ("Documentation"
12877 ["Show Version" org-version t]
12878 ["Info Documentation" org-info t])
12879 ("Customize"
12880 ["Browse Org Group" org-customize t]
12881 "--"
12882 ["Expand This Menu" org-create-customize-menu
12883 (fboundp 'customize-menu-create)])
12884 "--"
12885 ["Refresh setup" org-mode-restart t]
12888 (defun org-info (&optional node)
12889 "Read documentation for Org-mode in the info system.
12890 With optional NODE, go directly to that node."
12891 (interactive)
12892 (info (format "(org)%s" (or node ""))))
12894 (defun org-install-agenda-files-menu ()
12895 (let ((bl (buffer-list)))
12896 (save-excursion
12897 (while bl
12898 (set-buffer (pop bl))
12899 (if (org-mode-p) (setq bl nil)))
12900 (when (org-mode-p)
12901 (easy-menu-change
12902 '("Org") "File List for Agenda"
12903 (append
12904 (list
12905 ["Edit File List" (org-edit-agenda-file-list) t]
12906 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12907 ["Remove Current File from List" org-remove-file t]
12908 ["Cycle through agenda files" org-cycle-agenda-files t]
12909 ["Occur in all agenda files" org-occur-in-agenda-files t]
12910 "--")
12911 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12913 ;;;; Documentation
12915 (defun org-require-autoloaded-modules ()
12916 (interactive)
12917 (mapc 'require
12918 '(org-agenda org-archive org-clock org-colview
12919 org-exp org-export-latex org-publish
12920 org-remember org-table)))
12922 (defun org-customize ()
12923 "Call the customize function with org as argument."
12924 (interactive)
12925 (org-load-modules-maybe)
12926 (org-require-autoloaded-modules)
12927 (customize-browse 'org))
12929 (defun org-create-customize-menu ()
12930 "Create a full customization menu for Org-mode, insert it into the menu."
12931 (interactive)
12932 (org-load-modules-maybe)
12933 (org-require-autoloaded-modules)
12934 (if (fboundp 'customize-menu-create)
12935 (progn
12936 (easy-menu-change
12937 '("Org") "Customize"
12938 `(["Browse Org group" org-customize t]
12939 "--"
12940 ,(customize-menu-create 'org)
12941 ["Set" Custom-set t]
12942 ["Save" Custom-save t]
12943 ["Reset to Current" Custom-reset-current t]
12944 ["Reset to Saved" Custom-reset-saved t]
12945 ["Reset to Standard Settings" Custom-reset-standard t]))
12946 (message "\"Org\"-menu now contains full customization menu"))
12947 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12949 ;;;; Miscellaneous stuff
12951 ;;; Generally useful functions
12953 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12954 "Display the given MESSAGE as a warning."
12955 (if (fboundp 'display-warning)
12956 (display-warning 'org message
12957 (if (featurep 'xemacs)
12958 'warning
12959 :warning))
12960 (let ((buf (get-buffer-create "*Org warnings*")))
12961 (with-current-buffer buf
12962 (goto-char (point-max))
12963 (insert "Warning (Org): " message)
12964 (unless (bolp)
12965 (newline)))
12966 (display-buffer buf)
12967 (sit-for 0))))
12969 (defun org-quote-csv-field (s)
12970 "Quote field for inclusion in CSV material."
12971 (if (string-match "[\",]" s)
12972 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
12975 (defun org-plist-delete (plist property)
12976 "Delete PROPERTY from PLIST.
12977 This is in contrast to merely setting it to 0."
12978 (let (p)
12979 (while plist
12980 (if (not (eq property (car plist)))
12981 (setq p (plist-put p (car plist) (nth 1 plist))))
12982 (setq plist (cddr plist)))
12985 (defun org-force-self-insert (N)
12986 "Needed to enforce self-insert under remapping."
12987 (interactive "p")
12988 (self-insert-command N))
12990 (defun org-string-width (s)
12991 "Compute width of string, ignoring invisible characters.
12992 This ignores character with invisibility property `org-link', and also
12993 characters with property `org-cwidth', because these will become invisible
12994 upon the next fontification round."
12995 (let (b l)
12996 (when (or (eq t buffer-invisibility-spec)
12997 (assq 'org-link buffer-invisibility-spec))
12998 (while (setq b (text-property-any 0 (length s)
12999 'invisible 'org-link s))
13000 (setq s (concat (substring s 0 b)
13001 (substring s (or (next-single-property-change
13002 b 'invisible s) (length s)))))))
13003 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13004 (setq s (concat (substring s 0 b)
13005 (substring s (or (next-single-property-change
13006 b 'org-cwidth s) (length s))))))
13007 (setq l (string-width s) b -1)
13008 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13009 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13012 (defun org-base-buffer (buffer)
13013 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13014 (if (not buffer)
13015 buffer
13016 (or (buffer-base-buffer buffer)
13017 buffer)))
13019 (defun org-trim (s)
13020 "Remove whitespace at beginning and end of string."
13021 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13022 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13025 (defun org-wrap (string &optional width lines)
13026 "Wrap string to either a number of lines, or a width in characters.
13027 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13028 that costs. If there is a word longer than WIDTH, the text is actually
13029 wrapped to the length of that word.
13030 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13031 many lines, whatever width that takes.
13032 The return value is a list of lines, without newlines at the end."
13033 (let* ((words (org-split-string string "[ \t\n]+"))
13034 (maxword (apply 'max (mapcar 'org-string-width words)))
13035 w ll)
13036 (cond (width
13037 (org-do-wrap words (max maxword width)))
13038 (lines
13039 (setq w maxword)
13040 (setq ll (org-do-wrap words maxword))
13041 (if (<= (length ll) lines)
13043 (setq ll words)
13044 (while (> (length ll) lines)
13045 (setq w (1+ w))
13046 (setq ll (org-do-wrap words w)))
13047 ll))
13048 (t (error "Cannot wrap this")))))
13050 (defun org-do-wrap (words width)
13051 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13052 (let (lines line)
13053 (while words
13054 (setq line (pop words))
13055 (while (and words (< (+ (length line) (length (car words))) width))
13056 (setq line (concat line " " (pop words))))
13057 (setq lines (push line lines)))
13058 (nreverse lines)))
13060 (defun org-split-string (string &optional separators)
13061 "Splits STRING into substrings at SEPARATORS.
13062 No empty strings are returned if there are matches at the beginning
13063 and end of string."
13064 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13065 (start 0)
13066 notfirst
13067 (list nil))
13068 (while (and (string-match rexp string
13069 (if (and notfirst
13070 (= start (match-beginning 0))
13071 (< start (length string)))
13072 (1+ start) start))
13073 (< (match-beginning 0) (length string)))
13074 (setq notfirst t)
13075 (or (eq (match-beginning 0) 0)
13076 (and (eq (match-beginning 0) (match-end 0))
13077 (eq (match-beginning 0) start))
13078 (setq list
13079 (cons (substring string start (match-beginning 0))
13080 list)))
13081 (setq start (match-end 0)))
13082 (or (eq start (length string))
13083 (setq list
13084 (cons (substring string start)
13085 list)))
13086 (nreverse list)))
13088 (defun org-context ()
13089 "Return a list of contexts of the current cursor position.
13090 If several contexts apply, all are returned.
13091 Each context entry is a list with a symbol naming the context, and
13092 two positions indicating start and end of the context. Possible
13093 contexts are:
13095 :headline anywhere in a headline
13096 :headline-stars on the leading stars in a headline
13097 :todo-keyword on a TODO keyword (including DONE) in a headline
13098 :tags on the TAGS in a headline
13099 :priority on the priority cookie in a headline
13100 :item on the first line of a plain list item
13101 :item-bullet on the bullet/number of a plain list item
13102 :checkbox on the checkbox in a plain list item
13103 :table in an org-mode table
13104 :table-special on a special filed in a table
13105 :table-table in a table.el table
13106 :link on a hyperlink
13107 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13108 :target on a <<target>>
13109 :radio-target on a <<<radio-target>>>
13110 :latex-fragment on a LaTeX fragment
13111 :latex-preview on a LaTeX fragment with overlayed preview image
13113 This function expects the position to be visible because it uses font-lock
13114 faces as a help to recognize the following contexts: :table-special, :link,
13115 and :keyword."
13116 (let* ((f (get-text-property (point) 'face))
13117 (faces (if (listp f) f (list f)))
13118 (p (point)) clist o)
13119 ;; First the large context
13120 (cond
13121 ((org-on-heading-p t)
13122 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13123 (when (progn
13124 (beginning-of-line 1)
13125 (looking-at org-todo-line-tags-regexp))
13126 (push (org-point-in-group p 1 :headline-stars) clist)
13127 (push (org-point-in-group p 2 :todo-keyword) clist)
13128 (push (org-point-in-group p 4 :tags) clist))
13129 (goto-char p)
13130 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13131 (if (looking-at "\\[#[A-Z0-9]\\]")
13132 (push (org-point-in-group p 0 :priority) clist)))
13134 ((org-at-item-p)
13135 (push (org-point-in-group p 2 :item-bullet) clist)
13136 (push (list :item (point-at-bol)
13137 (save-excursion (org-end-of-item) (point)))
13138 clist)
13139 (and (org-at-item-checkbox-p)
13140 (push (org-point-in-group p 0 :checkbox) clist)))
13142 ((org-at-table-p)
13143 (push (list :table (org-table-begin) (org-table-end)) clist)
13144 (if (memq 'org-formula faces)
13145 (push (list :table-special
13146 (previous-single-property-change p 'face)
13147 (next-single-property-change p 'face)) clist)))
13148 ((org-at-table-p 'any)
13149 (push (list :table-table) clist)))
13150 (goto-char p)
13152 ;; Now the small context
13153 (cond
13154 ((org-at-timestamp-p)
13155 (push (org-point-in-group p 0 :timestamp) clist))
13156 ((memq 'org-link faces)
13157 (push (list :link
13158 (previous-single-property-change p 'face)
13159 (next-single-property-change p 'face)) clist))
13160 ((memq 'org-special-keyword faces)
13161 (push (list :keyword
13162 (previous-single-property-change p 'face)
13163 (next-single-property-change p 'face)) clist))
13164 ((org-on-target-p)
13165 (push (org-point-in-group p 0 :target) clist)
13166 (goto-char (1- (match-beginning 0)))
13167 (if (looking-at org-radio-target-regexp)
13168 (push (org-point-in-group p 0 :radio-target) clist))
13169 (goto-char p))
13170 ((setq o (car (delq nil
13171 (mapcar
13172 (lambda (x)
13173 (if (memq x org-latex-fragment-image-overlays) x))
13174 (org-overlays-at (point))))))
13175 (push (list :latex-fragment
13176 (org-overlay-start o) (org-overlay-end o)) clist)
13177 (push (list :latex-preview
13178 (org-overlay-start o) (org-overlay-end o)) clist))
13179 ((org-inside-LaTeX-fragment-p)
13180 ;; FIXME: positions wrong.
13181 (push (list :latex-fragment (point) (point)) clist)))
13183 (setq clist (nreverse (delq nil clist)))
13184 clist))
13186 ;; FIXME: Compare with at-regexp-p Do we need both?
13187 (defun org-in-regexp (re &optional nlines visually)
13188 "Check if point is inside a match of regexp.
13189 Normally only the current line is checked, but you can include NLINES extra
13190 lines both before and after point into the search.
13191 If VISUALLY is set, require that the cursor is not after the match but
13192 really on, so that the block visually is on the match."
13193 (catch 'exit
13194 (let ((pos (point))
13195 (eol (point-at-eol (+ 1 (or nlines 0))))
13196 (inc (if visually 1 0)))
13197 (save-excursion
13198 (beginning-of-line (- 1 (or nlines 0)))
13199 (while (re-search-forward re eol t)
13200 (if (and (<= (match-beginning 0) pos)
13201 (>= (+ inc (match-end 0)) pos))
13202 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13204 (defun org-at-regexp-p (regexp)
13205 "Is point inside a match of REGEXP in the current line?"
13206 (catch 'exit
13207 (save-excursion
13208 (let ((pos (point)) (end (point-at-eol)))
13209 (beginning-of-line 1)
13210 (while (re-search-forward regexp end t)
13211 (if (and (<= (match-beginning 0) pos)
13212 (>= (match-end 0) pos))
13213 (throw 'exit t)))
13214 nil))))
13216 (defun org-occur-in-agenda-files (regexp &optional nlines)
13217 "Call `multi-occur' with buffers for all agenda files."
13218 (interactive "sOrg-files matching: \np")
13219 (let* ((files (org-agenda-files))
13220 (tnames (mapcar 'file-truename files))
13221 (extra org-agenda-text-search-extra-files)
13223 (when (eq (car extra) 'agenda-archives)
13224 (setq extra (cdr extra))
13225 (setq files (org-add-archive-files files)))
13226 (while (setq f (pop extra))
13227 (unless (member (file-truename f) tnames)
13228 (add-to-list 'files f 'append)
13229 (add-to-list 'tnames (file-truename f) 'append)))
13230 (multi-occur
13231 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13232 regexp)))
13234 (if (boundp 'occur-mode-find-occurrence-hook)
13235 ;; Emacs 23
13236 (add-hook 'occur-mode-find-occurrence-hook
13237 (lambda ()
13238 (when (org-mode-p)
13239 (org-reveal))))
13240 ;; Emacs 22
13241 (defadvice occur-mode-goto-occurrence
13242 (after org-occur-reveal activate)
13243 (and (org-mode-p) (org-reveal)))
13244 (defadvice occur-mode-goto-occurrence-other-window
13245 (after org-occur-reveal activate)
13246 (and (org-mode-p) (org-reveal)))
13247 (defadvice occur-mode-display-occurrence
13248 (after org-occur-reveal activate)
13249 (when (org-mode-p)
13250 (let ((pos (occur-mode-find-occurrence)))
13251 (with-current-buffer (marker-buffer pos)
13252 (save-excursion
13253 (goto-char pos)
13254 (org-reveal)))))))
13256 (defun org-uniquify (list)
13257 "Remove duplicate elements from LIST."
13258 (let (res)
13259 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13260 res))
13262 (defun org-delete-all (elts list)
13263 "Remove all elements in ELTS from LIST."
13264 (while elts
13265 (setq list (delete (pop elts) list)))
13266 list)
13268 (defun org-back-over-empty-lines ()
13269 "Move backwards over witespace, to the beginning of the first empty line.
13270 Returns the number of empty lines passed."
13271 (let ((pos (point)))
13272 (skip-chars-backward " \t\n\r")
13273 (beginning-of-line 2)
13274 (goto-char (min (point) pos))
13275 (count-lines (point) pos)))
13277 (defun org-skip-whitespace ()
13278 (skip-chars-forward " \t\n\r"))
13280 (defun org-point-in-group (point group &optional context)
13281 "Check if POINT is in match-group GROUP.
13282 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13283 match. If the match group does ot exist or point is not inside it,
13284 return nil."
13285 (and (match-beginning group)
13286 (>= point (match-beginning group))
13287 (<= point (match-end group))
13288 (if context
13289 (list context (match-beginning group) (match-end group))
13290 t)))
13292 (defun org-switch-to-buffer-other-window (&rest args)
13293 "Switch to buffer in a second window on the current frame.
13294 In particular, do not allow pop-up frames."
13295 (let (pop-up-frames special-display-buffer-names special-display-regexps
13296 special-display-function)
13297 (apply 'switch-to-buffer-other-window args)))
13299 (defun org-combine-plists (&rest plists)
13300 "Create a single property list from all plists in PLISTS.
13301 The process starts by copying the first list, and then setting properties
13302 from the other lists. Settings in the last list are the most significant
13303 ones and overrule settings in the other lists."
13304 (let ((rtn (copy-sequence (pop plists)))
13305 p v ls)
13306 (while plists
13307 (setq ls (pop plists))
13308 (while ls
13309 (setq p (pop ls) v (pop ls))
13310 (setq rtn (plist-put rtn p v))))
13311 rtn))
13313 (defun org-move-line-down (arg)
13314 "Move the current line down. With prefix argument, move it past ARG lines."
13315 (interactive "p")
13316 (let ((col (current-column))
13317 beg end pos)
13318 (beginning-of-line 1) (setq beg (point))
13319 (beginning-of-line 2) (setq end (point))
13320 (beginning-of-line (+ 1 arg))
13321 (setq pos (move-marker (make-marker) (point)))
13322 (insert (delete-and-extract-region beg end))
13323 (goto-char pos)
13324 (org-move-to-column col)))
13326 (defun org-move-line-up (arg)
13327 "Move the current line up. With prefix argument, move it past ARG lines."
13328 (interactive "p")
13329 (let ((col (current-column))
13330 beg end pos)
13331 (beginning-of-line 1) (setq beg (point))
13332 (beginning-of-line 2) (setq end (point))
13333 (beginning-of-line (- arg))
13334 (setq pos (move-marker (make-marker) (point)))
13335 (insert (delete-and-extract-region beg end))
13336 (goto-char pos)
13337 (org-move-to-column col)))
13339 (defun org-replace-escapes (string table)
13340 "Replace %-escapes in STRING with values in TABLE.
13341 TABLE is an association list with keys like \"%a\" and string values.
13342 The sequences in STRING may contain normal field width and padding information,
13343 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13344 so values can contain further %-escapes if they are define later in TABLE."
13345 (let ((case-fold-search nil)
13346 e re rpl)
13347 (while (setq e (pop table))
13348 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13349 (while (string-match re string)
13350 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13351 (cdr e)))
13352 (setq string (replace-match rpl t t string))))
13353 string))
13356 (defun org-sublist (list start end)
13357 "Return a section of LIST, from START to END.
13358 Counting starts at 1."
13359 (let (rtn (c start))
13360 (setq list (nthcdr (1- start) list))
13361 (while (and list (<= c end))
13362 (push (pop list) rtn)
13363 (setq c (1+ c)))
13364 (nreverse rtn)))
13366 (defun org-find-base-buffer-visiting (file)
13367 "Like `find-buffer-visiting' but alway return the base buffer and
13368 not an indirect buffer."
13369 (let ((buf (find-buffer-visiting file)))
13370 (if buf
13371 (or (buffer-base-buffer buf) buf)
13372 nil)))
13374 (defun org-image-file-name-regexp ()
13375 "Return regexp matching the file names of images."
13376 (if (fboundp 'image-file-name-regexp)
13377 (image-file-name-regexp)
13378 (let ((image-file-name-extensions
13379 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13380 "xbm" "xpm" "pbm" "pgm" "ppm")))
13381 (concat "\\."
13382 (regexp-opt (nconc (mapcar 'upcase
13383 image-file-name-extensions)
13384 image-file-name-extensions)
13386 "\\'"))))
13388 (defun org-file-image-p (file)
13389 "Return non-nil if FILE is an image."
13390 (save-match-data
13391 (string-match (org-image-file-name-regexp) file)))
13393 ;;; Paragraph filling stuff.
13394 ;; We want this to be just right, so use the full arsenal.
13396 (defun org-indent-line-function ()
13397 "Indent line like previous, but further if previous was headline or item."
13398 (interactive)
13399 (let* ((pos (point))
13400 (itemp (org-at-item-p))
13401 column bpos bcol tpos tcol bullet btype bullet-type)
13402 ;; Find the previous relevant line
13403 (beginning-of-line 1)
13404 (cond
13405 ((looking-at "#") (setq column 0))
13406 ((looking-at "\\*+ ") (setq column 0))
13408 (beginning-of-line 0)
13409 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13410 (beginning-of-line 0))
13411 (cond
13412 ((looking-at "\\*+[ \t]+")
13413 (goto-char (match-end 0))
13414 (setq column (current-column)))
13415 ((org-in-item-p)
13416 (org-beginning-of-item)
13417 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13418 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13419 (setq bpos (match-beginning 1) tpos (match-end 0)
13420 bcol (progn (goto-char bpos) (current-column))
13421 tcol (progn (goto-char tpos) (current-column))
13422 bullet (match-string 1)
13423 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13424 (if (> tcol (+ bcol org-description-max-indent))
13425 (setq tcol (+ bcol 5)))
13426 (if (not itemp)
13427 (setq column tcol)
13428 (goto-char pos)
13429 (beginning-of-line 1)
13430 (if (looking-at "\\S-")
13431 (progn
13432 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13433 (setq bullet (match-string 1)
13434 btype (if (string-match "[0-9]" bullet) "n" bullet))
13435 (setq column (if (equal btype bullet-type) bcol tcol)))
13436 (setq column (org-get-indentation)))))
13437 (t (setq column (org-get-indentation))))))
13438 (goto-char pos)
13439 (if (<= (current-column) (current-indentation))
13440 (org-indent-line-to column)
13441 (save-excursion (org-indent-line-to column)))
13442 (setq column (current-column))
13443 (beginning-of-line 1)
13444 (if (looking-at
13445 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13446 (replace-match (concat "\\1" (format org-property-format
13447 (match-string 2) (match-string 3)))
13448 t nil))
13449 (org-move-to-column column)))
13451 (defun org-set-autofill-regexps ()
13452 (interactive)
13453 ;; In the paragraph separator we include headlines, because filling
13454 ;; text in a line directly attached to a headline would otherwise
13455 ;; fill the headline as well.
13456 (org-set-local 'comment-start-skip "^#+[ \t]*")
13457 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13458 ;; The paragraph starter includes hand-formatted lists.
13459 (org-set-local 'paragraph-start
13460 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13461 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13462 ;; But only if the user has not turned off tables or fixed-width regions
13463 (org-set-local
13464 'auto-fill-inhibit-regexp
13465 (concat "\\*+ \\|#\\+"
13466 "\\|[ \t]*" org-keyword-time-regexp
13467 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13468 (concat
13469 "\\|[ \t]*["
13470 (if org-enable-table-editor "|" "")
13471 (if org-enable-fixed-width-editor ":" "")
13472 "]"))))
13473 ;; We use our own fill-paragraph function, to make sure that tables
13474 ;; and fixed-width regions are not wrapped. That function will pass
13475 ;; through to `fill-paragraph' when appropriate.
13476 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13477 ; Adaptive filling: To get full control, first make sure that
13478 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13479 (org-set-local 'adaptive-fill-regexp "\000")
13480 (org-set-local 'adaptive-fill-function
13481 'org-adaptive-fill-function)
13482 (org-set-local
13483 'align-mode-rules-list
13484 '((org-in-buffer-settings
13485 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13486 (modes . '(org-mode))))))
13488 (defun org-fill-paragraph (&optional justify)
13489 "Re-align a table, pass through to fill-paragraph if no table."
13490 (let ((table-p (org-at-table-p))
13491 (table.el-p (org-at-table.el-p)))
13492 (cond ((and (equal (char-after (point-at-bol)) ?*)
13493 (save-excursion (goto-char (point-at-bol))
13494 (looking-at outline-regexp)))
13495 t) ; skip headlines
13496 (table.el-p t) ; skip table.el tables
13497 (table-p (org-table-align) t) ; align org-mode tables
13498 (t nil)))) ; call paragraph-fill
13500 ;; For reference, this is the default value of adaptive-fill-regexp
13501 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13503 (defun org-adaptive-fill-function ()
13504 "Return a fill prefix for org-mode files.
13505 In particular, this makes sure hanging paragraphs for hand-formatted lists
13506 work correctly."
13507 (cond ((looking-at "#[ \t]+")
13508 (match-string 0))
13509 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13510 (save-excursion
13511 (if (> (match-end 1) (+ (match-beginning 1)
13512 org-description-max-indent))
13513 (goto-char (+ (match-beginning 1) 5))
13514 (goto-char (match-end 0)))
13515 (make-string (current-column) ?\ )))
13516 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13517 (save-excursion
13518 (goto-char (match-end 0))
13519 (make-string (current-column) ?\ )))
13520 (t nil)))
13522 ;;; Other stuff.
13524 (defun org-toggle-fixed-width-section (arg)
13525 "Toggle the fixed-width export.
13526 If there is no active region, the QUOTE keyword at the current headline is
13527 inserted or removed. When present, it causes the text between this headline
13528 and the next to be exported as fixed-width text, and unmodified.
13529 If there is an active region, this command adds or removes a colon as the
13530 first character of this line. If the first character of a line is a colon,
13531 this line is also exported in fixed-width font."
13532 (interactive "P")
13533 (let* ((cc 0)
13534 (regionp (org-region-active-p))
13535 (beg (if regionp (region-beginning) (point)))
13536 (end (if regionp (region-end)))
13537 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13538 (case-fold-search nil)
13539 (re "[ \t]*\\(:\\)")
13540 off)
13541 (if regionp
13542 (save-excursion
13543 (goto-char beg)
13544 (setq cc (current-column))
13545 (beginning-of-line 1)
13546 (setq off (looking-at re))
13547 (while (> nlines 0)
13548 (setq nlines (1- nlines))
13549 (beginning-of-line 1)
13550 (cond
13551 (arg
13552 (org-move-to-column cc t)
13553 (insert ":\n")
13554 (forward-line -1))
13555 ((and off (looking-at re))
13556 (replace-match "" t t nil 1))
13557 ((not off) (org-move-to-column cc t) (insert ":")))
13558 (forward-line 1)))
13559 (save-excursion
13560 (org-back-to-heading)
13561 (if (looking-at (concat outline-regexp
13562 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13563 (replace-match "" t t nil 1)
13564 (if (looking-at outline-regexp)
13565 (progn
13566 (goto-char (match-end 0))
13567 (insert org-quote-string " "))))))))
13569 ;;;; Functions extending outline functionality
13571 (defun org-beginning-of-line (&optional arg)
13572 "Go to the beginning of the current line. If that is invisible, continue
13573 to a visible line beginning. This makes the function of C-a more intuitive.
13574 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13575 first attempt, and only move to after the tags when the cursor is already
13576 beyond the end of the headline."
13577 (interactive "P")
13578 (let ((pos (point)))
13579 (beginning-of-line 1)
13580 (if (bobp)
13582 (backward-char 1)
13583 (if (org-invisible-p)
13584 (while (and (not (bobp)) (org-invisible-p))
13585 (backward-char 1)
13586 (beginning-of-line 1))
13587 (forward-char 1)))
13588 (when org-special-ctrl-a/e
13589 (cond
13590 ((and (looking-at org-todo-line-regexp)
13591 (= (char-after (match-end 1)) ?\ ))
13592 (goto-char
13593 (if (eq org-special-ctrl-a/e t)
13594 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13595 ((= pos (point)) (match-beginning 3))
13596 (t (point)))
13597 (cond ((> pos (point)) (point))
13598 ((not (eq last-command this-command)) (point))
13599 (t (match-beginning 3))))))
13600 ((org-at-item-p)
13601 (goto-char
13602 (if (eq org-special-ctrl-a/e t)
13603 (cond ((> pos (match-end 4)) (match-end 4))
13604 ((= pos (point)) (match-end 4))
13605 (t (point)))
13606 (cond ((> pos (point)) (point))
13607 ((not (eq last-command this-command)) (point))
13608 (t (match-end 4))))))))))
13610 (defun org-end-of-line (&optional arg)
13611 "Go to the end of the line.
13612 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13613 first attempt, and only move to after the tags when the cursor is already
13614 beyond the end of the headline."
13615 (interactive "P")
13616 (if (or (not org-special-ctrl-a/e)
13617 (not (org-on-heading-p)))
13618 (end-of-line arg)
13619 (let ((pos (point)))
13620 (beginning-of-line 1)
13621 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13622 (if (eq org-special-ctrl-a/e t)
13623 (if (or (< pos (match-beginning 1))
13624 (= pos (match-end 0)))
13625 (goto-char (match-beginning 1))
13626 (goto-char (match-end 0)))
13627 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13628 (goto-char (match-end 0))
13629 (goto-char (match-beginning 1))))
13630 (end-of-line arg)))))
13632 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13633 (define-key org-mode-map "\C-e" 'org-end-of-line)
13635 (defun org-kill-line (&optional arg)
13636 "Kill line, to tags or end of line."
13637 (interactive "P")
13638 (cond
13639 ((or (not org-special-ctrl-k)
13640 (bolp)
13641 (not (org-on-heading-p)))
13642 (call-interactively 'kill-line))
13643 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13644 (kill-region (point) (match-beginning 1))
13645 (org-set-tags nil t))
13646 (t (kill-region (point) (point-at-eol)))))
13648 (define-key org-mode-map "\C-k" 'org-kill-line)
13650 (defun org-invisible-p ()
13651 "Check if point is at a character currently not visible."
13652 ;; Early versions of noutline don't have `outline-invisible-p'.
13653 (if (fboundp 'outline-invisible-p)
13654 (outline-invisible-p)
13655 (get-char-property (point) 'invisible)))
13657 (defun org-invisible-p2 ()
13658 "Check if point is at a character currently not visible."
13659 (save-excursion
13660 (if (and (eolp) (not (bobp))) (backward-char 1))
13661 ;; Early versions of noutline don't have `outline-invisible-p'.
13662 (if (fboundp 'outline-invisible-p)
13663 (outline-invisible-p)
13664 (get-char-property (point) 'invisible))))
13666 (defalias 'org-back-to-heading 'outline-back-to-heading)
13667 (defalias 'org-on-heading-p 'outline-on-heading-p)
13668 (defalias 'org-at-heading-p 'outline-on-heading-p)
13669 (defun org-at-heading-or-item-p ()
13670 (or (org-on-heading-p) (org-at-item-p)))
13672 (defun org-on-target-p ()
13673 (or (org-in-regexp org-radio-target-regexp)
13674 (org-in-regexp org-target-regexp)))
13676 (defun org-up-heading-all (arg)
13677 "Move to the heading line of which the present line is a subheading.
13678 This function considers both visible and invisible heading lines.
13679 With argument, move up ARG levels."
13680 (if (fboundp 'outline-up-heading-all)
13681 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13682 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13684 (defun org-up-heading-safe ()
13685 "Move to the heading line of which the present line is a subheading.
13686 This version will not throw an error. It will return the level of the
13687 headline found, or nil if no higher level is found."
13688 (let ((pos (point)) start-level level
13689 (re (concat "^" outline-regexp)))
13690 (catch 'exit
13691 (outline-back-to-heading t)
13692 (setq start-level (funcall outline-level))
13693 (if (equal start-level 1) (throw 'exit nil))
13694 (while (re-search-backward re nil t)
13695 (setq level (funcall outline-level))
13696 (if (< level start-level) (throw 'exit level)))
13697 nil)))
13699 (defun org-first-sibling-p ()
13700 "Is this heading the first child of its parents?"
13701 (interactive)
13702 (let ((re (concat "^" outline-regexp))
13703 level l)
13704 (unless (org-at-heading-p t)
13705 (error "Not at a heading"))
13706 (setq level (funcall outline-level))
13707 (save-excursion
13708 (if (not (re-search-backward re nil t))
13710 (setq l (funcall outline-level))
13711 (< l level)))))
13713 (defun org-goto-sibling (&optional previous)
13714 "Goto the next sibling, even if it is invisible.
13715 When PREVIOUS is set, go to the previous sibling instead. Returns t
13716 when a sibling was found. When none is found, return nil and don't
13717 move point."
13718 (let ((fun (if previous 're-search-backward 're-search-forward))
13719 (pos (point))
13720 (re (concat "^" outline-regexp))
13721 level l)
13722 (when (condition-case nil (org-back-to-heading t) (error nil))
13723 (setq level (funcall outline-level))
13724 (catch 'exit
13725 (or previous (forward-char 1))
13726 (while (funcall fun re nil t)
13727 (setq l (funcall outline-level))
13728 (when (< l level) (goto-char pos) (throw 'exit nil))
13729 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13730 (goto-char pos)
13731 nil))))
13733 (defun org-show-siblings ()
13734 "Show all siblings of the current headline."
13735 (save-excursion
13736 (while (org-goto-sibling) (org-flag-heading nil)))
13737 (save-excursion
13738 (while (org-goto-sibling 'previous)
13739 (org-flag-heading nil))))
13741 (defun org-show-hidden-entry ()
13742 "Show an entry where even the heading is hidden."
13743 (save-excursion
13744 (org-show-entry)))
13746 (defun org-flag-heading (flag &optional entry)
13747 "Flag the current heading. FLAG non-nil means make invisible.
13748 When ENTRY is non-nil, show the entire entry."
13749 (save-excursion
13750 (org-back-to-heading t)
13751 ;; Check if we should show the entire entry
13752 (if entry
13753 (progn
13754 (org-show-entry)
13755 (save-excursion
13756 (and (outline-next-heading)
13757 (org-flag-heading nil))))
13758 (outline-flag-region (max (point-min) (1- (point)))
13759 (save-excursion (outline-end-of-heading) (point))
13760 flag))))
13762 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13763 ;; This is an exact copy of the original function, but it uses
13764 ;; `org-back-to-heading', to make it work also in invisible
13765 ;; trees. And is uses an invisible-OK argument.
13766 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13767 (org-back-to-heading invisible-OK)
13768 (let ((first t)
13769 (level (funcall outline-level)))
13770 (while (and (not (eobp))
13771 (or first (> (funcall outline-level) level)))
13772 (setq first nil)
13773 (outline-next-heading))
13774 (unless to-heading
13775 (if (memq (preceding-char) '(?\n ?\^M))
13776 (progn
13777 ;; Go to end of line before heading
13778 (forward-char -1)
13779 (if (memq (preceding-char) '(?\n ?\^M))
13780 ;; leave blank line before heading
13781 (forward-char -1))))))
13782 (point))
13784 (defun org-show-subtree ()
13785 "Show everything after this heading at deeper levels."
13786 (outline-flag-region
13787 (point)
13788 (save-excursion
13789 (outline-end-of-subtree) (outline-next-heading) (point))
13790 nil))
13792 (defun org-show-entry ()
13793 "Show the body directly following this heading.
13794 Show the heading too, if it is currently invisible."
13795 (interactive)
13796 (save-excursion
13797 (condition-case nil
13798 (progn
13799 (org-back-to-heading t)
13800 (outline-flag-region
13801 (max (point-min) (1- (point)))
13802 (save-excursion
13803 (re-search-forward
13804 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13805 (or (match-beginning 1) (point-max)))
13806 nil))
13807 (error nil))))
13809 (defun org-make-options-regexp (kwds)
13810 "Make a regular expression for keyword lines."
13811 (concat
13813 "#?[ \t]*\\+\\("
13814 (mapconcat 'regexp-quote kwds "\\|")
13815 "\\):[ \t]*"
13816 "\\(.+\\)"))
13818 ;; Make isearch reveal the necessary context
13819 (defun org-isearch-end ()
13820 "Reveal context after isearch exits."
13821 (when isearch-success ; only if search was successful
13822 (if (featurep 'xemacs)
13823 ;; Under XEmacs, the hook is run in the correct place,
13824 ;; we directly show the context.
13825 (org-show-context 'isearch)
13826 ;; In Emacs the hook runs *before* restoring the overlays.
13827 ;; So we have to use a one-time post-command-hook to do this.
13828 ;; (Emacs 22 has a special variable, see function `org-mode')
13829 (unless (and (boundp 'isearch-mode-end-hook-quit)
13830 isearch-mode-end-hook-quit)
13831 ;; Only when the isearch was not quitted.
13832 (org-add-hook 'post-command-hook 'org-isearch-post-command
13833 'append 'local)))))
13835 (defun org-isearch-post-command ()
13836 "Remove self from hook, and show context."
13837 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13838 (org-show-context 'isearch))
13841 ;;;; Integration with and fixes for other packages
13843 ;;; Imenu support
13845 (defvar org-imenu-markers nil
13846 "All markers currently used by Imenu.")
13847 (make-variable-buffer-local 'org-imenu-markers)
13849 (defun org-imenu-new-marker (&optional pos)
13850 "Return a new marker for use by Imenu, and remember the marker."
13851 (let ((m (make-marker)))
13852 (move-marker m (or pos (point)))
13853 (push m org-imenu-markers)
13856 (defun org-imenu-get-tree ()
13857 "Produce the index for Imenu."
13858 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13859 (setq org-imenu-markers nil)
13860 (let* ((n org-imenu-depth)
13861 (re (concat "^" outline-regexp))
13862 (subs (make-vector (1+ n) nil))
13863 (last-level 0)
13864 m tree level head)
13865 (save-excursion
13866 (save-restriction
13867 (widen)
13868 (goto-char (point-max))
13869 (while (re-search-backward re nil t)
13870 (setq level (org-reduced-level (funcall outline-level)))
13871 (when (<= level n)
13872 (looking-at org-complex-heading-regexp)
13873 (setq head (org-match-string-no-properties 4)
13874 m (org-imenu-new-marker))
13875 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13876 (if (>= level last-level)
13877 (push (cons head m) (aref subs level))
13878 (push (cons head (aref subs (1+ level))) (aref subs level))
13879 (loop for i from (1+ level) to n do (aset subs i nil)))
13880 (setq last-level level)))))
13881 (aref subs 1)))
13883 (eval-after-load "imenu"
13884 '(progn
13885 (add-hook 'imenu-after-jump-hook
13886 (lambda () (org-show-context 'org-goto)))))
13888 ;; Speedbar support
13890 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13891 "Overlay marking the agenda restriction line in speedbar.")
13892 (org-overlay-put org-speedbar-restriction-lock-overlay
13893 'face 'org-agenda-restriction-lock)
13894 (org-overlay-put org-speedbar-restriction-lock-overlay
13895 'help-echo "Agendas are currently limited to this item.")
13896 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13898 (defun org-speedbar-set-agenda-restriction ()
13899 "Restrict future agenda commands to the location at point in speedbar.
13900 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13901 (interactive)
13902 (require 'org-agenda)
13903 (let (p m tp np dir txt w)
13904 (cond
13905 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13906 'org-imenu t))
13907 (setq m (get-text-property p 'org-imenu-marker))
13908 (save-excursion
13909 (save-restriction
13910 (set-buffer (marker-buffer m))
13911 (goto-char m)
13912 (org-agenda-set-restriction-lock 'subtree))))
13913 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13914 'speedbar-function 'speedbar-find-file))
13915 (setq tp (previous-single-property-change
13916 (1+ p) 'speedbar-function)
13917 np (next-single-property-change
13918 tp 'speedbar-function)
13919 dir (speedbar-line-directory)
13920 txt (buffer-substring-no-properties (or tp (point-min))
13921 (or np (point-max))))
13922 (save-excursion
13923 (save-restriction
13924 (set-buffer (find-file-noselect
13925 (let ((default-directory dir))
13926 (expand-file-name txt))))
13927 (unless (org-mode-p)
13928 (error "Cannot restrict to non-Org-mode file"))
13929 (org-agenda-set-restriction-lock 'file))))
13930 (t (error "Don't know how to restrict Org-mode's agenda")))
13931 (org-move-overlay org-speedbar-restriction-lock-overlay
13932 (point-at-bol) (point-at-eol))
13933 (setq current-prefix-arg nil)
13934 (org-agenda-maybe-redo)))
13936 (eval-after-load "speedbar"
13937 '(progn
13938 (speedbar-add-supported-extension ".org")
13939 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13940 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13941 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13942 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13943 (add-hook 'speedbar-visiting-tag-hook
13944 (lambda () (org-show-context 'org-goto)))))
13947 ;;; Fixes and Hacks for problems with other packages
13949 ;; Make flyspell not check words in links, to not mess up our keymap
13950 (defun org-mode-flyspell-verify ()
13951 "Don't let flyspell put overlays at active buttons."
13952 (not (get-text-property (point) 'keymap)))
13954 ;; Make `bookmark-jump' show the jump location if it was hidden.
13955 (eval-after-load "bookmark"
13956 '(if (boundp 'bookmark-after-jump-hook)
13957 ;; We can use the hook
13958 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13959 ;; Hook not available, use advice
13960 (defadvice bookmark-jump (after org-make-visible activate)
13961 "Make the position visible."
13962 (org-bookmark-jump-unhide))))
13964 (defun org-bookmark-jump-unhide ()
13965 "Unhide the current position, to show the bookmark location."
13966 (and (org-mode-p)
13967 (or (org-invisible-p)
13968 (save-excursion (goto-char (max (point-min) (1- (point))))
13969 (org-invisible-p)))
13970 (org-show-context 'bookmark-jump)))
13972 ;; Make session.el ignore our circular variable
13973 (eval-after-load "session"
13974 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13976 ;;;; Experimental code
13978 (defun org-closed-in-range ()
13979 "Sparse tree of items closed in a certain time range.
13980 Still experimental, may disappear in the future."
13981 (interactive)
13982 ;; Get the time interval from the user.
13983 (let* ((time1 (time-to-seconds
13984 (org-read-date nil 'to-time nil "Starting date: ")))
13985 (time2 (time-to-seconds
13986 (org-read-date nil 'to-time nil "End date:")))
13987 ;; callback function
13988 (callback (lambda ()
13989 (let ((time
13990 (time-to-seconds
13991 (apply 'encode-time
13992 (org-parse-time-string
13993 (match-string 1))))))
13994 ;; check if time in interval
13995 (and (>= time time1) (<= time time2))))))
13996 ;; make tree, check each match with the callback
13997 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14000 ;;;; Finish up
14002 (provide 'org)
14004 (run-hooks 'org-load-hook)
14006 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14008 ;;; org.el ends here