Release 6.15a
[org-mode/org-tableheadings.git] / lisp / org.el
blob86ad833f1dc835e0cc636e8954769bc05c368444
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.15a
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)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.15a"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-modules'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global IDs for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
176 (const :tag " mouse: Additional mouse support" org-mouse)
178 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
179 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
180 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
181 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
182 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
183 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
184 (const :tag "C eval: Include command output as text" org-eval)
185 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
186 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
187 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
188 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
189 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
190 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
191 (const :tag "C mtags: Support for muse-like tags" org-mtags)
192 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
193 (const :tag "C registry: A registry for Org links" org-registry)
194 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
195 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
196 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
197 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
198 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
201 (defgroup org-startup nil
202 "Options concerning startup of Org-mode."
203 :tag "Org Startup"
204 :group 'org)
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-startup-align-all-tables nil
228 "Non-nil means, align all tables when visiting a file.
229 This is useful when the column width in tables is forced with <N> cookies
230 in table fields. Such tables will look correct only after the first re-align.
231 This can also be configured on a per-file basis by adding one of
232 the following lines anywhere in the buffer:
233 #+STARTUP: align
234 #+STARTUP: noalign"
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-insert-mode-line-in-empty-file nil
239 "Non-nil means insert the first line setting Org-mode in empty files.
240 When the function `org-mode' is called interactively in an empty file, this
241 normally means that the file name does not automatically trigger Org-mode.
242 To ensure that the file will always be in Org-mode in the future, a
243 line enforcing Org-mode will be inserted into the buffer, if this option
244 has been set."
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-replace-disputed-keys nil
249 "Non-nil means use alternative key bindings for some keys.
250 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
251 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
252 If you want to use Org-mode together with one of these other modes,
253 or more generally if you would like to move some Org-mode commands to
254 other keys, set this variable and configure the keys with the variable
255 `org-disputed-keys'.
257 This option is only relevant at load-time of Org-mode, and must be set
258 *before* org.el is loaded. Changing it requires a restart of Emacs to
259 become effective."
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-use-extra-keys nil
264 "Non-nil means use extra key sequence definitions for certain
265 commands. This happens automatically if you run XEmacs or if
266 window-system is nil. This variable lets you do the same
267 manually. You must set it before loading org.
269 Example: on Carbon Emacs 22 running graphically, with an external
270 keyboard on a Powerbook, the default way of setting M-left might
271 not work for either Alt or ESC. Setting this variable will make
272 it work for ESC."
273 :group 'org-startup
274 :type 'boolean)
276 (if (fboundp 'defvaralias)
277 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
279 (defcustom org-disputed-keys
280 '(([(shift up)] . [(meta p)])
281 ([(shift down)] . [(meta n)])
282 ([(shift left)] . [(meta -)])
283 ([(shift right)] . [(meta +)])
284 ([(control shift right)] . [(meta shift +)])
285 ([(control shift left)] . [(meta shift -)]))
286 "Keys for which Org-mode and other modes compete.
287 This is an alist, cars are the default keys, second element specifies
288 the alternative to use when `org-replace-disputed-keys' is t.
290 Keys can be specified in any syntax supported by `define-key'.
291 The value of this option takes effect only at Org-mode's startup,
292 therefore you'll have to restart Emacs to apply it after changing."
293 :group 'org-startup
294 :type 'alist)
296 (defun org-key (key)
297 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
298 Or return the original if not disputed."
299 (if org-replace-disputed-keys
300 (let* ((nkey (key-description key))
301 (x (org-find-if (lambda (x)
302 (equal (key-description (car x)) nkey))
303 org-disputed-keys)))
304 (if x (cdr x) key))
305 key))
307 (defun org-find-if (predicate seq)
308 (catch 'exit
309 (while seq
310 (if (funcall predicate (car seq))
311 (throw 'exit (car seq))
312 (pop seq)))))
314 (defun org-defkey (keymap key def)
315 "Define a key, possibly translated, as returned by `org-key'."
316 (define-key keymap (org-key key) def))
318 (defcustom org-ellipsis nil
319 "The ellipsis to use in the Org-mode outline.
320 When nil, just use the standard three dots. When a string, use that instead,
321 When a face, use the standart 3 dots, but with the specified face.
322 The change affects only Org-mode (which will then use its own display table).
323 Changing this requires executing `M-x org-mode' in a buffer to become
324 effective."
325 :group 'org-startup
326 :type '(choice (const :tag "Default" nil)
327 (face :tag "Face" :value org-warning)
328 (string :tag "String" :value "...#")))
330 (defvar org-display-table nil
331 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
333 (defgroup org-keywords nil
334 "Keywords in Org-mode."
335 :tag "Org Keywords"
336 :group 'org)
338 (defcustom org-deadline-string "DEADLINE:"
339 "String to mark deadline entries.
340 A deadline is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-deadline].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-scheduled-string "SCHEDULED:"
348 "String to mark scheduled TODO entries.
349 A schedule is this string, followed by a time stamp. Should be a word,
350 terminated by a colon. You can insert a schedule keyword and
351 a timestamp with \\[org-schedule].
352 Changes become only effective after restarting Emacs."
353 :group 'org-keywords
354 :type 'string)
356 (defcustom org-closed-string "CLOSED:"
357 "String used as the prefix for timestamps logging closing a TODO entry."
358 :group 'org-keywords
359 :type 'string)
361 (defcustom org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item."
363 :group 'org-keywords
364 :type 'string)
366 (defcustom org-comment-string "COMMENT"
367 "Entries starting with this keyword will never be exported.
368 An entry can be toggled between COMMENT and normal with
369 \\[org-toggle-comment].
370 Changes become only effective after restarting Emacs."
371 :group 'org-keywords
372 :type 'string)
374 (defcustom org-quote-string "QUOTE"
375 "Entries starting with this keyword will be exported in fixed-width font.
376 Quoting applies only to the text in the entry following the headline, and does
377 not extend beyond the next headline, even if that is lower level.
378 An entry can be toggled between QUOTE and normal with
379 \\[org-toggle-fixed-width-section]."
380 :group 'org-keywords
381 :type 'string)
383 (defconst org-repeat-re
384 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
385 "Regular expression for specifying repeated events.
386 After a match, group 1 contains the repeat expression.")
388 (defgroup org-structure nil
389 "Options concerning the general structure of Org-mode files."
390 :tag "Org Structure"
391 :group 'org)
393 (defgroup org-reveal-location nil
394 "Options about how to make context of a location visible."
395 :tag "Org Reveal Location"
396 :group 'org-structure)
398 (defconst org-context-choice
399 '(choice
400 (const :tag "Always" t)
401 (const :tag "Never" nil)
402 (repeat :greedy t :tag "Individual contexts"
403 (cons
404 (choice :tag "Context"
405 (const agenda)
406 (const org-goto)
407 (const occur-tree)
408 (const tags-tree)
409 (const link-search)
410 (const mark-goto)
411 (const bookmark-jump)
412 (const isearch)
413 (const default))
414 (boolean))))
415 "Contexts for the reveal options.")
417 (defcustom org-show-hierarchy-above '((default . t))
418 "Non-nil means, show full hierarchy when revealing a location.
419 Org-mode often shows locations in an org-mode file which might have
420 been invisible before. When this is set, the hierarchy of headings
421 above the exposed location is shown.
422 Turning this off for example for sparse trees makes them very compact.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. Valid contexts are
425 agenda when exposing an entry from the agenda
426 org-goto when using the command `org-goto' on key C-c C-j
427 occur-tree when using the command `org-occur' on key C-c /
428 tags-tree when constructing a sparse tree based on tags matches
429 link-search when exposing search matches associated with a link
430 mark-goto when exposing the jump goal of a mark
431 bookmark-jump when exposing a bookmark location
432 isearch when exiting from an incremental search
433 default default for all contexts not set explicitly"
434 :group 'org-reveal-location
435 :type org-context-choice)
437 (defcustom org-show-following-heading '((default . nil))
438 "Non-nil means, show following heading when revealing a location.
439 Org-mode often shows locations in an org-mode file which might have
440 been invisible before. When this is set, the heading following the
441 match is shown.
442 Turning this off for example for sparse trees makes them very compact,
443 but makes it harder to edit the location of the match. In such a case,
444 use the command \\[org-reveal] to show more context.
445 Instead of t, this can also be an alist specifying this option for different
446 contexts. See `org-show-hierarchy-above' for valid contexts."
447 :group 'org-reveal-location
448 :type org-context-choice)
450 (defcustom org-show-siblings '((default . nil) (isearch t))
451 "Non-nil means, show all sibling heading when revealing a location.
452 Org-mode often shows locations in an org-mode file which might have
453 been invisible before. When this is set, the sibling of the current entry
454 heading are all made visible. If `org-show-hierarchy-above' is t,
455 the same happens on each level of the hierarchy above the current entry.
457 By default this is on for the isearch context, off for all other contexts.
458 Turning this off for example for sparse trees makes them very compact,
459 but makes it harder to edit the location of the match. In such a case,
460 use the command \\[org-reveal] to show more context.
461 Instead of t, this can also be an alist specifying this option for different
462 contexts. See `org-show-hierarchy-above' for valid contexts."
463 :group 'org-reveal-location
464 :type org-context-choice)
466 (defcustom org-show-entry-below '((default . nil))
467 "Non-nil means, show the entry below a headline when revealing a location.
468 Org-mode often shows locations in an org-mode file which might have
469 been invisible before. When this is set, the text below the headline that is
470 exposed is also shown.
472 By default this is off for all contexts.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
478 (defcustom org-indirect-buffer-display 'other-window
479 "How should indirect tree buffers be displayed?
480 This applies to indirect buffers created with the commands
481 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
482 Valid values are:
483 current-window Display in the current window
484 other-window Just display in another window.
485 dedicated-frame Create one new frame, and re-use it each time.
486 new-frame Make a new frame each time. Note that in this case
487 previously-made indirect buffers are kept, and you need to
488 kill these buffers yourself."
489 :group 'org-structure
490 :group 'org-agenda-windows
491 :type '(choice
492 (const :tag "In current window" current-window)
493 (const :tag "In current frame, other window" other-window)
494 (const :tag "Each time a new frame" new-frame)
495 (const :tag "One dedicated frame" dedicated-frame)))
497 (defgroup org-cycle nil
498 "Options concerning visibility cycling in Org-mode."
499 :tag "Org Cycle"
500 :group 'org-structure)
502 (defcustom org-drawers '("PROPERTIES" "CLOCK")
503 "Names of drawers. Drawers are not opened by cycling on the headline above.
504 Drawers only open with a TAB on the drawer line itself. A drawer looks like
505 this:
506 :DRAWERNAME:
507 .....
508 :END:
509 The drawer \"PROPERTIES\" is special for capturing properties through
510 the property API.
512 Drawers can be defined on the per-file basis with a line like:
514 #+DRAWERS: HIDDEN STATE PROPERTIES"
515 :group 'org-structure
516 :type '(repeat (string :tag "Drawer Name")))
518 (defcustom org-cycle-global-at-bob nil
519 "Cycle globally if cursor is at beginning of buffer and not at a headline.
520 This makes it possible to do global cycling without having to use S-TAB or
521 C-u TAB. For this special case to work, the first line of the buffer
522 must not be a headline - it may be empty ot some other text. When used in
523 this way, `org-cycle-hook' is disables temporarily, to make sure the
524 cursor stays at the beginning of the buffer.
525 When this option is nil, don't do anything special at the beginning
526 of the buffer."
527 :group 'org-cycle
528 :type 'boolean)
530 (defcustom org-cycle-emulate-tab t
531 "Where should `org-cycle' emulate TAB.
532 nil Never
533 white Only in completely white lines
534 whitestart Only at the beginning of lines, before the first non-white char
535 t Everywhere except in headlines
536 exc-hl-bol Everywhere except at the start of a headline
537 If TAB is used in a place where it does not emulate TAB, the current subtree
538 visibility is cycled."
539 :group 'org-cycle
540 :type '(choice (const :tag "Never" nil)
541 (const :tag "Only in completely white lines" white)
542 (const :tag "Before first char in a line" whitestart)
543 (const :tag "Everywhere except in headlines" t)
544 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
547 (defcustom org-cycle-separator-lines 2
548 "Number of empty lines needed to keep an empty line between collapsed trees.
549 If you leave an empty line between the end of a subtree and the following
550 headline, this empty line is hidden when the subtree is folded.
551 Org-mode will leave (exactly) one empty line visible if the number of
552 empty lines is equal or larger to the number given in this variable.
553 So the default 2 means, at least 2 empty lines after the end of a subtree
554 are needed to produce free space between a collapsed subtree and the
555 following headline.
557 Special case: when 0, never leave empty lines in collapsed view."
558 :group 'org-cycle
559 :type 'integer)
560 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
562 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
563 org-cycle-hide-drawers
564 org-cycle-show-empty-lines
565 org-optimize-window-after-visibility-change)
566 "Hook that is run after `org-cycle' has changed the buffer visibility.
567 The function(s) in this hook must accept a single argument which indicates
568 the new state that was set by the most recent `org-cycle' command. The
569 argument is a symbol. After a global state change, it can have the values
570 `overview', `content', or `all'. After a local state change, it can have
571 the values `folded', `children', or `subtree'."
572 :group 'org-cycle
573 :type 'hook)
575 (defgroup org-edit-structure nil
576 "Options concerning structure editing in Org-mode."
577 :tag "Org Edit Structure"
578 :group 'org-structure)
580 (defcustom org-odd-levels-only nil
581 "Non-nil means, skip even levels and only use odd levels for the outline.
582 This has the effect that two stars are being added/taken away in
583 promotion/demotion commands. It also influences how levels are
584 handled by the exporters.
585 Changing it requires restart of `font-lock-mode' to become effective
586 for fontification also in regions already fontified.
587 You may also set this on a per-file basis by adding one of the following
588 lines to the buffer:
590 #+STARTUP: odd
591 #+STARTUP: oddeven"
592 :group 'org-edit-structure
593 :group 'org-font-lock
594 :type 'boolean)
596 (defcustom org-adapt-indentation t
597 "Non-nil means, adapt indentation when promoting and demoting.
598 When this is set and the *entire* text in an entry is indented, the
599 indentation is increased by one space in a demotion command, and
600 decreased by one in a promotion command. If any line in the entry
601 body starts at column 0, indentation is not changed at all."
602 :group 'org-edit-structure
603 :type 'boolean)
605 (defcustom org-special-ctrl-a/e nil
606 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
607 When t, `C-a' will bring back the cursor to the beginning of the
608 headline text, i.e. after the stars and after a possible TODO keyword.
609 In an item, this will be the position after the bullet.
610 When the cursor is already at that position, another `C-a' will bring
611 it to the beginning of the line.
612 `C-e' will jump to the end of the headline, ignoring the presence of tags
613 in the headline. A second `C-e' will then jump to the true end of the
614 line, after any tags.
615 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
616 and only a directly following, identical keypress will bring the cursor
617 to the special positions."
618 :group 'org-edit-structure
619 :type '(choice
620 (const :tag "off" nil)
621 (const :tag "after bullet first" t)
622 (const :tag "border first" reversed)))
624 (if (fboundp 'defvaralias)
625 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
627 (defcustom org-special-ctrl-k nil
628 "Non-nil means `C-k' will behave specially in headlines.
629 When nil, `C-k' will call the default `kill-line' command.
630 When t, the following will happen while the cursor is in the headline:
632 - When the cursor is at the beginning of a headline, kill the entire
633 line and possible the folded subtree below the line.
634 - When in the middle of the headline text, kill the headline up to the tags.
635 - When after the headline text, kill the tags."
636 :group 'org-edit-structure
637 :type 'boolean)
639 (defcustom org-yank-folded-subtrees t
640 "Non-nil means, when yanking subtrees, fold them.
641 If the kill is a single subtree, or a sequence of subtrees, i.e. if
642 it starts with a heading and all other headings in it are either children
643 or siblings, then fold all the subtrees. However, do this only if no
644 text after the yank would be swallowed into a folded tree by this action."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defcustom org-yank-adjusted-subtrees t
649 "Non-nil means, when yanking subtrees, adjust the level.
650 With this setting, `org-paste-subtree' is used to insert the subtree, see
651 this function for details."
652 :group 'org-edit-structure
653 :type 'boolean)
655 (defcustom org-M-RET-may-split-line '((default . t))
656 "Non-nil means, M-RET will split the line at the cursor position.
657 When nil, it will go to the end of the line before making a
658 new line.
659 You may also set this option in a different way for different
660 contexts. Valid contexts are:
662 headline when creating a new headline
663 item when creating a new item
664 table in a table field
665 default the value to be used for all contexts not explicitly
666 customized"
667 :group 'org-structure
668 :group 'org-table
669 :type '(choice
670 (const :tag "Always" t)
671 (const :tag "Never" nil)
672 (repeat :greedy t :tag "Individual contexts"
673 (cons
674 (choice :tag "Context"
675 (const headline)
676 (const item)
677 (const table)
678 (const default))
679 (boolean)))))
682 (defcustom org-insert-heading-respect-content nil
683 "Non-nil means, insert new headings after the current subtree.
684 When nil, the new heading is created directly after the current line.
685 The commands \\[org-insert-heading-respect-content] and
686 \\[org-insert-todo-heading-respect-content] turn this variable on
687 for the duration of the command."
688 :group 'org-structure
689 :type 'boolean)
691 (defcustom org-blank-before-new-entry '((heading . nil)
692 (plain-list-item . nil))
693 "Should `org-insert-heading' leave a blank line before new heading/item?
694 The value is an alist, with `heading' and `plain-list-item' as car,
695 and a boolean flag as cdr."
696 :group 'org-edit-structure
697 :type '(list
698 (cons (const heading) (boolean))
699 (cons (const plain-list-item) (boolean))))
701 (defcustom org-insert-heading-hook nil
702 "Hook being run after inserting a new heading."
703 :group 'org-edit-structure
704 :type 'hook)
706 (defcustom org-enable-fixed-width-editor t
707 "Non-nil means, lines starting with \":\" are treated as fixed-width.
708 This currently only means, they are never auto-wrapped.
709 When nil, such lines will be treated like ordinary lines.
710 See also the QUOTE keyword."
711 :group 'org-edit-structure
712 :type 'boolean)
714 (defcustom org-edit-src-region-extra nil
715 "Additional regexps to identify regions for editing with `org-edit-src-code'.
716 For examples see the function `org-edit-src-find-region-and-lang'.
717 The regular expression identifying the begin marker should end with a newline,
718 and the regexp marking the end line should start with a newline, to make sure
719 there are kept outside the narrowed region."
720 :group 'org-edit-structure
721 :type '(repeat
722 (list
723 (regexp :tag "begin regexp")
724 (regexp :tag "end regexp")
725 (choice :tag "language"
726 (string :tag "specify")
727 (integer :tag "from match group")
728 (const :tag "from `lang' element")
729 (const :tag "from `style' element")))))
731 (defcustom org-edit-fixed-width-region-mode 'artist-mode
732 "The mode that should be used to edit fixed-width regions.
733 These are the regions where each line starts with a colon."
734 :group 'org-edit-structure
735 :type '(choice
736 (const artist-mode)
737 (const picture-mode)
738 (const fundamental-mode)
739 (function :tag "Other (specify)")))
741 (defcustom org-goto-auto-isearch t
742 "Non-nil means, typing characters in org-goto starts incremental search."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defgroup org-sparse-trees nil
747 "Options concerning sparse trees in Org-mode."
748 :tag "Org Sparse Trees"
749 :group 'org-structure)
751 (defcustom org-highlight-sparse-tree-matches t
752 "Non-nil means, highlight all matches that define a sparse tree.
753 The highlights will automatically disappear the next time the buffer is
754 changed by an edit command."
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-remove-highlights-with-change t
759 "Non-nil means, any change to the buffer will remove temporary highlights.
760 Such highlights are created by `org-occur' and `org-clock-display'.
761 When nil, `C-c C-c needs to be used to get rid of the highlights.
762 The highlights created by `org-preview-latex-fragment' always need
763 `C-c C-c' to be removed."
764 :group 'org-sparse-trees
765 :group 'org-time
766 :type 'boolean)
769 (defcustom org-occur-hook '(org-first-headline-recenter)
770 "Hook that is run after `org-occur' has constructed a sparse tree.
771 This can be used to recenter the window to show as much of the structure
772 as possible."
773 :group 'org-sparse-trees
774 :type 'hook)
776 (defgroup org-imenu-and-speedbar nil
777 "Options concerning imenu and speedbar in Org-mode."
778 :tag "Org Imenu and Speedbar"
779 :group 'org-structure)
781 (defcustom org-imenu-depth 2
782 "The maximum level for Imenu access to Org-mode headlines.
783 This also applied for speedbar access."
784 :group 'org-imenu-and-speedbar
785 :type 'number)
787 (defgroup org-table nil
788 "Options concerning tables in Org-mode."
789 :tag "Org Table"
790 :group 'org)
792 (defcustom org-enable-table-editor 'optimized
793 "Non-nil means, lines starting with \"|\" are handled by the table editor.
794 When nil, such lines will be treated like ordinary lines.
796 When equal to the symbol `optimized', the table editor will be optimized to
797 do the following:
798 - Automatic overwrite mode in front of whitespace in table fields.
799 This makes the structure of the table stay in tact as long as the edited
800 field does not exceed the column width.
801 - Minimize the number of realigns. Normally, the table is aligned each time
802 TAB or RET are pressed to move to another field. With optimization this
803 happens only if changes to a field might have changed the column width.
804 Optimization requires replacing the functions `self-insert-command',
805 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
806 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
807 very good at guessing when a re-align will be necessary, but you can always
808 force one with \\[org-ctrl-c-ctrl-c].
810 If you would like to use the optimized version in Org-mode, but the
811 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
813 This variable can be used to turn on and off the table editor during a session,
814 but in order to toggle optimization, a restart is required.
816 See also the variable `org-table-auto-blank-field'."
817 :group 'org-table
818 :type '(choice
819 (const :tag "off" nil)
820 (const :tag "on" t)
821 (const :tag "on, optimized" optimized)))
823 (defcustom org-table-tab-recognizes-table.el t
824 "Non-nil means, TAB will automatically notice a table.el table.
825 When it sees such a table, it moves point into it and - if necessary -
826 calls `table-recognize-table'."
827 :group 'org-table-editing
828 :type 'boolean)
830 (defgroup org-link nil
831 "Options concerning links in Org-mode."
832 :tag "Org Link"
833 :group 'org)
835 (defvar org-link-abbrev-alist-local nil
836 "Buffer-local version of `org-link-abbrev-alist', which see.
837 The value of this is taken from the #+LINK lines.")
838 (make-variable-buffer-local 'org-link-abbrev-alist-local)
840 (defcustom org-link-abbrev-alist nil
841 "Alist of link abbreviations.
842 The car of each element is a string, to be replaced at the start of a link.
843 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
844 links in Org-mode buffers can have an optional tag after a double colon, e.g.
846 [[linkkey:tag][description]]
848 If REPLACE is a string, the tag will simply be appended to create the link.
849 If the string contains \"%s\", the tag will be inserted there. Alternatively,
850 the placeholder \"%h\" will cause a url-encoded version of the tag to
851 be inserted at that point (see the function `url-hexify-string').
853 REPLACE may also be a function that will be called with the tag as the
854 only argument to create the link, which should be returned as a string.
856 See the manual for examples."
857 :group 'org-link
858 :type '(repeat
859 (cons
860 (string :tag "Protocol")
861 (choice
862 (string :tag "Format")
863 (function)))))
865 (defcustom org-descriptive-links t
866 "Non-nil means, hide link part and only show description of bracket links.
867 Bracket links are like [[link][descritpion]]. This variable sets the initial
868 state in new org-mode buffers. The setting can then be toggled on a
869 per-buffer basis from the Org->Hyperlinks menu."
870 :group 'org-link
871 :type 'boolean)
873 (defcustom org-link-file-path-type 'adaptive
874 "How the path name in file links should be stored.
875 Valid values are:
877 relative Relative to the current directory, i.e. the directory of the file
878 into which the link is being inserted.
879 absolute Absolute path, if possible with ~ for home directory.
880 noabbrev Absolute path, no abbreviation of home directory.
881 adaptive Use relative path for files in the current directory and sub-
882 directories of it. For other files, use an absolute path."
883 :group 'org-link
884 :type '(choice
885 (const relative)
886 (const absolute)
887 (const noabbrev)
888 (const adaptive)))
890 (defcustom org-activate-links '(bracket angle plain radio tag date)
891 "Types of links that should be activated in Org-mode files.
892 This is a list of symbols, each leading to the activation of a certain link
893 type. In principle, it does not hurt to turn on most link types - there may
894 be a small gain when turning off unused link types. The types are:
896 bracket The recommended [[link][description]] or [[link]] links with hiding.
897 angular Links in angular brackes that may contain whitespace like
898 <bbdb:Carsten Dominik>.
899 plain Plain links in normal text, no whitespace, like http://google.com.
900 radio Text that is matched by a radio target, see manual for details.
901 tag Tag settings in a headline (link to tag search).
902 date Time stamps (link to calendar).
904 Changing this variable requires a restart of Emacs to become effective."
905 :group 'org-link
906 :type '(set (const :tag "Double bracket links (new style)" bracket)
907 (const :tag "Angular bracket links (old style)" angular)
908 (const :tag "Plain text links" plain)
909 (const :tag "Radio target matches" radio)
910 (const :tag "Tags" tag)
911 (const :tag "Timestamps" date)))
913 (defcustom org-make-link-description-function nil
914 "Function to use to generate link descriptions from links. If
915 nil the link location will be used. This function must take two
916 parameters; the first is the link and the second the description
917 org-insert-link has generated, and should return the description
918 to use."
919 :group 'org-link
920 :type 'function)
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode."
924 :tag "Org Store Link"
925 :group 'org-link)
927 (defcustom org-email-link-description-format "Email %c: %.30s"
928 "Format of the description part of a link to an email or usenet message.
929 The following %-excapes will be replaced by corresponding information:
931 %F full \"From\" field
932 %f name, taken from \"From\" field, address if no name
933 %T full \"To\" field
934 %t first name in \"To\" field, address if no name
935 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
936 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
937 %s subject
938 %m message-id.
940 You may use normal field width specification between the % and the letter.
941 This is for example useful to limit the length of the subject.
943 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944 :group 'org-link-store
945 :type 'string)
947 (defcustom org-from-is-user-regexp
948 (let (r1 r2)
949 (when (and user-mail-address (not (string= user-mail-address "")))
950 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951 (when (and user-full-name (not (string= user-full-name "")))
952 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954 "Regexp mached against the \"From:\" header of an email or usenet message.
955 It should match if the message is from the user him/herself."
956 :group 'org-link-store
957 :type 'regexp)
959 (defcustom org-link-to-org-use-id 'create-if-interactive
960 "Non-nil means, storing a link to an Org file will use entry IDs.
962 Note that before this variable is even considered, org-id must be loaded,
963 to please customize `org-modules' and turn it on.
965 The variable can have the following values:
967 t Create an ID if needed to make a link to the current entry.
969 create-if-interactive
970 If `org-store-link' is called directly (interactively, as a user
971 command), do create an ID to support the link. But when doing the
972 job for remember, only use the ID if it already exists. The
973 purpose of this setting is to avoid proliferation of unwanted
974 IDs, just because you happen to be in an Org file when you
975 call `org-remember' that automatically and preemptively
976 creates a link. If you do want to get an ID link in a remember
977 template to an entry not having an ID, create it first by
978 explicitly creating a link to it, using `C-c C-l' first.
980 use-existing
981 Use existing ID, do not create one.
983 nil Never use an ID to make a link, instead link using a text search for
984 the headline text."
985 :group 'org-link-store
986 :type '(choice
987 (const :tag "Create ID to make link" t)
988 (const :tag "Create if string link interactively"
989 'create-if-interactive)
990 (const :tag "Only use existing" 'use-existing)
991 (const :tag "Do not use ID to create link" nil)))
993 (defcustom org-context-in-file-links t
994 "Non-nil means, file links from `org-store-link' contain context.
995 A search string will be added to the file name with :: as separator and
996 used to find the context when the link is activated by the command
997 `org-open-at-point'.
998 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
999 negates this setting for the duration of the command."
1000 :group 'org-link-store
1001 :type 'boolean)
1003 (defcustom org-keep-stored-link-after-insertion nil
1004 "Non-nil means, keep link in list for entire session.
1006 The command `org-store-link' adds a link pointing to the current
1007 location to an internal list. These links accumulate during a session.
1008 The command `org-insert-link' can be used to insert links into any
1009 Org-mode file (offering completion for all stored links). When this
1010 option is nil, every link which has been inserted once using \\[org-insert-link]
1011 will be removed from the list, to make completing the unused links
1012 more efficient."
1013 :group 'org-link-store
1014 :type 'boolean)
1016 (defgroup org-link-follow nil
1017 "Options concerning following links in Org-mode."
1018 :tag "Org Follow Link"
1019 :group 'org-link)
1021 (defcustom org-link-translation-function nil
1022 "Function to translate links with different syntax to Org syntax.
1023 This can be used to translate links created for example by the Planner
1024 or emacs-wiki packages to Org syntax.
1025 The function must accept two parameters, a TYPE containing the link
1026 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1027 which is everything after the link protocol. It should return a cons
1028 with possibly modifed values of type and path.
1029 Org contains a function for this, so if you set this variable to
1030 `org-translate-link-from-planner', you should be able follow many
1031 links created by planner."
1032 :group 'org-link-follow
1033 :type 'function)
1035 (defcustom org-follow-link-hook nil
1036 "Hook that is run after a link has been followed."
1037 :group 'org-link-follow
1038 :type 'hook)
1040 (defcustom org-tab-follows-link nil
1041 "Non-nil means, on links TAB will follow the link.
1042 Needs to be set before org.el is loaded."
1043 :group 'org-link-follow
1044 :type 'boolean)
1046 (defcustom org-return-follows-link nil
1047 "Non-nil means, on links RET will follow the link.
1048 Needs to be set before org.el is loaded."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-mouse-1-follows-link
1053 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1054 "Non-nil means, mouse-1 on a link will follow the link.
1055 A longer mouse click will still set point. Does not work on XEmacs.
1056 Needs to be set before org.el is loaded."
1057 :group 'org-link-follow
1058 :type 'boolean)
1060 (defcustom org-mark-ring-length 4
1061 "Number of different positions to be recorded in the ring
1062 Changing this requires a restart of Emacs to work correctly."
1063 :group 'org-link-follow
1064 :type 'interger)
1066 (defcustom org-link-frame-setup
1067 '((vm . vm-visit-folder-other-frame)
1068 (gnus . gnus-other-frame)
1069 (file . find-file-other-window))
1070 "Setup the frame configuration for following links.
1071 When following a link with Emacs, it may often be useful to display
1072 this link in another window or frame. This variable can be used to
1073 set this up for the different types of links.
1074 For VM, use any of
1075 `vm-visit-folder'
1076 `vm-visit-folder-other-frame'
1077 For Gnus, use any of
1078 `gnus'
1079 `gnus-other-frame'
1080 `org-gnus-no-new-news'
1081 For FILE, use any of
1082 `find-file'
1083 `find-file-other-window'
1084 `find-file-other-frame'
1085 For the calendar, use the variable `calendar-setup'.
1086 For BBDB, it is currently only possible to display the matches in
1087 another window."
1088 :group 'org-link-follow
1089 :type '(list
1090 (cons (const vm)
1091 (choice
1092 (const vm-visit-folder)
1093 (const vm-visit-folder-other-window)
1094 (const vm-visit-folder-other-frame)))
1095 (cons (const gnus)
1096 (choice
1097 (const gnus)
1098 (const gnus-other-frame)
1099 (const org-gnus-no-new-news)))
1100 (cons (const file)
1101 (choice
1102 (const find-file)
1103 (const find-file-other-window)
1104 (const find-file-other-frame)))))
1106 (defcustom org-display-internal-link-with-indirect-buffer nil
1107 "Non-nil means, use indirect buffer to display infile links.
1108 Activating internal links (from one location in a file to another location
1109 in the same file) normally just jumps to the location. When the link is
1110 activated with a C-u prefix (or with mouse-3), the link is displayed in
1111 another window. When this option is set, the other window actually displays
1112 an indirect buffer clone of the current buffer, to avoid any visibility
1113 changes to the current buffer."
1114 :group 'org-link-follow
1115 :type 'boolean)
1117 (defcustom org-open-non-existing-files nil
1118 "Non-nil means, `org-open-file' will open non-existing files.
1119 When nil, an error will be generated."
1120 :group 'org-link-follow
1121 :type 'boolean)
1123 (defcustom org-open-directory-means-index-dot-org nil
1124 "Non-nil means, a link to a directory really means to index.org.
1125 When nil, following a directory link will run dired or open a finder/explorer
1126 window on that directory."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1131 "Function and arguments to call for following mailto links.
1132 This is a list with the first element being a lisp function, and the
1133 remaining elements being arguments to the function. In string arguments,
1134 %a will be replaced by the address, and %s will be replaced by the subject
1135 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1136 :group 'org-link-follow
1137 :type '(choice
1138 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1139 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1140 (const :tag "message-mail" (message-mail "%a" "%s"))
1141 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1143 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1144 "Non-nil means, ask for confirmation before executing shell links.
1145 Shell links can be dangerous: just think about a link
1147 [[shell:rm -rf ~/*][Google Search]]
1149 This link would show up in your Org-mode document as \"Google Search\",
1150 but really it would remove your entire home directory.
1151 Therefore we advise against setting this variable to nil.
1152 Just change it to `y-or-n-p' of you want to confirm with a
1153 single keystroke rather than having to type \"yes\"."
1154 :group 'org-link-follow
1155 :type '(choice
1156 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1157 (const :tag "with y-or-n (faster)" y-or-n-p)
1158 (const :tag "no confirmation (dangerous)" nil)))
1160 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1161 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1162 Elisp links can be dangerous: just think about a link
1164 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1166 This link would show up in your Org-mode document as \"Google Search\",
1167 but really it would remove your entire home directory.
1168 Therefore we advise against setting this variable to nil.
1169 Just change it to `y-or-n-p' of you want to confirm with a
1170 single keystroke rather than having to type \"yes\"."
1171 :group 'org-link-follow
1172 :type '(choice
1173 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1174 (const :tag "with y-or-n (faster)" y-or-n-p)
1175 (const :tag "no confirmation (dangerous)" nil)))
1177 (defconst org-file-apps-defaults-gnu
1178 '((remote . emacs)
1179 (system . mailcap)
1180 (t . mailcap))
1181 "Default file applications on a UNIX or GNU/Linux system.
1182 See `org-file-apps'.")
1184 (defconst org-file-apps-defaults-macosx
1185 '((remote . emacs)
1186 (t . "open %s")
1187 (system . "open %s")
1188 ("ps.gz" . "gv %s")
1189 ("eps.gz" . "gv %s")
1190 ("dvi" . "xdvi %s")
1191 ("fig" . "xfig %s"))
1192 "Default file applications on a MacOS X system.
1193 The system \"open\" is known as a default, but we use X11 applications
1194 for some files for which the OS does not have a good default.
1195 See `org-file-apps'.")
1197 (defconst org-file-apps-defaults-windowsnt
1198 (list
1199 '(remote . emacs)
1200 (cons t
1201 (list (if (featurep 'xemacs)
1202 'mswindows-shell-execute
1203 'w32-shell-execute)
1204 "open" 'file))
1205 (cons 'system
1206 (list (if (featurep 'xemacs)
1207 'mswindows-shell-execute
1208 'w32-shell-execute)
1209 "open" 'file)))
1210 "Default file applications on a Windows NT system.
1211 The system \"open\" is used for most files.
1212 See `org-file-apps'.")
1214 (defcustom org-file-apps
1216 (auto-mode . emacs)
1217 ("\\.x?html?\\'" . default)
1218 ("\\.pdf\\'" . default)
1220 "External applications for opening `file:path' items in a document.
1221 Org-mode uses system defaults for different file types, but
1222 you can use this variable to set the application for a given file
1223 extension. The entries in this list are cons cells where the car identifies
1224 files and the cdr the corresponding command. Possible values for the
1225 file identifier are
1226 \"regex\" Regular expression matched against the file name. For backward
1227 compatibility, this can also be a string with only alphanumeric
1228 characters, which is then interpreted as an extension.
1229 `directory' Matches a directory
1230 `remote' Matches a remote file, accessible through tramp or efs.
1231 Remote files most likely should be visited through Emacs
1232 because external applications cannot handle such paths.
1233 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1234 so all files Emacs knows how to handle. Using this with
1235 command `emacs' will open most files in Emacs. Beware that this
1236 will also open html files insite Emacs, unless you add
1237 (\"html\" . default) to the list as well.
1238 t Default for files not matched by any of the other options.
1239 `system' The system command to open files, like `open' on Windows
1240 and Mac OS X, and mailcap under GNU/Linux. This is the command
1241 that will be selected if you call `C-c C-o' with a double
1242 `C-u C-u' prefix.
1244 Possible values for the command are:
1245 `emacs' The file will be visited by the current Emacs process.
1246 `default' Use the default application for this file type, which is the
1247 association for t in the list, most likely in the system-specific
1248 part.
1249 This can be used to overrule an unwanted seting in the
1250 system-specific variable.
1251 `system' Use the system command for opening files, like \"open\".
1252 This command is specified by the entry whose car is `system'.
1253 Most likely, the system-specific version of this variable
1254 does define this command, but you can overrule/replace it
1255 here.
1256 string A command to be executed by a shell; %s will be replaced
1257 by the path to the file.
1258 sexp A Lisp form which will be evaluated. The file path will
1259 be available in the Lisp variable `file'.
1260 For more examples, see the system specific constants
1261 `org-file-apps-defaults-macosx'
1262 `org-file-apps-defaults-windowsnt'
1263 `org-file-apps-defaults-gnu'."
1264 :group 'org-link-follow
1265 :type '(repeat
1266 (cons (choice :value ""
1267 (string :tag "Extension")
1268 (const :tag "System command to open files" system)
1269 (const :tag "Default for unrecognized files" t)
1270 (const :tag "Remote file" remote)
1271 (const :tag "Links to a directory" directory)
1272 (const :tag "Any files that have Emacs modes"
1273 auto-mode))
1274 (choice :value ""
1275 (const :tag "Visit with Emacs" emacs)
1276 (const :tag "Use default" default)
1277 (const :tag "Use the system command" system)
1278 (string :tag "Command")
1279 (sexp :tag "Lisp form")))))
1281 (defgroup org-refile nil
1282 "Options concerning refiling entries in Org-mode."
1283 :tag "Org Refile"
1284 :group 'org)
1286 (defcustom org-directory "~/org"
1287 "Directory with org files.
1288 This directory will be used as default to prompt for org files.
1289 Used by the hooks for remember.el."
1290 :group 'org-refile
1291 :group 'org-remember
1292 :type 'directory)
1294 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1295 "Default target for storing notes.
1296 Used by the hooks for remember.el. This can be a string, or nil to mean
1297 the value of `remember-data-file'.
1298 You can set this on a per-template basis with the variable
1299 `org-remember-templates'."
1300 :group 'org-refile
1301 :group 'org-remember
1302 :type '(choice
1303 (const :tag "Default from remember-data-file" nil)
1304 file))
1306 (defcustom org-goto-interface 'outline
1307 "The default interface to be used for `org-goto'.
1308 Allowed vaues are:
1309 outline The interface shows an outline of the relevant file
1310 and the correct heading is found by moving through
1311 the outline or by searching with incremental search.
1312 outline-path-completion Headlines in the current buffer are offered via
1313 completion. This is the interface also used by
1314 the refile command."
1315 :group 'org-refile
1316 :type '(choice
1317 (const :tag "Outline" outline)
1318 (const :tag "Outline-path-completion" outline-path-completion)))
1320 (defcustom org-goto-max-level 5
1321 "Maximum level to be considered when running org-goto with refile interface."
1322 :group 'org-refile
1323 :type 'number)
1325 (defcustom org-reverse-note-order nil
1326 "Non-nil means, store new notes at the beginning of a file or entry.
1327 When nil, new notes will be filed to the end of a file or entry.
1328 This can also be a list with cons cells of regular expressions that
1329 are matched against file names, and values."
1330 :group 'org-remember
1331 :group 'org-refile
1332 :type '(choice
1333 (const :tag "Reverse always" t)
1334 (const :tag "Reverse never" nil)
1335 (repeat :tag "By file name regexp"
1336 (cons regexp boolean))))
1338 (defcustom org-refile-targets nil
1339 "Targets for refiling entries with \\[org-refile].
1340 This is list of cons cells. Each cell contains:
1341 - a specification of the files to be considered, either a list of files,
1342 or a symbol whose function or variable value will be used to retrieve
1343 a file name or a list of file names. Nil means, refile to a different
1344 heading in the current buffer.
1345 - A specification of how to find candidate refile targets. This may be
1346 any of
1347 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1348 This tag has to be present in all target headlines, inheritance will
1349 not be considered.
1350 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1351 todo keyword.
1352 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1353 headlines that are refiling targets.
1354 - a cons cell (:level . N). Any headline of level N is considered a target.
1355 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1357 When this variable is nil, all top-level headlines in the current buffer
1358 are used, equivalent to the value `((nil . (:level . 1))'."
1359 :group 'org-refile
1360 :type '(repeat
1361 (cons
1362 (choice :value org-agenda-files
1363 (const :tag "All agenda files" org-agenda-files)
1364 (const :tag "Current buffer" nil)
1365 (function) (variable) (file))
1366 (choice :tag "Identify target headline by"
1367 (cons :tag "Specific tag" (const :value :tag) (string))
1368 (cons :tag "TODO keyword" (const :value :todo) (string))
1369 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1370 (cons :tag "Level number" (const :value :level) (integer))
1371 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1373 (defcustom org-refile-use-outline-path nil
1374 "Non-nil means, provide refile targets as paths.
1375 So a level 3 headline will be available as level1/level2/level3.
1376 When the value is `file', also include the file name (without directory)
1377 into the path. When `full-file-path', include the full file path."
1378 :group 'org-refile
1379 :type '(choice
1380 (const :tag "Not" nil)
1381 (const :tag "Yes" t)
1382 (const :tag "Start with file name" file)
1383 (const :tag "Start with full file path" full-file-path)))
1385 (defcustom org-outline-path-complete-in-steps t
1386 "Non-nil means, complete the outline path in hierarchical steps.
1387 When Org-mode uses the refile interface to select an outline path
1388 \(see variable `org-refile-use-outline-path'), the completion of
1389 the path can be done is a single go, or if can be done in steps down
1390 the headline hierarchy. Going in steps is probably the best if you
1391 do not use a special completion package like `ido' or `icicles'.
1392 However, when using these packages, going in one step can be very
1393 fast, while still showing the whole path to the entry."
1394 :group 'org-refile
1395 :type 'boolean)
1397 (defgroup org-todo nil
1398 "Options concerning TODO items in Org-mode."
1399 :tag "Org TODO"
1400 :group 'org)
1402 (defgroup org-progress nil
1403 "Options concerning Progress logging in Org-mode."
1404 :tag "Org Progress"
1405 :group 'org-time)
1407 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1408 "List of TODO entry keyword sequences and their interpretation.
1409 \\<org-mode-map>This is a list of sequences.
1411 Each sequence starts with a symbol, either `sequence' or `type',
1412 indicating if the keywords should be interpreted as a sequence of
1413 action steps, or as different types of TODO items. The first
1414 keywords are states requiring action - these states will select a headline
1415 for inclusion into the global TODO list Org-mode produces. If one of
1416 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1417 signify that no further action is necessary. If \"|\" is not found,
1418 the last keyword is treated as the only DONE state of the sequence.
1420 The command \\[org-todo] cycles an entry through these states, and one
1421 additional state where no keyword is present. For details about this
1422 cycling, see the manual.
1424 TODO keywords and interpretation can also be set on a per-file basis with
1425 the special #+SEQ_TODO and #+TYP_TODO lines.
1427 Each keyword can optionally specify a character for fast state selection
1428 \(in combination with the variable `org-use-fast-todo-selection')
1429 and specifiers for state change logging, using the same syntax
1430 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1431 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1432 indicates to record a time stamp each time this state is selected.
1434 Each keyword may also specify if a timestamp or a note should be
1435 recorded when entering or leaving the state, by adding additional
1436 characters in the parenthesis after the keyword. This looks like this:
1437 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1438 record only the time of the state change. With X and Y being either
1439 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1440 Y when leaving the state if and only if the *target* state does not
1441 define X. You may omit any of the fast-selection key or X or /Y,
1442 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1444 For backward compatibility, this variable may also be just a list
1445 of keywords - in this case the interptetation (sequence or type) will be
1446 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1447 :group 'org-todo
1448 :group 'org-keywords
1449 :type '(choice
1450 (repeat :tag "Old syntax, just keywords"
1451 (string :tag "Keyword"))
1452 (repeat :tag "New syntax"
1453 (cons
1454 (choice
1455 :tag "Interpretation"
1456 (const :tag "Sequence (cycling hits every state)" sequence)
1457 (const :tag "Type (cycling directly to DONE)" type))
1458 (repeat
1459 (string :tag "Keyword"))))))
1461 (defvar org-todo-keywords-1 nil
1462 "All TODO and DONE keywords active in a buffer.")
1463 (make-variable-buffer-local 'org-todo-keywords-1)
1464 (defvar org-todo-keywords-for-agenda nil)
1465 (defvar org-done-keywords-for-agenda nil)
1466 (defvar org-todo-keyword-alist-for-agenda nil)
1467 (defvar org-tag-alist-for-agenda nil)
1468 (defvar org-agenda-contributing-files nil)
1469 (defvar org-not-done-keywords nil)
1470 (make-variable-buffer-local 'org-not-done-keywords)
1471 (defvar org-done-keywords nil)
1472 (make-variable-buffer-local 'org-done-keywords)
1473 (defvar org-todo-heads nil)
1474 (make-variable-buffer-local 'org-todo-heads)
1475 (defvar org-todo-sets nil)
1476 (make-variable-buffer-local 'org-todo-sets)
1477 (defvar org-todo-log-states nil)
1478 (make-variable-buffer-local 'org-todo-log-states)
1479 (defvar org-todo-kwd-alist nil)
1480 (make-variable-buffer-local 'org-todo-kwd-alist)
1481 (defvar org-todo-key-alist nil)
1482 (make-variable-buffer-local 'org-todo-key-alist)
1483 (defvar org-todo-key-trigger nil)
1484 (make-variable-buffer-local 'org-todo-key-trigger)
1486 (defcustom org-todo-interpretation 'sequence
1487 "Controls how TODO keywords are interpreted.
1488 This variable is in principle obsolete and is only used for
1489 backward compatibility, if the interpretation of todo keywords is
1490 not given already in `org-todo-keywords'. See that variable for
1491 more information."
1492 :group 'org-todo
1493 :group 'org-keywords
1494 :type '(choice (const sequence)
1495 (const type)))
1497 (defcustom org-use-fast-todo-selection 'prefix
1498 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1499 This variable describes if and under what circumstances the cycling
1500 mechanism for TODO keywords will be replaced by a single-key, direct
1501 selection scheme.
1503 When nil, fast selection is never used.
1505 When the symbol `prefix', it will be used when `org-todo' is called with
1506 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1507 in an agenda buffer.
1509 When t, fast selection is used by default. In this case, the prefix
1510 argument forces cycling instead.
1512 In all cases, the special interface is only used if access keys have actually
1513 been assigned by the user, i.e. if keywords in the configuration are followed
1514 by a letter in parenthesis, like TODO(t)."
1515 :group 'org-todo
1516 :type '(choice
1517 (const :tag "Never" nil)
1518 (const :tag "By default" t)
1519 (const :tag "Only with C-u C-c C-t" prefix)))
1521 (defcustom org-provide-todo-statistics t
1522 "Non-nil means, update todo statistics after insert and toggle.
1523 When this is set, todo statistics is updated in the parent of the current
1524 entry each time a todo state is changed."
1525 :group 'org-todo
1526 :type 'boolean)
1528 (defcustom org-after-todo-state-change-hook nil
1529 "Hook which is run after the state of a TODO item was changed.
1530 The new state (a string with a TODO keyword, or nil) is available in the
1531 Lisp variable `state'."
1532 :group 'org-todo
1533 :type 'hook)
1535 (defcustom org-todo-state-tags-triggers nil
1536 "Tag changes that should be triggered by TODO state changes.
1537 This is a list. Each entry is
1539 (state-change (tag . flag) .......)
1541 State-change can be a string with a state, and empty string to indicate the
1542 state that has no TODO keyword, or it can be one of the symbols `todo'
1543 or `done', meaning any not-done or done state, respectively."
1544 :group 'org-todo
1545 :group 'org-tags
1546 :type '(repeat
1547 (cons (choice :tag "When changing to"
1548 (const :tag "Not-done state" todo)
1549 (const :tag "Done state" done)
1550 (string :tag "State"))
1551 (repeat
1552 (cons :tag "Tag action"
1553 (string :tag "Tag")
1554 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1556 (defcustom org-log-done nil
1557 "Information to record when a task moves to the DONE state.
1559 Possible values are:
1561 nil Don't add anything, just change the keyword
1562 time Add a time stamp to the task
1563 note Prompt a closing note and add it with template `org-log-note-headings'
1565 This option can also be set with on a per-file-basis with
1567 #+STARTUP: nologdone
1568 #+STARTUP: logdone
1569 #+STARTUP: lognotedone
1571 You can have local logging settings for a subtree by setting the LOGGING
1572 property to one or more of these keywords."
1573 :group 'org-todo
1574 :group 'org-progress
1575 :type '(choice
1576 (const :tag "No logging" nil)
1577 (const :tag "Record CLOSED timestamp" time)
1578 (const :tag "Record CLOSED timestamp with closing note." note)))
1580 ;; Normalize old uses of org-log-done.
1581 (cond
1582 ((eq org-log-done t) (setq org-log-done 'time))
1583 ((and (listp org-log-done) (memq 'done org-log-done))
1584 (setq org-log-done 'note)))
1586 (defcustom org-log-note-clock-out nil
1587 "Non-nil means, record a note when clocking out of an item.
1588 This can also be configured on a per-file basis by adding one of
1589 the following lines anywhere in the buffer:
1591 #+STARTUP: lognoteclock-out
1592 #+STARTUP: nolognoteclock-out"
1593 :group 'org-todo
1594 :group 'org-progress
1595 :type 'boolean)
1597 (defcustom org-log-done-with-time t
1598 "Non-nil means, the CLOSED time stamp will contain date and time.
1599 When nil, only the date will be recorded."
1600 :group 'org-progress
1601 :type 'boolean)
1603 (defcustom org-log-note-headings
1604 '((done . "CLOSING NOTE %t")
1605 (state . "State %-12s %t")
1606 (note . "Note taken on %t")
1607 (clock-out . ""))
1608 "Headings for notes added to entries.
1609 The value is an alist, with the car being a symbol indicating the note
1610 context, and the cdr is the heading to be used. The heading may also be the
1611 empty string.
1612 %t in the heading will be replaced by a time stamp.
1613 %s will be replaced by the new TODO state, in double quotes.
1614 %u will be replaced by the user name.
1615 %U will be replaced by the full user name."
1616 :group 'org-todo
1617 :group 'org-progress
1618 :type '(list :greedy t
1619 (cons (const :tag "Heading when closing an item" done) string)
1620 (cons (const :tag
1621 "Heading when changing todo state (todo sequence only)"
1622 state) string)
1623 (cons (const :tag "Heading when just taking a note" note) string)
1624 (cons (const :tag "Heading when clocking out" clock-out) string)))
1626 (unless (assq 'note org-log-note-headings)
1627 (push '(note . "%t") org-log-note-headings))
1629 (defcustom org-log-state-notes-insert-after-drawers nil
1630 "Non-nil means, insert state change notes after any drawers in entry.
1631 Only the drawers that *immediately* follow the headline and the
1632 deadline/scheduled line are skipped.
1633 When nil, insert notes right after the heading and perhaps the line
1634 with deadline/scheduling if present."
1635 :group 'org-todo
1636 :group 'org-progress
1637 :type 'boolean)
1639 (defcustom org-log-states-order-reversed t
1640 "Non-nil means, the latest state change note will be directly after heading.
1641 When nil, the notes will be orderer according to time."
1642 :group 'org-todo
1643 :group 'org-progress
1644 :type 'boolean)
1646 (defcustom org-log-repeat 'time
1647 "Non-nil means, record moving through the DONE state when triggering repeat.
1648 An auto-repeating tasks is immediately switched back to TODO when marked
1649 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1650 the TODO keyword definition, or recording a closing note by setting
1651 `org-log-done', there will be no record of the task moving through DONE.
1652 This variable forces taking a note anyway. Possible values are:
1654 nil Don't force a record
1655 time Record a time stamp
1656 note Record a note
1658 This option can also be set with on a per-file-basis with
1660 #+STARTUP: logrepeat
1661 #+STARTUP: lognoterepeat
1662 #+STARTUP: nologrepeat
1664 You can have local logging settings for a subtree by setting the LOGGING
1665 property to one or more of these keywords."
1666 :group 'org-todo
1667 :group 'org-progress
1668 :type '(choice
1669 (const :tag "Don't force a record" nil)
1670 (const :tag "Force recording the DONE state" time)
1671 (const :tag "Force recording a note with the DONE state" note)))
1674 (defgroup org-priorities nil
1675 "Priorities in Org-mode."
1676 :tag "Org Priorities"
1677 :group 'org-todo)
1679 (defcustom org-highest-priority ?A
1680 "The highest priority of TODO items. A character like ?A, ?B etc.
1681 Must have a smaller ASCII number than `org-lowest-priority'."
1682 :group 'org-priorities
1683 :type 'character)
1685 (defcustom org-lowest-priority ?C
1686 "The lowest priority of TODO items. A character like ?A, ?B etc.
1687 Must have a larger ASCII number than `org-highest-priority'."
1688 :group 'org-priorities
1689 :type 'character)
1691 (defcustom org-default-priority ?B
1692 "The default priority of TODO items.
1693 This is the priority an item get if no explicit priority is given."
1694 :group 'org-priorities
1695 :type 'character)
1697 (defcustom org-priority-start-cycle-with-default t
1698 "Non-nil means, start with default priority when starting to cycle.
1699 When this is nil, the first step in the cycle will be (depending on the
1700 command used) one higher or lower that the default priority."
1701 :group 'org-priorities
1702 :type 'boolean)
1704 (defgroup org-time nil
1705 "Options concerning time stamps and deadlines in Org-mode."
1706 :tag "Org Time"
1707 :group 'org)
1709 (defcustom org-insert-labeled-timestamps-at-point nil
1710 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1711 When nil, these labeled time stamps are forces into the second line of an
1712 entry, just after the headline. When scheduling from the global TODO list,
1713 the time stamp will always be forced into the second line."
1714 :group 'org-time
1715 :type 'boolean)
1717 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1718 "Formats for `format-time-string' which are used for time stamps.
1719 It is not recommended to change this constant.")
1721 (defcustom org-time-stamp-rounding-minutes '(0 5)
1722 "Number of minutes to round time stamps to.
1723 These are two values, the first applies when first creating a time stamp.
1724 The second applies when changing it with the commands `S-up' and `S-down'.
1725 When changing the time stamp, this means that it will change in steps
1726 of N minutes, as given by the second value.
1728 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1729 numbers should be factors of 60, so for example 5, 10, 15.
1731 When this is larger than 1, you can still force an exact time-stamp by using
1732 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1733 and by using a prefix arg to `S-up/down' to specify the exact number
1734 of minutes to shift."
1735 :group 'org-time
1736 :get '(lambda (var) ; Make sure all entries have 5 elements
1737 (if (integerp (default-value var))
1738 (list (default-value var) 5)
1739 (default-value var)))
1740 :type '(list
1741 (integer :tag "when inserting times")
1742 (integer :tag "when modifying times")))
1744 ;; Normalize old customizations of this variable.
1745 (when (integerp org-time-stamp-rounding-minutes)
1746 (setq org-time-stamp-rounding-minutes
1747 (list org-time-stamp-rounding-minutes
1748 org-time-stamp-rounding-minutes)))
1750 (defcustom org-display-custom-times nil
1751 "Non-nil means, overlay custom formats over all time stamps.
1752 The formats are defined through the variable `org-time-stamp-custom-formats'.
1753 To turn this on on a per-file basis, insert anywhere in the file:
1754 #+STARTUP: customtime"
1755 :group 'org-time
1756 :set 'set-default
1757 :type 'sexp)
1758 (make-variable-buffer-local 'org-display-custom-times)
1760 (defcustom org-time-stamp-custom-formats
1761 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1762 "Custom formats for time stamps. See `format-time-string' for the syntax.
1763 These are overlayed over the default ISO format if the variable
1764 `org-display-custom-times' is set. Time like %H:%M should be at the
1765 end of the second format."
1766 :group 'org-time
1767 :type 'sexp)
1769 (defun org-time-stamp-format (&optional long inactive)
1770 "Get the right format for a time string."
1771 (let ((f (if long (cdr org-time-stamp-formats)
1772 (car org-time-stamp-formats))))
1773 (if inactive
1774 (concat "[" (substring f 1 -1) "]")
1775 f)))
1777 (defcustom org-time-clocksum-format "%d:%02d"
1778 "The format string used when creating CLOCKSUM lines, or when
1779 org-mode generates a time duration."
1780 :group 'org-time
1781 :type 'string)
1783 (defcustom org-deadline-warning-days 14
1784 "No. of days before expiration during which a deadline becomes active.
1785 This variable governs the display in sparse trees and in the agenda.
1786 When 0 or negative, it means use this number (the absolute value of it)
1787 even if a deadline has a different individual lead time specified."
1788 :group 'org-time
1789 :group 'org-agenda-daily/weekly
1790 :type 'number)
1792 (defcustom org-read-date-prefer-future t
1793 "Non-nil means, assume future for incomplete date input from user.
1794 This affects the following situations:
1795 1. The user gives a day, but no month.
1796 For example, if today is the 15th, and you enter \"3\", Org-mode will
1797 read this as the third of *next* month. However, if you enter \"17\",
1798 it will be considered as *this* month.
1799 2. The user gives a month but not a year.
1800 For example, if it is april and you enter \"feb 2\", this will be read
1801 as feb 2, *next* year. \"May 5\", however, will be this year.
1803 Currently this does not work for ISO week specifications.
1805 When this option is nil, the current month and year will always be used
1806 as defaults."
1807 :group 'org-time
1808 :type 'boolean)
1810 (defcustom org-read-date-display-live t
1811 "Non-nil means, display current interpretation of date prompt live.
1812 This display will be in an overlay, in the minibuffer."
1813 :group 'org-time
1814 :type 'boolean)
1816 (defcustom org-read-date-popup-calendar t
1817 "Non-nil means, pop up a calendar when prompting for a date.
1818 In the calendar, the date can be selected with mouse-1. However, the
1819 minibuffer will also be active, and you can simply enter the date as well.
1820 When nil, only the minibuffer will be available."
1821 :group 'org-time
1822 :type 'boolean)
1823 (if (fboundp 'defvaralias)
1824 (defvaralias 'org-popup-calendar-for-date-prompt
1825 'org-read-date-popup-calendar))
1827 (defcustom org-extend-today-until 0
1828 "The hour when your day really ends. Must be an integer.
1829 This has influence for the following applications:
1830 - When switching the agenda to \"today\". It it is still earlier than
1831 the time given here, the day recognized as TODAY is actually yesterday.
1832 - When a date is read from the user and it is still before the time given
1833 here, the current date and time will be assumed to be yesterday, 23:59.
1834 Also, timestamps inserted in remember templates follow this rule.
1836 IMPORTANT: This is a feature whose implementation is and likely will
1837 remain incomplete. Really, it is only here because past midnight seems to
1838 be the favorite working time of John Wiegley :-)"
1839 :group 'org-time
1840 :type 'number)
1842 (defcustom org-edit-timestamp-down-means-later nil
1843 "Non-nil means, S-down will increase the time in a time stamp.
1844 When nil, S-up will increase."
1845 :group 'org-time
1846 :type 'boolean)
1848 (defcustom org-calendar-follow-timestamp-change t
1849 "Non-nil means, make the calendar window follow timestamp changes.
1850 When a timestamp is modified and the calendar window is visible, it will be
1851 moved to the new date."
1852 :group 'org-time
1853 :type 'boolean)
1855 (defgroup org-tags nil
1856 "Options concerning tags in Org-mode."
1857 :tag "Org Tags"
1858 :group 'org)
1860 (defcustom org-tag-alist nil
1861 "List of tags allowed in Org-mode files.
1862 When this list is nil, Org-mode will base TAG input on what is already in the
1863 buffer.
1864 The value of this variable is an alist, the car of each entry must be a
1865 keyword as a string, the cdr may be a character that is used to select
1866 that tag through the fast-tag-selection interface.
1867 See the manual for details."
1868 :group 'org-tags
1869 :type '(repeat
1870 (choice
1871 (cons (string :tag "Tag name")
1872 (character :tag "Access char"))
1873 (const :tag "Start radio group" (:startgroup))
1874 (const :tag "End radio group" (:endgroup)))))
1876 (defvar org-file-tags nil
1877 "List of tags that can be inherited by all entries in the file.
1878 The tags will be inherited if the variable `org-use-tag-inheritance'
1879 says they should be.
1880 This variable is populated from #+TAG lines.")
1882 (defcustom org-use-fast-tag-selection 'auto
1883 "Non-nil means, use fast tag selection scheme.
1884 This is a special interface to select and deselect tags with single keys.
1885 When nil, fast selection is never used.
1886 When the symbol `auto', fast selection is used if and only if selection
1887 characters for tags have been configured, either through the variable
1888 `org-tag-alist' or through a #+TAGS line in the buffer.
1889 When t, fast selection is always used and selection keys are assigned
1890 automatically if necessary."
1891 :group 'org-tags
1892 :type '(choice
1893 (const :tag "Always" t)
1894 (const :tag "Never" nil)
1895 (const :tag "When selection characters are configured" 'auto)))
1897 (defcustom org-fast-tag-selection-single-key nil
1898 "Non-nil means, fast tag selection exits after first change.
1899 When nil, you have to press RET to exit it.
1900 During fast tag selection, you can toggle this flag with `C-c'.
1901 This variable can also have the value `expert'. In this case, the window
1902 displaying the tags menu is not even shown, until you press C-c again."
1903 :group 'org-tags
1904 :type '(choice
1905 (const :tag "No" nil)
1906 (const :tag "Yes" t)
1907 (const :tag "Expert" expert)))
1909 (defvar org-fast-tag-selection-include-todo nil
1910 "Non-nil means, fast tags selection interface will also offer TODO states.
1911 This is an undocumented feature, you should not rely on it.")
1913 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1914 "The column to which tags should be indented in a headline.
1915 If this number is positive, it specifies the column. If it is negative,
1916 it means that the tags should be flushright to that column. For example,
1917 -80 works well for a normal 80 character screen."
1918 :group 'org-tags
1919 :type 'integer)
1921 (defcustom org-auto-align-tags t
1922 "Non-nil means, realign tags after pro/demotion of TODO state change.
1923 These operations change the length of a headline and therefore shift
1924 the tags around. With this options turned on, after each such operation
1925 the tags are again aligned to `org-tags-column'."
1926 :group 'org-tags
1927 :type 'boolean)
1929 (defcustom org-use-tag-inheritance t
1930 "Non-nil means, tags in levels apply also for sublevels.
1931 When nil, only the tags directly given in a specific line apply there.
1932 This may also be a list of tags that should be inherited, or a regexp that
1933 matches tags that should be inherited. Additional control is possible
1934 with the variable `org-tags-exclude-from-inheritance' which gives an
1935 explicit list of tags to be excluded from inheritance., even if the value of
1936 `org-use-tag-inheritance' would select it for inheritance.
1938 If this option is t, a match early-on in a tree can lead to a large
1939 number of matches in the subtree when constructing the agenda or creating
1940 a sparse tree. If you only want to see the first match in a tree during
1941 a search, check out the variable `org-tags-match-list-sublevels'."
1942 :group 'org-tags
1943 :type '(choice
1944 (const :tag "Not" nil)
1945 (const :tag "Always" t)
1946 (repeat :tag "Specific tags" (string :tag "Tag"))
1947 (regexp :tag "Tags matched by regexp")))
1949 (defcustom org-tags-exclude-from-inheritance nil
1950 "List of tags that should never be inherited.
1951 This is a way to exclude a few tags from inheritance. For way to do
1952 the opposite, to actively allow inheritance for selected tags,
1953 see the variable `org-use-tag-inheritance'."
1954 :group 'org-tags
1955 :type '(repeat (string :tag "Tag")))
1957 (defun org-tag-inherit-p (tag)
1958 "Check if TAG is one that should be inherited."
1959 (cond
1960 ((member tag org-tags-exclude-from-inheritance) nil)
1961 ((eq org-use-tag-inheritance t) t)
1962 ((not org-use-tag-inheritance) nil)
1963 ((stringp org-use-tag-inheritance)
1964 (string-match org-use-tag-inheritance tag))
1965 ((listp org-use-tag-inheritance)
1966 (member tag org-use-tag-inheritance))
1967 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1969 (defcustom org-tags-match-list-sublevels t
1970 "Non-nil means list also sublevels of headlines matching tag search.
1971 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1972 the sublevels of a headline matching a tag search often also match
1973 the same search. Listing all of them can create very long lists.
1974 Setting this variable to nil causes subtrees of a match to be skipped.
1975 This option is off by default, because inheritance in on. If you turn
1976 inheritance off, you very likely want to turn this option on.
1978 As a special case, if the tag search is restricted to TODO items, the
1979 value of this variable is ignored and sublevels are always checked, to
1980 make sure all corresponding TODO items find their way into the list.
1982 This variable is semi-obsolete and probably should always be true. It
1983 is better to limit inheritance to certain tags using the variables
1984 `org-use-tag-inheritanc'e and `org-tags-exclude-from-inheritance'."
1985 :group 'org-tags
1986 :type 'boolean)
1988 (defvar org-tags-history nil
1989 "History of minibuffer reads for tags.")
1990 (defvar org-last-tags-completion-table nil
1991 "The last used completion table for tags.")
1992 (defvar org-after-tags-change-hook nil
1993 "Hook that is run after the tags in a line have changed.")
1995 (defgroup org-properties nil
1996 "Options concerning properties in Org-mode."
1997 :tag "Org Properties"
1998 :group 'org)
2000 (defcustom org-property-format "%-10s %s"
2001 "How property key/value pairs should be formatted by `indent-line'.
2002 When `indent-line' hits a property definition, it will format the line
2003 according to this format, mainly to make sure that the values are
2004 lined-up with respect to each other."
2005 :group 'org-properties
2006 :type 'string)
2008 (defcustom org-use-property-inheritance nil
2009 "Non-nil means, properties apply also for sublevels.
2011 This setting is chiefly used during property searches. Turning it on can
2012 cause significant overhead when doing a search, which is why it is not
2013 on by default.
2015 When nil, only the properties directly given in the current entry count.
2016 When t, every property is inherited. The value may also be a list of
2017 properties that should have inheritance, or a regular expression matching
2018 properties that should be inherited.
2020 However, note that some special properties use inheritance under special
2021 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2022 and the properties ending in \"_ALL\" when they are used as descriptor
2023 for valid values of a property.
2025 Note for programmers:
2026 When querying an entry with `org-entry-get', you can control if inheritance
2027 should be used. By default, `org-entry-get' looks only at the local
2028 properties. You can request inheritance by setting the inherit argument
2029 to t (to force inheritance) or to `selective' (to respect the setting
2030 in this variable)."
2031 :group 'org-properties
2032 :type '(choice
2033 (const :tag "Not" nil)
2034 (const :tag "Always" t)
2035 (repeat :tag "Specific properties" (string :tag "Property"))
2036 (regexp :tag "Properties matched by regexp")))
2038 (defun org-property-inherit-p (property)
2039 "Check if PROPERTY is one that should be inherited."
2040 (cond
2041 ((eq org-use-property-inheritance t) t)
2042 ((not org-use-property-inheritance) nil)
2043 ((stringp org-use-property-inheritance)
2044 (string-match org-use-property-inheritance property))
2045 ((listp org-use-property-inheritance)
2046 (member property org-use-property-inheritance))
2047 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2049 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2050 "The default column format, if no other format has been defined.
2051 This variable can be set on the per-file basis by inserting a line
2053 #+COLUMNS: %25ITEM ....."
2054 :group 'org-properties
2055 :type 'string)
2057 (defcustom org-columns-ellipses ".."
2058 "The ellipses to be used when a field in column view is truncated.
2059 When this is the empty string, as many characters as possible are shown,
2060 but then there will be no visual indication that the field has been truncated.
2061 When this is a string of length N, the last N characters of a truncated
2062 field are replaced by this string. If the column is narrower than the
2063 ellipses string, only part of the ellipses string will be shown."
2064 :group 'org-properties
2065 :type 'string)
2067 (defcustom org-columns-modify-value-for-display-function nil
2068 "Function that modifies values for display in column view.
2069 For example, it can be used to cut out a certain part from a time stamp.
2070 The function must take 2 arguments:
2072 column-title The tite of the column (*not* the property name)
2073 value The value that should be modified.
2075 The function should return the value that should be displayed,
2076 or nil if the normal value should be used."
2077 :group 'org-properties
2078 :type 'function)
2080 (defcustom org-effort-property "Effort"
2081 "The property that is being used to keep track of effort estimates.
2082 Effort estimates given in this property need to have the format H:MM."
2083 :group 'org-properties
2084 :group 'org-progress
2085 :type '(string :tag "Property"))
2087 (defconst org-global-properties-fixed
2088 '(("VISIBILITY_ALL" . "folded children content all"))
2089 "List of property/value pairs that can be inherited by any entry.
2090 These are fixed values, for the preset properties.")
2093 (defcustom org-global-properties nil
2094 "List of property/value pairs that can be inherited by any entry.
2095 You can set buffer-local values for the same purpose in the variable
2096 `org-file-properties' this by adding lines like
2098 #+PROPERTY: NAME VALUE"
2099 :group 'org-properties
2100 :type '(repeat
2101 (cons (string :tag "Property")
2102 (string :tag "Value"))))
2104 (defvar org-file-properties nil
2105 "List of property/value pairs that can be inherited by any entry.
2106 Valid for the current buffer.
2107 This variable is populated from #+PROPERTY lines.")
2108 (make-variable-buffer-local 'org-file-properties)
2110 (defgroup org-agenda nil
2111 "Options concerning agenda views in Org-mode."
2112 :tag "Org Agenda"
2113 :group 'org)
2115 (defvar org-category nil
2116 "Variable used by org files to set a category for agenda display.
2117 Such files should use a file variable to set it, for example
2119 # -*- mode: org; org-category: \"ELisp\"
2121 or contain a special line
2123 #+CATEGORY: ELisp
2125 If the file does not specify a category, then file's base name
2126 is used instead.")
2127 (make-variable-buffer-local 'org-category)
2128 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2130 (defcustom org-agenda-files nil
2131 "The files to be used for agenda display.
2132 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2133 \\[org-remove-file]. You can also use customize to edit the list.
2135 If an entry is a directory, all files in that directory that are matched by
2136 `org-agenda-file-regexp' will be part of the file list.
2138 If the value of the variable is not a list but a single file name, then
2139 the list of agenda files is actually stored and maintained in that file, one
2140 agenda file per line."
2141 :group 'org-agenda
2142 :type '(choice
2143 (repeat :tag "List of files and directories" file)
2144 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2146 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2147 "Regular expression to match files for `org-agenda-files'.
2148 If any element in the list in that variable contains a directory instead
2149 of a normal file, all files in that directory that are matched by this
2150 regular expression will be included."
2151 :group 'org-agenda
2152 :type 'regexp)
2154 (defcustom org-agenda-text-search-extra-files nil
2155 "List of extra files to be searched by text search commands.
2156 These files will be search in addition to the agenda files by the
2157 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2158 Note that these files will only be searched for text search commands,
2159 not for the other agenda views like todo lists, tag searches or the weekly
2160 agenda. This variable is intended to list notes and possibly archive files
2161 that should also be searched by these two commands.
2162 In fact, if the first element in the list is the symbol `agenda-archives',
2163 than all archive files of all agenda files will be added to the search
2164 scope."
2165 :group 'org-agenda
2166 :type '(set :greedy t
2167 (const :tag "Agenda Archives" agenda-archives)
2168 (repeat :inline t (file))))
2170 (if (fboundp 'defvaralias)
2171 (defvaralias 'org-agenda-multi-occur-extra-files
2172 'org-agenda-text-search-extra-files))
2174 (defcustom org-agenda-skip-unavailable-files nil
2175 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2176 A nil value means to remove them, after a query, from the list."
2177 :group 'org-agenda
2178 :type 'boolean)
2180 (defcustom org-calendar-to-agenda-key [?c]
2181 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2182 The command `org-calendar-goto-agenda' will be bound to this key. The
2183 default is the character `c' because then `c' can be used to switch back and
2184 forth between agenda and calendar."
2185 :group 'org-agenda
2186 :type 'sexp)
2188 (defcustom org-calendar-agenda-action-key [?k]
2189 "The key to be installed in `calendar-mode-map' for agenda-action.
2190 The command `org-agenda-action' will be bound to this key. The
2191 default is the character `k' because we use the same key in the agenda."
2192 :group 'org-agenda
2193 :type 'sexp)
2195 (eval-after-load "calendar"
2196 '(progn
2197 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2198 'org-calendar-goto-agenda)
2199 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2200 'org-agenda-action)))
2202 (defgroup org-latex nil
2203 "Options for embedding LaTeX code into Org-mode."
2204 :tag "Org LaTeX"
2205 :group 'org)
2207 (defcustom org-format-latex-options
2208 '(:foreground default :background default :scale 1.0
2209 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2210 :matchers ("begin" "$" "$$" "\\(" "\\["))
2211 "Options for creating images from LaTeX fragments.
2212 This is a property list with the following properties:
2213 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2214 `default' means use the foreground of the default face.
2215 :background the background color, or \"Transparent\".
2216 `default' means use the background of the default face.
2217 :scale a scaling factor for the size of the images.
2218 :html-foreground, :html-background, :html-scale
2219 the same numbers for HTML export.
2220 :matchers a list indicating which matchers should be used to
2221 find LaTeX fragments. Valid members of this list are:
2222 \"begin\" find environments
2223 \"$\" find math expressions surrounded by $...$
2224 \"$$\" find math expressions surrounded by $$....$$
2225 \"\\(\" find math expressions surrounded by \\(...\\)
2226 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2227 :group 'org-latex
2228 :type 'plist)
2230 (defcustom org-format-latex-header "\\documentclass{article}
2231 \\usepackage{fullpage} % do not remove
2232 \\usepackage{amssymb}
2233 \\usepackage[usenames]{color}
2234 \\usepackage{amsmath}
2235 \\usepackage{latexsym}
2236 \\usepackage[mathscr]{eucal}
2237 \\pagestyle{empty} % do not remove"
2238 "The document header used for processing LaTeX fragments."
2239 :group 'org-latex
2240 :type 'string)
2243 (defgroup org-font-lock nil
2244 "Font-lock settings for highlighting in Org-mode."
2245 :tag "Org Font Lock"
2246 :group 'org)
2248 (defcustom org-level-color-stars-only nil
2249 "Non-nil means fontify only the stars in each headline.
2250 When nil, the entire headline is fontified.
2251 Changing it requires restart of `font-lock-mode' to become effective
2252 also in regions already fontified."
2253 :group 'org-font-lock
2254 :type 'boolean)
2256 (defcustom org-hide-leading-stars nil
2257 "Non-nil means, hide the first N-1 stars in a headline.
2258 This works by using the face `org-hide' for these stars. This
2259 face is white for a light background, and black for a dark
2260 background. You may have to customize the face `org-hide' to
2261 make this work.
2262 Changing it requires restart of `font-lock-mode' to become effective
2263 also in regions already fontified.
2264 You may also set this on a per-file basis by adding one of the following
2265 lines to the buffer:
2267 #+STARTUP: hidestars
2268 #+STARTUP: showstars"
2269 :group 'org-font-lock
2270 :type 'boolean)
2272 (defcustom org-fontify-done-headline nil
2273 "Non-nil means, change the face of a headline if it is marked DONE.
2274 Normally, only the TODO/DONE keyword indicates the state of a headline.
2275 When this is non-nil, the headline after the keyword is set to the
2276 `org-headline-done' as an additional indication."
2277 :group 'org-font-lock
2278 :type 'boolean)
2280 (defcustom org-fontify-emphasized-text t
2281 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2282 Changing this variable requires a restart of Emacs to take effect."
2283 :group 'org-font-lock
2284 :type 'boolean)
2286 (defcustom org-highlight-latex-fragments-and-specials nil
2287 "Non-nil means, fontify what is treated specially by the exporters."
2288 :group 'org-font-lock
2289 :type 'boolean)
2291 (defcustom org-hide-emphasis-markers nil
2292 "Non-nil mean font-lock should hide the emphasis marker characters."
2293 :group 'org-font-lock
2294 :type 'boolean)
2296 (defvar org-emph-re nil
2297 "Regular expression for matching emphasis.")
2298 (defvar org-verbatim-re nil
2299 "Regular expression for matching verbatim text.")
2300 (defvar org-emphasis-regexp-components) ; defined just below
2301 (defvar org-emphasis-alist) ; defined just below
2302 (defun org-set-emph-re (var val)
2303 "Set variable and compute the emphasis regular expression."
2304 (set var val)
2305 (when (and (boundp 'org-emphasis-alist)
2306 (boundp 'org-emphasis-regexp-components)
2307 org-emphasis-alist org-emphasis-regexp-components)
2308 (let* ((e org-emphasis-regexp-components)
2309 (pre (car e))
2310 (post (nth 1 e))
2311 (border (nth 2 e))
2312 (body (nth 3 e))
2313 (nl (nth 4 e))
2314 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2315 (body1 (concat body "*?"))
2316 (markers (mapconcat 'car org-emphasis-alist ""))
2317 (vmarkers (mapconcat
2318 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2319 org-emphasis-alist "")))
2320 ;; make sure special characters appear at the right position in the class
2321 (if (string-match "\\^" markers)
2322 (setq markers (concat (replace-match "" t t markers) "^")))
2323 (if (string-match "-" markers)
2324 (setq markers (concat (replace-match "" t t markers) "-")))
2325 (if (string-match "\\^" vmarkers)
2326 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2327 (if (string-match "-" vmarkers)
2328 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2329 (if (> nl 0)
2330 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2331 (int-to-string nl) "\\}")))
2332 ;; Make the regexp
2333 (setq org-emph-re
2334 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2335 "\\("
2336 "\\([" markers "]\\)"
2337 "\\("
2338 "[^" border "]\\|"
2339 "[^" border (if (and nil stacked) markers) "]"
2340 body1
2341 "[^" border (if (and nil stacked) markers) "]"
2342 "\\)"
2343 "\\3\\)"
2344 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2345 (setq org-verbatim-re
2346 (concat "\\([" pre "]\\|^\\)"
2347 "\\("
2348 "\\([" vmarkers "]\\)"
2349 "\\("
2350 "[^" border "]\\|"
2351 "[^" border "]"
2352 body1
2353 "[^" border "]"
2354 "\\)"
2355 "\\3\\)"
2356 "\\([" post "]\\|$\\)")))))
2358 (defcustom org-emphasis-regexp-components
2359 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2360 "Components used to build the regular expression for emphasis.
2361 This is a list with 6 entries. Terminology: In an emphasis string
2362 like \" *strong word* \", we call the initial space PREMATCH, the final
2363 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2364 and \"trong wor\" is the body. The different components in this variable
2365 specify what is allowed/forbidden in each part:
2367 pre Chars allowed as prematch. Beginning of line will be allowed too.
2368 post Chars allowed as postmatch. End of line will be allowed too.
2369 border The chars *forbidden* as border characters.
2370 body-regexp A regexp like \".\" to match a body character. Don't use
2371 non-shy groups here, and don't allow newline here.
2372 newline The maximum number of newlines allowed in an emphasis exp.
2374 Use customize to modify this, or restart Emacs after changing it."
2375 :group 'org-font-lock
2376 :set 'org-set-emph-re
2377 :type '(list
2378 (sexp :tag "Allowed chars in pre ")
2379 (sexp :tag "Allowed chars in post ")
2380 (sexp :tag "Forbidden chars in border ")
2381 (sexp :tag "Regexp for body ")
2382 (integer :tag "number of newlines allowed")
2383 (option (boolean :tag "Please ignore this button"))))
2385 (defcustom org-emphasis-alist
2386 `(("*" bold "<b>" "</b>")
2387 ("/" italic "<i>" "</i>")
2388 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2389 ("=" org-code "<code>" "</code>" verbatim)
2390 ("~" org-verbatim "<code>" "</code>" verbatim)
2391 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2392 "<del>" "</del>")
2394 "Special syntax for emphasized text.
2395 Text starting and ending with a special character will be emphasized, for
2396 example *bold*, _underlined_ and /italic/. This variable sets the marker
2397 characters, the face to be used by font-lock for highlighting in Org-mode
2398 Emacs buffers, and the HTML tags to be used for this.
2399 Use customize to modify this, or restart Emacs after changing it."
2400 :group 'org-font-lock
2401 :set 'org-set-emph-re
2402 :type '(repeat
2403 (list
2404 (string :tag "Marker character")
2405 (choice
2406 (face :tag "Font-lock-face")
2407 (plist :tag "Face property list"))
2408 (string :tag "HTML start tag")
2409 (string :tag "HTML end tag")
2410 (option (const verbatim)))))
2412 ;;; Miscellaneous options
2414 (defgroup org-completion nil
2415 "Completion in Org-mode."
2416 :tag "Org Completion"
2417 :group 'org)
2419 (defcustom org-completion-use-ido nil
2420 "Non-nil means, use ido completion wherever possible."
2421 :group 'org-completion
2422 :type 'boolean)
2424 (defcustom org-completion-fallback-command 'hippie-expand
2425 "The expansion command called by \\[org-complete] in normal context.
2426 Normal means, no org-mode-specific context."
2427 :group 'org-completion
2428 :type 'function)
2430 ;;; Functions and variables from ther packages
2431 ;; Declared here to avoid compiler warnings
2433 ;; XEmacs only
2434 (defvar outline-mode-menu-heading)
2435 (defvar outline-mode-menu-show)
2436 (defvar outline-mode-menu-hide)
2437 (defvar zmacs-regions) ; XEmacs regions
2439 ;; Emacs only
2440 (defvar mark-active)
2442 ;; Various packages
2443 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2444 (declare-function calendar-forward-day "cal-move" (arg))
2445 (declare-function calendar-goto-date "cal-move" (date))
2446 (declare-function calendar-goto-today "cal-move" ())
2447 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2448 (defvar calc-embedded-close-formula)
2449 (defvar calc-embedded-open-formula)
2450 (declare-function cdlatex-tab "ext:cdlatex" ())
2451 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2452 (defvar font-lock-unfontify-region-function)
2453 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2454 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2455 (defvar iswitchb-temp-buflist)
2456 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2457 (declare-function org-agenda-skip "org-agenda" ())
2458 (declare-function org-format-agenda-item "org-agenda"
2459 (extra txt &optional category tags dotime noprefix remove-re))
2460 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2461 (declare-function org-agenda-change-all-lines "org-agenda"
2462 (newhead hdmarker &optional fixface just-this))
2463 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2464 (declare-function org-agenda-maybe-redo "org-agenda" ())
2465 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2466 (beg end))
2467 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2468 (declare-function parse-time-string "parse-time" (string))
2469 (declare-function remember "remember" (&optional initial))
2470 (declare-function remember-buffer-desc "remember" ())
2471 (declare-function remember-finalize "remember" ())
2472 (defvar remember-save-after-remembering)
2473 (defvar remember-data-file)
2474 (defvar remember-register)
2475 (defvar remember-buffer)
2476 (defvar remember-handler-functions)
2477 (defvar remember-annotation-functions)
2478 (defvar texmathp-why)
2479 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2480 (declare-function table--at-cell-p "table" (position &optional object at-column))
2482 (defvar w3m-current-url)
2483 (defvar w3m-current-title)
2485 (defvar org-latex-regexps)
2487 ;;; Autoload and prepare some org modules
2489 ;; Some table stuff that needs to be defined here, because it is used
2490 ;; by the functions setting up org-mode or checking for table context.
2492 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2493 "Detects an org-type or table-type table.")
2494 (defconst org-table-line-regexp "^[ \t]*|"
2495 "Detects an org-type table line.")
2496 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2497 "Detects an org-type table line.")
2498 (defconst org-table-hline-regexp "^[ \t]*|-"
2499 "Detects an org-type table hline.")
2500 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2501 "Detects a table-type table hline.")
2502 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2503 "Searching from within a table (any type) this finds the first line
2504 outside the table.")
2506 ;; Autoload the functions in org-table.el that are needed by functions here.
2508 (eval-and-compile
2509 (org-autoload "org-table"
2510 '(org-table-align org-table-begin org-table-blank-field
2511 org-table-convert org-table-convert-region org-table-copy-down
2512 org-table-copy-region org-table-create
2513 org-table-create-or-convert-from-region
2514 org-table-create-with-table.el org-table-current-dline
2515 org-table-cut-region org-table-delete-column org-table-edit-field
2516 org-table-edit-formulas org-table-end org-table-eval-formula
2517 org-table-export org-table-field-info
2518 org-table-get-stored-formulas org-table-goto-column
2519 org-table-hline-and-move org-table-import org-table-insert-column
2520 org-table-insert-hline org-table-insert-row org-table-iterate
2521 org-table-justify-field-maybe org-table-kill-row
2522 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2523 org-table-move-column org-table-move-column-left
2524 org-table-move-column-right org-table-move-row
2525 org-table-move-row-down org-table-move-row-up
2526 org-table-next-field org-table-next-row org-table-paste-rectangle
2527 org-table-previous-field org-table-recalculate
2528 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2529 org-table-toggle-coordinate-overlays
2530 org-table-toggle-formula-debugger org-table-wrap-region
2531 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2533 (defun org-at-table-p (&optional table-type)
2534 "Return t if the cursor is inside an org-type table.
2535 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2536 (if org-enable-table-editor
2537 (save-excursion
2538 (beginning-of-line 1)
2539 (looking-at (if table-type org-table-any-line-regexp
2540 org-table-line-regexp)))
2541 nil))
2542 (defsubst org-table-p () (org-at-table-p))
2544 (defun org-at-table.el-p ()
2545 "Return t if and only if we are at a table.el table."
2546 (and (org-at-table-p 'any)
2547 (save-excursion
2548 (goto-char (org-table-begin 'any))
2549 (looking-at org-table1-hline-regexp))))
2550 (defun org-table-recognize-table.el ()
2551 "If there is a table.el table nearby, recognize it and move into it."
2552 (if org-table-tab-recognizes-table.el
2553 (if (org-at-table.el-p)
2554 (progn
2555 (beginning-of-line 1)
2556 (if (looking-at org-table-dataline-regexp)
2558 (if (looking-at org-table1-hline-regexp)
2559 (progn
2560 (beginning-of-line 2)
2561 (if (looking-at org-table-any-border-regexp)
2562 (beginning-of-line -1)))))
2563 (if (re-search-forward "|" (org-table-end t) t)
2564 (progn
2565 (require 'table)
2566 (if (table--at-cell-p (point))
2568 (message "recognizing table.el table...")
2569 (table-recognize-table)
2570 (message "recognizing table.el table...done")))
2571 (error "This should not happen..."))
2573 nil)
2574 nil))
2576 (defun org-at-table-hline-p ()
2577 "Return t if the cursor is inside a hline in a table."
2578 (if org-enable-table-editor
2579 (save-excursion
2580 (beginning-of-line 1)
2581 (looking-at org-table-hline-regexp))
2582 nil))
2584 (defvar org-table-clean-did-remove-column nil)
2586 (defun org-table-map-tables (function)
2587 "Apply FUNCTION to the start of all tables in the buffer."
2588 (save-excursion
2589 (save-restriction
2590 (widen)
2591 (goto-char (point-min))
2592 (while (re-search-forward org-table-any-line-regexp nil t)
2593 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2594 (beginning-of-line 1)
2595 (if (looking-at org-table-line-regexp)
2596 (save-excursion (funcall function)))
2597 (re-search-forward org-table-any-border-regexp nil 1))))
2598 (message "Mapping tables: done"))
2600 ;; Declare and autoload functions from org-exp.el
2602 (declare-function org-default-export-plist "org-exp")
2603 (declare-function org-infile-export-plist "org-exp")
2604 (declare-function org-get-current-options "org-exp")
2605 (eval-and-compile
2606 (org-autoload "org-exp"
2607 '(org-export org-export-as-ascii org-export-visible
2608 org-insert-export-options-template org-export-as-html-and-open
2609 org-export-as-html-batch org-export-as-html-to-buffer
2610 org-replace-region-by-html org-export-region-as-html
2611 org-export-as-html org-export-icalendar-this-file
2612 org-export-icalendar-all-agenda-files
2613 org-table-clean-before-export
2614 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2616 ;; Declare and autoload functions from org-agenda.el
2618 (eval-and-compile
2619 (org-autoload "org-agenda"
2620 '(org-agenda org-agenda-list org-search-view
2621 org-todo-list org-tags-view org-agenda-list-stuck-projects
2622 org-diary org-agenda-to-appt)))
2624 ;; Autoload org-remember
2626 (eval-and-compile
2627 (org-autoload "org-remember"
2628 '(org-remember-insinuate org-remember-annotation
2629 org-remember-apply-template org-remember org-remember-handler)))
2631 ;; Autoload org-clock.el
2634 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2635 (beg end))
2636 (declare-function org-update-mode-line "org-clock" ())
2637 (defvar org-clock-start-time)
2638 (defvar org-clock-marker (make-marker)
2639 "Marker recording the last clock-in.")
2641 (eval-and-compile
2642 (org-autoload
2643 "org-clock"
2644 '(org-clock-in org-clock-out org-clock-cancel
2645 org-clock-goto org-clock-sum org-clock-display
2646 org-remove-clock-overlays org-clock-report
2647 org-clocktable-shift org-dblock-write:clocktable
2648 org-get-clocktable)))
2650 (defun org-clock-update-time-maybe ()
2651 "If this is a CLOCK line, update it and return t.
2652 Otherwise, return nil."
2653 (interactive)
2654 (save-excursion
2655 (beginning-of-line 1)
2656 (skip-chars-forward " \t")
2657 (when (looking-at org-clock-string)
2658 (let ((re (concat "[ \t]*" org-clock-string
2659 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2660 "\\([ \t]*=>.*\\)?\\)?"))
2661 ts te h m s neg)
2662 (cond
2663 ((not (looking-at re))
2664 nil)
2665 ((not (match-end 2))
2666 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2667 (> org-clock-marker (point))
2668 (<= org-clock-marker (point-at-eol)))
2669 ;; The clock is running here
2670 (setq org-clock-start-time
2671 (apply 'encode-time
2672 (org-parse-time-string (match-string 1))))
2673 (org-update-mode-line)))
2675 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2676 (end-of-line 1)
2677 (setq ts (match-string 1)
2678 te (match-string 3))
2679 (setq s (- (time-to-seconds
2680 (apply 'encode-time (org-parse-time-string te)))
2681 (time-to-seconds
2682 (apply 'encode-time (org-parse-time-string ts))))
2683 neg (< s 0)
2684 s (abs s)
2685 h (floor (/ s 3600))
2686 s (- s (* 3600 h))
2687 m (floor (/ s 60))
2688 s (- s (* 60 s)))
2689 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2690 t))))))
2692 (defun org-check-running-clock ()
2693 "Check if the current buffer contains the running clock.
2694 If yes, offer to stop it and to save the buffer with the changes."
2695 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2696 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2697 (buffer-name))))
2698 (org-clock-out)
2699 (when (y-or-n-p "Save changed buffer?")
2700 (save-buffer))))
2702 (defun org-clocktable-try-shift (dir n)
2703 "Check if this line starts a clock table, if yes, shift the time block."
2704 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2705 (org-clocktable-shift dir n)))
2707 ;; Autoload org-timer.el
2709 ;(declare-function org-timer "org-timer")
2711 (eval-and-compile
2712 (org-autoload
2713 "org-timer"
2714 '(org-timer-start org-timer org-timer-item
2715 org-timer-change-times-in-region)))
2718 ;; Autoload archiving code
2719 ;; The stuff that is needed for cycling and tags has to be defined here.
2721 (defgroup org-archive nil
2722 "Options concerning archiving in Org-mode."
2723 :tag "Org Archive"
2724 :group 'org-structure)
2726 (defcustom org-archive-location "%s_archive::"
2727 "The location where subtrees should be archived.
2729 The value of this variable is a string, consisting of two parts,
2730 separated by a double-colon. The first part is a filename and
2731 the second part is a headline.
2733 When the filename is omitted, archiving happens in the same file.
2734 %s in the filename will be replaced by the current file
2735 name (without the directory part). Archiving to a different file
2736 is useful to keep archived entries from contributing to the
2737 Org-mode Agenda.
2739 The archived entries will be filed as subtrees of the specified
2740 headline. When the headline is omitted, the subtrees are simply
2741 filed away at the end of the file, as top-level entries.
2743 Here are a few examples:
2744 \"%s_archive::\"
2745 If the current file is Projects.org, archive in file
2746 Projects.org_archive, as top-level trees. This is the default.
2748 \"::* Archived Tasks\"
2749 Archive in the current file, under the top-level headline
2750 \"* Archived Tasks\".
2752 \"~/org/archive.org::\"
2753 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2755 \"basement::** Finished Tasks\"
2756 Archive in file ./basement (relative path), as level 3 trees
2757 below the level 2 heading \"** Finished Tasks\".
2759 You may set this option on a per-file basis by adding to the buffer a
2760 line like
2762 #+ARCHIVE: basement::** Finished Tasks
2764 You may also define it locally for a subtree by setting an ARCHIVE property
2765 in the entry. If such a property is found in an entry, or anywhere up
2766 the hierarchy, it will be used."
2767 :group 'org-archive
2768 :type 'string)
2770 (defcustom org-archive-tag "ARCHIVE"
2771 "The tag that marks a subtree as archived.
2772 An archived subtree does not open during visibility cycling, and does
2773 not contribute to the agenda listings.
2774 After changing this, font-lock must be restarted in the relevant buffers to
2775 get the proper fontification."
2776 :group 'org-archive
2777 :group 'org-keywords
2778 :type 'string)
2780 (defcustom org-agenda-skip-archived-trees t
2781 "Non-nil means, the agenda will skip any items located in archived trees.
2782 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2783 variable is no longer recommended, you should leave it at the value t.
2784 Instead, use the key `v' to cycle the archives-mode in the agenda."
2785 :group 'org-archive
2786 :group 'org-agenda-skip
2787 :type 'boolean)
2789 (defcustom org-cycle-open-archived-trees nil
2790 "Non-nil means, `org-cycle' will open archived trees.
2791 An archived tree is a tree marked with the tag ARCHIVE.
2792 When nil, archived trees will stay folded. You can still open them with
2793 normal outline commands like `show-all', but not with the cycling commands."
2794 :group 'org-archive
2795 :group 'org-cycle
2796 :type 'boolean)
2798 (defcustom org-sparse-tree-open-archived-trees nil
2799 "Non-nil means sparse tree construction shows matches in archived trees.
2800 When nil, matches in these trees are highlighted, but the trees are kept in
2801 collapsed state."
2802 :group 'org-archive
2803 :group 'org-sparse-trees
2804 :type 'boolean)
2806 (defun org-cycle-hide-archived-subtrees (state)
2807 "Re-hide all archived subtrees after a visibility state change."
2808 (when (and (not org-cycle-open-archived-trees)
2809 (not (memq state '(overview folded))))
2810 (save-excursion
2811 (let* ((globalp (memq state '(contents all)))
2812 (beg (if globalp (point-min) (point)))
2813 (end (if globalp (point-max) (org-end-of-subtree t))))
2814 (org-hide-archived-subtrees beg end)
2815 (goto-char beg)
2816 (if (looking-at (concat ".*:" org-archive-tag ":"))
2817 (message "%s" (substitute-command-keys
2818 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2820 (defun org-force-cycle-archived ()
2821 "Cycle subtree even if it is archived."
2822 (interactive)
2823 (setq this-command 'org-cycle)
2824 (let ((org-cycle-open-archived-trees t))
2825 (call-interactively 'org-cycle)))
2827 (defun org-hide-archived-subtrees (beg end)
2828 "Re-hide all archived subtrees after a visibility state change."
2829 (save-excursion
2830 (let* ((re (concat ":" org-archive-tag ":")))
2831 (goto-char beg)
2832 (while (re-search-forward re end t)
2833 (and (org-on-heading-p) (hide-subtree))
2834 (org-end-of-subtree t)))))
2836 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2838 (eval-and-compile
2839 (org-autoload "org-archive"
2840 '(org-add-archive-files org-archive-subtree
2841 org-archive-to-archive-sibling org-toggle-archive-tag)))
2843 ;; Autoload Column View Code
2845 (declare-function org-columns-number-to-string "org-colview")
2846 (declare-function org-columns-get-format-and-top-level "org-colview")
2847 (declare-function org-columns-compute "org-colview")
2849 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2850 '(org-columns-number-to-string org-columns-get-format-and-top-level
2851 org-columns-compute org-agenda-columns org-columns-remove-overlays
2852 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2854 ;; Autoload ID code
2856 (declare-function org-id-store-link "org-id")
2857 (org-autoload "org-id"
2858 '(org-id-get-create org-id-new org-id-copy org-id-get
2859 org-id-get-with-outline-path-completion
2860 org-id-get-with-outline-drilling
2861 org-id-goto org-id-find org-id-store-link))
2863 ;;; Variables for pre-computed regular expressions, all buffer local
2865 (defvar org-drawer-regexp nil
2866 "Matches first line of a hidden block.")
2867 (make-variable-buffer-local 'org-drawer-regexp)
2868 (defvar org-todo-regexp nil
2869 "Matches any of the TODO state keywords.")
2870 (make-variable-buffer-local 'org-todo-regexp)
2871 (defvar org-not-done-regexp nil
2872 "Matches any of the TODO state keywords except the last one.")
2873 (make-variable-buffer-local 'org-not-done-regexp)
2874 (defvar org-todo-line-regexp nil
2875 "Matches a headline and puts TODO state into group 2 if present.")
2876 (make-variable-buffer-local 'org-todo-line-regexp)
2877 (defvar org-complex-heading-regexp nil
2878 "Matches a headline and puts everything into groups:
2879 group 1: the stars
2880 group 2: The todo keyword, maybe
2881 group 3: Priority cookie
2882 group 4: True headline
2883 group 5: Tags")
2884 (make-variable-buffer-local 'org-complex-heading-regexp)
2885 (defvar org-todo-line-tags-regexp nil
2886 "Matches a headline and puts TODO state into group 2 if present.
2887 Also put tags into group 4 if tags are present.")
2888 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2889 (defvar org-nl-done-regexp nil
2890 "Matches newline followed by a headline with the DONE keyword.")
2891 (make-variable-buffer-local 'org-nl-done-regexp)
2892 (defvar org-looking-at-done-regexp nil
2893 "Matches the DONE keyword a point.")
2894 (make-variable-buffer-local 'org-looking-at-done-regexp)
2895 (defvar org-ds-keyword-length 12
2896 "Maximum length of the Deadline and SCHEDULED keywords.")
2897 (make-variable-buffer-local 'org-ds-keyword-length)
2898 (defvar org-deadline-regexp nil
2899 "Matches the DEADLINE keyword.")
2900 (make-variable-buffer-local 'org-deadline-regexp)
2901 (defvar org-deadline-time-regexp nil
2902 "Matches the DEADLINE keyword together with a time stamp.")
2903 (make-variable-buffer-local 'org-deadline-time-regexp)
2904 (defvar org-deadline-line-regexp nil
2905 "Matches the DEADLINE keyword and the rest of the line.")
2906 (make-variable-buffer-local 'org-deadline-line-regexp)
2907 (defvar org-scheduled-regexp nil
2908 "Matches the SCHEDULED keyword.")
2909 (make-variable-buffer-local 'org-scheduled-regexp)
2910 (defvar org-scheduled-time-regexp nil
2911 "Matches the SCHEDULED keyword together with a time stamp.")
2912 (make-variable-buffer-local 'org-scheduled-time-regexp)
2913 (defvar org-closed-time-regexp nil
2914 "Matches the CLOSED keyword together with a time stamp.")
2915 (make-variable-buffer-local 'org-closed-time-regexp)
2917 (defvar org-keyword-time-regexp nil
2918 "Matches any of the 4 keywords, together with the time stamp.")
2919 (make-variable-buffer-local 'org-keyword-time-regexp)
2920 (defvar org-keyword-time-not-clock-regexp nil
2921 "Matches any of the 3 keywords, together with the time stamp.")
2922 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2923 (defvar org-maybe-keyword-time-regexp nil
2924 "Matches a timestamp, possibly preceeded by a keyword.")
2925 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2926 (defvar org-planning-or-clock-line-re nil
2927 "Matches a line with planning or clock info.")
2928 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2930 (defconst org-plain-time-of-day-regexp
2931 (concat
2932 "\\(\\<[012]?[0-9]"
2933 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2934 "\\(--?"
2935 "\\(\\<[012]?[0-9]"
2936 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2937 "\\)?")
2938 "Regular expression to match a plain time or time range.
2939 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2940 groups carry important information:
2941 0 the full match
2942 1 the first time, range or not
2943 8 the second time, if it is a range.")
2945 (defconst org-plain-time-extension-regexp
2946 (concat
2947 "\\(\\<[012]?[0-9]"
2948 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2949 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2950 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2951 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2952 groups carry important information:
2953 0 the full match
2954 7 hours of duration
2955 9 minutes of duration")
2957 (defconst org-stamp-time-of-day-regexp
2958 (concat
2959 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2960 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2961 "\\(--?"
2962 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2963 "Regular expression to match a timestamp time or time range.
2964 After a match, the following groups carry important information:
2965 0 the full match
2966 1 date plus weekday, for backreferencing to make sure both times on same day
2967 2 the first time, range or not
2968 4 the second time, if it is a range.")
2970 (defconst org-startup-options
2971 '(("fold" org-startup-folded t)
2972 ("overview" org-startup-folded t)
2973 ("nofold" org-startup-folded nil)
2974 ("showall" org-startup-folded nil)
2975 ("content" org-startup-folded content)
2976 ("hidestars" org-hide-leading-stars t)
2977 ("showstars" org-hide-leading-stars nil)
2978 ("odd" org-odd-levels-only t)
2979 ("oddeven" org-odd-levels-only nil)
2980 ("align" org-startup-align-all-tables t)
2981 ("noalign" org-startup-align-all-tables nil)
2982 ("customtime" org-display-custom-times t)
2983 ("logdone" org-log-done time)
2984 ("lognotedone" org-log-done note)
2985 ("nologdone" org-log-done nil)
2986 ("lognoteclock-out" org-log-note-clock-out t)
2987 ("nolognoteclock-out" org-log-note-clock-out nil)
2988 ("logrepeat" org-log-repeat state)
2989 ("lognoterepeat" org-log-repeat note)
2990 ("nologrepeat" org-log-repeat nil)
2991 ("constcgs" constants-unit-system cgs)
2992 ("constSI" constants-unit-system SI))
2993 "Variable associated with STARTUP options for org-mode.
2994 Each element is a list of three items: The startup options as written
2995 in the #+STARTUP line, the corresponding variable, and the value to
2996 set this variable to if the option is found. An optional forth element PUSH
2997 means to push this value onto the list in the variable.")
2999 (defun org-set-regexps-and-options ()
3000 "Precompute regular expressions for current buffer."
3001 (when (org-mode-p)
3002 (org-set-local 'org-todo-kwd-alist nil)
3003 (org-set-local 'org-todo-key-alist nil)
3004 (org-set-local 'org-todo-key-trigger nil)
3005 (org-set-local 'org-todo-keywords-1 nil)
3006 (org-set-local 'org-done-keywords nil)
3007 (org-set-local 'org-todo-heads nil)
3008 (org-set-local 'org-todo-sets nil)
3009 (org-set-local 'org-todo-log-states nil)
3010 (org-set-local 'org-file-properties nil)
3011 (org-set-local 'org-file-tags nil)
3012 (let ((re (org-make-options-regexp
3013 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3014 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3015 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3016 (splitre "[ \t]+")
3017 kwds kws0 kwsa key log value cat arch tags const links hw dws
3018 tail sep kws1 prio props ftags drawers
3019 ext-setup-or-nil setup-contents (start 0))
3020 (save-excursion
3021 (save-restriction
3022 (widen)
3023 (goto-char (point-min))
3024 (while (or (and ext-setup-or-nil
3025 (string-match re ext-setup-or-nil start)
3026 (setq start (match-end 0)))
3027 (and (setq ext-setup-or-nil nil start 0)
3028 (re-search-forward re nil t)))
3029 (setq key (upcase (match-string 1 ext-setup-or-nil))
3030 value (org-match-string-no-properties 2 ext-setup-or-nil))
3031 (cond
3032 ((equal key "CATEGORY")
3033 (if (string-match "[ \t]+$" value)
3034 (setq value (replace-match "" t t value)))
3035 (setq cat value))
3036 ((member key '("SEQ_TODO" "TODO"))
3037 (push (cons 'sequence (org-split-string value splitre)) kwds))
3038 ((equal key "TYP_TODO")
3039 (push (cons 'type (org-split-string value splitre)) kwds))
3040 ((equal key "TAGS")
3041 (setq tags (append tags (org-split-string value splitre))))
3042 ((equal key "COLUMNS")
3043 (org-set-local 'org-columns-default-format value))
3044 ((equal key "LINK")
3045 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3046 (push (cons (match-string 1 value)
3047 (org-trim (match-string 2 value)))
3048 links)))
3049 ((equal key "PRIORITIES")
3050 (setq prio (org-split-string value " +")))
3051 ((equal key "PROPERTY")
3052 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3053 (push (cons (match-string 1 value) (match-string 2 value))
3054 props)))
3055 ((equal key "FILETAGS")
3056 (when (string-match "\\S-" value)
3057 (setq ftags
3058 (append
3059 ftags
3060 (apply 'append
3061 (mapcar (lambda (x) (org-split-string x ":"))
3062 (org-split-string value)))))))
3063 ((equal key "DRAWERS")
3064 (setq drawers (org-split-string value splitre)))
3065 ((equal key "CONSTANTS")
3066 (setq const (append const (org-split-string value splitre))))
3067 ((equal key "STARTUP")
3068 (let ((opts (org-split-string value splitre))
3069 l var val)
3070 (while (setq l (pop opts))
3071 (when (setq l (assoc l org-startup-options))
3072 (setq var (nth 1 l) val (nth 2 l))
3073 (if (not (nth 3 l))
3074 (set (make-local-variable var) val)
3075 (if (not (listp (symbol-value var)))
3076 (set (make-local-variable var) nil))
3077 (set (make-local-variable var) (symbol-value var))
3078 (add-to-list var val))))))
3079 ((equal key "ARCHIVE")
3080 (string-match " *$" value)
3081 (setq arch (replace-match "" t t value))
3082 (remove-text-properties 0 (length arch)
3083 '(face t fontified t) arch))
3084 ((equal key "SETUPFILE")
3085 (setq setup-contents (org-file-contents
3086 (expand-file-name
3087 (org-remove-double-quotes value))
3088 'noerror))
3089 (if (not ext-setup-or-nil)
3090 (setq ext-setup-or-nil setup-contents start 0)
3091 (setq ext-setup-or-nil
3092 (concat (substring ext-setup-or-nil 0 start)
3093 "\n" setup-contents "\n"
3094 (substring ext-setup-or-nil start)))))
3095 ))))
3096 (when cat
3097 (org-set-local 'org-category (intern cat))
3098 (push (cons "CATEGORY" cat) props))
3099 (when prio
3100 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3101 (setq prio (mapcar 'string-to-char prio))
3102 (org-set-local 'org-highest-priority (nth 0 prio))
3103 (org-set-local 'org-lowest-priority (nth 1 prio))
3104 (org-set-local 'org-default-priority (nth 2 prio)))
3105 (and props (org-set-local 'org-file-properties (nreverse props)))
3106 (and ftags (org-set-local 'org-file-tags ftags))
3107 (and drawers (org-set-local 'org-drawers drawers))
3108 (and arch (org-set-local 'org-archive-location arch))
3109 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3110 ;; Process the TODO keywords
3111 (unless kwds
3112 ;; Use the global values as if they had been given locally.
3113 (setq kwds (default-value 'org-todo-keywords))
3114 (if (stringp (car kwds))
3115 (setq kwds (list (cons org-todo-interpretation
3116 (default-value 'org-todo-keywords)))))
3117 (setq kwds (reverse kwds)))
3118 (setq kwds (nreverse kwds))
3119 (let (inter kws kw)
3120 (while (setq kws (pop kwds))
3121 (setq inter (pop kws) sep (member "|" kws)
3122 kws0 (delete "|" (copy-sequence kws))
3123 kwsa nil
3124 kws1 (mapcar
3125 (lambda (x)
3126 ;; 1 2
3127 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3128 (progn
3129 (setq kw (match-string 1 x)
3130 key (and (match-end 2) (match-string 2 x))
3131 log (org-extract-log-state-settings x))
3132 (push (cons kw (and key (string-to-char key))) kwsa)
3133 (and log (push log org-todo-log-states))
3135 (error "Invalid TODO keyword %s" x)))
3136 kws0)
3137 kwsa (if kwsa (append '((:startgroup))
3138 (nreverse kwsa)
3139 '((:endgroup))))
3140 hw (car kws1)
3141 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3142 tail (list inter hw (car dws) (org-last dws)))
3143 (add-to-list 'org-todo-heads hw 'append)
3144 (push kws1 org-todo-sets)
3145 (setq org-done-keywords (append org-done-keywords dws nil))
3146 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3147 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3148 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3149 (setq org-todo-sets (nreverse org-todo-sets)
3150 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3151 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3152 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3153 ;; Process the constants
3154 (when const
3155 (let (e cst)
3156 (while (setq e (pop const))
3157 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3158 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3159 (setq org-table-formula-constants-local cst)))
3161 ;; Process the tags.
3162 (when tags
3163 (let (e tgs)
3164 (while (setq e (pop tags))
3165 (cond
3166 ((equal e "{") (push '(:startgroup) tgs))
3167 ((equal e "}") (push '(:endgroup) tgs))
3168 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3169 (push (cons (match-string 1 e)
3170 (string-to-char (match-string 2 e)))
3171 tgs))
3172 (t (push (list e) tgs))))
3173 (org-set-local 'org-tag-alist nil)
3174 (while (setq e (pop tgs))
3175 (or (and (stringp (car e))
3176 (assoc (car e) org-tag-alist))
3177 (push e org-tag-alist)))))
3179 ;; Compute the regular expressions and other local variables
3180 (if (not org-done-keywords)
3181 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3182 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3183 (length org-scheduled-string)
3184 (length org-clock-string)
3185 (length org-closed-string)))
3186 org-drawer-regexp
3187 (concat "^[ \t]*:\\("
3188 (mapconcat 'regexp-quote org-drawers "\\|")
3189 "\\):[ \t]*$")
3190 org-not-done-keywords
3191 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3192 org-todo-regexp
3193 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3194 "\\|") "\\)\\>")
3195 org-not-done-regexp
3196 (concat "\\<\\("
3197 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3198 "\\)\\>")
3199 org-todo-line-regexp
3200 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3201 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3202 "\\)\\>\\)?[ \t]*\\(.*\\)")
3203 org-complex-heading-regexp
3204 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3205 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3206 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3207 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3208 org-nl-done-regexp
3209 (concat "\n\\*+[ \t]+"
3210 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3211 "\\)" "\\>")
3212 org-todo-line-tags-regexp
3213 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3214 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3215 (org-re
3216 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3217 org-looking-at-done-regexp
3218 (concat "^" "\\(?:"
3219 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3220 "\\>")
3221 org-deadline-regexp (concat "\\<" org-deadline-string)
3222 org-deadline-time-regexp
3223 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3224 org-deadline-line-regexp
3225 (concat "\\<\\(" org-deadline-string "\\).*")
3226 org-scheduled-regexp
3227 (concat "\\<" org-scheduled-string)
3228 org-scheduled-time-regexp
3229 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3230 org-closed-time-regexp
3231 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3232 org-keyword-time-regexp
3233 (concat "\\<\\(" org-scheduled-string
3234 "\\|" org-deadline-string
3235 "\\|" org-closed-string
3236 "\\|" org-clock-string "\\)"
3237 " *[[<]\\([^]>]+\\)[]>]")
3238 org-keyword-time-not-clock-regexp
3239 (concat "\\<\\(" org-scheduled-string
3240 "\\|" org-deadline-string
3241 "\\|" org-closed-string
3242 "\\)"
3243 " *[[<]\\([^]>]+\\)[]>]")
3244 org-maybe-keyword-time-regexp
3245 (concat "\\(\\<\\(" org-scheduled-string
3246 "\\|" org-deadline-string
3247 "\\|" org-closed-string
3248 "\\|" org-clock-string "\\)\\)?"
3249 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3250 org-planning-or-clock-line-re
3251 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3252 "\\|" org-deadline-string
3253 "\\|" org-closed-string "\\|" org-clock-string
3254 "\\)\\>\\)")
3256 (org-compute-latex-and-specials-regexp)
3257 (org-set-font-lock-defaults))))
3259 (defun org-file-contents (file &optional noerror)
3260 "Return the contents of FILE, as a string."
3261 (if (or (not file)
3262 (not (file-readable-p file)))
3263 (if noerror
3264 (progn
3265 (message "Cannot read file %s" file)
3266 (ding) (sit-for 2)
3268 (error "Cannot read file %s" file))
3269 (with-temp-buffer
3270 (insert-file-contents file)
3271 (buffer-string))))
3273 (defun org-extract-log-state-settings (x)
3274 "Extract the log state setting from a TODO keyword string.
3275 This will extract info from a string like \"WAIT(w@/!)\"."
3276 (let (kw key log1 log2)
3277 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3278 (setq kw (match-string 1 x)
3279 key (and (match-end 2) (match-string 2 x))
3280 log1 (and (match-end 3) (match-string 3 x))
3281 log2 (and (match-end 4) (match-string 4 x)))
3282 (and (or log1 log2)
3283 (list kw
3284 (and log1 (if (equal log1 "!") 'time 'note))
3285 (and log2 (if (equal log2 "!") 'time 'note)))))))
3287 (defun org-remove-keyword-keys (list)
3288 "Remove a pair of parenthesis at the end of each string in LIST."
3289 (mapcar (lambda (x)
3290 (if (string-match "(.*)$" x)
3291 (substring x 0 (match-beginning 0))
3293 list))
3295 ;; FIXME: this could be done much better, using second characters etc.
3296 (defun org-assign-fast-keys (alist)
3297 "Assign fast keys to a keyword-key alist.
3298 Respect keys that are already there."
3299 (let (new e k c c1 c2 (char ?a))
3300 (while (setq e (pop alist))
3301 (cond
3302 ((equal e '(:startgroup)) (push e new))
3303 ((equal e '(:endgroup)) (push e new))
3305 (setq k (car e) c2 nil)
3306 (if (cdr e)
3307 (setq c (cdr e))
3308 ;; automatically assign a character.
3309 (setq c1 (string-to-char
3310 (downcase (substring
3311 k (if (= (string-to-char k) ?@) 1 0)))))
3312 (if (or (rassoc c1 new) (rassoc c1 alist))
3313 (while (or (rassoc char new) (rassoc char alist))
3314 (setq char (1+ char)))
3315 (setq c2 c1))
3316 (setq c (or c2 char)))
3317 (push (cons k c) new))))
3318 (nreverse new)))
3320 ;;; Some variables used in various places
3322 (defvar org-window-configuration nil
3323 "Used in various places to store a window configuration.")
3324 (defvar org-finish-function nil
3325 "Function to be called when `C-c C-c' is used.
3326 This is for getting out of special buffers like remember.")
3329 ;; FIXME: Occasionally check by commenting these, to make sure
3330 ;; no other functions uses these, forgetting to let-bind them.
3331 (defvar entry)
3332 (defvar state)
3333 (defvar last-state)
3334 (defvar date)
3335 (defvar description)
3337 ;; Defined somewhere in this file, but used before definition.
3338 (defvar org-html-entities)
3339 (defvar org-struct-menu)
3340 (defvar org-org-menu)
3341 (defvar org-tbl-menu)
3342 (defvar org-agenda-keymap)
3344 ;;;; Define the Org-mode
3346 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3347 (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."))
3350 ;; We use a before-change function to check if a table might need
3351 ;; an update.
3352 (defvar org-table-may-need-update t
3353 "Indicates that a table might need an update.
3354 This variable is set by `org-before-change-function'.
3355 `org-table-align' sets it back to nil.")
3356 (defun org-before-change-function (beg end)
3357 "Every change indicates that a table might need an update."
3358 (setq org-table-may-need-update t))
3359 (defvar org-mode-map)
3360 (defvar org-mode-hook nil)
3361 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3362 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3363 (defvar org-table-buffer-is-an nil)
3364 (defconst org-outline-regexp "\\*+ ")
3366 ;;;###autoload
3367 (define-derived-mode org-mode outline-mode "Org"
3368 "Outline-based notes management and organizer, alias
3369 \"Carsten's outline-mode for keeping track of everything.\"
3371 Org-mode develops organizational tasks around a NOTES file which
3372 contains information about projects as plain text. Org-mode is
3373 implemented on top of outline-mode, which is ideal to keep the content
3374 of large files well structured. It supports ToDo items, deadlines and
3375 time stamps, which magically appear in the diary listing of the Emacs
3376 calendar. Tables are easily created with a built-in table editor.
3377 Plain text URL-like links connect to websites, emails (VM), Usenet
3378 messages (Gnus), BBDB entries, and any files related to the project.
3379 For printing and sharing of notes, an Org-mode file (or a part of it)
3380 can be exported as a structured ASCII or HTML file.
3382 The following commands are available:
3384 \\{org-mode-map}"
3386 ;; Get rid of Outline menus, they are not needed
3387 ;; Need to do this here because define-derived-mode sets up
3388 ;; the keymap so late. Still, it is a waste to call this each time
3389 ;; we switch another buffer into org-mode.
3390 (if (featurep 'xemacs)
3391 (when (boundp 'outline-mode-menu-heading)
3392 ;; Assume this is Greg's port, it used easymenu
3393 (easy-menu-remove outline-mode-menu-heading)
3394 (easy-menu-remove outline-mode-menu-show)
3395 (easy-menu-remove outline-mode-menu-hide))
3396 (define-key org-mode-map [menu-bar headings] 'undefined)
3397 (define-key org-mode-map [menu-bar hide] 'undefined)
3398 (define-key org-mode-map [menu-bar show] 'undefined))
3400 (org-load-modules-maybe)
3401 (easy-menu-add org-org-menu)
3402 (easy-menu-add org-tbl-menu)
3403 (org-install-agenda-files-menu)
3404 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3405 (org-add-to-invisibility-spec '(org-cwidth))
3406 (when (featurep 'xemacs)
3407 (org-set-local 'line-move-ignore-invisible t))
3408 (org-set-local 'outline-regexp org-outline-regexp)
3409 (org-set-local 'outline-level 'org-outline-level)
3410 (when (and org-ellipsis
3411 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3412 (fboundp 'make-glyph-code))
3413 (unless org-display-table
3414 (setq org-display-table (make-display-table)))
3415 (set-display-table-slot
3416 org-display-table 4
3417 (vconcat (mapcar
3418 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3419 org-ellipsis)))
3420 (if (stringp org-ellipsis) org-ellipsis "..."))))
3421 (setq buffer-display-table org-display-table))
3422 (org-set-regexps-and-options)
3423 ;; Calc embedded
3424 (org-set-local 'calc-embedded-open-mode "# ")
3425 (modify-syntax-entry ?# "<")
3426 (modify-syntax-entry ?@ "w")
3427 (if org-startup-truncated (setq truncate-lines t))
3428 (org-set-local 'font-lock-unfontify-region-function
3429 'org-unfontify-region)
3430 ;; Activate before-change-function
3431 (org-set-local 'org-table-may-need-update t)
3432 (org-add-hook 'before-change-functions 'org-before-change-function nil
3433 'local)
3434 ;; Check for running clock before killing a buffer
3435 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3436 ;; Paragraphs and auto-filling
3437 (org-set-autofill-regexps)
3438 (setq indent-line-function 'org-indent-line-function)
3439 (org-update-radio-target-regexp)
3441 ;; Comment characters
3442 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3443 (org-set-local 'comment-padding " ")
3445 ;; Align options lines
3446 (org-set-local
3447 'align-mode-rules-list
3448 '((org-in-buffer-settings
3449 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3450 (modes . '(org-mode)))))
3452 ;; Imenu
3453 (org-set-local 'imenu-create-index-function
3454 'org-imenu-get-tree)
3456 ;; Make isearch reveal context
3457 (if (or (featurep 'xemacs)
3458 (not (boundp 'outline-isearch-open-invisible-function)))
3459 ;; Emacs 21 and XEmacs make use of the hook
3460 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3461 ;; Emacs 22 deals with this through a special variable
3462 (org-set-local 'outline-isearch-open-invisible-function
3463 (lambda (&rest ignore) (org-show-context 'isearch))))
3465 ;; If empty file that did not turn on org-mode automatically, make it to.
3466 (if (and org-insert-mode-line-in-empty-file
3467 (interactive-p)
3468 (= (point-min) (point-max)))
3469 (insert "# -*- mode: org -*-\n\n"))
3471 (unless org-inhibit-startup
3472 (when org-startup-align-all-tables
3473 (let ((bmp (buffer-modified-p)))
3474 (org-table-map-tables 'org-table-align)
3475 (set-buffer-modified-p bmp)))
3476 (org-set-startup-visibility)))
3478 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3480 (defun org-current-time ()
3481 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3482 (if (> (car org-time-stamp-rounding-minutes) 1)
3483 (let ((r (car org-time-stamp-rounding-minutes))
3484 (time (decode-time)))
3485 (apply 'encode-time
3486 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3487 (nthcdr 2 time))))
3488 (current-time)))
3490 ;;;; Font-Lock stuff, including the activators
3492 (defvar org-mouse-map (make-sparse-keymap))
3493 (org-defkey org-mouse-map
3494 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3495 (org-defkey org-mouse-map
3496 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3497 (when org-mouse-1-follows-link
3498 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3499 (when org-tab-follows-link
3500 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3501 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3502 (when org-return-follows-link
3503 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3504 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3506 (require 'font-lock)
3508 (defconst org-non-link-chars "]\t\n\r<>")
3509 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3510 "shell" "elisp"))
3511 (defvar org-link-types-re nil
3512 "Matches a link that has a url-like prefix like \"http:\"")
3513 (defvar org-link-re-with-space nil
3514 "Matches a link with spaces, optional angular brackets around it.")
3515 (defvar org-link-re-with-space2 nil
3516 "Matches a link with spaces, optional angular brackets around it.")
3517 (defvar org-link-re-with-space3 nil
3518 "Matches a link with spaces, only for internal part in bracket links.")
3519 (defvar org-angle-link-re nil
3520 "Matches link with angular brackets, spaces are allowed.")
3521 (defvar org-plain-link-re nil
3522 "Matches plain link, without spaces.")
3523 (defvar org-bracket-link-regexp nil
3524 "Matches a link in double brackets.")
3525 (defvar org-bracket-link-analytic-regexp nil
3526 "Regular expression used to analyze links.
3527 Here is what the match groups contain after a match:
3528 1: http:
3529 2: http
3530 3: path
3531 4: [desc]
3532 5: desc")
3533 (defvar org-any-link-re nil
3534 "Regular expression matching any link.")
3536 (defun org-make-link-regexps ()
3537 "Update the link regular expressions.
3538 This should be called after the variable `org-link-types' has changed."
3539 (setq org-link-types-re
3540 (concat
3541 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3542 org-link-re-with-space
3543 (concat
3544 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3545 "\\([^" org-non-link-chars " ]"
3546 "[^" org-non-link-chars "]*"
3547 "[^" org-non-link-chars " ]\\)>?")
3548 org-link-re-with-space2
3549 (concat
3550 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3551 "\\([^" org-non-link-chars " ]"
3552 "[^\t\n\r]*"
3553 "[^" org-non-link-chars " ]\\)>?")
3554 org-link-re-with-space3
3555 (concat
3556 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3557 "\\([^" org-non-link-chars " ]"
3558 "[^\t\n\r]*\\)")
3559 org-angle-link-re
3560 (concat
3561 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3562 "\\([^" org-non-link-chars " ]"
3563 "[^" org-non-link-chars "]*"
3564 "\\)>")
3565 org-plain-link-re
3566 (concat
3567 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3568 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3569 org-bracket-link-regexp
3570 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3571 org-bracket-link-analytic-regexp
3572 (concat
3573 "\\[\\["
3574 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3575 "\\([^]]+\\)"
3576 "\\]"
3577 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3578 "\\]")
3579 org-any-link-re
3580 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3581 org-angle-link-re "\\)\\|\\("
3582 org-plain-link-re "\\)")))
3584 (org-make-link-regexps)
3586 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3587 "Regular expression for fast time stamp matching.")
3588 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3589 "Regular expression for fast time stamp matching.")
3590 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3591 "Regular expression matching time strings for analysis.
3592 This one does not require the space after the date, so it can be used
3593 on a string that terminates immediately after the date.")
3594 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3595 "Regular expression matching time strings for analysis.")
3596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3597 "Regular expression matching time stamps, with groups.")
3598 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3599 "Regular expression matching time stamps (also [..]), with groups.")
3600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3601 "Regular expression matching a time stamp range.")
3602 (defconst org-tr-regexp-both
3603 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3604 "Regular expression matching a time stamp range.")
3605 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3606 org-ts-regexp "\\)?")
3607 "Regular expression matching a time stamp or time stamp range.")
3608 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3609 org-ts-regexp-both "\\)?")
3610 "Regular expression matching a time stamp or time stamp range.
3611 The time stamps may be either active or inactive.")
3613 (defvar org-emph-face nil)
3615 (defun org-do-emphasis-faces (limit)
3616 "Run through the buffer and add overlays to links."
3617 (let (rtn)
3618 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3619 (if (not (= (char-after (match-beginning 3))
3620 (char-after (match-beginning 4))))
3621 (progn
3622 (setq rtn t)
3623 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3624 'face
3625 (nth 1 (assoc (match-string 3)
3626 org-emphasis-alist)))
3627 (add-text-properties (match-beginning 2) (match-end 2)
3628 '(font-lock-multiline t))
3629 (when org-hide-emphasis-markers
3630 (add-text-properties (match-end 4) (match-beginning 5)
3631 '(invisible org-link))
3632 (add-text-properties (match-beginning 3) (match-end 3)
3633 '(invisible org-link)))))
3634 (backward-char 1))
3635 rtn))
3637 (defun org-emphasize (&optional char)
3638 "Insert or change an emphasis, i.e. a font like bold or italic.
3639 If there is an active region, change that region to a new emphasis.
3640 If there is no region, just insert the marker characters and position
3641 the cursor between them.
3642 CHAR should be either the marker character, or the first character of the
3643 HTML tag associated with that emphasis. If CHAR is a space, the means
3644 to remove the emphasis of the selected region.
3645 If char is not given (for example in an interactive call) it
3646 will be prompted for."
3647 (interactive)
3648 (let ((eal org-emphasis-alist) e det
3649 (erc org-emphasis-regexp-components)
3650 (prompt "")
3651 (string "") beg end move tag c s)
3652 (if (org-region-active-p)
3653 (setq beg (region-beginning) end (region-end)
3654 string (buffer-substring beg end))
3655 (setq move t))
3657 (while (setq e (pop eal))
3658 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3659 c (aref tag 0))
3660 (push (cons c (string-to-char (car e))) det)
3661 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3662 (substring tag 1)))))
3663 (setq det (nreverse det))
3664 (unless char
3665 (message "%s" (concat "Emphasis marker or tag:" prompt))
3666 (setq char (read-char-exclusive)))
3667 (setq char (or (cdr (assoc char det)) char))
3668 (if (equal char ?\ )
3669 (setq s "" move nil)
3670 (unless (assoc (char-to-string char) org-emphasis-alist)
3671 (error "No such emphasis marker: \"%c\"" char))
3672 (setq s (char-to-string char)))
3673 (while (and (> (length string) 1)
3674 (equal (substring string 0 1) (substring string -1))
3675 (assoc (substring string 0 1) org-emphasis-alist))
3676 (setq string (substring string 1 -1)))
3677 (setq string (concat s string s))
3678 (if beg (delete-region beg end))
3679 (unless (or (bolp)
3680 (string-match (concat "[" (nth 0 erc) "\n]")
3681 (char-to-string (char-before (point)))))
3682 (insert " "))
3683 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3684 (char-to-string (char-after (point))))
3685 (insert " ") (backward-char 1))
3686 (insert string)
3687 (and move (backward-char 1))))
3689 (defconst org-nonsticky-props
3690 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3693 (defun org-activate-plain-links (limit)
3694 "Run through the buffer and add overlays to links."
3695 (catch 'exit
3696 (let (f)
3697 (while (re-search-forward org-plain-link-re limit t)
3698 (setq f (get-text-property (match-beginning 0) 'face))
3699 (if (or (eq f 'org-tag)
3700 (and (listp f) (memq 'org-tag f)))
3702 (add-text-properties (match-beginning 0) (match-end 0)
3703 (list 'mouse-face 'highlight
3704 'rear-nonsticky org-nonsticky-props
3705 'keymap org-mouse-map
3707 (throw 'exit t))))))
3709 (defun org-activate-code (limit)
3710 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3711 (progn
3712 (remove-text-properties (match-beginning 0) (match-end 0)
3713 '(display t invisible t intangible t))
3714 t)))
3716 (defun org-activate-angle-links (limit)
3717 "Run through the buffer and add overlays to links."
3718 (if (re-search-forward org-angle-link-re limit t)
3719 (progn
3720 (add-text-properties (match-beginning 0) (match-end 0)
3721 (list 'mouse-face 'highlight
3722 'rear-nonsticky org-nonsticky-props
3723 'keymap org-mouse-map
3725 t)))
3727 (defun org-activate-bracket-links (limit)
3728 "Run through the buffer and add overlays to bracketed links."
3729 (if (re-search-forward org-bracket-link-regexp limit t)
3730 (let* ((help (concat "LINK: "
3731 (org-match-string-no-properties 1)))
3732 ;; FIXME: above we should remove the escapes.
3733 ;; but that requires another match, protecting match data,
3734 ;; a lot of overhead for font-lock.
3735 (ip (org-maybe-intangible
3736 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3737 'keymap org-mouse-map 'mouse-face 'highlight
3738 'font-lock-multiline t 'help-echo help)))
3739 (vp (list 'rear-nonsticky org-nonsticky-props
3740 'keymap org-mouse-map 'mouse-face 'highlight
3741 ' font-lock-multiline t 'help-echo help)))
3742 ;; We need to remove the invisible property here. Table narrowing
3743 ;; may have made some of this invisible.
3744 (remove-text-properties (match-beginning 0) (match-end 0)
3745 '(invisible nil))
3746 (if (match-end 3)
3747 (progn
3748 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3749 (add-text-properties (match-beginning 3) (match-end 3) vp)
3750 (add-text-properties (match-end 3) (match-end 0) ip))
3751 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3752 (add-text-properties (match-beginning 1) (match-end 1) vp)
3753 (add-text-properties (match-end 1) (match-end 0) ip))
3754 t)))
3756 (defun org-activate-dates (limit)
3757 "Run through the buffer and add overlays to dates."
3758 (if (re-search-forward org-tsr-regexp-both limit t)
3759 (progn
3760 (add-text-properties (match-beginning 0) (match-end 0)
3761 (list 'mouse-face 'highlight
3762 'rear-nonsticky org-nonsticky-props
3763 'keymap org-mouse-map))
3764 (when org-display-custom-times
3765 (if (match-end 3)
3766 (org-display-custom-time (match-beginning 3) (match-end 3)))
3767 (org-display-custom-time (match-beginning 1) (match-end 1)))
3768 t)))
3770 (defvar org-target-link-regexp nil
3771 "Regular expression matching radio targets in plain text.")
3772 (make-variable-buffer-local 'org-target-link-regexp)
3773 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3774 "Regular expression matching a link target.")
3775 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3776 "Regular expression matching a radio target.")
3777 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3778 "Regular expression matching any target.")
3780 (defun org-activate-target-links (limit)
3781 "Run through the buffer and add overlays to target matches."
3782 (when org-target-link-regexp
3783 (let ((case-fold-search t))
3784 (if (re-search-forward org-target-link-regexp limit t)
3785 (progn
3786 (add-text-properties (match-beginning 0) (match-end 0)
3787 (list 'mouse-face 'highlight
3788 'rear-nonsticky org-nonsticky-props
3789 'keymap org-mouse-map
3790 'help-echo "Radio target link"
3791 'org-linked-text t))
3792 t)))))
3794 (defun org-update-radio-target-regexp ()
3795 "Find all radio targets in this file and update the regular expression."
3796 (interactive)
3797 (when (memq 'radio org-activate-links)
3798 (setq org-target-link-regexp
3799 (org-make-target-link-regexp (org-all-targets 'radio)))
3800 (org-restart-font-lock)))
3802 (defun org-hide-wide-columns (limit)
3803 (let (s e)
3804 (setq s (text-property-any (point) (or limit (point-max))
3805 'org-cwidth t))
3806 (when s
3807 (setq e (next-single-property-change s 'org-cwidth))
3808 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3809 (goto-char e)
3810 t)))
3812 (defvar org-latex-and-specials-regexp nil
3813 "Regular expression for highlighting export special stuff.")
3814 (defvar org-match-substring-regexp)
3815 (defvar org-match-substring-with-braces-regexp)
3816 (defvar org-export-html-special-string-regexps)
3818 (defun org-compute-latex-and-specials-regexp ()
3819 "Compute regular expression for stuff treated specially by exporters."
3820 (if (not org-highlight-latex-fragments-and-specials)
3821 (org-set-local 'org-latex-and-specials-regexp nil)
3822 (require 'org-exp)
3823 (let*
3824 ((matchers (plist-get org-format-latex-options :matchers))
3825 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3826 org-latex-regexps)))
3827 (options (org-combine-plists (org-default-export-plist)
3828 (org-infile-export-plist)))
3829 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3830 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3831 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3832 (org-export-html-expand (plist-get options :expand-quoted-html))
3833 (org-export-with-special-strings (plist-get options :special-strings))
3834 (re-sub
3835 (cond
3836 ((equal org-export-with-sub-superscripts '{})
3837 (list org-match-substring-with-braces-regexp))
3838 (org-export-with-sub-superscripts
3839 (list org-match-substring-regexp))
3840 (t nil)))
3841 (re-latex
3842 (if org-export-with-LaTeX-fragments
3843 (mapcar (lambda (x) (nth 1 x)) latexs)))
3844 (re-macros
3845 (if org-export-with-TeX-macros
3846 (list (concat "\\\\"
3847 (regexp-opt
3848 (append (mapcar 'car org-html-entities)
3849 (if (boundp 'org-latex-entities)
3850 org-latex-entities nil))
3851 'words))) ; FIXME
3853 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3854 (re-special (if org-export-with-special-strings
3855 (mapcar (lambda (x) (car x))
3856 org-export-html-special-string-regexps)))
3857 (re-rest
3858 (delq nil
3859 (list
3860 (if org-export-html-expand "@<[^>\n]+>")
3861 ))))
3862 (org-set-local
3863 'org-latex-and-specials-regexp
3864 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3865 re-rest) "\\|")))))
3867 (defun org-do-latex-and-special-faces (limit)
3868 "Run through the buffer and add overlays to links."
3869 (when org-latex-and-specials-regexp
3870 (let (rtn d)
3871 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3872 limit t))
3873 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3874 'face))
3875 '(org-code org-verbatim underline)))
3876 (progn
3877 (setq rtn t
3878 d (cond ((member (char-after (1+ (match-beginning 0)))
3879 '(?_ ?^)) 1)
3880 (t 0)))
3881 (font-lock-prepend-text-property
3882 (+ d (match-beginning 0)) (match-end 0)
3883 'face 'org-latex-and-export-specials)
3884 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3885 '(font-lock-multiline t)))))
3886 rtn)))
3888 (defun org-restart-font-lock ()
3889 "Restart font-lock-mode, to force refontification."
3890 (when (and (boundp 'font-lock-mode) font-lock-mode)
3891 (font-lock-mode -1)
3892 (font-lock-mode 1)))
3894 (defun org-all-targets (&optional radio)
3895 "Return a list of all targets in this file.
3896 With optional argument RADIO, only find radio targets."
3897 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3898 rtn)
3899 (save-excursion
3900 (goto-char (point-min))
3901 (while (re-search-forward re nil t)
3902 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3903 rtn)))
3905 (defun org-make-target-link-regexp (targets)
3906 "Make regular expression matching all strings in TARGETS.
3907 The regular expression finds the targets also if there is a line break
3908 between words."
3909 (and targets
3910 (concat
3911 "\\<\\("
3912 (mapconcat
3913 (lambda (x)
3914 (while (string-match " +" x)
3915 (setq x (replace-match "\\s-+" t t x)))
3917 targets
3918 "\\|")
3919 "\\)\\>")))
3921 (defun org-activate-tags (limit)
3922 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3923 (progn
3924 (add-text-properties (match-beginning 1) (match-end 1)
3925 (list 'mouse-face 'highlight
3926 'rear-nonsticky org-nonsticky-props
3927 'keymap org-mouse-map))
3928 t)))
3930 (defun org-outline-level ()
3931 (save-excursion
3932 (looking-at outline-regexp)
3933 (if (match-beginning 1)
3934 (+ (org-get-string-indentation (match-string 1)) 1000)
3935 (1- (- (match-end 0) (match-beginning 0))))))
3937 (defvar org-font-lock-keywords nil)
3939 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3940 "Regular expression matching a property line.")
3942 (defvar org-font-lock-hook nil
3943 "Functions to be called for special font lock stuff.")
3945 (defun org-font-lock-hook (limit)
3946 (run-hook-with-args 'org-font-lock-hook limit))
3948 (defun org-set-font-lock-defaults ()
3949 (let* ((em org-fontify-emphasized-text)
3950 (lk org-activate-links)
3951 (org-font-lock-extra-keywords
3952 (list
3953 ;; Call the hook
3954 '(org-font-lock-hook)
3955 ;; Headlines
3956 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3957 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3958 ;; Table lines
3959 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3960 (1 'org-table t))
3961 ;; Table internals
3962 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3963 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3964 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3965 ;; Drawers
3966 (list org-drawer-regexp '(0 'org-special-keyword t))
3967 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3968 ;; Properties
3969 (list org-property-re
3970 '(1 'org-special-keyword t)
3971 '(3 'org-property-value t))
3972 (if org-format-transports-properties-p
3973 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3974 ;; Links
3975 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3976 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3977 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3978 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3979 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3980 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3981 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3982 '(org-hide-wide-columns (0 nil append))
3983 ;; TODO lines
3984 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3985 '(1 (org-get-todo-face 1) t))
3986 ;; DONE
3987 (if org-fontify-done-headline
3988 (list (concat "^[*]+ +\\<\\("
3989 (mapconcat 'regexp-quote org-done-keywords "\\|")
3990 "\\)\\(.*\\)")
3991 '(2 'org-headline-done t))
3992 nil)
3993 ;; Priorities
3994 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3995 ;; Tags
3996 '(org-font-lock-add-tag-faces)
3997 ;; Special keywords
3998 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3999 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4000 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4001 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4002 ;; Emphasis
4003 (if em
4004 (if (featurep 'xemacs)
4005 '(org-do-emphasis-faces (0 nil append))
4006 '(org-do-emphasis-faces)))
4007 ;; Checkboxes
4008 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4009 2 'bold prepend)
4010 (if org-provide-checkbox-statistics
4011 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4012 (0 (org-get-checkbox-statistics-face) t)))
4013 ;; Description list items
4014 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4015 2 'bold prepend)
4016 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4017 '(1 'org-archived prepend))
4018 ;; Specials
4019 '(org-do-latex-and-special-faces)
4020 ;; Code
4021 '(org-activate-code (1 'org-code t))
4022 ;; COMMENT
4023 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4024 "\\|" org-quote-string "\\)\\>")
4025 '(1 'org-special-keyword t))
4026 '("^#.*" (0 'font-lock-comment-face t))
4028 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4029 ;; Now set the full font-lock-keywords
4030 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4031 (org-set-local 'font-lock-defaults
4032 '(org-font-lock-keywords t nil nil backward-paragraph))
4033 (kill-local-variable 'font-lock-keywords) nil))
4035 (defvar org-m nil)
4036 (defvar org-l nil)
4037 (defvar org-f nil)
4038 (defun org-get-level-face (n)
4039 "Get the right face for match N in font-lock matching of healdines."
4040 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4041 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4042 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4043 (cond
4044 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4045 ((eq n 2) org-f)
4046 (t (if org-level-color-stars-only nil org-f))))
4048 (defun org-get-todo-face (kwd)
4049 "Get the right face for a TODO keyword KWD.
4050 If KWD is a number, get the corresponding match group."
4051 (if (numberp kwd) (setq kwd (match-string kwd)))
4052 (or (cdr (assoc kwd org-todo-keyword-faces))
4053 (and (member kwd org-done-keywords) 'org-done)
4054 'org-todo))
4056 (defun org-font-lock-add-tag-faces (limit)
4057 "Add the special tag faces."
4058 (when (and org-tag-faces org-tags-special-faces-re)
4059 (while (re-search-forward org-tags-special-faces-re limit t)
4060 (add-text-properties (match-beginning 1) (match-end 1)
4061 (list 'face (org-get-tag-face 1)
4062 'font-lock-fontified t))
4063 (backward-char 1))))
4065 (defun org-get-tag-face (kwd)
4066 "Get the right face for a TODO keyword KWD.
4067 If KWD is a number, get the corresponding match group."
4068 (if (numberp kwd) (setq kwd (match-string kwd)))
4069 (or (cdr (assoc kwd org-tag-faces))
4070 'org-tag))
4072 (defun org-unfontify-region (beg end &optional maybe_loudly)
4073 "Remove fontification and activation overlays from links."
4074 (font-lock-default-unfontify-region beg end)
4075 (let* ((buffer-undo-list t)
4076 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4077 (inhibit-modification-hooks t)
4078 deactivate-mark buffer-file-name buffer-file-truename)
4079 (remove-text-properties beg end
4080 '(mouse-face t keymap t org-linked-text t
4081 invisible t intangible t))))
4083 ;;;; Visibility cycling, including org-goto and indirect buffer
4085 ;;; Cycling
4087 (defvar org-cycle-global-status nil)
4088 (make-variable-buffer-local 'org-cycle-global-status)
4089 (defvar org-cycle-subtree-status nil)
4090 (make-variable-buffer-local 'org-cycle-subtree-status)
4092 ;;;###autoload
4093 (defun org-cycle (&optional arg)
4094 "Visibility cycling for Org-mode.
4096 - When this function is called with a prefix argument, rotate the entire
4097 buffer through 3 states (global cycling)
4098 1. OVERVIEW: Show only top-level headlines.
4099 2. CONTENTS: Show all headlines of all levels, but no body text.
4100 3. SHOW ALL: Show everything.
4101 When called with two C-u C-u prefixes, switch to the startup visibility,
4102 determined by the variable `org-startup-folded', and by any VISIBILITY
4103 properties in the buffer.
4104 When called with three C-u C-u C-u prefixed, show the entire buffer,
4105 including drawers.
4107 - When point is at the beginning of a headline, rotate the subtree started
4108 by this line through 3 different states (local cycling)
4109 1. FOLDED: Only the main headline is shown.
4110 2. CHILDREN: The main headline and the direct children are shown.
4111 From this state, you can move to one of the children
4112 and zoom in further.
4113 3. SUBTREE: Show the entire subtree, including body text.
4115 - When there is a numeric prefix, go up to a heading with level ARG, do
4116 a `show-subtree' and return to the previous cursor position. If ARG
4117 is negative, go up that many levels.
4119 - When point is not at the beginning of a headline, execute the global
4120 binding for TAB, which is re-indenting the line. See the option
4121 `org-cycle-emulate-tab' for details.
4123 - Special case: if point is at the beginning of the buffer and there is
4124 no headline in line 1, this function will act as if called with prefix arg.
4125 But only if also the variable `org-cycle-global-at-bob' is t."
4126 (interactive "P")
4127 (org-load-modules-maybe)
4128 (let* ((outline-regexp
4129 (if (and (org-mode-p) org-cycle-include-plain-lists)
4130 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4131 outline-regexp))
4132 (bob-special (and org-cycle-global-at-bob (bobp)
4133 (not (looking-at outline-regexp))))
4134 (org-cycle-hook
4135 (if bob-special
4136 (delq 'org-optimize-window-after-visibility-change
4137 (copy-sequence org-cycle-hook))
4138 org-cycle-hook))
4139 (pos (point)))
4141 (if (or bob-special (equal arg '(4)))
4142 ;; special case: use global cycling
4143 (setq arg t))
4145 (cond
4147 ((equal arg '(16))
4148 (org-set-startup-visibility)
4149 (message "Startup visibility, plus VISIBILITY properties"))
4151 ((equal arg '(64))
4152 (show-all)
4153 (message "Entire buffer visible, including drawers"))
4155 ((org-at-table-p 'any)
4156 ;; Enter the table or move to the next field in the table
4157 (or (org-table-recognize-table.el)
4158 (progn
4159 (if arg (org-table-edit-field t)
4160 (org-table-justify-field-maybe)
4161 (call-interactively 'org-table-next-field)))))
4163 ((eq arg t) ;; Global cycling
4165 (cond
4166 ((and (eq last-command this-command)
4167 (eq org-cycle-global-status 'overview))
4168 ;; We just created the overview - now do table of contents
4169 ;; This can be slow in very large buffers, so indicate action
4170 (message "CONTENTS...")
4171 (org-content)
4172 (message "CONTENTS...done")
4173 (setq org-cycle-global-status 'contents)
4174 (run-hook-with-args 'org-cycle-hook 'contents))
4176 ((and (eq last-command this-command)
4177 (eq org-cycle-global-status 'contents))
4178 ;; We just showed the table of contents - now show everything
4179 (show-all)
4180 (message "SHOW ALL")
4181 (setq org-cycle-global-status 'all)
4182 (run-hook-with-args 'org-cycle-hook 'all))
4185 ;; Default action: go to overview
4186 (org-overview)
4187 (message "OVERVIEW")
4188 (setq org-cycle-global-status 'overview)
4189 (run-hook-with-args 'org-cycle-hook 'overview))))
4191 ((and org-drawers org-drawer-regexp
4192 (save-excursion
4193 (beginning-of-line 1)
4194 (looking-at org-drawer-regexp)))
4195 ;; Toggle block visibility
4196 (org-flag-drawer
4197 (not (get-char-property (match-end 0) 'invisible))))
4199 ((integerp arg)
4200 ;; Show-subtree, ARG levels up from here.
4201 (save-excursion
4202 (org-back-to-heading)
4203 (outline-up-heading (if (< arg 0) (- arg)
4204 (- (funcall outline-level) arg)))
4205 (org-show-subtree)))
4207 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4208 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4209 ;; At a heading: rotate between three different views
4210 (org-back-to-heading)
4211 (let ((goal-column 0) eoh eol eos)
4212 ;; First, some boundaries
4213 (save-excursion
4214 (org-back-to-heading)
4215 (save-excursion
4216 (beginning-of-line 2)
4217 (while (and (not (eobp)) ;; this is like `next-line'
4218 (get-char-property (1- (point)) 'invisible))
4219 (beginning-of-line 2)) (setq eol (point)))
4220 (outline-end-of-heading) (setq eoh (point))
4221 (org-end-of-subtree t)
4222 (unless (eobp)
4223 (skip-chars-forward " \t\n")
4224 (beginning-of-line 1) ; in case this is an item
4226 (setq eos (1- (point))))
4227 ;; Find out what to do next and set `this-command'
4228 (cond
4229 ((= eos eoh)
4230 ;; Nothing is hidden behind this heading
4231 (message "EMPTY ENTRY")
4232 (setq org-cycle-subtree-status nil)
4233 (save-excursion
4234 (goto-char eos)
4235 (outline-next-heading)
4236 (if (org-invisible-p) (org-flag-heading nil))))
4237 ((or (>= eol eos)
4238 (not (string-match "\\S-" (buffer-substring eol eos))))
4239 ;; Entire subtree is hidden in one line: open it
4240 (org-show-entry)
4241 (show-children)
4242 (message "CHILDREN")
4243 (save-excursion
4244 (goto-char eos)
4245 (outline-next-heading)
4246 (if (org-invisible-p) (org-flag-heading nil)))
4247 (setq org-cycle-subtree-status 'children)
4248 (run-hook-with-args 'org-cycle-hook 'children))
4249 ((and (eq last-command this-command)
4250 (eq org-cycle-subtree-status 'children))
4251 ;; We just showed the children, now show everything.
4252 (org-show-subtree)
4253 (message "SUBTREE")
4254 (setq org-cycle-subtree-status 'subtree)
4255 (run-hook-with-args 'org-cycle-hook 'subtree))
4257 ;; Default action: hide the subtree.
4258 (hide-subtree)
4259 (message "FOLDED")
4260 (setq org-cycle-subtree-status 'folded)
4261 (run-hook-with-args 'org-cycle-hook 'folded)))))
4263 ;; TAB emulation and template completion
4264 (buffer-read-only (org-back-to-heading))
4266 ((org-try-structure-completion))
4268 ((org-try-cdlatex-tab))
4270 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4271 (or (not (bolp))
4272 (not (looking-at outline-regexp))))
4273 (call-interactively (global-key-binding "\t")))
4275 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4276 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4277 (or (and (eq org-cycle-emulate-tab 'white)
4278 (= (match-end 0) (point-at-eol)))
4279 (and (eq org-cycle-emulate-tab 'whitestart)
4280 (>= (match-end 0) pos))))
4282 (eq org-cycle-emulate-tab t))
4283 (call-interactively (global-key-binding "\t")))
4285 (t (save-excursion
4286 (org-back-to-heading)
4287 (org-cycle))))))
4289 ;;;###autoload
4290 (defun org-global-cycle (&optional arg)
4291 "Cycle the global visibility. For details see `org-cycle'.
4292 With C-u prefix arg, switch to startup visibility.
4293 With a numeric prefix, show all headlines up to that level."
4294 (interactive "P")
4295 (let ((org-cycle-include-plain-lists
4296 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4297 (cond
4298 ((integerp arg)
4299 (show-all)
4300 (hide-sublevels arg)
4301 (setq org-cycle-global-status 'contents))
4302 ((equal arg '(4))
4303 (org-set-startup-visibility)
4304 (message "Startup visibility, plus VISIBILITY properties."))
4306 (org-cycle '(4))))))
4308 (defun org-set-startup-visibility ()
4309 "Set the visibility required by startup options and properties."
4310 (cond
4311 ((eq org-startup-folded t)
4312 (org-cycle '(4)))
4313 ((eq org-startup-folded 'content)
4314 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4315 (org-cycle '(4)) (org-cycle '(4)))))
4316 (org-set-visibility-according-to-property 'no-cleanup)
4317 (org-cycle-hide-archived-subtrees 'all)
4318 (org-cycle-hide-drawers 'all)
4319 (org-cycle-show-empty-lines 'all))
4321 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4322 "Switch subtree visibilities according to :VISIBILITY: property."
4323 (interactive)
4324 (let (state)
4325 (save-excursion
4326 (goto-char (point-min))
4327 (while (re-search-forward
4328 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4329 nil t)
4330 (setq state (match-string 1))
4331 (save-excursion
4332 (org-back-to-heading t)
4333 (hide-subtree)
4334 (org-reveal)
4335 (cond
4336 ((equal state '("fold" "folded"))
4337 (hide-subtree))
4338 ((equal state "children")
4339 (org-show-hidden-entry)
4340 (show-children))
4341 ((equal state "content")
4342 (save-excursion
4343 (save-restriction
4344 (org-narrow-to-subtree)
4345 (org-content))))
4346 ((member state '("all" "showall"))
4347 (show-subtree)))))
4348 (unless no-cleanup
4349 (org-cycle-hide-archived-subtrees 'all)
4350 (org-cycle-hide-drawers 'all)
4351 (org-cycle-show-empty-lines 'all)))))
4353 (defun org-overview ()
4354 "Switch to overview mode, shoing only top-level headlines.
4355 Really, this shows all headlines with level equal or greater than the level
4356 of the first headline in the buffer. This is important, because if the
4357 first headline is not level one, then (hide-sublevels 1) gives confusing
4358 results."
4359 (interactive)
4360 (let ((level (save-excursion
4361 (goto-char (point-min))
4362 (if (re-search-forward (concat "^" outline-regexp) nil t)
4363 (progn
4364 (goto-char (match-beginning 0))
4365 (funcall outline-level))))))
4366 (and level (hide-sublevels level))))
4368 (defun org-content (&optional arg)
4369 "Show all headlines in the buffer, like a table of contents.
4370 With numerical argument N, show content up to level N."
4371 (interactive "P")
4372 (save-excursion
4373 ;; Visit all headings and show their offspring
4374 (and (integerp arg) (org-overview))
4375 (goto-char (point-max))
4376 (catch 'exit
4377 (while (and (progn (condition-case nil
4378 (outline-previous-visible-heading 1)
4379 (error (goto-char (point-min))))
4381 (looking-at outline-regexp))
4382 (if (integerp arg)
4383 (show-children (1- arg))
4384 (show-branches))
4385 (if (bobp) (throw 'exit nil))))))
4388 (defun org-optimize-window-after-visibility-change (state)
4389 "Adjust the window after a change in outline visibility.
4390 This function is the default value of the hook `org-cycle-hook'."
4391 (when (get-buffer-window (current-buffer))
4392 (cond
4393 ; ((eq state 'overview) (org-first-headline-recenter 1))
4394 ; ((eq state 'overview) (org-beginning-of-line))
4395 ((eq state 'content) nil)
4396 ((eq state 'all) nil)
4397 ((eq state 'folded) nil)
4398 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4399 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4401 (defun org-compact-display-after-subtree-move ()
4402 (let (beg end)
4403 (save-excursion
4404 (if (org-up-heading-safe)
4405 (progn
4406 (hide-subtree)
4407 (show-entry)
4408 (show-children)
4409 (org-cycle-show-empty-lines 'children)
4410 (org-cycle-hide-drawers 'children))
4411 (org-overview)))))
4413 (defun org-cycle-show-empty-lines (state)
4414 "Show empty lines above all visible headlines.
4415 The region to be covered depends on STATE when called through
4416 `org-cycle-hook'. Lisp program can use t for STATE to get the
4417 entire buffer covered. Note that an empty line is only shown if there
4418 are at least `org-cycle-separator-lines' empty lines before the headeline."
4419 (when (> org-cycle-separator-lines 0)
4420 (save-excursion
4421 (let* ((n org-cycle-separator-lines)
4422 (re (cond
4423 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4424 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4425 (t (let ((ns (number-to-string (- n 2))))
4426 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4427 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4428 beg end)
4429 (cond
4430 ((memq state '(overview contents t))
4431 (setq beg (point-min) end (point-max)))
4432 ((memq state '(children folded))
4433 (setq beg (point) end (progn (org-end-of-subtree t t)
4434 (beginning-of-line 2)
4435 (point)))))
4436 (when beg
4437 (goto-char beg)
4438 (while (re-search-forward re end t)
4439 (if (not (get-char-property (match-end 1) 'invisible))
4440 (outline-flag-region
4441 (match-beginning 1) (match-end 1) nil)))))))
4442 ;; Never hide empty lines at the end of the file.
4443 (save-excursion
4444 (goto-char (point-max))
4445 (outline-previous-heading)
4446 (outline-end-of-heading)
4447 (if (and (looking-at "[ \t\n]+")
4448 (= (match-end 0) (point-max)))
4449 (outline-flag-region (point) (match-end 0) nil))))
4451 (defun org-show-empty-lines-in-parent ()
4452 "Move to the parent and re-show empty lines before visible headlines."
4453 (save-excursion
4454 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4455 (org-cycle-show-empty-lines context))))
4457 (defun org-cycle-hide-drawers (state)
4458 "Re-hide all drawers after a visibility state change."
4459 (when (and (org-mode-p)
4460 (not (memq state '(overview folded))))
4461 (save-excursion
4462 (let* ((globalp (memq state '(contents all)))
4463 (beg (if globalp (point-min) (point)))
4464 (end (if globalp (point-max) (org-end-of-subtree t))))
4465 (goto-char beg)
4466 (while (re-search-forward org-drawer-regexp end t)
4467 (org-flag-drawer t))))))
4469 (defun org-flag-drawer (flag)
4470 (save-excursion
4471 (beginning-of-line 1)
4472 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4473 (let ((b (match-end 0))
4474 (outline-regexp org-outline-regexp))
4475 (if (re-search-forward
4476 "^[ \t]*:END:"
4477 (save-excursion (outline-next-heading) (point)) t)
4478 (outline-flag-region b (point-at-eol) flag)
4479 (error ":END: line missing"))))))
4481 (defun org-subtree-end-visible-p ()
4482 "Is the end of the current subtree visible?"
4483 (pos-visible-in-window-p
4484 (save-excursion (org-end-of-subtree t) (point))))
4486 (defun org-first-headline-recenter (&optional N)
4487 "Move cursor to the first headline and recenter the headline.
4488 Optional argument N means, put the headline into the Nth line of the window."
4489 (goto-char (point-min))
4490 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4491 (beginning-of-line)
4492 (recenter (prefix-numeric-value N))))
4494 ;;; Org-goto
4496 (defvar org-goto-window-configuration nil)
4497 (defvar org-goto-marker nil)
4498 (defvar org-goto-map
4499 (let ((map (make-sparse-keymap)))
4500 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4501 (while (setq cmd (pop cmds))
4502 (substitute-key-definition cmd cmd map global-map)))
4503 (suppress-keymap map)
4504 (org-defkey map "\C-m" 'org-goto-ret)
4505 (org-defkey map [(return)] 'org-goto-ret)
4506 (org-defkey map [(left)] 'org-goto-left)
4507 (org-defkey map [(right)] 'org-goto-right)
4508 (org-defkey map [(control ?g)] 'org-goto-quit)
4509 (org-defkey map "\C-i" 'org-cycle)
4510 (org-defkey map [(tab)] 'org-cycle)
4511 (org-defkey map [(down)] 'outline-next-visible-heading)
4512 (org-defkey map [(up)] 'outline-previous-visible-heading)
4513 (if org-goto-auto-isearch
4514 (if (fboundp 'define-key-after)
4515 (define-key-after map [t] 'org-goto-local-auto-isearch)
4516 nil)
4517 (org-defkey map "q" 'org-goto-quit)
4518 (org-defkey map "n" 'outline-next-visible-heading)
4519 (org-defkey map "p" 'outline-previous-visible-heading)
4520 (org-defkey map "f" 'outline-forward-same-level)
4521 (org-defkey map "b" 'outline-backward-same-level)
4522 (org-defkey map "u" 'outline-up-heading))
4523 (org-defkey map "/" 'org-occur)
4524 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4525 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4526 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4527 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4528 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4529 map))
4531 (defconst org-goto-help
4532 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4533 RET=jump to location [Q]uit and return to previous location
4534 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4536 (defvar org-goto-start-pos) ; dynamically scoped parameter
4538 ;; FIXME: Docstring doe not mention both interfaces
4539 (defun org-goto (&optional alternative-interface)
4540 "Look up a different location in the current file, keeping current visibility.
4542 When you want look-up or go to a different location in a document, the
4543 fastest way is often to fold the entire buffer and then dive into the tree.
4544 This method has the disadvantage, that the previous location will be folded,
4545 which may not be what you want.
4547 This command works around this by showing a copy of the current buffer
4548 in an indirect buffer, in overview mode. You can dive into the tree in
4549 that copy, use org-occur and incremental search to find a location.
4550 When pressing RET or `Q', the command returns to the original buffer in
4551 which the visibility is still unchanged. After RET is will also jump to
4552 the location selected in the indirect buffer and expose the
4553 the headline hierarchy above."
4554 (interactive "P")
4555 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4556 (org-refile-use-outline-path t)
4557 (interface
4558 (if (not alternative-interface)
4559 org-goto-interface
4560 (if (eq org-goto-interface 'outline)
4561 'outline-path-completion
4562 'outline)))
4563 (org-goto-start-pos (point))
4564 (selected-point
4565 (if (eq interface 'outline)
4566 (car (org-get-location (current-buffer) org-goto-help))
4567 (nth 3 (org-refile-get-location "Goto: ")))))
4568 (if selected-point
4569 (progn
4570 (org-mark-ring-push org-goto-start-pos)
4571 (goto-char selected-point)
4572 (if (or (org-invisible-p) (org-invisible-p2))
4573 (org-show-context 'org-goto)))
4574 (message "Quit"))))
4576 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4577 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4578 (defvar org-goto-local-auto-isearch-map) ; defined below
4580 (defun org-get-location (buf help)
4581 "Let the user select a location in the Org-mode buffer BUF.
4582 This function uses a recursive edit. It returns the selected position
4583 or nil."
4584 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4585 (isearch-hide-immediately nil)
4586 (isearch-search-fun-function
4587 (lambda () 'org-goto-local-search-headings))
4588 (org-goto-selected-point org-goto-exit-command))
4589 (save-excursion
4590 (save-window-excursion
4591 (delete-other-windows)
4592 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4593 (switch-to-buffer
4594 (condition-case nil
4595 (make-indirect-buffer (current-buffer) "*org-goto*")
4596 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4597 (with-output-to-temp-buffer "*Help*"
4598 (princ help))
4599 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4600 (setq buffer-read-only nil)
4601 (let ((org-startup-truncated t)
4602 (org-startup-folded nil)
4603 (org-startup-align-all-tables nil))
4604 (org-mode)
4605 (org-overview))
4606 (setq buffer-read-only t)
4607 (if (and (boundp 'org-goto-start-pos)
4608 (integer-or-marker-p org-goto-start-pos))
4609 (let ((org-show-hierarchy-above t)
4610 (org-show-siblings t)
4611 (org-show-following-heading t))
4612 (goto-char org-goto-start-pos)
4613 (and (org-invisible-p) (org-show-context)))
4614 (goto-char (point-min)))
4615 (org-beginning-of-line)
4616 (message "Select location and press RET")
4617 (use-local-map org-goto-map)
4618 (recursive-edit)
4620 (kill-buffer "*org-goto*")
4621 (cons org-goto-selected-point org-goto-exit-command)))
4623 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4624 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4625 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4626 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4628 (defun org-goto-local-search-headings (string bound noerror)
4629 "Search and make sure that any matches are in headlines."
4630 (catch 'return
4631 (while (if isearch-forward
4632 (search-forward string bound noerror)
4633 (search-backward string bound noerror))
4634 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4635 (and (member :headline context)
4636 (not (member :tags context))))
4637 (throw 'return (point))))))
4639 (defun org-goto-local-auto-isearch ()
4640 "Start isearch."
4641 (interactive)
4642 (goto-char (point-min))
4643 (let ((keys (this-command-keys)))
4644 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4645 (isearch-mode t)
4646 (isearch-process-search-char (string-to-char keys)))))
4648 (defun org-goto-ret (&optional arg)
4649 "Finish `org-goto' by going to the new location."
4650 (interactive "P")
4651 (setq org-goto-selected-point (point)
4652 org-goto-exit-command 'return)
4653 (throw 'exit nil))
4655 (defun org-goto-left ()
4656 "Finish `org-goto' by going to the new location."
4657 (interactive)
4658 (if (org-on-heading-p)
4659 (progn
4660 (beginning-of-line 1)
4661 (setq org-goto-selected-point (point)
4662 org-goto-exit-command 'left)
4663 (throw 'exit nil))
4664 (error "Not on a heading")))
4666 (defun org-goto-right ()
4667 "Finish `org-goto' by going to the new location."
4668 (interactive)
4669 (if (org-on-heading-p)
4670 (progn
4671 (setq org-goto-selected-point (point)
4672 org-goto-exit-command 'right)
4673 (throw 'exit nil))
4674 (error "Not on a heading")))
4676 (defun org-goto-quit ()
4677 "Finish `org-goto' without cursor motion."
4678 (interactive)
4679 (setq org-goto-selected-point nil)
4680 (setq org-goto-exit-command 'quit)
4681 (throw 'exit nil))
4683 ;;; Indirect buffer display of subtrees
4685 (defvar org-indirect-dedicated-frame nil
4686 "This is the frame being used for indirect tree display.")
4687 (defvar org-last-indirect-buffer nil)
4689 (defun org-tree-to-indirect-buffer (&optional arg)
4690 "Create indirect buffer and narrow it to current subtree.
4691 With numerical prefix ARG, go up to this level and then take that tree.
4692 If ARG is negative, go up that many levels.
4693 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4694 indirect buffer previously made with this command, to avoid proliferation of
4695 indirect buffers. However, when you call the command with a `C-u' prefix, or
4696 when `org-indirect-buffer-display' is `new-frame', the last buffer
4697 is kept so that you can work with several indirect buffers at the same time.
4698 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4699 requests that a new frame be made for the new buffer, so that the dedicated
4700 frame is not changed."
4701 (interactive "P")
4702 (let ((cbuf (current-buffer))
4703 (cwin (selected-window))
4704 (pos (point))
4705 beg end level heading ibuf)
4706 (save-excursion
4707 (org-back-to-heading t)
4708 (when (numberp arg)
4709 (setq level (org-outline-level))
4710 (if (< arg 0) (setq arg (+ level arg)))
4711 (while (> (setq level (org-outline-level)) arg)
4712 (outline-up-heading 1 t)))
4713 (setq beg (point)
4714 heading (org-get-heading))
4715 (org-end-of-subtree t) (setq end (point)))
4716 (if (and (buffer-live-p org-last-indirect-buffer)
4717 (not (eq org-indirect-buffer-display 'new-frame))
4718 (not arg))
4719 (kill-buffer org-last-indirect-buffer))
4720 (setq ibuf (org-get-indirect-buffer cbuf)
4721 org-last-indirect-buffer ibuf)
4722 (cond
4723 ((or (eq org-indirect-buffer-display 'new-frame)
4724 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4725 (select-frame (make-frame))
4726 (delete-other-windows)
4727 (switch-to-buffer ibuf)
4728 (org-set-frame-title heading))
4729 ((eq org-indirect-buffer-display 'dedicated-frame)
4730 (raise-frame
4731 (select-frame (or (and org-indirect-dedicated-frame
4732 (frame-live-p org-indirect-dedicated-frame)
4733 org-indirect-dedicated-frame)
4734 (setq org-indirect-dedicated-frame (make-frame)))))
4735 (delete-other-windows)
4736 (switch-to-buffer ibuf)
4737 (org-set-frame-title (concat "Indirect: " heading)))
4738 ((eq org-indirect-buffer-display 'current-window)
4739 (switch-to-buffer ibuf))
4740 ((eq org-indirect-buffer-display 'other-window)
4741 (pop-to-buffer ibuf))
4742 (t (error "Invalid value.")))
4743 (if (featurep 'xemacs)
4744 (save-excursion (org-mode) (turn-on-font-lock)))
4745 (narrow-to-region beg end)
4746 (show-all)
4747 (goto-char pos)
4748 (and (window-live-p cwin) (select-window cwin))))
4750 (defun org-get-indirect-buffer (&optional buffer)
4751 (setq buffer (or buffer (current-buffer)))
4752 (let ((n 1) (base (buffer-name buffer)) bname)
4753 (while (buffer-live-p
4754 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4755 (setq n (1+ n)))
4756 (condition-case nil
4757 (make-indirect-buffer buffer bname 'clone)
4758 (error (make-indirect-buffer buffer bname)))))
4760 (defun org-set-frame-title (title)
4761 "Set the title of the current frame to the string TITLE."
4762 ;; FIXME: how to name a single frame in XEmacs???
4763 (unless (featurep 'xemacs)
4764 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4766 ;;;; Structure editing
4768 ;;; Inserting headlines
4770 (defun org-insert-heading (&optional force-heading)
4771 "Insert a new heading or item with same depth at point.
4772 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4773 If point is at the beginning of a headline, insert a sibling before the
4774 current headline. If point is not at the beginning, do not split the line,
4775 but create the new headline after the current line."
4776 (interactive "P")
4777 (if (= (buffer-size) 0)
4778 (insert "\n* ")
4779 (when (or force-heading (not (org-insert-item)))
4780 (let* ((head (save-excursion
4781 (condition-case nil
4782 (progn
4783 (org-back-to-heading)
4784 (match-string 0))
4785 (error "*"))))
4786 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4787 pos hide-previous previous-pos)
4788 (cond
4789 ((and (org-on-heading-p) (bolp)
4790 (or (bobp)
4791 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4792 ;; insert before the current line
4793 (open-line (if blank 2 1)))
4794 ((and (bolp)
4795 (or (bobp)
4796 (save-excursion
4797 (backward-char 1) (not (org-invisible-p)))))
4798 ;; insert right here
4799 nil)
4801 ;; somewhere in the line
4802 (save-excursion
4803 (setq previous-pos (point-at-bol))
4804 (end-of-line)
4805 (setq hide-previous (org-invisible-p)))
4806 (and org-insert-heading-respect-content (org-show-subtree))
4807 (let ((split
4808 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4809 (save-excursion
4810 (let ((p (point)))
4811 (goto-char (point-at-bol))
4812 (and (looking-at org-complex-heading-regexp)
4813 (> p (match-beginning 4)))))))
4814 tags pos)
4815 (cond
4816 (org-insert-heading-respect-content
4817 (org-end-of-subtree nil t)
4818 (or (bolp) (newline))
4819 (open-line 1))
4820 ((org-on-heading-p)
4821 (when hide-previous
4822 (show-children)
4823 (org-show-entry))
4824 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4825 (setq tags (and (match-end 2) (match-string 2)))
4826 (and (match-end 1)
4827 (delete-region (match-beginning 1) (match-end 1)))
4828 (setq pos (point-at-bol))
4829 (or split (end-of-line 1))
4830 (delete-horizontal-space)
4831 (newline (if blank 2 1))
4832 (when tags
4833 (save-excursion
4834 (goto-char pos)
4835 (end-of-line 1)
4836 (insert " " tags)
4837 (org-set-tags nil 'align))))
4839 (or split (end-of-line 1))
4840 (newline (if blank 2 1)))))))
4841 (insert head) (just-one-space)
4842 (setq pos (point))
4843 (end-of-line 1)
4844 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4845 (when (and org-insert-heading-respect-content hide-previous)
4846 (save-excursion
4847 (goto-char previous-pos)
4848 (hide-subtree)))
4849 (run-hooks 'org-insert-heading-hook)))))
4851 (defun org-get-heading (&optional no-tags)
4852 "Return the heading of the current entry, without the stars."
4853 (save-excursion
4854 (org-back-to-heading t)
4855 (if (looking-at
4856 (if no-tags
4857 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4858 "\\*+[ \t]+\\([^\r\n]*\\)"))
4859 (match-string 1) "")))
4861 (defun org-insert-heading-after-current ()
4862 "Insert a new heading with same level as current, after current subtree."
4863 (interactive)
4864 (org-back-to-heading)
4865 (org-insert-heading)
4866 (org-move-subtree-down)
4867 (end-of-line 1))
4869 (defun org-insert-heading-respect-content ()
4870 (interactive)
4871 (let ((org-insert-heading-respect-content t))
4872 (org-insert-heading t)))
4874 (defun org-insert-todo-heading-respect-content (&optional force-state)
4875 (interactive "P")
4876 (let ((org-insert-heading-respect-content t))
4877 (org-insert-todo-heading force-state t)))
4879 (defun org-insert-todo-heading (arg &optional force-heading)
4880 "Insert a new heading with the same level and TODO state as current heading.
4881 If the heading has no TODO state, or if the state is DONE, use the first
4882 state (TODO by default). Also with prefix arg, force first state."
4883 (interactive "P")
4884 (when (or force-heading (not (org-insert-item 'checkbox)))
4885 (org-insert-heading force-heading)
4886 (save-excursion
4887 (org-back-to-heading)
4888 (outline-previous-heading)
4889 (looking-at org-todo-line-regexp))
4890 (if (or arg
4891 (not (match-beginning 2))
4892 (member (match-string 2) org-done-keywords))
4893 (insert (car org-todo-keywords-1) " ")
4894 (insert (match-string 2) " "))
4895 (when org-provide-todo-statistics
4896 (org-update-parent-todo-statistics))))
4898 (defun org-insert-subheading (arg)
4899 "Insert a new subheading and demote it.
4900 Works for outline headings and for plain lists alike."
4901 (interactive "P")
4902 (org-insert-heading arg)
4903 (cond
4904 ((org-on-heading-p) (org-do-demote))
4905 ((org-at-item-p) (org-indent-item 1))))
4907 (defun org-insert-todo-subheading (arg)
4908 "Insert a new subheading with TODO keyword or checkbox and demote it.
4909 Works for outline headings and for plain lists alike."
4910 (interactive "P")
4911 (org-insert-todo-heading arg)
4912 (cond
4913 ((org-on-heading-p) (org-do-demote))
4914 ((org-at-item-p) (org-indent-item 1))))
4916 ;;; Promotion and Demotion
4918 (defun org-promote-subtree ()
4919 "Promote the entire subtree.
4920 See also `org-promote'."
4921 (interactive)
4922 (save-excursion
4923 (org-map-tree 'org-promote))
4924 (org-fix-position-after-promote))
4926 (defun org-demote-subtree ()
4927 "Demote the entire subtree. See `org-demote'.
4928 See also `org-promote'."
4929 (interactive)
4930 (save-excursion
4931 (org-map-tree 'org-demote))
4932 (org-fix-position-after-promote))
4935 (defun org-do-promote ()
4936 "Promote the current heading higher up the tree.
4937 If the region is active in `transient-mark-mode', promote all headings
4938 in the region."
4939 (interactive)
4940 (save-excursion
4941 (if (org-region-active-p)
4942 (org-map-region 'org-promote (region-beginning) (region-end))
4943 (org-promote)))
4944 (org-fix-position-after-promote))
4946 (defun org-do-demote ()
4947 "Demote the current heading lower down the tree.
4948 If the region is active in `transient-mark-mode', demote all headings
4949 in the region."
4950 (interactive)
4951 (save-excursion
4952 (if (org-region-active-p)
4953 (org-map-region 'org-demote (region-beginning) (region-end))
4954 (org-demote)))
4955 (org-fix-position-after-promote))
4957 (defun org-fix-position-after-promote ()
4958 "Make sure that after pro/demotion cursor position is right."
4959 (let ((pos (point)))
4960 (when (save-excursion
4961 (beginning-of-line 1)
4962 (looking-at org-todo-line-regexp)
4963 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4964 (cond ((eobp) (insert " "))
4965 ((eolp) (insert " "))
4966 ((equal (char-after) ?\ ) (forward-char 1))))))
4968 (defun org-reduced-level (l)
4969 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4971 (defun org-get-valid-level (level &optional change)
4972 "Rectify a level change under the influence of `org-odd-levels-only'
4973 LEVEL is a current level, CHANGE is by how much the level should be
4974 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4975 even level numbers will become the next higher odd number."
4976 (if org-odd-levels-only
4977 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4978 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4979 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4980 (max 1 (+ level change))))
4982 (if (boundp 'define-obsolete-function-alias)
4983 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4984 (define-obsolete-function-alias 'org-get-legal-level
4985 'org-get-valid-level)
4986 (define-obsolete-function-alias 'org-get-legal-level
4987 'org-get-valid-level "23.1")))
4989 (defun org-promote ()
4990 "Promote the current heading higher up the tree.
4991 If the region is active in `transient-mark-mode', promote all headings
4992 in the region."
4993 (org-back-to-heading t)
4994 (let* ((level (save-match-data (funcall outline-level)))
4995 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4996 (diff (abs (- level (length up-head) -1))))
4997 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4998 (replace-match up-head nil t)
4999 ;; Fixup tag positioning
5000 (and org-auto-align-tags (org-set-tags nil t))
5001 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5003 (defun org-demote ()
5004 "Demote the current heading lower down the tree.
5005 If the region is active in `transient-mark-mode', demote all headings
5006 in the region."
5007 (org-back-to-heading t)
5008 (let* ((level (save-match-data (funcall outline-level)))
5009 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5010 (diff (abs (- level (length down-head) -1))))
5011 (replace-match down-head nil t)
5012 ;; Fixup tag positioning
5013 (and org-auto-align-tags (org-set-tags nil t))
5014 (if org-adapt-indentation (org-fixup-indentation diff))))
5016 (defun org-map-tree (fun)
5017 "Call FUN for every heading underneath the current one."
5018 (org-back-to-heading)
5019 (let ((level (funcall outline-level)))
5020 (save-excursion
5021 (funcall fun)
5022 (while (and (progn
5023 (outline-next-heading)
5024 (> (funcall outline-level) level))
5025 (not (eobp)))
5026 (funcall fun)))))
5028 (defun org-map-region (fun beg end)
5029 "Call FUN for every heading between BEG and END."
5030 (let ((org-ignore-region t))
5031 (save-excursion
5032 (setq end (copy-marker end))
5033 (goto-char beg)
5034 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5035 (< (point) end))
5036 (funcall fun))
5037 (while (and (progn
5038 (outline-next-heading)
5039 (< (point) end))
5040 (not (eobp)))
5041 (funcall fun)))))
5043 (defun org-fixup-indentation (diff)
5044 "Change the indentation in the current entry by DIFF
5045 However, if any line in the current entry has no indentation, or if it
5046 would end up with no indentation after the change, nothing at all is done."
5047 (save-excursion
5048 (let ((end (save-excursion (outline-next-heading)
5049 (point-marker)))
5050 (prohibit (if (> diff 0)
5051 "^\\S-"
5052 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5053 col)
5054 (unless (save-excursion (end-of-line 1)
5055 (re-search-forward prohibit end t))
5056 (while (and (< (point) end)
5057 (re-search-forward "^[ \t]+" end t))
5058 (goto-char (match-end 0))
5059 (setq col (current-column))
5060 (if (< diff 0) (replace-match ""))
5061 (org-indent-to-column (+ diff col))))
5062 (move-marker end nil))))
5064 (defun org-convert-to-odd-levels ()
5065 "Convert an org-mode file with all levels allowed to one with odd levels.
5066 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5067 level 5 etc."
5068 (interactive)
5069 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5070 (let ((org-odd-levels-only nil) n)
5071 (save-excursion
5072 (goto-char (point-min))
5073 (while (re-search-forward "^\\*\\*+ " nil t)
5074 (setq n (- (length (match-string 0)) 2))
5075 (while (>= (setq n (1- n)) 0)
5076 (org-demote))
5077 (end-of-line 1))))))
5080 (defun org-convert-to-oddeven-levels ()
5081 "Convert an org-mode file with only odd levels to one with odd and even levels.
5082 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5083 section with an even level, conversion would destroy the structure of the file. An error
5084 is signaled in this case."
5085 (interactive)
5086 (goto-char (point-min))
5087 ;; First check if there are no even levels
5088 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5089 (org-show-context t)
5090 (error "Not all levels are odd in this file. Conversion not possible."))
5091 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5092 (let ((org-odd-levels-only nil) n)
5093 (save-excursion
5094 (goto-char (point-min))
5095 (while (re-search-forward "^\\*\\*+ " nil t)
5096 (setq n (/ (1- (length (match-string 0))) 2))
5097 (while (>= (setq n (1- n)) 0)
5098 (org-promote))
5099 (end-of-line 1))))))
5101 (defun org-tr-level (n)
5102 "Make N odd if required."
5103 (if org-odd-levels-only (1+ (/ n 2)) n))
5105 ;;; Vertical tree motion, cutting and pasting of subtrees
5107 (defun org-move-subtree-up (&optional arg)
5108 "Move the current subtree up past ARG headlines of the same level."
5109 (interactive "p")
5110 (org-move-subtree-down (- (prefix-numeric-value arg))))
5112 (defun org-move-subtree-down (&optional arg)
5113 "Move the current subtree down past ARG headlines of the same level."
5114 (interactive "p")
5115 (setq arg (prefix-numeric-value arg))
5116 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5117 'outline-get-last-sibling))
5118 (ins-point (make-marker))
5119 (cnt (abs arg))
5120 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5121 ;; Select the tree
5122 (org-back-to-heading)
5123 (setq beg0 (point))
5124 (save-excursion
5125 (setq ne-beg (org-back-over-empty-lines))
5126 (setq beg (point)))
5127 (save-match-data
5128 (save-excursion (outline-end-of-heading)
5129 (setq folded (org-invisible-p)))
5130 (outline-end-of-subtree))
5131 (outline-next-heading)
5132 (setq ne-end (org-back-over-empty-lines))
5133 (setq end (point))
5134 (goto-char beg0)
5135 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5136 ;; include less whitespace
5137 (save-excursion
5138 (goto-char beg)
5139 (forward-line (- ne-beg ne-end))
5140 (setq beg (point))))
5141 ;; Find insertion point, with error handling
5142 (while (> cnt 0)
5143 (or (and (funcall movfunc) (looking-at outline-regexp))
5144 (progn (goto-char beg0)
5145 (error "Cannot move past superior level or buffer limit")))
5146 (setq cnt (1- cnt)))
5147 (if (> arg 0)
5148 ;; Moving forward - still need to move over subtree
5149 (progn (org-end-of-subtree t t)
5150 (save-excursion
5151 (org-back-over-empty-lines)
5152 (or (bolp) (newline)))))
5153 (setq ne-ins (org-back-over-empty-lines))
5154 (move-marker ins-point (point))
5155 (setq txt (buffer-substring beg end))
5156 (org-save-markers-in-region beg end)
5157 (delete-region beg end)
5158 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5159 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5160 (let ((bbb (point)))
5161 (insert-before-markers txt)
5162 (org-reinstall-markers-in-region bbb)
5163 (move-marker ins-point bbb))
5164 (or (bolp) (insert "\n"))
5165 (setq ins-end (point))
5166 (goto-char ins-point)
5167 (org-skip-whitespace)
5168 (when (and (< arg 0)
5169 (org-first-sibling-p)
5170 (> ne-ins ne-beg))
5171 ;; Move whitespace back to beginning
5172 (save-excursion
5173 (goto-char ins-end)
5174 (let ((kill-whole-line t))
5175 (kill-line (- ne-ins ne-beg)) (point)))
5176 (insert (make-string (- ne-ins ne-beg) ?\n)))
5177 (move-marker ins-point nil)
5178 (org-compact-display-after-subtree-move)
5179 (org-show-empty-lines-in-parent)
5180 (unless folded
5181 (org-show-entry)
5182 (show-children)
5183 (org-cycle-hide-drawers 'children))))
5185 (defvar org-subtree-clip ""
5186 "Clipboard for cut and paste of subtrees.
5187 This is actually only a copy of the kill, because we use the normal kill
5188 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5190 (defvar org-subtree-clip-folded nil
5191 "Was the last copied subtree folded?
5192 This is used to fold the tree back after pasting.")
5194 (defun org-cut-subtree (&optional n)
5195 "Cut the current subtree into the clipboard.
5196 With prefix arg N, cut this many sequential subtrees.
5197 This is a short-hand for marking the subtree and then cutting it."
5198 (interactive "p")
5199 (org-copy-subtree n 'cut))
5201 (defun org-copy-subtree (&optional n cut force-store-markers)
5202 "Cut the current subtree into the clipboard.
5203 With prefix arg N, cut this many sequential subtrees.
5204 This is a short-hand for marking the subtree and then copying it.
5205 If CUT is non-nil, actually cut the subtree.
5206 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5207 of some markers in the region, even if CUT is non-nil. This is
5208 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5209 (interactive "p")
5210 (let (beg end folded (beg0 (point)))
5211 (if (interactive-p)
5212 (org-back-to-heading nil) ; take what looks like a subtree
5213 (org-back-to-heading t)) ; take what is really there
5214 (org-back-over-empty-lines)
5215 (setq beg (point))
5216 (skip-chars-forward " \t\r\n")
5217 (save-match-data
5218 (save-excursion (outline-end-of-heading)
5219 (setq folded (org-invisible-p)))
5220 (condition-case nil
5221 (outline-forward-same-level (1- n))
5222 (error nil))
5223 (org-end-of-subtree t t))
5224 (org-back-over-empty-lines)
5225 (setq end (point))
5226 (goto-char beg0)
5227 (when (> end beg)
5228 (setq org-subtree-clip-folded folded)
5229 (when (or cut force-store-markers)
5230 (org-save-markers-in-region beg end))
5231 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5232 (setq org-subtree-clip (current-kill 0))
5233 (message "%s: Subtree(s) with %d characters"
5234 (if cut "Cut" "Copied")
5235 (length org-subtree-clip)))))
5237 (defun org-paste-subtree (&optional level tree for-yank)
5238 "Paste the clipboard as a subtree, with modification of headline level.
5239 The entire subtree is promoted or demoted in order to match a new headline
5240 level.
5242 If the cursor is at the beginning of a headline, the same level as
5243 that headline is used to paste the tree
5245 If not, the new level is derived from the *visible* headings
5246 before and after the insertion point, and taken to be the inferior headline
5247 level of the two. So if the previous visible heading is level 3 and the
5248 next is level 4 (or vice versa), level 4 will be used for insertion.
5249 This makes sure that the subtree remains an independent subtree and does
5250 not swallow low level entries.
5252 You can also force a different level, either by using a numeric prefix
5253 argument, or by inserting the heading marker by hand. For example, if the
5254 cursor is after \"*****\", then the tree will be shifted to level 5.
5256 If optional TREE is given, use this text instead of the kill ring.
5258 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5259 move back over whitespace before inserting, and move point to the end of
5260 the inserted text when done."
5261 (interactive "P")
5262 (unless (org-kill-is-subtree-p tree)
5263 (error "%s"
5264 (substitute-command-keys
5265 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5266 (let* ((visp (not (org-invisible-p)))
5267 (txt (or tree (and kill-ring (current-kill 0))))
5268 (^re (concat "^\\(" outline-regexp "\\)"))
5269 (re (concat "\\(" outline-regexp "\\)"))
5270 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5272 (old-level (if (string-match ^re txt)
5273 (- (match-end 0) (match-beginning 0) 1)
5274 -1))
5275 (force-level (cond (level (prefix-numeric-value level))
5276 ((and (looking-at "[ \t]*$")
5277 (string-match
5278 ^re_ (buffer-substring
5279 (point-at-bol) (point))))
5280 (- (match-end 1) (match-beginning 1)))
5281 ((and (bolp)
5282 (looking-at org-outline-regexp))
5283 (- (match-end 0) (point) 1))
5284 (t nil)))
5285 (previous-level (save-excursion
5286 (condition-case nil
5287 (progn
5288 (outline-previous-visible-heading 1)
5289 (if (looking-at re)
5290 (- (match-end 0) (match-beginning 0) 1)
5292 (error 1))))
5293 (next-level (save-excursion
5294 (condition-case nil
5295 (progn
5296 (or (looking-at outline-regexp)
5297 (outline-next-visible-heading 1))
5298 (if (looking-at re)
5299 (- (match-end 0) (match-beginning 0) 1)
5301 (error 1))))
5302 (new-level (or force-level (max previous-level next-level)))
5303 (shift (if (or (= old-level -1)
5304 (= new-level -1)
5305 (= old-level new-level))
5307 (- new-level old-level)))
5308 (delta (if (> shift 0) -1 1))
5309 (func (if (> shift 0) 'org-demote 'org-promote))
5310 (org-odd-levels-only nil)
5311 beg end newend)
5312 ;; Remove the forced level indicator
5313 (if force-level
5314 (delete-region (point-at-bol) (point)))
5315 ;; Paste
5316 (beginning-of-line 1)
5317 (unless for-yank (org-back-over-empty-lines))
5318 (setq beg (point))
5319 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5320 (insert-before-markers txt)
5321 (unless (string-match "\n\\'" txt) (insert "\n"))
5322 (setq newend (point))
5323 (org-reinstall-markers-in-region beg)
5324 (setq end (point))
5325 (goto-char beg)
5326 (skip-chars-forward " \t\n\r")
5327 (setq beg (point))
5328 (if (and (org-invisible-p) visp)
5329 (save-excursion (outline-show-heading)))
5330 ;; Shift if necessary
5331 (unless (= shift 0)
5332 (save-restriction
5333 (narrow-to-region beg end)
5334 (while (not (= shift 0))
5335 (org-map-region func (point-min) (point-max))
5336 (setq shift (+ delta shift)))
5337 (goto-char (point-min))
5338 (setq newend (point-max))))
5339 (when (or (interactive-p) for-yank)
5340 (message "Clipboard pasted as level %d subtree" new-level))
5341 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5342 kill-ring
5343 (eq org-subtree-clip (current-kill 0))
5344 org-subtree-clip-folded)
5345 ;; The tree was folded before it was killed/copied
5346 (hide-subtree))
5347 (and for-yank (goto-char newend))))
5349 (defun org-kill-is-subtree-p (&optional txt)
5350 "Check if the current kill is an outline subtree, or a set of trees.
5351 Returns nil if kill does not start with a headline, or if the first
5352 headline level is not the largest headline level in the tree.
5353 So this will actually accept several entries of equal levels as well,
5354 which is OK for `org-paste-subtree'.
5355 If optional TXT is given, check this string instead of the current kill."
5356 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5357 (start-level (and kill
5358 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5359 org-outline-regexp "\\)")
5360 kill)
5361 (- (match-end 2) (match-beginning 2) 1)))
5362 (re (concat "^" org-outline-regexp))
5363 (start (1+ (or (match-beginning 2) -1))))
5364 (if (not start-level)
5365 (progn
5366 nil) ;; does not even start with a heading
5367 (catch 'exit
5368 (while (setq start (string-match re kill (1+ start)))
5369 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5370 (throw 'exit nil)))
5371 t))))
5373 (defvar org-markers-to-move nil
5374 "Markers that should be moved with a cut-and-paste operation.
5375 Those markers are stored together with their positions relative to
5376 the start of the region.")
5378 (defun org-save-markers-in-region (beg end)
5379 "Check markers in region.
5380 If these markers are between BEG and END, record their position relative
5381 to BEG, so that after moving the block of text, we can put the markers back
5382 into place.
5383 This function gets called just before an entry or tree gets cut from the
5384 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5385 called immediately, to move the markers with the entries."
5386 (setq org-markers-to-move nil)
5387 (when (featurep 'org-clock)
5388 (org-clock-save-markers-for-cut-and-paste beg end))
5389 (when (featurep 'org-agenda)
5390 (org-agenda-save-markers-for-cut-and-paste beg end)))
5392 (defun org-check-and-save-marker (marker beg end)
5393 "Check if MARKER is between BEG and END.
5394 If yes, remember the marker and the distance to BEG."
5395 (when (and (marker-buffer marker)
5396 (equal (marker-buffer marker) (current-buffer)))
5397 (if (and (>= marker beg) (< marker end))
5398 (push (cons marker (- marker beg)) org-markers-to-move))))
5400 (defun org-reinstall-markers-in-region (beg)
5401 "Move all remembered markers to their position relative to BEG."
5402 (mapc (lambda (x)
5403 (move-marker (car x) (+ beg (cdr x))))
5404 org-markers-to-move)
5405 (setq org-markers-to-move nil))
5407 (defun org-narrow-to-subtree ()
5408 "Narrow buffer to the current subtree."
5409 (interactive)
5410 (save-excursion
5411 (save-match-data
5412 (narrow-to-region
5413 (progn (org-back-to-heading) (point))
5414 (progn (org-end-of-subtree t) (point))))))
5417 ;;; Outline Sorting
5419 (defun org-sort (with-case)
5420 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5421 Optional argument WITH-CASE means sort case-sensitively."
5422 (interactive "P")
5423 (if (org-at-table-p)
5424 (org-call-with-arg 'org-table-sort-lines with-case)
5425 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5427 (defun org-sort-remove-invisible (s)
5428 (remove-text-properties 0 (length s) org-rm-props s)
5429 (while (string-match org-bracket-link-regexp s)
5430 (setq s (replace-match (if (match-end 2)
5431 (match-string 3 s)
5432 (match-string 1 s)) t t s)))
5435 (defvar org-priority-regexp) ; defined later in the file
5437 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5438 "Sort entries on a certain level of an outline tree.
5439 If there is an active region, the entries in the region are sorted.
5440 Else, if the cursor is before the first entry, sort the top-level items.
5441 Else, the children of the entry at point are sorted.
5443 Sorting can be alphabetically, numerically, and by date/time as given by
5444 the first time stamp in the entry. The command prompts for the sorting
5445 type unless it has been given to the function through the SORTING-TYPE
5446 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5447 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5448 called with point at the beginning of the record. It must return either
5449 a string or a number that should serve as the sorting key for that record.
5451 Comparing entries ignores case by default. However, with an optional argument
5452 WITH-CASE, the sorting considers case as well."
5453 (interactive "P")
5454 (let ((case-func (if with-case 'identity 'downcase))
5455 start beg end stars re re2
5456 txt what tmp plain-list-p)
5457 ;; Find beginning and end of region to sort
5458 (cond
5459 ((org-region-active-p)
5460 ;; we will sort the region
5461 (setq end (region-end)
5462 what "region")
5463 (goto-char (region-beginning))
5464 (if (not (org-on-heading-p)) (outline-next-heading))
5465 (setq start (point)))
5466 ((org-at-item-p)
5467 ;; we will sort this plain list
5468 (org-beginning-of-item-list) (setq start (point))
5469 (org-end-of-item-list) (setq end (point))
5470 (goto-char start)
5471 (setq plain-list-p t
5472 what "plain list"))
5473 ((or (org-on-heading-p)
5474 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5475 ;; we will sort the children of the current headline
5476 (org-back-to-heading)
5477 (setq start (point)
5478 end (progn (org-end-of-subtree t t)
5479 (org-back-over-empty-lines)
5480 (point))
5481 what "children")
5482 (goto-char start)
5483 (show-subtree)
5484 (outline-next-heading))
5486 ;; we will sort the top-level entries in this file
5487 (goto-char (point-min))
5488 (or (org-on-heading-p) (outline-next-heading))
5489 (setq start (point) end (point-max) what "top-level")
5490 (goto-char start)
5491 (show-all)))
5493 (setq beg (point))
5494 (if (>= beg end) (error "Nothing to sort"))
5496 (unless plain-list-p
5497 (looking-at "\\(\\*+\\)")
5498 (setq stars (match-string 1)
5499 re (concat "^" (regexp-quote stars) " +")
5500 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5501 txt (buffer-substring beg end))
5502 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5503 (if (and (not (equal stars "*")) (string-match re2 txt))
5504 (error "Region to sort contains a level above the first entry")))
5506 (unless sorting-type
5507 (message
5508 (if plain-list-p
5509 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5510 "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:")
5511 what)
5512 (setq sorting-type (read-char-exclusive))
5514 (and (= (downcase sorting-type) ?f)
5515 (setq getkey-func
5516 (org-ido-completing-read "Sort using function: "
5517 obarray 'fboundp t nil nil))
5518 (setq getkey-func (intern getkey-func)))
5520 (and (= (downcase sorting-type) ?r)
5521 (setq property
5522 (org-ido-completing-read "Property: "
5523 (mapcar 'list (org-buffer-property-keys t))
5524 nil t))))
5526 (message "Sorting entries...")
5528 (save-restriction
5529 (narrow-to-region start end)
5531 (let ((dcst (downcase sorting-type))
5532 (now (current-time)))
5533 (sort-subr
5534 (/= dcst sorting-type)
5535 ;; This function moves to the beginning character of the "record" to
5536 ;; be sorted.
5537 (if plain-list-p
5538 (lambda nil
5539 (if (org-at-item-p) t (goto-char (point-max))))
5540 (lambda nil
5541 (if (re-search-forward re nil t)
5542 (goto-char (match-beginning 0))
5543 (goto-char (point-max)))))
5544 ;; This function moves to the last character of the "record" being
5545 ;; sorted.
5546 (if plain-list-p
5547 'org-end-of-item
5548 (lambda nil
5549 (save-match-data
5550 (condition-case nil
5551 (outline-forward-same-level 1)
5552 (error
5553 (goto-char (point-max)))))))
5555 ;; This function returns the value that gets sorted against.
5556 (if plain-list-p
5557 (lambda nil
5558 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5559 (cond
5560 ((= dcst ?n)
5561 (string-to-number (buffer-substring (match-end 0)
5562 (point-at-eol))))
5563 ((= dcst ?a)
5564 (buffer-substring (match-end 0) (point-at-eol)))
5565 ((= dcst ?t)
5566 (if (re-search-forward org-ts-regexp
5567 (point-at-eol) t)
5568 (org-time-string-to-time (match-string 0))
5569 now))
5570 ((= dcst ?f)
5571 (if getkey-func
5572 (progn
5573 (setq tmp (funcall getkey-func))
5574 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5575 tmp)
5576 (error "Invalid key function `%s'" getkey-func)))
5577 (t (error "Invalid sorting type `%c'" sorting-type)))))
5578 (lambda nil
5579 (cond
5580 ((= dcst ?n)
5581 (if (looking-at org-complex-heading-regexp)
5582 (string-to-number (match-string 4))
5583 nil))
5584 ((= dcst ?a)
5585 (if (looking-at org-complex-heading-regexp)
5586 (funcall case-func (match-string 4))
5587 nil))
5588 ((= dcst ?t)
5589 (if (re-search-forward org-ts-regexp
5590 (save-excursion
5591 (forward-line 2)
5592 (point)) t)
5593 (org-time-string-to-time (match-string 0))
5594 now))
5595 ((= dcst ?p)
5596 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5597 (string-to-char (match-string 2))
5598 org-default-priority))
5599 ((= dcst ?r)
5600 (or (org-entry-get nil property) ""))
5601 ((= dcst ?o)
5602 (if (looking-at org-complex-heading-regexp)
5603 (- 9999 (length (member (match-string 2)
5604 org-todo-keywords-1)))))
5605 ((= dcst ?f)
5606 (if getkey-func
5607 (progn
5608 (setq tmp (funcall getkey-func))
5609 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5610 tmp)
5611 (error "Invalid key function `%s'" getkey-func)))
5612 (t (error "Invalid sorting type `%c'" sorting-type)))))
5614 (cond
5615 ((= dcst ?a) 'string<)
5616 ((= dcst ?t) 'time-less-p)
5617 (t nil)))))
5618 (message "Sorting entries...done")))
5620 (defun org-do-sort (table what &optional with-case sorting-type)
5621 "Sort TABLE of WHAT according to SORTING-TYPE.
5622 The user will be prompted for the SORTING-TYPE if the call to this
5623 function does not specify it. WHAT is only for the prompt, to indicate
5624 what is being sorted. The sorting key will be extracted from
5625 the car of the elements of the table.
5626 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5627 (unless sorting-type
5628 (message
5629 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5630 what)
5631 (setq sorting-type (read-char-exclusive)))
5632 (let ((dcst (downcase sorting-type))
5633 extractfun comparefun)
5634 ;; Define the appropriate functions
5635 (cond
5636 ((= dcst ?n)
5637 (setq extractfun 'string-to-number
5638 comparefun (if (= dcst sorting-type) '< '>)))
5639 ((= dcst ?a)
5640 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5641 (lambda(x) (downcase (org-sort-remove-invisible x))))
5642 comparefun (if (= dcst sorting-type)
5643 'string<
5644 (lambda (a b) (and (not (string< a b))
5645 (not (string= a b)))))))
5646 ((= dcst ?t)
5647 (setq extractfun
5648 (lambda (x)
5649 (if (string-match org-ts-regexp x)
5650 (time-to-seconds
5651 (org-time-string-to-time (match-string 0 x)))
5653 comparefun (if (= dcst sorting-type) '< '>)))
5654 (t (error "Invalid sorting type `%c'" sorting-type)))
5656 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5657 table)
5658 (lambda (a b) (funcall comparefun (car a) (car b))))))
5660 ;;; Editing source examples
5662 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5663 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5664 (defvar org-edit-src-force-single-line nil)
5665 (defvar org-edit-src-from-org-mode nil)
5666 (defvar org-edit-src-picture nil)
5668 (define-minor-mode org-exit-edit-mode
5669 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5671 (defun org-edit-src-code ()
5672 "Edit the source code example at point.
5673 An indirect buffer is created, and that buffer is then narrowed to the
5674 example at point and switched to the correct language mode. When done,
5675 exit by killing the buffer with \\[org-edit-src-exit]."
5676 (interactive)
5677 (let ((line (org-current-line))
5678 (case-fold-search t)
5679 (msg (substitute-command-keys
5680 "Edit, then exit with C-c ' (C-c and single quote)"))
5681 (info (org-edit-src-find-region-and-lang))
5682 (org-mode-p (eq major-mode 'org-mode))
5683 beg end lang lang-f single)
5684 (if (not info)
5686 (setq beg (nth 0 info)
5687 end (nth 1 info)
5688 lang (nth 2 info)
5689 single (nth 3 info)
5690 lang-f (intern (concat lang "-mode")))
5691 (unless (functionp lang-f)
5692 (error "No such language mode: %s" lang-f))
5693 (goto-line line)
5694 (if (get-buffer "*Org Edit Src Example*")
5695 (kill-buffer "*Org Edit Src Example*"))
5696 (switch-to-buffer (make-indirect-buffer (current-buffer)
5697 "*Org Edit Src Example*"))
5698 (narrow-to-region beg end)
5699 (remove-text-properties beg end '(display nil invisible nil
5700 intangible nil))
5701 (let ((org-inhibit-startup t))
5702 (funcall lang-f))
5703 (set (make-local-variable 'org-edit-src-force-single-line) single)
5704 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5705 (when org-mode-p
5706 (goto-char (point-min))
5707 (while (re-search-forward "^," nil t)
5708 (replace-match "")))
5709 (goto-line line)
5710 (org-exit-edit-mode)
5711 (org-set-local 'header-line-format msg)
5712 (message "%s" msg)
5713 t)))
5715 (defun org-edit-fixed-width-region ()
5716 "Edit the fixed-width ascii drawing at point.
5717 This must be a region where each line starts with ca colon followed by
5718 a space character.
5719 An indirect buffer is created, and that buffer is then narrowed to the
5720 example at point and switched to artist-mode. When done,
5721 exit by killing the buffer with \\[org-edit-src-exit]."
5722 (interactive)
5723 (let ((line (org-current-line))
5724 (case-fold-search t)
5725 (msg (substitute-command-keys
5726 "Edit, then exit with C-c ' (C-c and single quote)"))
5727 (org-mode-p (eq major-mode 'org-mode))
5728 beg end lang lang-f)
5729 (beginning-of-line 1)
5730 (if (looking-at "[ \t]*[^:\n \t]")
5732 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5733 (setq beg (point) end beg)
5734 (save-excursion
5735 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5736 (setq beg (point-at-bol 2))
5737 (setq beg (point))))
5738 (save-excursion
5739 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5740 (setq end (1- (match-beginning 0)))
5741 (setq end (point))))
5742 (goto-line line))
5743 (if (get-buffer "*Org Edit Picture*")
5744 (kill-buffer "*Org Edit Picture*"))
5745 (switch-to-buffer (make-indirect-buffer (current-buffer)
5746 "*Org Edit Picture*"))
5747 (narrow-to-region beg end)
5748 (remove-text-properties beg end '(display nil invisible nil
5749 intangible nil))
5750 (when (fboundp 'font-lock-unfontify-region)
5751 (font-lock-unfontify-region (point-min) (point-max)))
5752 (cond
5753 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5754 (fundamental-mode)
5755 (artist-mode 1))
5756 (t (funcall org-edit-fixed-width-region-mode)))
5757 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5758 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5759 (set (make-local-variable 'org-edit-src-picture) t)
5760 (goto-char (point-min))
5761 (while (re-search-forward "^[ \t]*: ?" nil t)
5762 (replace-match ""))
5763 (goto-line line)
5764 (org-exit-edit-mode)
5765 (org-set-local 'header-line-format msg)
5766 (message "%s" msg)
5767 t)))
5770 (defun org-edit-src-find-region-and-lang ()
5771 "Find the region and language for a local edit.
5772 Return a list with beginning and end of the region, a string representing
5773 the language, a switch telling of the content should be in a single line."
5774 (let ((re-list
5775 (append
5776 org-edit-src-region-extra
5778 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5779 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5780 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5781 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5782 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5783 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5784 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5785 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5786 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5787 ("^#\\+html:" "\n" "html" single-line)
5788 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5789 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5790 ("^#\\+latex:" "\n" "latex" single-line)
5791 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5792 ("^#\\+ascii:" "\n" "ascii" single-line)
5794 (pos (point))
5795 re re1 re2 single beg end lang)
5796 (catch 'exit
5797 (while (setq entry (pop re-list))
5798 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5799 single (nth 3 entry))
5800 (save-excursion
5801 (if (or (looking-at re1)
5802 (re-search-backward re1 nil t))
5803 (progn
5804 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5805 (if (and (re-search-forward re2 nil t)
5806 (>= (match-end 0) pos))
5807 (throw 'exit (list beg (match-beginning 0) lang single))))
5808 (if (or (looking-at re2)
5809 (re-search-forward re2 nil t))
5810 (progn
5811 (setq end (match-beginning 0))
5812 (if (and (re-search-backward re1 nil t)
5813 (<= (match-beginning 0) pos))
5814 (throw 'exit
5815 (list (match-end 0) end
5816 (org-edit-src-get-lang lang) single)))))))))))
5818 (defun org-edit-src-get-lang (lang)
5819 "Extract the src language."
5820 (let ((m (match-string 0)))
5821 (cond
5822 ((stringp lang) lang)
5823 ((integerp lang) (match-string lang))
5824 ((and (eq lang 'lang)
5825 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5826 (match-string 1 m))
5827 ((and (eq lang 'style)
5828 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5829 (match-string 1 m))
5830 (t "fundamental"))))
5832 (defun org-edit-src-exit ()
5833 "Exit special edit and protect problematic lines."
5834 (interactive)
5835 (unless (buffer-base-buffer (current-buffer))
5836 (error "This is not an indirect buffer, something is wrong..."))
5837 (unless (> (point-min) 1)
5838 (error "This buffer is not narrowed, something is wrong..."))
5839 (goto-char (point-min))
5840 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5841 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5842 (when (org-bound-and-true-p org-edit-src-force-single-line)
5843 (goto-char (point-min))
5844 (while (re-search-forward "\n" nil t)
5845 (replace-match " "))
5846 (goto-char (point-min))
5847 (if (looking-at "\\s-*") (replace-match " "))
5848 (if (re-search-forward "\\s-+\\'" nil t)
5849 (replace-match "")))
5850 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5851 (goto-char (point-min))
5852 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5853 (replace-match ",\\1"))
5854 (when font-lock-mode
5855 (font-lock-unfontify-region (point-min) (point-max)))
5856 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5857 (when (org-bound-and-true-p org-edit-src-picture)
5858 (untabify (point-min) (point-max))
5859 (goto-char (point-min))
5860 (while (re-search-forward "^" nil t)
5861 (replace-match ": "))
5862 (when font-lock-mode
5863 (font-lock-unfontify-region (point-min) (point-max)))
5864 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5865 (kill-buffer (current-buffer))
5866 (and (org-mode-p) (org-restart-font-lock)))
5869 ;;; The orgstruct minor mode
5871 ;; Define a minor mode which can be used in other modes in order to
5872 ;; integrate the org-mode structure editing commands.
5874 ;; This is really a hack, because the org-mode structure commands use
5875 ;; keys which normally belong to the major mode. Here is how it
5876 ;; works: The minor mode defines all the keys necessary to operate the
5877 ;; structure commands, but wraps the commands into a function which
5878 ;; tests if the cursor is currently at a headline or a plain list
5879 ;; item. If that is the case, the structure command is used,
5880 ;; temporarily setting many Org-mode variables like regular
5881 ;; expressions for filling etc. However, when any of those keys is
5882 ;; used at a different location, function uses `key-binding' to look
5883 ;; up if the key has an associated command in another currently active
5884 ;; keymap (minor modes, major mode, global), and executes that
5885 ;; command. There might be problems if any of the keys is otherwise
5886 ;; used as a prefix key.
5888 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5889 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5890 ;; addresses this by checking explicitly for both bindings.
5892 (defvar orgstruct-mode-map (make-sparse-keymap)
5893 "Keymap for the minor `orgstruct-mode'.")
5895 (defvar org-local-vars nil
5896 "List of local variables, for use by `orgstruct-mode'")
5898 ;;;###autoload
5899 (define-minor-mode orgstruct-mode
5900 "Toggle the minor more `orgstruct-mode'.
5901 This mode is for using Org-mode structure commands in other modes.
5902 The following key behave as if Org-mode was active, if the cursor
5903 is on a headline, or on a plain list item (both in the definition
5904 of Org-mode).
5906 M-up Move entry/item up
5907 M-down Move entry/item down
5908 M-left Promote
5909 M-right Demote
5910 M-S-up Move entry/item up
5911 M-S-down Move entry/item down
5912 M-S-left Promote subtree
5913 M-S-right Demote subtree
5914 M-q Fill paragraph and items like in Org-mode
5915 C-c ^ Sort entries
5916 C-c - Cycle list bullet
5917 TAB Cycle item visibility
5918 M-RET Insert new heading/item
5919 S-M-RET Insert new TODO heading / Chekbox item
5920 C-c C-c Set tags / toggle checkbox"
5921 nil " OrgStruct" nil
5922 (org-load-modules-maybe)
5923 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5925 ;;;###autoload
5926 (defun turn-on-orgstruct ()
5927 "Unconditionally turn on `orgstruct-mode'."
5928 (orgstruct-mode 1))
5930 ;;;###autoload
5931 (defun turn-on-orgstruct++ ()
5932 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5933 In addition to setting orgstruct-mode, this also exports all indentation and
5934 autofilling variables from org-mode into the buffer. Note that turning
5935 off orgstruct-mode will *not* remove these additional settings."
5936 (orgstruct-mode 1)
5937 (let (var val)
5938 (mapc
5939 (lambda (x)
5940 (when (string-match
5941 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5942 (symbol-name (car x)))
5943 (setq var (car x) val (nth 1 x))
5944 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5945 org-local-vars)))
5947 (defun orgstruct-error ()
5948 "Error when there is no default binding for a structure key."
5949 (interactive)
5950 (error "This key has no function outside structure elements"))
5952 (defun orgstruct-setup ()
5953 "Setup orgstruct keymaps."
5954 (let ((nfunc 0)
5955 (bindings
5956 (list
5957 '([(meta up)] org-metaup)
5958 '([(meta down)] org-metadown)
5959 '([(meta left)] org-metaleft)
5960 '([(meta right)] org-metaright)
5961 '([(meta shift up)] org-shiftmetaup)
5962 '([(meta shift down)] org-shiftmetadown)
5963 '([(meta shift left)] org-shiftmetaleft)
5964 '([(meta shift right)] org-shiftmetaright)
5965 '([(shift up)] org-shiftup)
5966 '([(shift down)] org-shiftdown)
5967 '([(shift left)] org-shiftleft)
5968 '([(shift right)] org-shiftright)
5969 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5970 '("\M-q" fill-paragraph)
5971 '("\C-c^" org-sort)
5972 '("\C-c-" org-cycle-list-bullet)))
5973 elt key fun cmd)
5974 (while (setq elt (pop bindings))
5975 (setq nfunc (1+ nfunc))
5976 (setq key (org-key (car elt))
5977 fun (nth 1 elt)
5978 cmd (orgstruct-make-binding fun nfunc key))
5979 (org-defkey orgstruct-mode-map key cmd))
5981 ;; Special treatment needed for TAB and RET
5982 (org-defkey orgstruct-mode-map [(tab)]
5983 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5984 (org-defkey orgstruct-mode-map "\C-i"
5985 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5987 (org-defkey orgstruct-mode-map "\M-\C-m"
5988 (orgstruct-make-binding 'org-insert-heading 105
5989 "\M-\C-m" [(meta return)]))
5990 (org-defkey orgstruct-mode-map [(meta return)]
5991 (orgstruct-make-binding 'org-insert-heading 106
5992 [(meta return)] "\M-\C-m"))
5994 (org-defkey orgstruct-mode-map [(shift meta return)]
5995 (orgstruct-make-binding 'org-insert-todo-heading 107
5996 [(meta return)] "\M-\C-m"))
5998 (unless org-local-vars
5999 (setq org-local-vars (org-get-local-variables)))
6003 (defun orgstruct-make-binding (fun n &rest keys)
6004 "Create a function for binding in the structure minor mode.
6005 FUN is the command to call inside a table. N is used to create a unique
6006 command name. KEYS are keys that should be checked in for a command
6007 to execute outside of tables."
6008 (eval
6009 (list 'defun
6010 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6011 '(arg)
6012 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6013 "Outside of structure, run the binding of `"
6014 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6015 "'.")
6016 '(interactive "p")
6017 (list 'if
6018 '(org-context-p 'headline 'item)
6019 (list 'org-run-like-in-org-mode (list 'quote fun))
6020 (list 'let '(orgstruct-mode)
6021 (list 'call-interactively
6022 (append '(or)
6023 (mapcar (lambda (k)
6024 (list 'key-binding k))
6025 keys)
6026 '('orgstruct-error))))))))
6028 (defun org-context-p (&rest contexts)
6029 "Check if local context is any of CONTEXTS.
6030 Possible values in the list of contexts are `table', `headline', and `item'."
6031 (let ((pos (point)))
6032 (goto-char (point-at-bol))
6033 (prog1 (or (and (memq 'table contexts)
6034 (looking-at "[ \t]*|"))
6035 (and (memq 'headline contexts)
6036 ;;????????? (looking-at "\\*+"))
6037 (looking-at outline-regexp))
6038 (and (memq 'item contexts)
6039 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6040 (goto-char pos))))
6042 (defun org-get-local-variables ()
6043 "Return a list of all local variables in an org-mode buffer."
6044 (let (varlist)
6045 (with-current-buffer (get-buffer-create "*Org tmp*")
6046 (erase-buffer)
6047 (org-mode)
6048 (setq varlist (buffer-local-variables)))
6049 (kill-buffer "*Org tmp*")
6050 (delq nil
6051 (mapcar
6052 (lambda (x)
6053 (setq x
6054 (if (symbolp x)
6055 (list x)
6056 (list (car x) (list 'quote (cdr x)))))
6057 (if (string-match
6058 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6059 (symbol-name (car x)))
6060 x nil))
6061 varlist))))
6063 ;;;###autoload
6064 (defun org-run-like-in-org-mode (cmd)
6065 (org-load-modules-maybe)
6066 (unless org-local-vars
6067 (setq org-local-vars (org-get-local-variables)))
6068 (eval (list 'let org-local-vars
6069 (list 'call-interactively (list 'quote cmd)))))
6071 ;;;; Archiving
6073 (defun org-get-category (&optional pos)
6074 "Get the category applying to position POS."
6075 (get-text-property (or pos (point)) 'org-category))
6077 (defun org-refresh-category-properties ()
6078 "Refresh category text properties in the buffer."
6079 (let ((def-cat (cond
6080 ((null org-category)
6081 (if buffer-file-name
6082 (file-name-sans-extension
6083 (file-name-nondirectory buffer-file-name))
6084 "???"))
6085 ((symbolp org-category) (symbol-name org-category))
6086 (t org-category)))
6087 beg end cat pos optionp)
6088 (org-unmodified
6089 (save-excursion
6090 (save-restriction
6091 (widen)
6092 (goto-char (point-min))
6093 (put-text-property (point) (point-max) 'org-category def-cat)
6094 (while (re-search-forward
6095 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6096 (setq pos (match-end 0)
6097 optionp (equal (char-after (match-beginning 0)) ?#)
6098 cat (org-trim (match-string 2)))
6099 (if optionp
6100 (setq beg (point-at-bol) end (point-max))
6101 (org-back-to-heading t)
6102 (setq beg (point) end (org-end-of-subtree t t)))
6103 (put-text-property beg end 'org-category cat)
6104 (goto-char pos)))))))
6107 ;;;; Link Stuff
6109 ;;; Link abbreviations
6111 (defun org-link-expand-abbrev (link)
6112 "Apply replacements as defined in `org-link-abbrev-alist."
6113 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6114 (let* ((key (match-string 1 link))
6115 (as (or (assoc key org-link-abbrev-alist-local)
6116 (assoc key org-link-abbrev-alist)))
6117 (tag (and (match-end 2) (match-string 3 link)))
6118 rpl)
6119 (if (not as)
6120 link
6121 (setq rpl (cdr as))
6122 (cond
6123 ((symbolp rpl) (funcall rpl tag))
6124 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6125 ((string-match "%h" rpl)
6126 (replace-match (url-hexify-string (or tag "")) t t rpl))
6127 (t (concat rpl tag)))))
6128 link))
6130 ;;; Storing and inserting links
6132 (defvar org-insert-link-history nil
6133 "Minibuffer history for links inserted with `org-insert-link'.")
6135 (defvar org-stored-links nil
6136 "Contains the links stored with `org-store-link'.")
6138 (defvar org-store-link-plist nil
6139 "Plist with info about the most recently link created with `org-store-link'.")
6141 (defvar org-link-protocols nil
6142 "Link protocols added to Org-mode using `org-add-link-type'.")
6144 (defvar org-store-link-functions nil
6145 "List of functions that are called to create and store a link.
6146 Each function will be called in turn until one returns a non-nil
6147 value. Each function should check if it is responsible for creating
6148 this link (for example by looking at the major mode).
6149 If not, it must exit and return nil.
6150 If yes, it should return a non-nil value after a calling
6151 `org-store-link-props' with a list of properties and values.
6152 Special properties are:
6154 :type The link prefix. like \"http\". This must be given.
6155 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6156 This is obligatory as well.
6157 :description Optional default description for the second pair
6158 of brackets in an Org-mode link. The user can still change
6159 this when inserting this link into an Org-mode buffer.
6161 In addition to these, any additional properties can be specified
6162 and then used in remember templates.")
6164 (defun org-add-link-type (type &optional follow export)
6165 "Add TYPE to the list of `org-link-types'.
6166 Re-compute all regular expressions depending on `org-link-types'
6168 FOLLOW and EXPORT are two functions.
6170 FOLLOW should take the link path as the single argument and do whatever
6171 is necessary to follow the link, for example find a file or display
6172 a mail message.
6174 EXPORT should format the link path for export to one of the export formats.
6175 It should be a function accepting three arguments:
6177 path the path of the link, the text after the prefix (like \"http:\")
6178 desc the description of the link, if any, nil if there was no descripton
6179 format the export format, a symbol like `html' or `latex'.
6181 The function may use the FORMAT information to return different values
6182 depending on the format. The return value will be put literally into
6183 the exported file.
6184 Org-mode has a built-in default for exporting links. If you are happy with
6185 this default, there is no need to define an export function for the link
6186 type. For a simple example of an export function, see `org-bbdb.el'."
6187 (add-to-list 'org-link-types type t)
6188 (org-make-link-regexps)
6189 (if (assoc type org-link-protocols)
6190 (setcdr (assoc type org-link-protocols) (list follow export))
6191 (push (list type follow export) org-link-protocols)))
6193 ;;;###autoload
6194 (defun org-store-link (arg)
6195 "\\<org-mode-map>Store an org-link to the current location.
6196 This link is added to `org-stored-links' and can later be inserted
6197 into an org-buffer with \\[org-insert-link].
6199 For some link types, a prefix arg is interpreted:
6200 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6201 For file links, arg negates `org-context-in-file-links'."
6202 (interactive "P")
6203 (org-load-modules-maybe)
6204 (setq org-store-link-plist nil) ; reset
6205 (let (link cpltxt desc description search txt)
6206 (cond
6208 ((run-hook-with-args-until-success 'org-store-link-functions)
6209 (setq link (plist-get org-store-link-plist :link)
6210 desc (or (plist-get org-store-link-plist :description) link)))
6212 ((eq major-mode 'calendar-mode)
6213 (let ((cd (calendar-cursor-to-date)))
6214 (setq link
6215 (format-time-string
6216 (car org-time-stamp-formats)
6217 (apply 'encode-time
6218 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6219 nil nil nil))))
6220 (org-store-link-props :type "calendar" :date cd)))
6222 ((eq major-mode 'w3-mode)
6223 (setq cpltxt (url-view-url t)
6224 link (org-make-link cpltxt))
6225 (org-store-link-props :type "w3" :url (url-view-url t)))
6227 ((eq major-mode 'w3m-mode)
6228 (setq cpltxt (or w3m-current-title w3m-current-url)
6229 link (org-make-link w3m-current-url))
6230 (org-store-link-props :type "w3m" :url (url-view-url t)))
6232 ((setq search (run-hook-with-args-until-success
6233 'org-create-file-search-functions))
6234 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6235 "::" search))
6236 (setq cpltxt (or description link)))
6238 ((eq major-mode 'image-mode)
6239 (setq cpltxt (concat "file:"
6240 (abbreviate-file-name buffer-file-name))
6241 link (org-make-link cpltxt))
6242 (org-store-link-props :type "image" :file buffer-file-name))
6244 ((eq major-mode 'dired-mode)
6245 ;; link to the file in the current line
6246 (setq cpltxt (concat "file:"
6247 (abbreviate-file-name
6248 (expand-file-name
6249 (dired-get-filename nil t))))
6250 link (org-make-link cpltxt)))
6252 ((and buffer-file-name (org-mode-p))
6253 (cond
6254 ((org-in-regexp "<<\\(.*?\\)>>")
6255 (setq cpltxt
6256 (concat "file:"
6257 (abbreviate-file-name buffer-file-name)
6258 "::" (match-string 1))
6259 link (org-make-link cpltxt)))
6260 ((and (featurep 'org-id)
6261 (or (eq org-link-to-org-use-id t)
6262 (and (eq org-link-to-org-use-id 'create-if-interactive)
6263 (interactive-p))
6264 (and org-link-to-org-use-id
6265 (condition-case nil
6266 (org-entry-get nil "ID")
6267 (error nil)))))
6268 ;; We can make a link using the ID.
6269 (setq link (condition-case nil
6270 (org-id-store-link)
6271 (error
6272 ;; probably before first headling, link to file only
6273 (concat "file:"
6274 (abbreviate-file-name buffer-file-name))))))
6276 ;; Just link to current headline
6277 (setq cpltxt (concat "file:"
6278 (abbreviate-file-name buffer-file-name)))
6279 ;; Add a context search string
6280 (when (org-xor org-context-in-file-links arg)
6281 (setq txt (cond
6282 ((org-on-heading-p) nil)
6283 ((org-region-active-p)
6284 (buffer-substring (region-beginning) (region-end)))
6285 (t nil)))
6286 (when (or (null txt) (string-match "\\S-" txt))
6287 (setq cpltxt
6288 (concat cpltxt "::"
6289 (condition-case nil
6290 (org-make-org-heading-search-string txt)
6291 (error "")))
6292 desc "NONE")))
6293 (if (string-match "::\\'" cpltxt)
6294 (setq cpltxt (substring cpltxt 0 -2)))
6295 (setq link (org-make-link cpltxt)))))
6297 ((buffer-file-name (buffer-base-buffer))
6298 ;; Just link to this file here.
6299 (setq cpltxt (concat "file:"
6300 (abbreviate-file-name
6301 (buffer-file-name (buffer-base-buffer)))))
6302 ;; Add a context string
6303 (when (org-xor org-context-in-file-links arg)
6304 (setq txt (if (org-region-active-p)
6305 (buffer-substring (region-beginning) (region-end))
6306 (buffer-substring (point-at-bol) (point-at-eol))))
6307 ;; Only use search option if there is some text.
6308 (when (string-match "\\S-" txt)
6309 (setq cpltxt
6310 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6311 desc "NONE")))
6312 (setq link (org-make-link cpltxt)))
6314 ((interactive-p)
6315 (error "Cannot link to a buffer which is not visiting a file"))
6317 (t (setq link nil)))
6319 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6320 (setq link (or link cpltxt)
6321 desc (or desc cpltxt))
6322 (if (equal desc "NONE") (setq desc nil))
6324 (if (and (interactive-p) link)
6325 (progn
6326 (setq org-stored-links
6327 (cons (list link desc) org-stored-links))
6328 (message "Stored: %s" (or desc link)))
6329 (and link (org-make-link-string link desc)))))
6331 (defun org-store-link-props (&rest plist)
6332 "Store link properties, extract names and addresses."
6333 (let (x adr)
6334 (when (setq x (plist-get plist :from))
6335 (setq adr (mail-extract-address-components x))
6336 (setq plist (plist-put plist :fromname (car adr)))
6337 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6338 (when (setq x (plist-get plist :to))
6339 (setq adr (mail-extract-address-components x))
6340 (setq plist (plist-put plist :toname (car adr)))
6341 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6342 (let ((from (plist-get plist :from))
6343 (to (plist-get plist :to)))
6344 (when (and from to org-from-is-user-regexp)
6345 (setq plist
6346 (plist-put plist :fromto
6347 (if (string-match org-from-is-user-regexp from)
6348 (concat "to %t")
6349 (concat "from %f"))))))
6350 (setq org-store-link-plist plist))
6352 (defun org-add-link-props (&rest plist)
6353 "Add these properties to the link property list."
6354 (let (key value)
6355 (while plist
6356 (setq key (pop plist) value (pop plist))
6357 (setq org-store-link-plist
6358 (plist-put org-store-link-plist key value)))))
6360 (defun org-email-link-description (&optional fmt)
6361 "Return the description part of an email link.
6362 This takes information from `org-store-link-plist' and formats it
6363 according to FMT (default from `org-email-link-description-format')."
6364 (setq fmt (or fmt org-email-link-description-format))
6365 (let* ((p org-store-link-plist)
6366 (to (plist-get p :toaddress))
6367 (from (plist-get p :fromaddress))
6368 (table
6369 (list
6370 (cons "%c" (plist-get p :fromto))
6371 (cons "%F" (plist-get p :from))
6372 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6373 (cons "%T" (plist-get p :to))
6374 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6375 (cons "%s" (plist-get p :subject))
6376 (cons "%m" (plist-get p :message-id)))))
6377 (when (string-match "%c" fmt)
6378 ;; Check if the user wrote this message
6379 (if (and org-from-is-user-regexp from to
6380 (save-match-data (string-match org-from-is-user-regexp from)))
6381 (setq fmt (replace-match "to %t" t t fmt))
6382 (setq fmt (replace-match "from %f" t t fmt))))
6383 (org-replace-escapes fmt table)))
6385 (defun org-make-org-heading-search-string (&optional string heading)
6386 "Make search string for STRING or current headline."
6387 (interactive)
6388 (let ((s (or string (org-get-heading))))
6389 (unless (and string (not heading))
6390 ;; We are using a headline, clean up garbage in there.
6391 (if (string-match org-todo-regexp s)
6392 (setq s (replace-match "" t t s)))
6393 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6394 (setq s (replace-match "" t t s)))
6395 (setq s (org-trim s))
6396 (if (string-match (concat "^\\(" org-quote-string "\\|"
6397 org-comment-string "\\)") s)
6398 (setq s (replace-match "" t t s)))
6399 (while (string-match org-ts-regexp s)
6400 (setq s (replace-match "" t t s))))
6401 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6402 (setq s (replace-match " " t t s)))
6403 (or string (setq s (concat "*" s))) ; Add * for headlines
6404 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6406 (defun org-make-link (&rest strings)
6407 "Concatenate STRINGS."
6408 (apply 'concat strings))
6410 (defun org-make-link-string (link &optional description)
6411 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6412 (unless (string-match "\\S-" link)
6413 (error "Empty link"))
6414 (when (stringp description)
6415 ;; Remove brackets from the description, they are fatal.
6416 (while (string-match "\\[" description)
6417 (setq description (replace-match "{" t t description)))
6418 (while (string-match "\\]" description)
6419 (setq description (replace-match "}" t t description))))
6420 (when (equal (org-link-escape link) description)
6421 ;; No description needed, it is identical
6422 (setq description nil))
6423 (when (and (not description)
6424 (not (equal link (org-link-escape link))))
6425 (setq description (org-extract-attributes link)))
6426 (concat "[[" (org-link-escape link) "]"
6427 (if description (concat "[" description "]") "")
6428 "]"))
6430 (defconst org-link-escape-chars
6431 '((?\ . "%20")
6432 (?\[ . "%5B")
6433 (?\] . "%5D")
6434 (?\340 . "%E0") ; `a
6435 (?\342 . "%E2") ; ^a
6436 (?\347 . "%E7") ; ,c
6437 (?\350 . "%E8") ; `e
6438 (?\351 . "%E9") ; 'e
6439 (?\352 . "%EA") ; ^e
6440 (?\356 . "%EE") ; ^i
6441 (?\364 . "%F4") ; ^o
6442 (?\371 . "%F9") ; `u
6443 (?\373 . "%FB") ; ^u
6444 (?\; . "%3B")
6445 (?? . "%3F")
6446 (?= . "%3D")
6447 (?+ . "%2B")
6449 "Association list of escapes for some characters problematic in links.
6450 This is the list that is used for internal purposes.")
6452 (defconst org-link-escape-chars-browser
6453 '((?\ . "%20")) ; 32 for the SPC char
6454 "Association list of escapes for some characters problematic in links.
6455 This is the list that is used before handing over to the browser.")
6457 (defun org-link-escape (text &optional table)
6458 "Escape characters in TEXT that are problematic for links."
6459 (setq table (or table org-link-escape-chars))
6460 (when text
6461 (let ((re (mapconcat (lambda (x) (regexp-quote
6462 (char-to-string (car x))))
6463 table "\\|")))
6464 (while (string-match re text)
6465 (setq text
6466 (replace-match
6467 (cdr (assoc (string-to-char (match-string 0 text))
6468 table))
6469 t t text)))
6470 text)))
6472 (defun org-link-unescape (text &optional table)
6473 "Reverse the action of `org-link-escape'."
6474 (setq table (or table org-link-escape-chars))
6475 (when text
6476 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6477 table "\\|")))
6478 (while (string-match re text)
6479 (setq text
6480 (replace-match
6481 (char-to-string (car (rassoc (match-string 0 text) table)))
6482 t t text)))
6483 text)))
6485 (defun org-xor (a b)
6486 "Exclusive or."
6487 (if a (not b) b))
6489 (defun org-get-header (header)
6490 "Find a header field in the current buffer."
6491 (save-excursion
6492 (goto-char (point-min))
6493 (let ((case-fold-search t) s)
6494 (cond
6495 ((eq header 'from)
6496 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6497 (setq s (match-string 1)))
6498 (while (string-match "\"" s)
6499 (setq s (replace-match "" t t s)))
6500 (if (string-match "[<(].*" s)
6501 (setq s (replace-match "" t t s))))
6502 ((eq header 'message-id)
6503 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6504 (setq s (match-string 1))))
6505 ((eq header 'subject)
6506 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6507 (setq s (match-string 1)))))
6508 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6509 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6510 s)))
6513 (defun org-fixup-message-id-for-http (s)
6514 "Replace special characters in a message id, so it can be used in an http query."
6515 (while (string-match "<" s)
6516 (setq s (replace-match "%3C" t t s)))
6517 (while (string-match ">" s)
6518 (setq s (replace-match "%3E" t t s)))
6519 (while (string-match "@" s)
6520 (setq s (replace-match "%40" t t s)))
6523 ;;;###autoload
6524 (defun org-insert-link-global ()
6525 "Insert a link like Org-mode does.
6526 This command can be called in any mode to insert a link in Org-mode syntax."
6527 (interactive)
6528 (org-load-modules-maybe)
6529 (org-run-like-in-org-mode 'org-insert-link))
6531 (defun org-insert-link (&optional complete-file link-location)
6532 "Insert a link. At the prompt, enter the link.
6534 Completion can be used to insert any of the link protocol prefixes like
6535 http or ftp in use.
6537 The history can be used to select a link previously stored with
6538 `org-store-link'. When the empty string is entered (i.e. if you just
6539 press RET at the prompt), the link defaults to the most recently
6540 stored link. As SPC triggers completion in the minibuffer, you need to
6541 use M-SPC or C-q SPC to force the insertion of a space character.
6543 You will also be prompted for a description, and if one is given, it will
6544 be displayed in the buffer instead of the link.
6546 If there is already a link at point, this command will allow you to edit link
6547 and description parts.
6549 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6550 be selected using completion. The path to the file will be relative to the
6551 current directory if the file is in the current directory or a subdirectory.
6552 Otherwise, the link will be the absolute path as completed in the minibuffer
6553 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6554 option `org-link-file-path-type'.
6556 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6557 the current directory or below.
6559 With three \\[universal-argument] prefixes, negate the meaning of
6560 `org-keep-stored-link-after-insertion'.
6562 If `org-make-link-description-function' is non-nil, this function will be
6563 called with the link target, and the result will be the default
6564 link description.
6566 If the LINK-LOCATION parameter is non-nil, this value will be
6567 used as the link location instead of reading one interactively."
6568 (interactive "P")
6569 (let* ((wcf (current-window-configuration))
6570 (region (if (org-region-active-p)
6571 (buffer-substring (region-beginning) (region-end))))
6572 (remove (and region (list (region-beginning) (region-end))))
6573 (desc region)
6574 tmphist ; byte-compile incorrectly complains about this
6575 (link link-location)
6576 entry file)
6577 (cond
6578 (link-location) ; specified by arg, just use it.
6579 ((org-in-regexp org-bracket-link-regexp 1)
6580 ;; We do have a link at point, and we are going to edit it.
6581 (setq remove (list (match-beginning 0) (match-end 0)))
6582 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6583 (setq link (read-string "Link: "
6584 (org-link-unescape
6585 (org-match-string-no-properties 1)))))
6586 ((or (org-in-regexp org-angle-link-re)
6587 (org-in-regexp org-plain-link-re))
6588 ;; Convert to bracket link
6589 (setq remove (list (match-beginning 0) (match-end 0))
6590 link (read-string "Link: "
6591 (org-remove-angle-brackets (match-string 0)))))
6592 ((member complete-file '((4) (16)))
6593 ;; Completing read for file names.
6594 (setq file (read-file-name "File: "))
6595 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6596 (pwd1 (file-name-as-directory (abbreviate-file-name
6597 (expand-file-name ".")))))
6598 (cond
6599 ((equal complete-file '(16))
6600 (setq link (org-make-link
6601 "file:"
6602 (abbreviate-file-name (expand-file-name file)))))
6603 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6604 (setq link (org-make-link "file:" (match-string 1 file))))
6605 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6606 (expand-file-name file))
6607 (setq link (org-make-link
6608 "file:" (match-string 1 (expand-file-name file)))))
6609 (t (setq link (org-make-link "file:" file))))))
6611 ;; Read link, with completion for stored links.
6612 (with-output-to-temp-buffer "*Org Links*"
6613 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6614 (when org-stored-links
6615 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6616 (princ (mapconcat
6617 (lambda (x)
6618 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6619 (reverse org-stored-links) "\n"))))
6620 (let ((cw (selected-window)))
6621 (select-window (get-buffer-window "*Org Links*"))
6622 (org-fit-window-to-buffer)
6623 (setq truncate-lines t)
6624 (select-window cw))
6625 ;; Fake a link history, containing the stored links.
6626 (setq tmphist (append (mapcar 'car org-stored-links)
6627 org-insert-link-history))
6628 (unwind-protect
6629 (setq link (org-completing-read
6630 "Link: "
6631 (append
6632 (mapcar (lambda (x) (list (concat (car x) ":")))
6633 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6634 (mapcar (lambda (x) (list (concat x ":")))
6635 org-link-types))
6636 nil nil nil
6637 'tmphist
6638 (or (car (car org-stored-links)))))
6639 (set-window-configuration wcf)
6640 (kill-buffer "*Org Links*"))
6641 (setq entry (assoc link org-stored-links))
6642 (or entry (push link org-insert-link-history))
6643 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6644 (not org-keep-stored-link-after-insertion))
6645 (setq org-stored-links (delq (assoc link org-stored-links)
6646 org-stored-links)))
6647 (setq desc (or desc (nth 1 entry)))))
6649 (if (string-match org-plain-link-re link)
6650 ;; URL-like link, normalize the use of angular brackets.
6651 (setq link (org-make-link (org-remove-angle-brackets link))))
6653 ;; Check if we are linking to the current file with a search option
6654 ;; If yes, simplify the link by using only the search option.
6655 (when (and buffer-file-name
6656 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6657 (let* ((path (match-string 1 link))
6658 (case-fold-search nil)
6659 (search (match-string 2 link)))
6660 (save-match-data
6661 (if (equal (file-truename buffer-file-name) (file-truename path))
6662 ;; We are linking to this same file, with a search option
6663 (setq link search)))))
6665 ;; Check if we can/should use a relative path. If yes, simplify the link
6666 (when (string-match "^file:\\(.*\\)" link)
6667 (let* ((path (match-string 1 link))
6668 (origpath path)
6669 (case-fold-search nil))
6670 (cond
6671 ((or (eq org-link-file-path-type 'absolute)
6672 (equal complete-file '(16)))
6673 (setq path (abbreviate-file-name (expand-file-name path))))
6674 ((eq org-link-file-path-type 'noabbrev)
6675 (setq path (expand-file-name path)))
6676 ((eq org-link-file-path-type 'relative)
6677 (setq path (file-relative-name path)))
6679 (save-match-data
6680 (if (string-match (concat "^" (regexp-quote
6681 (file-name-as-directory
6682 (expand-file-name "."))))
6683 (expand-file-name path))
6684 ;; We are linking a file with relative path name.
6685 (setq path (substring (expand-file-name path)
6686 (match-end 0)))
6687 (setq path (abbreviate-file-name (expand-file-name path)))))))
6688 (setq link (concat "file:" path))
6689 (if (equal desc origpath)
6690 (setq desc path))))
6692 (if org-make-link-description-function
6693 (setq desc (funcall org-make-link-description-function link desc)))
6695 (setq desc (read-string "Description: " desc))
6696 (unless (string-match "\\S-" desc) (setq desc nil))
6697 (if remove (apply 'delete-region remove))
6698 (insert (org-make-link-string link desc))))
6700 (defun org-completing-read (&rest args)
6701 "Completing-read with SPACE being a normal character."
6702 (let ((minibuffer-local-completion-map
6703 (copy-keymap minibuffer-local-completion-map)))
6704 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6705 (apply 'org-ido-completing-read args)))
6707 (defun org-ido-completing-read (&rest args)
6708 "Completing-read using `ido-mode' speedups if available"
6709 (if (and org-completion-use-ido
6710 (fboundp 'ido-completing-read)
6711 (boundp 'ido-mode) ido-mode
6712 (listp (second args)))
6713 (apply 'ido-completing-read (concat (car args)) (cdr args))
6714 (apply 'completing-read args)))
6716 (defun org-extract-attributes (s)
6717 "Extract the attributes cookie from a string and set as text property."
6718 (let (a attr (start 0) key value)
6719 (save-match-data
6720 (when (string-match "{{\\([^}]+\\)}}$" s)
6721 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6722 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6723 (setq key (match-string 1 a) value (match-string 2 a)
6724 start (match-end 0)
6725 attr (plist-put attr (intern key) value))))
6726 (org-add-props s nil 'org-attr attr))
6729 (defun org-attributes-to-string (plist)
6730 "Format a property list into an HTML attribute list."
6731 (let ((s "") key value)
6732 (while plist
6733 (setq key (pop plist) value (pop plist))
6734 (and value
6735 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6738 ;;; Opening/following a link
6740 (defvar org-link-search-failed nil)
6742 (defun org-next-link ()
6743 "Move forward to the next link.
6744 If the link is in hidden text, expose it."
6745 (interactive)
6746 (when (and org-link-search-failed (eq this-command last-command))
6747 (goto-char (point-min))
6748 (message "Link search wrapped back to beginning of buffer"))
6749 (setq org-link-search-failed nil)
6750 (let* ((pos (point))
6751 (ct (org-context))
6752 (a (assoc :link ct)))
6753 (if a (goto-char (nth 2 a)))
6754 (if (re-search-forward org-any-link-re nil t)
6755 (progn
6756 (goto-char (match-beginning 0))
6757 (if (org-invisible-p) (org-show-context)))
6758 (goto-char pos)
6759 (setq org-link-search-failed t)
6760 (error "No further link found"))))
6762 (defun org-previous-link ()
6763 "Move backward to the previous link.
6764 If the link is in hidden text, expose it."
6765 (interactive)
6766 (when (and org-link-search-failed (eq this-command last-command))
6767 (goto-char (point-max))
6768 (message "Link search wrapped back to end of buffer"))
6769 (setq org-link-search-failed nil)
6770 (let* ((pos (point))
6771 (ct (org-context))
6772 (a (assoc :link ct)))
6773 (if a (goto-char (nth 1 a)))
6774 (if (re-search-backward org-any-link-re nil t)
6775 (progn
6776 (goto-char (match-beginning 0))
6777 (if (org-invisible-p) (org-show-context)))
6778 (goto-char pos)
6779 (setq org-link-search-failed t)
6780 (error "No further link found"))))
6782 (defun org-translate-link (s)
6783 "Translate a link string if a translation function has been defined."
6784 (if (and org-link-translation-function
6785 (fboundp org-link-translation-function)
6786 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6787 (progn
6788 (setq s (funcall org-link-translation-function
6789 (match-string 1) (match-string 2)))
6790 (concat (car s) ":" (cdr s)))
6793 (defun org-translate-link-from-planner (type path)
6794 "Translate a link from Emacs Planner syntax so that Org can follow it.
6795 This is still an experimental function, your mileage may vary."
6796 (cond
6797 ((member type '("http" "https" "news" "ftp"))
6798 ;; standard Internet links are the same.
6799 nil)
6800 ((and (equal type "irc") (string-match "^//" path))
6801 ;; Planner has two / at the beginning of an irc link, we have 1.
6802 ;; We should have zero, actually....
6803 (setq path (substring path 1)))
6804 ((and (equal type "lisp") (string-match "^/" path))
6805 ;; Planner has a slash, we do not.
6806 (setq type "elisp" path (substring path 1)))
6807 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6808 ;; A typical message link. Planner has the id after the fina slash,
6809 ;; we separate it with a hash mark
6810 (setq path (concat (match-string 1 path) "#"
6811 (org-remove-angle-brackets (match-string 2 path)))))
6813 (cons type path))
6815 (defun org-find-file-at-mouse (ev)
6816 "Open file link or URL at mouse."
6817 (interactive "e")
6818 (mouse-set-point ev)
6819 (org-open-at-point 'in-emacs))
6821 (defun org-open-at-mouse (ev)
6822 "Open file link or URL at mouse."
6823 (interactive "e")
6824 (mouse-set-point ev)
6825 (if (eq major-mode 'org-agenda-mode)
6826 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
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 With a double prefix argument, try to open outside of Emacs, in the
6862 application the system uses for this file type."
6863 (interactive "P")
6864 (org-load-modules-maybe)
6865 (move-marker org-open-link-marker (point))
6866 (setq org-window-config-before-follow-link (current-window-configuration))
6867 (org-remove-occur-highlights nil nil t)
6868 (if (org-at-timestamp-p t)
6869 (org-follow-timestamp-link)
6870 (let (type path link line search (pos (point)))
6871 (catch 'match
6872 (save-excursion
6873 (skip-chars-forward "^]\n\r")
6874 (when (org-in-regexp org-bracket-link-regexp)
6875 (setq link (org-extract-attributes
6876 (org-link-unescape (org-match-string-no-properties 1))))
6877 (while (string-match " *\n *" link)
6878 (setq link (replace-match " " t t link)))
6879 (setq link (org-link-expand-abbrev link))
6880 (cond
6881 ((or (file-name-absolute-p link)
6882 (string-match "^\\.\\.?/" link))
6883 (setq type "file" path link))
6884 ((string-match org-link-re-with-space3 link)
6885 (setq type (match-string 1 link) path (match-string 2 link)))
6886 (t (setq type "thisfile" path link)))
6887 (throw 'match t)))
6889 (when (get-text-property (point) 'org-linked-text)
6890 (setq type "thisfile"
6891 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6892 (1+ (point)) (point))
6893 path (buffer-substring
6894 (previous-single-property-change pos 'org-linked-text)
6895 (next-single-property-change pos 'org-linked-text)))
6896 (throw 'match t))
6898 (save-excursion
6899 (when (or (org-in-regexp org-angle-link-re)
6900 (org-in-regexp org-plain-link-re))
6901 (setq type (match-string 1) path (match-string 2))
6902 (throw 'match t)))
6903 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6904 (setq type "tree-match"
6905 path (match-string 1))
6906 (throw 'match t))
6907 (save-excursion
6908 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6909 (setq type "tags"
6910 path (match-string 1))
6911 (while (string-match ":" path)
6912 (setq path (replace-match "+" t t path)))
6913 (throw 'match t))))
6914 (unless path
6915 (error "No link found"))
6916 ;; Remove any trailing spaces in path
6917 (if (string-match " +\\'" path)
6918 (setq path (replace-match "" t t path)))
6919 (if (and org-link-translation-function
6920 (fboundp org-link-translation-function))
6921 ;; Check if we need to translate the link
6922 (let ((tmp (funcall org-link-translation-function type path)))
6923 (setq type (car tmp) path (cdr tmp))))
6925 (cond
6927 ((assoc type org-link-protocols)
6928 (funcall (nth 1 (assoc type org-link-protocols)) path))
6930 ((equal type "mailto")
6931 (let ((cmd (car org-link-mailto-program))
6932 (args (cdr org-link-mailto-program)) args1
6933 (address path) (subject "") a)
6934 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6935 (setq address (match-string 1 path)
6936 subject (org-link-escape (match-string 2 path))))
6937 (while args
6938 (cond
6939 ((not (stringp (car args))) (push (pop args) args1))
6940 (t (setq a (pop args))
6941 (if (string-match "%a" a)
6942 (setq a (replace-match address t t a)))
6943 (if (string-match "%s" a)
6944 (setq a (replace-match subject t t a)))
6945 (push a args1))))
6946 (apply cmd (nreverse args1))))
6948 ((member type '("http" "https" "ftp" "news"))
6949 (browse-url (concat type ":" (org-link-escape
6950 path org-link-escape-chars-browser))))
6952 ((member type '("message"))
6953 (browse-url (concat type ":" path)))
6955 ((string= type "tags")
6956 (org-tags-view in-emacs path))
6957 ((string= type "thisfile")
6958 (if in-emacs
6959 (switch-to-buffer-other-window
6960 (org-get-buffer-for-internal-link (current-buffer)))
6961 (org-mark-ring-push))
6962 (let ((cmd `(org-link-search
6963 ,path
6964 ,(cond ((equal in-emacs '(4)) 'occur)
6965 ((equal in-emacs '(16)) 'org-occur)
6966 (t nil))
6967 ,pos)))
6968 (condition-case nil (eval cmd)
6969 (error (progn (widen) (eval cmd))))))
6971 ((string= type "tree-match")
6972 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6974 ((string= type "file")
6975 (if (string-match "::\\([0-9]+\\)\\'" path)
6976 (setq line (string-to-number (match-string 1 path))
6977 path (substring path 0 (match-beginning 0)))
6978 (if (string-match "::\\(.+\\)\\'" path)
6979 (setq search (match-string 1 path)
6980 path (substring path 0 (match-beginning 0)))))
6981 (if (string-match "[*?{]" (file-name-nondirectory path))
6982 (dired path)
6983 (org-open-file path in-emacs line search)))
6985 ((string= type "news")
6986 (require 'org-gnus)
6987 (org-gnus-follow-link path))
6989 ((string= type "shell")
6990 (let ((cmd path))
6991 (if (or (not org-confirm-shell-link-function)
6992 (funcall org-confirm-shell-link-function
6993 (format "Execute \"%s\" in shell? "
6994 (org-add-props cmd nil
6995 'face 'org-warning))))
6996 (progn
6997 (message "Executing %s" cmd)
6998 (shell-command cmd))
6999 (error "Abort"))))
7001 ((string= type "elisp")
7002 (let ((cmd path))
7003 (if (or (not org-confirm-elisp-link-function)
7004 (funcall org-confirm-elisp-link-function
7005 (format "Execute \"%s\" as elisp? "
7006 (org-add-props cmd nil
7007 'face 'org-warning))))
7008 (message "%s => %s" cmd
7009 (if (equal (string-to-char cmd) ?\()
7010 (eval (read cmd))
7011 (call-interactively (read cmd))))
7012 (error "Abort"))))
7015 (browse-url-at-point)))))
7016 (move-marker org-open-link-marker nil)
7017 (run-hook-with-args 'org-follow-link-hook))
7019 ;;;; Time estimates
7021 (defun org-get-effort (&optional pom)
7022 "Get the effort estimate for the current entry."
7023 (org-entry-get pom org-effort-property))
7025 ;;; File search
7027 (defvar org-create-file-search-functions nil
7028 "List of functions to construct the right search string for a file link.
7029 These functions are called in turn with point at the location to
7030 which the link should point.
7032 A function in the hook should first test if it would like to
7033 handle this file type, for example by checking the major-mode or
7034 the file extension. If it decides not to handle this file, it
7035 should just return nil to give other functions a chance. If it
7036 does handle the file, it must return the search string to be used
7037 when following the link. The search string will be part of the
7038 file link, given after a double colon, and `org-open-at-point'
7039 will automatically search for it. If special measures must be
7040 taken to make the search successful, another function should be
7041 added to the companion hook `org-execute-file-search-functions',
7042 which see.
7044 A function in this hook may also use `setq' to set the variable
7045 `description' to provide a suggestion for the descriptive text to
7046 be used for this link when it gets inserted into an Org-mode
7047 buffer with \\[org-insert-link].")
7049 (defvar org-execute-file-search-functions nil
7050 "List of functions to execute a file search triggered by a link.
7052 Functions added to this hook must accept a single argument, the
7053 search string that was part of the file link, the part after the
7054 double colon. The function must first check if it would like to
7055 handle this search, for example by checking the major-mode or the
7056 file extension. If it decides not to handle this search, it
7057 should just return nil to give other functions a chance. If it
7058 does handle the search, it must return a non-nil value to keep
7059 other functions from trying.
7061 Each function can access the current prefix argument through the
7062 variable `current-prefix-argument'. Note that a single prefix is
7063 used to force opening a link in Emacs, so it may be good to only
7064 use a numeric or double prefix to guide the search function.
7066 In case this is needed, a function in this hook can also restore
7067 the window configuration before `org-open-at-point' was called using:
7069 (set-window-configuration org-window-config-before-follow-link)")
7071 (defun org-link-search (s &optional type avoid-pos)
7072 "Search for a link search option.
7073 If S is surrounded by forward slashes, it is interpreted as a
7074 regular expression. In org-mode files, this will create an `org-occur'
7075 sparse tree. In ordinary files, `occur' will be used to list matches.
7076 If the current buffer is in `dired-mode', grep will be used to search
7077 in all files. If AVOID-POS is given, ignore matches near that position."
7078 (let ((case-fold-search t)
7079 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7080 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7081 (append '(("") (" ") ("\t") ("\n"))
7082 org-emphasis-alist)
7083 "\\|") "\\)"))
7084 (pos (point))
7085 (pre nil) (post nil)
7086 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7087 (cond
7088 ;; First check if there are any special
7089 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7090 ;; Now try the builtin stuff
7091 ((save-excursion
7092 (goto-char (point-min))
7093 (and
7094 (re-search-forward
7095 (concat "<<" (regexp-quote s0) ">>") nil t)
7096 (setq type 'dedicated
7097 pos (match-beginning 0))))
7098 ;; There is an exact target for this
7099 (goto-char pos))
7100 ((string-match "^/\\(.*\\)/$" s)
7101 ;; A regular expression
7102 (cond
7103 ((org-mode-p)
7104 (org-occur (match-string 1 s)))
7105 ;;((eq major-mode 'dired-mode)
7106 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7107 (t (org-do-occur (match-string 1 s)))))
7109 ;; A normal search strings
7110 (when (equal (string-to-char s) ?*)
7111 ;; Anchor on headlines, post may include tags.
7112 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7113 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7114 s (substring s 1)))
7115 (remove-text-properties
7116 0 (length s)
7117 '(face nil mouse-face nil keymap nil fontified nil) s)
7118 ;; Make a series of regular expressions to find a match
7119 (setq words (org-split-string s "[ \n\r\t]+")
7121 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7122 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7123 "\\)" markers)
7124 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7125 re2a (concat "[ \t\r\n]" re2a_)
7126 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7127 re4 (concat "[^a-zA-Z_]" re4_)
7129 re1 (concat pre re2 post)
7130 re3 (concat pre (if pre re4_ re4) post)
7131 re5 (concat pre ".*" re4)
7132 re2 (concat pre re2)
7133 re2a (concat pre (if pre re2a_ re2a))
7134 re4 (concat pre (if pre re4_ re4))
7135 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7136 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7137 re5 "\\)"
7139 (cond
7140 ((eq type 'org-occur) (org-occur reall))
7141 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7142 (t (goto-char (point-min))
7143 (setq type 'fuzzy)
7144 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7145 (org-search-not-self 1 re1 nil t)
7146 (org-search-not-self 1 re2 nil t)
7147 (org-search-not-self 1 re2a nil t)
7148 (org-search-not-self 1 re3 nil t)
7149 (org-search-not-self 1 re4 nil t)
7150 (org-search-not-self 1 re5 nil t)
7152 (goto-char (match-beginning 1))
7153 (goto-char pos)
7154 (error "No match")))))
7156 ;; Normal string-search
7157 (goto-char (point-min))
7158 (if (search-forward s nil t)
7159 (goto-char (match-beginning 0))
7160 (error "No match"))))
7161 (and (org-mode-p) (org-show-context 'link-search))
7162 type))
7164 (defun org-search-not-self (group &rest args)
7165 "Execute `re-search-forward', but only accept matches that do not
7166 enclose the position of `org-open-link-marker'."
7167 (let ((m org-open-link-marker))
7168 (catch 'exit
7169 (while (apply 're-search-forward args)
7170 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7171 (goto-char (match-end group))
7172 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7173 (> (match-beginning 0) (marker-position m))
7174 (< (match-end 0) (marker-position m)))
7175 (save-match-data
7176 (or (not (org-in-regexp
7177 org-bracket-link-analytic-regexp 1))
7178 (not (match-end 4)) ; no description
7179 (and (<= (match-beginning 4) (point))
7180 (>= (match-end 4) (point))))))
7181 (throw 'exit (point))))))))
7183 (defun org-get-buffer-for-internal-link (buffer)
7184 "Return a buffer to be used for displaying the link target of internal links."
7185 (cond
7186 ((not org-display-internal-link-with-indirect-buffer)
7187 buffer)
7188 ((string-match "(Clone)$" (buffer-name buffer))
7189 (message "Buffer is already a clone, not making another one")
7190 ;; we also do not modify visibility in this case
7191 buffer)
7192 (t ; make a new indirect buffer for displaying the link
7193 (let* ((bn (buffer-name buffer))
7194 (ibn (concat bn "(Clone)"))
7195 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7196 (with-current-buffer ib (org-overview))
7197 ib))))
7199 (defun org-do-occur (regexp &optional cleanup)
7200 "Call the Emacs command `occur'.
7201 If CLEANUP is non-nil, remove the printout of the regular expression
7202 in the *Occur* buffer. This is useful if the regex is long and not useful
7203 to read."
7204 (occur regexp)
7205 (when cleanup
7206 (let ((cwin (selected-window)) win beg end)
7207 (when (setq win (get-buffer-window "*Occur*"))
7208 (select-window win))
7209 (goto-char (point-min))
7210 (when (re-search-forward "match[a-z]+" nil t)
7211 (setq beg (match-end 0))
7212 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7213 (setq end (1- (match-beginning 0)))))
7214 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7215 (goto-char (point-min))
7216 (select-window cwin))))
7218 ;;; The mark ring for links jumps
7220 (defvar org-mark-ring nil
7221 "Mark ring for positions before jumps in Org-mode.")
7222 (defvar org-mark-ring-last-goto nil
7223 "Last position in the mark ring used to go back.")
7224 ;; Fill and close the ring
7225 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7226 (loop for i from 1 to org-mark-ring-length do
7227 (push (make-marker) org-mark-ring))
7228 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7229 org-mark-ring)
7231 (defun org-mark-ring-push (&optional pos buffer)
7232 "Put the current position or POS into the mark ring and rotate it."
7233 (interactive)
7234 (setq pos (or pos (point)))
7235 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7236 (move-marker (car org-mark-ring)
7237 (or pos (point))
7238 (or buffer (current-buffer)))
7239 (message "%s"
7240 (substitute-command-keys
7241 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7243 (defun org-mark-ring-goto (&optional n)
7244 "Jump to the previous position in the mark ring.
7245 With prefix arg N, jump back that many stored positions. When
7246 called several times in succession, walk through the entire ring.
7247 Org-mode commands jumping to a different position in the current file,
7248 or to another Org-mode file, automatically push the old position
7249 onto the ring."
7250 (interactive "p")
7251 (let (p m)
7252 (if (eq last-command this-command)
7253 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7254 (setq p org-mark-ring))
7255 (setq org-mark-ring-last-goto p)
7256 (setq m (car p))
7257 (switch-to-buffer (marker-buffer m))
7258 (goto-char m)
7259 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7261 (defun org-remove-angle-brackets (s)
7262 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7263 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7265 (defun org-add-angle-brackets (s)
7266 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7267 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7269 (defun org-remove-double-quotes (s)
7270 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7271 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7274 ;;; Following specific links
7276 (defun org-follow-timestamp-link ()
7277 (cond
7278 ((org-at-date-range-p t)
7279 (let ((org-agenda-start-on-weekday)
7280 (t1 (match-string 1))
7281 (t2 (match-string 2)))
7282 (setq t1 (time-to-days (org-time-string-to-time t1))
7283 t2 (time-to-days (org-time-string-to-time t2)))
7284 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7285 ((org-at-timestamp-p t)
7286 (org-agenda-list nil (time-to-days (org-time-string-to-time
7287 (substring (match-string 1) 0 10)))
7289 (t (error "This should not happen"))))
7292 ;;; Following file links
7293 (defvar org-wait nil)
7294 (defun org-open-file (path &optional in-emacs line search)
7295 "Open the file at PATH.
7296 First, this expands any special file name abbreviations. Then the
7297 configuration variable `org-file-apps' is checked if it contains an
7298 entry for this file type, and if yes, the corresponding command is launched.
7300 If no application is found, Emacs simply visits the file.
7302 With optional prefix argument IN-EMACS, Emacs will visit the file.
7303 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7304 and o use an external application to visit the file.
7306 Optional LINE specifies a line to go to, optional SEARCH a string to
7307 search for. If LINE or SEARCH is given, the file will always be
7308 opened in Emacs.
7309 If the file does not exist, an error is thrown."
7310 (setq in-emacs (or in-emacs line search))
7311 (let* ((file (if (equal path "")
7312 buffer-file-name
7313 (substitute-in-file-name (expand-file-name path))))
7314 (apps (append org-file-apps (org-default-apps)))
7315 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7316 (dirp (if remp nil (file-directory-p file)))
7317 (file (if (and dirp org-open-directory-means-index-dot-org)
7318 (concat (file-name-as-directory file) "index.org")
7319 file))
7320 (a-m-a-p (assq 'auto-mode apps))
7321 (dfile (downcase file))
7322 (old-buffer (current-buffer))
7323 (old-pos (point))
7324 (old-mode major-mode)
7325 ext cmd)
7326 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7327 (setq ext (match-string 1 dfile))
7328 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7329 (setq ext (match-string 1 dfile))))
7330 (cond
7331 ((equal in-emacs '(16))
7332 (setq cmd (cdr (assoc 'system apps))))
7333 (in-emacs (setq cmd 'emacs))
7335 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7336 (and dirp (cdr (assoc 'directory apps)))
7337 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7338 'string-match)
7339 (cdr (assoc ext apps))
7340 (cdr (assoc t apps))))))
7341 (when (eq cmd 'system)
7342 (setq cmd (cdr (assoc 'system apps))))
7343 (when (eq cmd 'default)
7344 (setq cmd (cdr (assoc t apps))))
7345 (when (eq cmd 'mailcap)
7346 (require 'mailcap)
7347 (mailcap-parse-mailcaps)
7348 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7349 (command (mailcap-mime-info mime-type)))
7350 (if (stringp command)
7351 (setq cmd command)
7352 (setq cmd 'emacs))))
7353 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7354 (not (file-exists-p file))
7355 (not org-open-non-existing-files))
7356 (error "No such file: %s" file))
7357 (cond
7358 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7359 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7360 (while (string-match "['\"]%s['\"]" cmd)
7361 (setq cmd (replace-match "%s" t t cmd)))
7362 (while (string-match "%s" cmd)
7363 (setq cmd (replace-match
7364 (save-match-data
7365 (shell-quote-argument
7366 (convert-standard-filename file)))
7367 t t cmd)))
7368 (save-window-excursion
7369 (start-process-shell-command cmd nil cmd)
7370 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7372 ((or (stringp cmd)
7373 (eq cmd 'emacs))
7374 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7375 (widen)
7376 (if line (goto-line line)
7377 (if search (org-link-search search))))
7378 ((consp cmd)
7379 (let ((file (convert-standard-filename file)))
7380 (eval cmd)))
7381 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7382 (and (org-mode-p) (eq old-mode 'org-mode)
7383 (or (not (equal old-buffer (current-buffer)))
7384 (not (equal old-pos (point))))
7385 (org-mark-ring-push old-pos old-buffer))))
7387 (defun org-default-apps ()
7388 "Return the default applications for this operating system."
7389 (cond
7390 ((eq system-type 'darwin)
7391 org-file-apps-defaults-macosx)
7392 ((eq system-type 'windows-nt)
7393 org-file-apps-defaults-windowsnt)
7394 (t org-file-apps-defaults-gnu)))
7396 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7397 "Convert extensions to regular expressions in the cars of LIST.
7398 Also, weed out any non-string entries, because the return value is used
7399 only for regexp matching.
7400 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7401 point to the symbol `emacs', indicating that the file should
7402 be opened in Emacs."
7403 (append
7404 (delq nil
7405 (mapcar (lambda (x)
7406 (if (not (stringp (car x)))
7408 (if (string-match "\\W" (car x))
7410 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7411 list))
7412 (if add-auto-mode
7413 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7415 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7416 (defun org-file-remote-p (file)
7417 "Test whether FILE specifies a location on a remote system.
7418 Return non-nil if the location is indeed remote.
7420 For example, the filename \"/user@host:/foo\" specifies a location
7421 on the system \"/user@host:\"."
7422 (cond ((fboundp 'file-remote-p)
7423 (file-remote-p file))
7424 ((fboundp 'tramp-handle-file-remote-p)
7425 (tramp-handle-file-remote-p file))
7426 ((and (boundp 'ange-ftp-name-format)
7427 (string-match (car ange-ftp-name-format) file))
7429 (t nil)))
7432 ;;;; Refiling
7434 (defun org-get-org-file ()
7435 "Read a filename, with default directory `org-directory'."
7436 (let ((default (or org-default-notes-file remember-data-file)))
7437 (read-file-name (format "File name [%s]: " default)
7438 (file-name-as-directory org-directory)
7439 default)))
7441 (defun org-notes-order-reversed-p ()
7442 "Check if the current file should receive notes in reversed order."
7443 (cond
7444 ((not org-reverse-note-order) nil)
7445 ((eq t org-reverse-note-order) t)
7446 ((not (listp org-reverse-note-order)) nil)
7447 (t (catch 'exit
7448 (let ((all org-reverse-note-order)
7449 entry)
7450 (while (setq entry (pop all))
7451 (if (string-match (car entry) buffer-file-name)
7452 (throw 'exit (cdr entry))))
7453 nil)))))
7455 (defvar org-refile-target-table nil
7456 "The list of refile targets, created by `org-refile'.")
7458 (defvar org-agenda-new-buffers nil
7459 "Buffers created to visit agenda files.")
7461 (defun org-get-refile-targets (&optional default-buffer)
7462 "Produce a table with refile targets."
7463 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7464 targets txt re files f desc descre fast-path-p level)
7465 (message "Getting targets...")
7466 (with-current-buffer (or default-buffer (current-buffer))
7467 (while (setq entry (pop entries))
7468 (setq files (car entry) desc (cdr entry))
7469 (setq fast-path-p nil)
7470 (cond
7471 ((null files) (setq files (list (current-buffer))))
7472 ((eq files 'org-agenda-files)
7473 (setq files (org-agenda-files 'unrestricted)))
7474 ((and (symbolp files) (fboundp files))
7475 (setq files (funcall files)))
7476 ((and (symbolp files) (boundp files))
7477 (setq files (symbol-value files))))
7478 (if (stringp files) (setq files (list files)))
7479 (cond
7480 ((eq (car desc) :tag)
7481 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7482 ((eq (car desc) :todo)
7483 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7484 ((eq (car desc) :regexp)
7485 (setq descre (cdr desc)))
7486 ((eq (car desc) :level)
7487 (setq descre (concat "^\\*\\{" (number-to-string
7488 (if org-odd-levels-only
7489 (1- (* 2 (cdr desc)))
7490 (cdr desc)))
7491 "\\}[ \t]")))
7492 ((eq (car desc) :maxlevel)
7493 (setq fast-path-p t)
7494 (setq descre (concat "^\\*\\{1," (number-to-string
7495 (if org-odd-levels-only
7496 (1- (* 2 (cdr desc)))
7497 (cdr desc)))
7498 "\\}[ \t]")))
7499 (t (error "Bad refiling target description %s" desc)))
7500 (while (setq f (pop files))
7501 (save-excursion
7502 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7503 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7504 (save-excursion
7505 (save-restriction
7506 (widen)
7507 (goto-char (point-min))
7508 (while (re-search-forward descre nil t)
7509 (goto-char (point-at-bol))
7510 (when (looking-at org-complex-heading-regexp)
7511 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7512 txt (org-link-display-format (match-string 4))
7513 re (concat "^" (regexp-quote
7514 (buffer-substring (match-beginning 1)
7515 (match-end 4)))))
7516 (if (match-end 5) (setq re (concat re "[ \t]+"
7517 (regexp-quote
7518 (match-string 5)))))
7519 (setq re (concat re "[ \t]*$"))
7520 (when org-refile-use-outline-path
7521 (setq txt (mapconcat 'org-protect-slash
7522 (append
7523 (if (eq org-refile-use-outline-path 'file)
7524 (list (file-name-nondirectory
7525 (buffer-file-name (buffer-base-buffer))))
7526 (if (eq org-refile-use-outline-path 'full-file-path)
7527 (list (buffer-file-name (buffer-base-buffer)))))
7528 (org-get-outline-path fast-path-p level txt)
7529 (list txt))
7530 "/")))
7531 (push (list txt f re (point)) targets))
7532 (goto-char (point-at-eol))))))))
7533 (message "Getting targets...done")
7534 (nreverse targets))))
7536 (defun org-protect-slash (s)
7537 (while (string-match "/" s)
7538 (setq s (replace-match "\\" t t s)))
7541 (defvar org-olpa (make-vector 20 nil))
7543 (defun org-get-outline-path (&optional fastp level heading)
7544 "Return the outline path to the current entry, as a list."
7545 (if (> level 19) (error "Outline path failure, more than 19 levels."))
7546 (if fastp
7547 (progn
7548 (loop for i from level upto 19 do
7549 (aset org-olpa i nil))
7550 (prog1
7551 (delq nil (append org-olpa nil))
7552 (aset org-olpa level heading)))
7553 (let (rtn)
7554 (save-excursion
7555 (while (org-up-heading-safe)
7556 (when (looking-at org-complex-heading-regexp)
7557 (push (org-match-string-no-properties 4) rtn)))
7558 rtn))))
7560 (defvar org-refile-history nil
7561 "History for refiling operations.")
7563 (defun org-refile (&optional goto default-buffer)
7564 "Move the entry at point to another heading.
7565 The list of target headings is compiled using the information in
7566 `org-refile-targets', which see. This list is created before each use
7567 and will therefore always be up-to-date.
7569 At the target location, the entry is filed as a subitem of the target heading.
7570 Depending on `org-reverse-note-order', the new subitem will either be the
7571 first or the last subitem.
7573 If there is an active region, all entries in that region will be moved.
7574 However, the region must fulfil the requirement that the first heading
7575 is the first one sets the top-level of the moved text - at most siblings
7576 below it are allowed.
7578 With prefix arg GOTO, the command will only visit the target location,
7579 not actually move anything.
7580 With a double prefix `C-u C-u', go to the location where the last refiling
7581 operation has put the subtree."
7582 (interactive "P")
7583 (let* ((cbuf (current-buffer))
7584 (regionp (org-region-active-p))
7585 (region-start (and regionp (region-beginning)))
7586 (region-end (and regionp (region-end)))
7587 (region-length (and regionp (- region-end region-start)))
7588 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7589 pos it nbuf file re level reversed)
7590 (when regionp (goto-char region-start)
7591 (unless (org-kill-is-subtree-p
7592 (buffer-substring region-start region-end))
7593 (error "The region is not a (sequence of) subtree(s)")))
7594 (if (equal goto '(16))
7595 (org-refile-goto-last-stored)
7596 (when (setq it (org-refile-get-location
7597 (if goto "Goto: " "Refile to: ") default-buffer))
7598 (setq file (nth 1 it)
7599 re (nth 2 it)
7600 pos (nth 3 it))
7601 (if (and (equal (buffer-file-name) file)
7602 (if regionp
7603 (and (>= pos region-start)
7604 (<= pos region-end))
7605 (and (>= pos (point))
7606 (< pos (save-excursion
7607 (org-end-of-subtree t t))))))
7608 (error "Cannot refile to position inside the tree or region"))
7610 (setq nbuf (or (find-buffer-visiting file)
7611 (find-file-noselect file)))
7612 (if goto
7613 (progn
7614 (switch-to-buffer nbuf)
7615 (goto-char pos)
7616 (org-show-context 'org-goto))
7617 (if regionp
7618 (progn
7619 (kill-new (buffer-substring region-start region-end))
7620 (org-save-markers-in-region region-start region-end))
7621 (org-copy-subtree 1 nil t))
7622 (save-excursion
7623 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7624 (find-file-noselect file))))
7625 (setq reversed (org-notes-order-reversed-p))
7626 (save-excursion
7627 (save-restriction
7628 (widen)
7629 (goto-char pos)
7630 (looking-at outline-regexp)
7631 (setq level (org-get-valid-level (funcall outline-level) 1))
7632 (goto-char
7633 (if reversed
7634 (or (outline-next-heading) (point-max))
7635 (or (save-excursion (outline-get-next-sibling))
7636 (org-end-of-subtree t t)
7637 (point-max))))
7638 (if (not (bolp)) (newline))
7639 (bookmark-set "org-refile-last-stored")
7640 (org-paste-subtree level))))
7641 (if regionp
7642 (delete-region (point) (+ (point) region-length))
7643 (org-cut-subtree))
7644 (setq org-markers-to-move nil)
7645 (message "Refiled to \"%s\"" (car it)))))))
7647 (defun org-refile-goto-last-stored ()
7648 "Go to the location where the last refile was stored."
7649 (interactive)
7650 (bookmark-jump "org-refile-last-stored")
7651 (message "This is the location of the last refile"))
7653 (defun org-refile-get-location (&optional prompt default-buffer)
7654 "Prompt the user for a refile location, using PROMPT."
7655 (let ((org-refile-targets org-refile-targets)
7656 (org-refile-use-outline-path org-refile-use-outline-path))
7657 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7658 (unless org-refile-target-table
7659 (error "No refile targets"))
7660 (let* ((cbuf (current-buffer))
7661 (cfunc (if (and org-refile-use-outline-path
7662 org-outline-path-complete-in-steps)
7663 'org-olpath-completing-read
7664 'org-ido-completing-read))
7665 (extra (if org-refile-use-outline-path "/" ""))
7666 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7667 (tbl (mapcar
7668 (lambda (x)
7669 (if (not (equal filename (nth 1 x)))
7670 (cons (concat (car x) extra " ("
7671 (file-name-nondirectory (nth 1 x)) ")")
7672 (cdr x))
7673 (cons (concat (car x) extra) (cdr x))))
7674 org-refile-target-table))
7675 (completion-ignore-case t))
7676 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7677 tbl)))
7679 (defun org-olpath-completing-read (prompt collection &rest args)
7680 "Read an outline path like a file name."
7681 (let ((thetable collection))
7682 (apply
7683 'org-ido-completing-read prompt
7684 (lambda (string predicate &optional flag)
7685 (let (rtn r s f (l (length string)))
7686 (cond
7687 ((eq flag nil)
7688 ;; try completion
7689 (try-completion string thetable))
7690 ((eq flag t)
7691 ;; all-completions
7692 (setq rtn (all-completions string thetable predicate))
7693 (mapcar
7694 (lambda (x)
7695 (setq r (substring x l))
7696 (if (string-match " ([^)]*)$" x)
7697 (setq f (match-string 0 x))
7698 (setq f ""))
7699 (if (string-match "/" r)
7700 (concat string (substring r 0 (match-end 0)) f)
7702 rtn))
7703 ((eq flag 'lambda)
7704 ;; exact match?
7705 (assoc string thetable)))
7707 args)))
7709 ;;;; Dynamic blocks
7711 (defun org-find-dblock (name)
7712 "Find the first dynamic block with name NAME in the buffer.
7713 If not found, stay at current position and return nil."
7714 (let (pos)
7715 (save-excursion
7716 (goto-char (point-min))
7717 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7718 nil t)
7719 (match-beginning 0))))
7720 (if pos (goto-char pos))
7721 pos))
7723 (defconst org-dblock-start-re
7724 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7725 "Matches the startline of a dynamic block, with parameters.")
7727 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7728 "Matches the end of a dyhamic block.")
7730 (defun org-create-dblock (plist)
7731 "Create a dynamic block section, with parameters taken from PLIST.
7732 PLIST must containe a :name entry which is used as name of the block."
7733 (unless (bolp) (newline))
7734 (let ((name (plist-get plist :name)))
7735 (insert "#+BEGIN: " name)
7736 (while plist
7737 (if (eq (car plist) :name)
7738 (setq plist (cddr plist))
7739 (insert " " (prin1-to-string (pop plist)))))
7740 (insert "\n\n#+END:\n")
7741 (beginning-of-line -2)))
7743 (defun org-prepare-dblock ()
7744 "Prepare dynamic block for refresh.
7745 This empties the block, puts the cursor at the insert position and returns
7746 the property list including an extra property :name with the block name."
7747 (unless (looking-at org-dblock-start-re)
7748 (error "Not at a dynamic block"))
7749 (let* ((begdel (1+ (match-end 0)))
7750 (name (org-no-properties (match-string 1)))
7751 (params (append (list :name name)
7752 (read (concat "(" (match-string 3) ")")))))
7753 (unless (re-search-forward org-dblock-end-re nil t)
7754 (error "Dynamic block not terminated"))
7755 (setq params
7756 (append params
7757 (list :content (buffer-substring
7758 begdel (match-beginning 0)))))
7759 (delete-region begdel (match-beginning 0))
7760 (goto-char begdel)
7761 (open-line 1)
7762 params))
7764 (defun org-map-dblocks (&optional command)
7765 "Apply COMMAND to all dynamic blocks in the current buffer.
7766 If COMMAND is not given, use `org-update-dblock'."
7767 (let ((cmd (or command 'org-update-dblock))
7768 pos)
7769 (save-excursion
7770 (goto-char (point-min))
7771 (while (re-search-forward org-dblock-start-re nil t)
7772 (goto-char (setq pos (match-beginning 0)))
7773 (condition-case nil
7774 (funcall cmd)
7775 (error (message "Error during update of dynamic block")))
7776 (goto-char pos)
7777 (unless (re-search-forward org-dblock-end-re nil t)
7778 (error "Dynamic block not terminated"))))))
7780 (defun org-dblock-update (&optional arg)
7781 "User command for updating dynamic blocks.
7782 Update the dynamic block at point. With prefix ARG, update all dynamic
7783 blocks in the buffer."
7784 (interactive "P")
7785 (if arg
7786 (org-update-all-dblocks)
7787 (or (looking-at org-dblock-start-re)
7788 (org-beginning-of-dblock))
7789 (org-update-dblock)))
7791 (defun org-update-dblock ()
7792 "Update the dynamic block at point
7793 This means to empty the block, parse for parameters and then call
7794 the correct writing function."
7795 (save-window-excursion
7796 (let* ((pos (point))
7797 (line (org-current-line))
7798 (params (org-prepare-dblock))
7799 (name (plist-get params :name))
7800 (cmd (intern (concat "org-dblock-write:" name))))
7801 (message "Updating dynamic block `%s' at line %d..." name line)
7802 (funcall cmd params)
7803 (message "Updating dynamic block `%s' at line %d...done" name line)
7804 (goto-char pos))))
7806 (defun org-beginning-of-dblock ()
7807 "Find the beginning of the dynamic block at point.
7808 Error if there is no scuh block at point."
7809 (let ((pos (point))
7810 beg)
7811 (end-of-line 1)
7812 (if (and (re-search-backward org-dblock-start-re nil t)
7813 (setq beg (match-beginning 0))
7814 (re-search-forward org-dblock-end-re nil t)
7815 (> (match-end 0) pos))
7816 (goto-char beg)
7817 (goto-char pos)
7818 (error "Not in a dynamic block"))))
7820 (defun org-update-all-dblocks ()
7821 "Update all dynamic blocks in the buffer.
7822 This function can be used in a hook."
7823 (when (org-mode-p)
7824 (org-map-dblocks 'org-update-dblock)))
7827 ;;;; Completion
7829 (defconst org-additional-option-like-keywords
7830 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7831 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7832 "BEGIN_EXAMPLE" "END_EXAMPLE"
7833 "BEGIN_QUOTE" "END_QUOTE"
7834 "BEGIN_VERSE" "END_VERSE"
7835 "BEGIN_SRC" "END_SRC"
7836 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7838 (defcustom org-structure-template-alist
7840 ("s" "#+begin_src ?\n\n#+end_src"
7841 "<src lang=\"?\">\n\n</src>")
7842 ("e" "#+begin_example\n?\n#+end_example"
7843 "<example>\n?\n</example>")
7844 ("q" "#+begin_quote\n?\n#+end_quote"
7845 "<quote>\n?\n</quote>")
7846 ("v" "#+begin_verse\n?\n#+end_verse"
7847 "<verse>\n?\n/verse>")
7848 ("l" "#+begin_latex\n?\n#+end_latex"
7849 "<literal style=\"latex\">\n?\n</literal>")
7850 ("L" "#+latex: "
7851 "<literal style=\"latex\">?</literal>")
7852 ("h" "#+begin_html\n?\n#+end_html"
7853 "<literal style=\"html\">\n?\n</literal>")
7854 ("H" "#+html: "
7855 "<literal style=\"html\">?</literal>")
7856 ("a" "#+begin_ascii\n?\n#+end_ascii")
7857 ("A" "#+ascii: ")
7858 ("i" "#+include %file ?"
7859 "<include file=%file markup=\"?\">")
7861 "Structure completion elements.
7862 This is a list of abbreviation keys and values. The value gets inserted
7863 it you type @samp{.} followed by the key and then the completion key,
7864 usually `M-TAB'. %file will be replaced by a file name after prompting
7865 for the file uning completion.
7866 There are two templates for each key, the first uses the original Org syntax,
7867 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7868 the default when the /org-mtags.el/ module has been loaded. See also the
7869 variable `org-mtags-prefer-muse-templates'.
7870 This is an experimental feature, it is undecided if it is going to stay in."
7871 :group 'org-completion
7872 :type '(repeat
7873 (string :tag "Key")
7874 (string :tag "Template")
7875 (string :tag "Muse Template")))
7877 (defun org-try-structure-completion ()
7878 "Try to complete a structure template before point.
7879 This looks for strings like \"<e\" on an otherwise empty line and
7880 expands them."
7881 (let ((l (buffer-substring (point-at-bol) (point)))
7883 (when (and (looking-at "[ \t]*$")
7884 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7885 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7886 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7887 (match-beginning 1)) a)
7888 t)))
7890 (defun org-complete-expand-structure-template (start cell)
7891 "Expand a structure template."
7892 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7893 (rpl (nth (if musep 2 1) cell)))
7894 (delete-region start (point))
7895 (when (string-match "\\`#\\+" rpl)
7896 (cond
7897 ((bolp))
7898 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7899 (delete-region (point-at-bol) (point)))
7900 (t (newline))))
7901 (setq start (point))
7902 (if (string-match "%file" rpl)
7903 (setq rpl (replace-match
7904 (concat
7905 "\""
7906 (save-match-data
7907 (abbreviate-file-name (read-file-name "Include file: ")))
7908 "\"")
7909 t t rpl)))
7910 (insert rpl)
7911 (if (re-search-backward "\\?" start t) (delete-char 1))))
7914 (defun org-complete (&optional arg)
7915 "Perform completion on word at point.
7916 At the beginning of a headline, this completes TODO keywords as given in
7917 `org-todo-keywords'.
7918 If the current word is preceded by a backslash, completes the TeX symbols
7919 that are supported for HTML support.
7920 If the current word is preceded by \"#+\", completes special words for
7921 setting file options.
7922 In the line after \"#+STARTUP:, complete valid keywords.\"
7923 At all other locations, this simply calls the value of
7924 `org-completion-fallback-command'."
7925 (interactive "P")
7926 (org-without-partial-completion
7927 (catch 'exit
7928 (let* ((a nil)
7929 (end (point))
7930 (beg1 (save-excursion
7931 (skip-chars-backward (org-re "[:alnum:]_@"))
7932 (point)))
7933 (beg (save-excursion
7934 (skip-chars-backward "a-zA-Z0-9_:$")
7935 (point)))
7936 (confirm (lambda (x) (stringp (car x))))
7937 (searchhead (equal (char-before beg) ?*))
7938 (struct
7939 (when (and (member (char-before beg1) '(?. ?<))
7940 (setq a (assoc (buffer-substring beg1 (point))
7941 org-structure-template-alist)))
7942 (org-complete-expand-structure-template (1- beg1) a)
7943 (throw 'exit t)))
7944 (tag (and (equal (char-before beg1) ?:)
7945 (equal (char-after (point-at-bol)) ?*)))
7946 (prop (and (equal (char-before beg1) ?:)
7947 (not (equal (char-after (point-at-bol)) ?*))))
7948 (texp (equal (char-before beg) ?\\))
7949 (link (equal (char-before beg) ?\[))
7950 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7951 beg)
7952 "#+"))
7953 (startup (string-match "^#\\+STARTUP:.*"
7954 (buffer-substring (point-at-bol) (point))))
7955 (completion-ignore-case opt)
7956 (type nil)
7957 (tbl nil)
7958 (table (cond
7959 (opt
7960 (setq type :opt)
7961 (require 'org-exp)
7962 (append
7963 (mapcar
7964 (lambda (x)
7965 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7966 (cons (match-string 2 x) (match-string 1 x)))
7967 (org-split-string (org-get-current-options) "\n"))
7968 (mapcar 'list org-additional-option-like-keywords)))
7969 (startup
7970 (setq type :startup)
7971 org-startup-options)
7972 (link (append org-link-abbrev-alist-local
7973 org-link-abbrev-alist))
7974 (texp
7975 (setq type :tex)
7976 org-html-entities)
7977 ((string-match "\\`\\*+[ \t]+\\'"
7978 (buffer-substring (point-at-bol) beg))
7979 (setq type :todo)
7980 (mapcar 'list org-todo-keywords-1))
7981 (searchhead
7982 (setq type :searchhead)
7983 (save-excursion
7984 (goto-char (point-min))
7985 (while (re-search-forward org-todo-line-regexp nil t)
7986 (push (list
7987 (org-make-org-heading-search-string
7988 (match-string 3) t))
7989 tbl)))
7990 tbl)
7991 (tag (setq type :tag beg beg1)
7992 (or org-tag-alist (org-get-buffer-tags)))
7993 (prop (setq type :prop beg beg1)
7994 (mapcar 'list (org-buffer-property-keys nil t t)))
7995 (t (progn
7996 (call-interactively org-completion-fallback-command)
7997 (throw 'exit nil)))))
7998 (pattern (buffer-substring-no-properties beg end))
7999 (completion (try-completion pattern table confirm)))
8000 (cond ((eq completion t)
8001 (if (not (assoc (upcase pattern) table))
8002 (message "Already complete")
8003 (if (and (equal type :opt)
8004 (not (member (car (assoc (upcase pattern) table))
8005 org-additional-option-like-keywords)))
8006 (insert (substring (cdr (assoc (upcase pattern) table))
8007 (length pattern)))
8008 (if (memq type '(:tag :prop)) (insert ":")))))
8009 ((null completion)
8010 (message "Can't find completion for \"%s\"" pattern)
8011 (ding))
8012 ((not (string= pattern completion))
8013 (delete-region beg end)
8014 (if (string-match " +$" completion)
8015 (setq completion (replace-match "" t t completion)))
8016 (insert completion)
8017 (if (get-buffer-window "*Completions*")
8018 (delete-window (get-buffer-window "*Completions*")))
8019 (if (assoc completion table)
8020 (if (eq type :todo) (insert " ")
8021 (if (memq type '(:tag :prop)) (insert ":"))))
8022 (if (and (equal type :opt) (assoc completion table))
8023 (message "%s" (substitute-command-keys
8024 "Press \\[org-complete] again to insert example settings"))))
8026 (message "Making completion list...")
8027 (let ((list (sort (all-completions pattern table confirm)
8028 'string<)))
8029 (with-output-to-temp-buffer "*Completions*"
8030 (condition-case nil
8031 ;; Protection needed for XEmacs and emacs 21
8032 (display-completion-list list pattern)
8033 (error (display-completion-list list)))))
8034 (message "Making completion list...%s" "done")))))))
8036 ;;;; TODO, DEADLINE, Comments
8038 (defun org-toggle-comment ()
8039 "Change the COMMENT state of an entry."
8040 (interactive)
8041 (save-excursion
8042 (org-back-to-heading)
8043 (let (case-fold-search)
8044 (if (looking-at (concat outline-regexp
8045 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8046 (replace-match "" t t nil 1)
8047 (if (looking-at outline-regexp)
8048 (progn
8049 (goto-char (match-end 0))
8050 (insert org-comment-string " ")))))))
8052 (defvar org-last-todo-state-is-todo nil
8053 "This is non-nil when the last TODO state change led to a TODO state.
8054 If the last change removed the TODO tag or switched to DONE, then
8055 this is nil.")
8057 (defvar org-setting-tags nil) ; dynamically skiped
8059 (defun org-parse-local-options (string var)
8060 "Parse STRING for startup setting relevant for variable VAR."
8061 (let ((rtn (symbol-value var))
8062 e opts)
8063 (save-match-data
8064 (if (or (not string) (not (string-match "\\S-" string)))
8066 (setq opts (delq nil (mapcar (lambda (x)
8067 (setq e (assoc x org-startup-options))
8068 (if (eq (nth 1 e) var) e nil))
8069 (org-split-string string "[ \t]+"))))
8070 (if (not opts)
8072 (setq rtn nil)
8073 (while (setq e (pop opts))
8074 (if (not (nth 3 e))
8075 (setq rtn (nth 2 e))
8076 (if (not (listp rtn)) (setq rtn nil))
8077 (push (nth 2 e) rtn)))
8078 rtn)))))
8080 (defvar org-blocker-hook nil
8081 "Hook for functions that are allowed to block a state change.
8083 Each function gets as its single argument a property list, see
8084 `org-trigger-hook' for more information about this list.
8086 If any of the functions in this hook returns nil, the state change
8087 is blocked.")
8089 (defvar org-trigger-hook nil
8090 "Hook for functions that are triggered by a state change.
8092 Each function gets as its single argument a property list with at least
8093 the following elements:
8095 (:type type-of-change :position pos-at-entry-start
8096 :from old-state :to new-state)
8098 Depending on the type, more properties may be present.
8100 This mechanism is currently implemented for:
8102 TODO state changes
8103 ------------------
8104 :type todo-state-change
8105 :from previous state (keyword as a string), or nil
8106 :to new state (keyword as a string), or nil")
8108 (defvar org-agenda-headline-snapshot-before-repeat)
8109 (defun org-todo (&optional arg)
8110 "Change the TODO state of an item.
8111 The state of an item is given by a keyword at the start of the heading,
8112 like
8113 *** TODO Write paper
8114 *** DONE Call mom
8116 The different keywords are specified in the variable `org-todo-keywords'.
8117 By default the available states are \"TODO\" and \"DONE\".
8118 So for this example: when the item starts with TODO, it is changed to DONE.
8119 When it starts with DONE, the DONE is removed. And when neither TODO nor
8120 DONE are present, add TODO at the beginning of the heading.
8122 With C-u prefix arg, use completion to determine the new state.
8123 With numeric prefix arg, switch to that state.
8125 For calling through lisp, arg is also interpreted in the following way:
8126 'none -> empty state
8127 \"\"(empty string) -> switch to empty state
8128 'done -> switch to DONE
8129 'nextset -> switch to the next set of keywords
8130 'previousset -> switch to the previous set of keywords
8131 \"WAITING\" -> switch to the specified keyword, but only if it
8132 really is a member of `org-todo-keywords'."
8133 (interactive "P")
8134 (save-excursion
8135 (catch 'exit
8136 (org-back-to-heading)
8137 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8138 (or (looking-at (concat " +" org-todo-regexp " *"))
8139 (looking-at " *"))
8140 (let* ((match-data (match-data))
8141 (startpos (point-at-bol))
8142 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8143 (org-log-done org-log-done)
8144 (org-log-repeat org-log-repeat)
8145 (org-todo-log-states org-todo-log-states)
8146 (this (match-string 1))
8147 (hl-pos (match-beginning 0))
8148 (head (org-get-todo-sequence-head this))
8149 (ass (assoc head org-todo-kwd-alist))
8150 (interpret (nth 1 ass))
8151 (done-word (nth 3 ass))
8152 (final-done-word (nth 4 ass))
8153 (last-state (or this ""))
8154 (completion-ignore-case t)
8155 (member (member this org-todo-keywords-1))
8156 (tail (cdr member))
8157 (state (cond
8158 ((and org-todo-key-trigger
8159 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8160 (and (not arg) org-use-fast-todo-selection
8161 (not (eq org-use-fast-todo-selection 'prefix)))))
8162 ;; Use fast selection
8163 (org-fast-todo-selection))
8164 ((and (equal arg '(4))
8165 (or (not org-use-fast-todo-selection)
8166 (not org-todo-key-trigger)))
8167 ;; Read a state with completion
8168 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8169 org-todo-keywords-1)
8170 nil t))
8171 ((eq arg 'right)
8172 (if this
8173 (if tail (car tail) nil)
8174 (car org-todo-keywords-1)))
8175 ((eq arg 'left)
8176 (if (equal member org-todo-keywords-1)
8178 (if this
8179 (nth (- (length org-todo-keywords-1) (length tail) 2)
8180 org-todo-keywords-1)
8181 (org-last org-todo-keywords-1))))
8182 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8183 (setq arg nil))) ; hack to fall back to cycling
8184 (arg
8185 ;; user or caller requests a specific state
8186 (cond
8187 ((equal arg "") nil)
8188 ((eq arg 'none) nil)
8189 ((eq arg 'done) (or done-word (car org-done-keywords)))
8190 ((eq arg 'nextset)
8191 (or (car (cdr (member head org-todo-heads)))
8192 (car org-todo-heads)))
8193 ((eq arg 'previousset)
8194 (let ((org-todo-heads (reverse org-todo-heads)))
8195 (or (car (cdr (member head org-todo-heads)))
8196 (car org-todo-heads))))
8197 ((car (member arg org-todo-keywords-1)))
8198 ((nth (1- (prefix-numeric-value arg))
8199 org-todo-keywords-1))))
8200 ((null member) (or head (car org-todo-keywords-1)))
8201 ((equal this final-done-word) nil) ;; -> make empty
8202 ((null tail) nil) ;; -> first entry
8203 ((eq interpret 'sequence)
8204 (car tail))
8205 ((memq interpret '(type priority))
8206 (if (eq this-command last-command)
8207 (car tail)
8208 (if (> (length tail) 0)
8209 (or done-word (car org-done-keywords))
8210 nil)))
8211 (t nil)))
8212 (next (if state (concat " " state " ") " "))
8213 (change-plist (list :type 'todo-state-change :from this :to state
8214 :position startpos))
8215 dolog now-done-p)
8216 (when org-blocker-hook
8217 (unless (save-excursion
8218 (save-match-data
8219 (run-hook-with-args-until-failure
8220 'org-blocker-hook change-plist)))
8221 (if (interactive-p)
8222 (error "TODO state change from %s to %s blocked" this state)
8223 ;; fail silently
8224 (message "TODO state change from %s to %s blocked" this state)
8225 (throw 'exit nil))))
8226 (store-match-data match-data)
8227 (replace-match next t t)
8228 (unless (pos-visible-in-window-p hl-pos)
8229 (message "TODO state changed to %s" (org-trim next)))
8230 (unless head
8231 (setq head (org-get-todo-sequence-head state)
8232 ass (assoc head org-todo-kwd-alist)
8233 interpret (nth 1 ass)
8234 done-word (nth 3 ass)
8235 final-done-word (nth 4 ass)))
8236 (when (memq arg '(nextset previousset))
8237 (message "Keyword-Set %d/%d: %s"
8238 (- (length org-todo-sets) -1
8239 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8240 (length org-todo-sets)
8241 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8242 (setq org-last-todo-state-is-todo
8243 (not (member state org-done-keywords)))
8244 (setq now-done-p (and (member state org-done-keywords)
8245 (not (member this org-done-keywords))))
8246 (and logging (org-local-logging logging))
8247 (when (and (or org-todo-log-states org-log-done)
8248 (not (memq arg '(nextset previousset))))
8249 ;; we need to look at recording a time and note
8250 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8251 (nth 2 (assoc this org-todo-log-states))))
8252 (when (and state
8253 (member state org-not-done-keywords)
8254 (not (member this org-not-done-keywords)))
8255 ;; This is now a todo state and was not one before
8256 ;; If there was a CLOSED time stamp, get rid of it.
8257 (org-add-planning-info nil nil 'closed))
8258 (when (and now-done-p org-log-done)
8259 ;; It is now done, and it was not done before
8260 (org-add-planning-info 'closed (org-current-time))
8261 (if (and (not dolog) (eq 'note org-log-done))
8262 (org-add-log-setup 'done state 'findpos 'note)))
8263 (when (and state dolog)
8264 ;; This is a non-nil state, and we need to log it
8265 (org-add-log-setup 'state state 'findpos dolog)))
8266 ;; Fixup tag positioning
8267 (org-todo-trigger-tag-changes state)
8268 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8269 (when org-provide-todo-statistics
8270 (org-update-parent-todo-statistics))
8271 (run-hooks 'org-after-todo-state-change-hook)
8272 (if (and arg (not (member state org-done-keywords)))
8273 (setq head (org-get-todo-sequence-head state)))
8274 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8275 ;; Do we need to trigger a repeat?
8276 (when now-done-p
8277 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8278 ;; This is for the agenda, take a snapshot of the headline.
8279 (save-match-data
8280 (setq org-agenda-headline-snapshot-before-repeat
8281 (org-get-heading))))
8282 (org-auto-repeat-maybe state))
8283 ;; Fixup cursor location if close to the keyword
8284 (if (and (outline-on-heading-p)
8285 (not (bolp))
8286 (save-excursion (beginning-of-line 1)
8287 (looking-at org-todo-line-regexp))
8288 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8289 (progn
8290 (goto-char (or (match-end 2) (match-end 1)))
8291 (just-one-space)))
8292 (when org-trigger-hook
8293 (save-excursion
8294 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8296 (defun org-update-parent-todo-statistics ()
8297 "Update any statistics cookie in the parent of the current headline."
8298 (interactive)
8299 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8300 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8301 (catch 'exit
8302 (save-excursion
8303 (setq level (org-up-heading-safe))
8304 (unless (and level
8305 (re-search-forward box-re (point-at-eol) t))
8306 (throw 'exit nil))
8307 (setq is-percent (match-end 2))
8308 (save-match-data
8309 (unless (outline-next-heading) (throw 'exit nil))
8310 (while (looking-at org-todo-line-regexp)
8311 (setq kwd (match-string 2))
8312 (and kwd (setq cnt-all (1+ cnt-all)))
8313 (and (member kwd org-done-keywords)
8314 (setq cnt-done (1+ cnt-done)))
8315 (condition-case nil
8316 (org-forward-same-level 1)
8317 (error (end-of-line 1)))))
8318 (replace-match
8319 (if is-percent
8320 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8321 (format "[%d/%d]" cnt-done cnt-all)))
8322 (run-hook-with-args 'org-after-todo-statistics-hook
8323 cnt-done (- cnt-all cnt-done))))))
8325 (defvar org-after-todo-statistics-hook nil
8326 "Hook that is called after a TODO statistics cookie has been updated.
8327 Each function is called with two arguments: the number of not-done entries
8328 and the number of done entries.
8330 For example, the following function, when added to this hook, will switch
8331 an entry to DONE when all children are done, and back to TODO when new
8332 entries are set to a TODO status. Note that this hook is only called
8333 when there is a statistics cookie in the headline!
8335 (defun org-summary-todo (n-done n-not-done)
8336 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8337 (let (org-log-done org-log-states) ; turn off logging
8338 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8341 (defun org-todo-trigger-tag-changes (state)
8342 "Apply the changes defined in `org-todo-state-tags-triggers'."
8343 (let ((l org-todo-state-tags-triggers)
8344 changes)
8345 (when (or (not state) (equal state ""))
8346 (setq changes (append changes (cdr (assoc "" l)))))
8347 (when (and (stringp state) (> (length state) 0))
8348 (setq changes (append changes (cdr (assoc state l)))))
8349 (when (member state org-not-done-keywords)
8350 (setq changes (append changes (cdr (assoc 'todo l)))))
8351 (when (member state org-done-keywords)
8352 (setq changes (append changes (cdr (assoc 'done l)))))
8353 (dolist (c changes)
8354 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8356 (defun org-local-logging (value)
8357 "Get logging settings from a property VALUE."
8358 (let* (words w a)
8359 ;; directly set the variables, they are already local.
8360 (setq org-log-done nil
8361 org-log-repeat nil
8362 org-todo-log-states nil)
8363 (setq words (org-split-string value))
8364 (while (setq w (pop words))
8365 (cond
8366 ((setq a (assoc w org-startup-options))
8367 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8368 (set (nth 1 a) (nth 2 a))))
8369 ((setq a (org-extract-log-state-settings w))
8370 (and (member (car a) org-todo-keywords-1)
8371 (push a org-todo-log-states)))))))
8373 (defun org-get-todo-sequence-head (kwd)
8374 "Return the head of the TODO sequence to which KWD belongs.
8375 If KWD is not set, check if there is a text property remembering the
8376 right sequence."
8377 (let (p)
8378 (cond
8379 ((not kwd)
8380 (or (get-text-property (point-at-bol) 'org-todo-head)
8381 (progn
8382 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8383 nil (point-at-eol)))
8384 (get-text-property p 'org-todo-head))))
8385 ((not (member kwd org-todo-keywords-1))
8386 (car org-todo-keywords-1))
8387 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8389 (defun org-fast-todo-selection ()
8390 "Fast TODO keyword selection with single keys.
8391 Returns the new TODO keyword, or nil if no state change should occur."
8392 (let* ((fulltable org-todo-key-alist)
8393 (done-keywords org-done-keywords) ;; needed for the faces.
8394 (maxlen (apply 'max (mapcar
8395 (lambda (x)
8396 (if (stringp (car x)) (string-width (car x)) 0))
8397 fulltable)))
8398 (expert nil)
8399 (fwidth (+ maxlen 3 1 3))
8400 (ncol (/ (- (window-width) 4) fwidth))
8401 tg cnt e c tbl
8402 groups ingroup)
8403 (save-window-excursion
8404 (if expert
8405 (set-buffer (get-buffer-create " *Org todo*"))
8406 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8407 (erase-buffer)
8408 (org-set-local 'org-done-keywords done-keywords)
8409 (setq tbl fulltable cnt 0)
8410 (while (setq e (pop tbl))
8411 (cond
8412 ((equal e '(:startgroup))
8413 (push '() groups) (setq ingroup t)
8414 (when (not (= cnt 0))
8415 (setq cnt 0)
8416 (insert "\n"))
8417 (insert "{ "))
8418 ((equal e '(:endgroup))
8419 (setq ingroup nil cnt 0)
8420 (insert "}\n"))
8422 (setq tg (car e) c (cdr e))
8423 (if ingroup (push tg (car groups)))
8424 (setq tg (org-add-props tg nil 'face
8425 (org-get-todo-face tg)))
8426 (if (and (= cnt 0) (not ingroup)) (insert " "))
8427 (insert "[" c "] " tg (make-string
8428 (- fwidth 4 (length tg)) ?\ ))
8429 (when (= (setq cnt (1+ cnt)) ncol)
8430 (insert "\n")
8431 (if ingroup (insert " "))
8432 (setq cnt 0)))))
8433 (insert "\n")
8434 (goto-char (point-min))
8435 (if (not expert) (org-fit-window-to-buffer))
8436 (message "[a-z..]:Set [SPC]:clear")
8437 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8438 (cond
8439 ((or (= c ?\C-g)
8440 (and (= c ?q) (not (rassoc c fulltable))))
8441 (setq quit-flag t))
8442 ((= c ?\ ) nil)
8443 ((setq e (rassoc c fulltable) tg (car e))
8445 (t (setq quit-flag t))))))
8447 (defun org-entry-is-todo-p ()
8448 (member (org-get-todo-state) org-not-done-keywords))
8450 (defun org-entry-is-done-p ()
8451 (member (org-get-todo-state) org-done-keywords))
8453 (defun org-get-todo-state ()
8454 (save-excursion
8455 (org-back-to-heading t)
8456 (and (looking-at org-todo-line-regexp)
8457 (match-end 2)
8458 (match-string 2))))
8460 (defun org-at-date-range-p (&optional inactive-ok)
8461 "Is the cursor inside a date range?"
8462 (interactive)
8463 (save-excursion
8464 (catch 'exit
8465 (let ((pos (point)))
8466 (skip-chars-backward "^[<\r\n")
8467 (skip-chars-backward "<[")
8468 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8469 (>= (match-end 0) pos)
8470 (throw 'exit t))
8471 (skip-chars-backward "^<[\r\n")
8472 (skip-chars-backward "<[")
8473 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8474 (>= (match-end 0) pos)
8475 (throw 'exit t)))
8476 nil)))
8478 (defun org-get-repeat ()
8479 "Check if there is a deadline/schedule with repeater in this entry."
8480 (save-match-data
8481 (save-excursion
8482 (org-back-to-heading t)
8483 (if (re-search-forward
8484 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8485 (match-string 1)))))
8487 (defvar org-last-changed-timestamp)
8488 (defvar org-last-inserted-timestamp)
8489 (defvar org-log-post-message)
8490 (defvar org-log-note-purpose)
8491 (defvar org-log-note-how)
8492 (defvar org-log-note-extra)
8493 (defun org-auto-repeat-maybe (done-word)
8494 "Check if the current headline contains a repeated deadline/schedule.
8495 If yes, set TODO state back to what it was and change the base date
8496 of repeating deadline/scheduled time stamps to new date.
8497 This function is run automatically after each state change to a DONE state."
8498 ;; last-state is dynamically scoped into this function
8499 (let* ((repeat (org-get-repeat))
8500 (aa (assoc last-state org-todo-kwd-alist))
8501 (interpret (nth 1 aa))
8502 (head (nth 2 aa))
8503 (whata '(("d" . day) ("m" . month) ("y" . year)))
8504 (msg "Entry repeats: ")
8505 (org-log-done nil)
8506 (org-todo-log-states nil)
8507 (nshiftmax 10) (nshift 0)
8508 re type n what ts mb0 time)
8509 (when repeat
8510 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8511 (org-todo (if (eq interpret 'type) last-state head))
8512 (when org-log-repeat
8513 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8514 (memq 'org-add-log-note post-command-hook))
8515 ;; OK, we are already setup for some record
8516 (if (eq org-log-repeat 'note)
8517 ;; make sure we take a note, not only a time stamp
8518 (setq org-log-note-how 'note))
8519 ;; Set up for taking a record
8520 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8521 'findpos org-log-repeat)))
8522 (org-back-to-heading t)
8523 (org-add-planning-info nil nil 'closed)
8524 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8525 org-deadline-time-regexp "\\)\\|\\("
8526 org-ts-regexp "\\)"))
8527 (while (re-search-forward
8528 re (save-excursion (outline-next-heading) (point)) t)
8529 (setq type (if (match-end 1) org-scheduled-string
8530 (if (match-end 3) org-deadline-string "Plain:"))
8531 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8532 mb0 (match-beginning 0))
8533 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8534 (setq n (string-to-number (match-string 2 ts))
8535 what (match-string 3 ts))
8536 (if (equal what "w") (setq n (* n 7) what "d"))
8537 ;; Preparation, see if we need to modify the start date for the change
8538 (when (match-end 1)
8539 (setq time (save-match-data (org-time-string-to-time ts)))
8540 (cond
8541 ((equal (match-string 1 ts) ".")
8542 ;; Shift starting date to today
8543 (org-timestamp-change
8544 (- (time-to-days (current-time)) (time-to-days time))
8545 'day))
8546 ((equal (match-string 1 ts) "+")
8547 (while (or (= nshift 0)
8548 (<= (time-to-days time) (time-to-days (current-time))))
8549 (when (= (incf nshift) nshiftmax)
8550 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8551 (error "Abort")))
8552 (org-timestamp-change n (cdr (assoc what whata)))
8553 (org-at-timestamp-p t)
8554 (setq ts (match-string 1))
8555 (setq time (save-match-data (org-time-string-to-time ts))))
8556 (org-timestamp-change (- n) (cdr (assoc what whata)))
8557 ;; rematch, so that we have everything in place for the real shift
8558 (org-at-timestamp-p t)
8559 (setq ts (match-string 1))
8560 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8561 (org-timestamp-change n (cdr (assoc what whata)))
8562 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8563 (setq org-log-post-message msg)
8564 (message "%s" msg))))
8566 (defun org-show-todo-tree (arg)
8567 "Make a compact tree which shows all headlines marked with TODO.
8568 The tree will show the lines where the regexp matches, and all higher
8569 headlines above the match.
8570 With a \\[universal-argument] prefix, also show the DONE entries.
8571 With a numeric prefix N, construct a sparse tree for the Nth element
8572 of `org-todo-keywords-1'."
8573 (interactive "P")
8574 (let ((case-fold-search nil)
8575 (kwd-re
8576 (cond ((null arg) org-not-done-regexp)
8577 ((equal arg '(4))
8578 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8579 (mapcar 'list org-todo-keywords-1))))
8580 (concat "\\("
8581 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8582 "\\)\\>")))
8583 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8584 (regexp-quote (nth (1- (prefix-numeric-value arg))
8585 org-todo-keywords-1)))
8586 (t (error "Invalid prefix argument: %s" arg)))))
8587 (message "%d TODO entries found"
8588 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8590 (defun org-deadline (&optional remove time)
8591 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8592 With argument REMOVE, remove any deadline from the item.
8593 When TIME is set, it should be an internal time specification, and the
8594 scheduling will use the corresponding date."
8595 (interactive "P")
8596 (if remove
8597 (progn
8598 (org-remove-timestamp-with-keyword org-deadline-string)
8599 (message "Item no longer has a deadline."))
8600 (if (org-get-repeat)
8601 (error "Cannot change deadline on task with repeater, please do that by hand")
8602 (org-add-planning-info 'deadline time 'closed)
8603 (message "Deadline on %s" org-last-inserted-timestamp))))
8605 (defun org-schedule (&optional remove time)
8606 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8607 With argument REMOVE, remove any scheduling date from the item.
8608 When TIME is set, it should be an internal time specification, and the
8609 scheduling will use the corresponding date."
8610 (interactive "P")
8611 (if remove
8612 (progn
8613 (org-remove-timestamp-with-keyword org-scheduled-string)
8614 (message "Item is no longer scheduled."))
8615 (if (org-get-repeat)
8616 (error "Cannot reschedule task with repeater, please do that by hand")
8617 (org-add-planning-info 'scheduled time 'closed)
8618 (message "Scheduled to %s" org-last-inserted-timestamp))))
8620 (defun org-remove-timestamp-with-keyword (keyword)
8621 "Remove all time stamps with KEYWORD in the current entry."
8622 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8623 beg)
8624 (save-excursion
8625 (org-back-to-heading t)
8626 (setq beg (point))
8627 (org-end-of-subtree t t)
8628 (while (re-search-backward re beg t)
8629 (replace-match "")
8630 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8631 (equal (char-before) ?\ ))
8632 (backward-delete-char 1)
8633 (if (string-match "^[ \t]*$" (buffer-substring
8634 (point-at-bol) (point-at-eol)))
8635 (delete-region (point-at-bol)
8636 (min (point-max) (1+ (point-at-eol))))))))))
8638 (defun org-add-planning-info (what &optional time &rest remove)
8639 "Insert new timestamp with keyword in the line directly after the headline.
8640 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8641 If non is given, the user is prompted for a date.
8642 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8643 be removed."
8644 (interactive)
8645 (let (org-time-was-given org-end-time-was-given ts
8646 end default-time default-input)
8648 (when (and (not time) (memq what '(scheduled deadline)))
8649 ;; Try to get a default date/time from existing timestamp
8650 (save-excursion
8651 (org-back-to-heading t)
8652 (setq end (save-excursion (outline-next-heading) (point)))
8653 (when (re-search-forward (if (eq what 'scheduled)
8654 org-scheduled-time-regexp
8655 org-deadline-time-regexp)
8656 end t)
8657 (setq ts (match-string 1)
8658 default-time
8659 (apply 'encode-time (org-parse-time-string ts))
8660 default-input (and ts (org-get-compact-tod ts))))))
8661 (when what
8662 ;; If necessary, get the time from the user
8663 (setq time (or time (org-read-date nil 'to-time nil nil
8664 default-time default-input))))
8666 (when (and org-insert-labeled-timestamps-at-point
8667 (member what '(scheduled deadline)))
8668 (insert
8669 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8670 (org-insert-time-stamp time org-time-was-given
8671 nil nil nil (list org-end-time-was-given))
8672 (setq what nil))
8673 (save-excursion
8674 (save-restriction
8675 (let (col list elt ts buffer-invisibility-spec)
8676 (org-back-to-heading t)
8677 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8678 (goto-char (match-end 1))
8679 (setq col (current-column))
8680 (goto-char (match-end 0))
8681 (if (eobp) (insert "\n") (forward-char 1))
8682 (if (and (not (looking-at outline-regexp))
8683 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8684 "[^\r\n]*"))
8685 (not (equal (match-string 1) org-clock-string)))
8686 (narrow-to-region (match-beginning 0) (match-end 0))
8687 (insert-before-markers "\n")
8688 (backward-char 1)
8689 (narrow-to-region (point) (point))
8690 (and org-adapt-indentation (org-indent-to-column col)))
8691 ;; Check if we have to remove something.
8692 (setq list (cons what remove))
8693 (while list
8694 (setq elt (pop list))
8695 (goto-char (point-min))
8696 (when (or (and (eq elt 'scheduled)
8697 (re-search-forward org-scheduled-time-regexp nil t))
8698 (and (eq elt 'deadline)
8699 (re-search-forward org-deadline-time-regexp nil t))
8700 (and (eq elt 'closed)
8701 (re-search-forward org-closed-time-regexp nil t)))
8702 (replace-match "")
8703 (if (looking-at "--+<[^>]+>") (replace-match ""))
8704 (if (looking-at " +") (replace-match ""))))
8705 (goto-char (point-max))
8706 (when what
8707 (insert
8708 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8709 (cond ((eq what 'scheduled) org-scheduled-string)
8710 ((eq what 'deadline) org-deadline-string)
8711 ((eq what 'closed) org-closed-string))
8712 " ")
8713 (setq ts (org-insert-time-stamp
8714 time
8715 (or org-time-was-given
8716 (and (eq what 'closed) org-log-done-with-time))
8717 (eq what 'closed)
8718 nil nil (list org-end-time-was-given)))
8719 (end-of-line 1))
8720 (goto-char (point-min))
8721 (widen)
8722 (if (and (looking-at "[ \t]+\n")
8723 (equal (char-before) ?\n))
8724 (delete-region (1- (point)) (point-at-eol)))
8725 ts)))))
8727 (defvar org-log-note-marker (make-marker))
8728 (defvar org-log-note-purpose nil)
8729 (defvar org-log-note-state nil)
8730 (defvar org-log-note-how nil)
8731 (defvar org-log-note-extra nil)
8732 (defvar org-log-note-window-configuration nil)
8733 (defvar org-log-note-return-to (make-marker))
8734 (defvar org-log-post-message nil
8735 "Message to be displayed after a log note has been stored.
8736 The auto-repeater uses this.")
8738 (defun org-add-note ()
8739 "Add a note to the current entry.
8740 This is done in the same way as adding a state change note."
8741 (interactive)
8742 (org-add-log-setup 'note nil 'findpos nil))
8744 (defvar org-property-end-re)
8745 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8746 "Set up the post command hook to take a note.
8747 If this is about to TODO state change, the new state is expected in STATE.
8748 When FINDPOS is non-nil, find the correct position for the note in
8749 the current entry. If not, assume that it can be inserted at point.
8750 HOW is an indicator what kind of note should be created.
8751 EXTRA is additional text that will be inserted into the notes buffer."
8752 (save-restriction
8753 (save-excursion
8754 (when findpos
8755 (org-back-to-heading t)
8756 (narrow-to-region (point) (save-excursion
8757 (outline-next-heading) (point)))
8758 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8759 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8760 "[^\r\n]*\\)?"))
8761 (goto-char (match-end 0))
8762 (when (and org-log-state-notes-insert-after-drawers
8763 (save-excursion
8764 (forward-line) (looking-at org-drawer-regexp)))
8765 (progn (forward-line)
8766 (while (looking-at org-drawer-regexp)
8767 (goto-char (match-end 0))
8768 (re-search-forward org-property-end-re (point-max) t)
8769 (forward-line))
8770 (forward-line -1)))
8771 (unless org-log-states-order-reversed
8772 (and (= (char-after) ?\n) (forward-char 1))
8773 (org-skip-over-state-notes)
8774 (skip-chars-backward " \t\n\r")))
8775 (move-marker org-log-note-marker (point))
8776 (setq org-log-note-purpose purpose
8777 org-log-note-state state
8778 org-log-note-how how
8779 org-log-note-extra extra)
8780 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8782 (defun org-skip-over-state-notes ()
8783 "Skip past the list of State notes in an entry."
8784 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8785 (while (looking-at "[ \t]*- State")
8786 (condition-case nil
8787 (org-next-item)
8788 (error (org-end-of-item)))))
8790 (defun org-add-log-note (&optional purpose)
8791 "Pop up a window for taking a note, and add this note later at point."
8792 (remove-hook 'post-command-hook 'org-add-log-note)
8793 (setq org-log-note-window-configuration (current-window-configuration))
8794 (delete-other-windows)
8795 (move-marker org-log-note-return-to (point))
8796 (switch-to-buffer (marker-buffer org-log-note-marker))
8797 (goto-char org-log-note-marker)
8798 (org-switch-to-buffer-other-window "*Org Note*")
8799 (erase-buffer)
8800 (if (memq org-log-note-how '(time state))
8801 (let (current-prefix-arg) (org-store-log-note))
8802 (let ((org-inhibit-startup t)) (org-mode))
8803 (insert (format "# Insert note for %s.
8804 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8805 (cond
8806 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8807 ((eq org-log-note-purpose 'done) "closed todo item")
8808 ((eq org-log-note-purpose 'state)
8809 (format "state change to \"%s\"" org-log-note-state))
8810 ((eq org-log-note-purpose 'note)
8811 "this entry")
8812 (t (error "This should not happen")))))
8813 (if org-log-note-extra (insert org-log-note-extra))
8814 (org-set-local 'org-finish-function 'org-store-log-note)))
8816 (defvar org-note-abort nil) ; dynamically scoped
8817 (defun org-store-log-note ()
8818 "Finish taking a log note, and insert it to where it belongs."
8819 (let ((txt (buffer-string))
8820 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8821 lines ind)
8822 (kill-buffer (current-buffer))
8823 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8824 (setq txt (replace-match "" t t txt)))
8825 (if (string-match "\\s-+\\'" txt)
8826 (setq txt (replace-match "" t t txt)))
8827 (setq lines (org-split-string txt "\n"))
8828 (when (and note (string-match "\\S-" note))
8829 (setq note
8830 (org-replace-escapes
8831 note
8832 (list (cons "%u" (user-login-name))
8833 (cons "%U" user-full-name)
8834 (cons "%t" (format-time-string
8835 (org-time-stamp-format 'long 'inactive)
8836 (current-time)))
8837 (cons "%s" (if org-log-note-state
8838 (concat "\"" org-log-note-state "\"")
8839 "")))))
8840 (if lines (setq note (concat note " \\\\")))
8841 (push note lines))
8842 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8843 (when lines
8844 (save-excursion
8845 (set-buffer (marker-buffer org-log-note-marker))
8846 (save-excursion
8847 (goto-char org-log-note-marker)
8848 (move-marker org-log-note-marker nil)
8849 (end-of-line 1)
8850 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8851 (indent-relative nil)
8852 (insert "- " (pop lines))
8853 (org-indent-line-function)
8854 (beginning-of-line 1)
8855 (looking-at "[ \t]*")
8856 (setq ind (concat (match-string 0) " "))
8857 (end-of-line 1)
8858 (while lines (insert "\n" ind (pop lines)))))))
8859 (set-window-configuration org-log-note-window-configuration)
8860 (with-current-buffer (marker-buffer org-log-note-return-to)
8861 (goto-char org-log-note-return-to))
8862 (move-marker org-log-note-return-to nil)
8863 (and org-log-post-message (message "%s" org-log-post-message)))
8865 (defun org-sparse-tree (&optional arg)
8866 "Create a sparse tree, prompt for the details.
8867 This command can create sparse trees. You first need to select the type
8868 of match used to create the tree:
8870 t Show entries with a specific TODO keyword.
8871 T Show entries selected by a tags match.
8872 p Enter a property name and its value (both with completion on existing
8873 names/values) and show entries with that property.
8874 r Show entries matching a regular expression
8875 d Show deadlines due within `org-deadline-warning-days'."
8876 (interactive "P")
8877 (let (ans kwd value)
8878 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8879 (setq ans (read-char-exclusive))
8880 (cond
8881 ((equal ans ?d)
8882 (call-interactively 'org-check-deadlines))
8883 ((equal ans ?b)
8884 (call-interactively 'org-check-before-date))
8885 ((equal ans ?t)
8886 (org-show-todo-tree '(4)))
8887 ((equal ans ?T)
8888 (call-interactively 'org-tags-sparse-tree))
8889 ((member ans '(?p ?P))
8890 (setq kwd (org-ido-completing-read "Property: "
8891 (mapcar 'list (org-buffer-property-keys))))
8892 (setq value (org-ido-completing-read "Value: "
8893 (mapcar 'list (org-property-values kwd))))
8894 (unless (string-match "\\`{.*}\\'" value)
8895 (setq value (concat "\"" value "\"")))
8896 (org-tags-sparse-tree arg (concat kwd "=" value)))
8897 ((member ans '(?r ?R ?/))
8898 (call-interactively 'org-occur))
8899 (t (error "No such sparse tree command \"%c\"" ans)))))
8901 (defvar org-occur-highlights nil
8902 "List of overlays used for occur matches.")
8903 (make-variable-buffer-local 'org-occur-highlights)
8904 (defvar org-occur-parameters nil
8905 "Parameters of the active org-occur calls.
8906 This is a list, each call to org-occur pushes as cons cell,
8907 containing the regular expression and the callback, onto the list.
8908 The list can contain several entries if `org-occur' has been called
8909 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8910 will only contain one set of parameters. When the highlights are
8911 removed (for example with `C-c C-c', or with the next edit (depending
8912 on `org-remove-highlights-with-change'), this variable is emptied
8913 as well.")
8914 (make-variable-buffer-local 'org-occur-parameters)
8916 (defun org-occur (regexp &optional keep-previous callback)
8917 "Make a compact tree which shows all matches of REGEXP.
8918 The tree will show the lines where the regexp matches, and all higher
8919 headlines above the match. It will also show the heading after the match,
8920 to make sure editing the matching entry is easy.
8921 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8922 call to `org-occur' will be kept, to allow stacking of calls to this
8923 command.
8924 If CALLBACK is non-nil, it is a function which is called to confirm
8925 that the match should indeed be shown."
8926 (interactive "sRegexp: \nP")
8927 (unless keep-previous
8928 (org-remove-occur-highlights nil nil t))
8929 (push (cons regexp callback) org-occur-parameters)
8930 (let ((cnt 0))
8931 (save-excursion
8932 (goto-char (point-min))
8933 (if (or (not keep-previous) ; do not want to keep
8934 (not org-occur-highlights)) ; no previous matches
8935 ;; hide everything
8936 (org-overview))
8937 (while (re-search-forward regexp nil t)
8938 (when (or (not callback)
8939 (save-match-data (funcall callback)))
8940 (setq cnt (1+ cnt))
8941 (when org-highlight-sparse-tree-matches
8942 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8943 (org-show-context 'occur-tree))))
8944 (when org-remove-highlights-with-change
8945 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8946 nil 'local))
8947 (unless org-sparse-tree-open-archived-trees
8948 (org-hide-archived-subtrees (point-min) (point-max)))
8949 (run-hooks 'org-occur-hook)
8950 (if (interactive-p)
8951 (message "%d match(es) for regexp %s" cnt regexp))
8952 cnt))
8954 (defun org-show-context (&optional key)
8955 "Make sure point and context and visible.
8956 How much context is shown depends upon the variables
8957 `org-show-hierarchy-above', `org-show-following-heading'. and
8958 `org-show-siblings'."
8959 (let ((heading-p (org-on-heading-p t))
8960 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8961 (following-p (org-get-alist-option org-show-following-heading key))
8962 (entry-p (org-get-alist-option org-show-entry-below key))
8963 (siblings-p (org-get-alist-option org-show-siblings key)))
8964 (catch 'exit
8965 ;; Show heading or entry text
8966 (if (and heading-p (not entry-p))
8967 (org-flag-heading nil) ; only show the heading
8968 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8969 (org-show-hidden-entry))) ; show entire entry
8970 (when following-p
8971 ;; Show next sibling, or heading below text
8972 (save-excursion
8973 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8974 (org-flag-heading nil))))
8975 (when siblings-p (org-show-siblings))
8976 (when hierarchy-p
8977 ;; show all higher headings, possibly with siblings
8978 (save-excursion
8979 (while (and (condition-case nil
8980 (progn (org-up-heading-all 1) t)
8981 (error nil))
8982 (not (bobp)))
8983 (org-flag-heading nil)
8984 (when siblings-p (org-show-siblings))))))))
8986 (defun org-reveal (&optional siblings)
8987 "Show current entry, hierarchy above it, and the following headline.
8988 This can be used to show a consistent set of context around locations
8989 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8990 not t for the search context.
8992 With optional argument SIBLINGS, on each level of the hierarchy all
8993 siblings are shown. This repairs the tree structure to what it would
8994 look like when opened with hierarchical calls to `org-cycle'."
8995 (interactive "P")
8996 (let ((org-show-hierarchy-above t)
8997 (org-show-following-heading t)
8998 (org-show-siblings (if siblings t org-show-siblings)))
8999 (org-show-context nil)))
9001 (defun org-highlight-new-match (beg end)
9002 "Highlight from BEG to END and mark the highlight is an occur headline."
9003 (let ((ov (org-make-overlay beg end)))
9004 (org-overlay-put ov 'face 'secondary-selection)
9005 (push ov org-occur-highlights)))
9007 (defun org-remove-occur-highlights (&optional beg end noremove)
9008 "Remove the occur highlights from the buffer.
9009 BEG and END are ignored. If NOREMOVE is nil, remove this function
9010 from the `before-change-functions' in the current buffer."
9011 (interactive)
9012 (unless org-inhibit-highlight-removal
9013 (mapc 'org-delete-overlay org-occur-highlights)
9014 (setq org-occur-highlights nil)
9015 (setq org-occur-parameters nil)
9016 (unless noremove
9017 (remove-hook 'before-change-functions
9018 'org-remove-occur-highlights 'local))))
9020 ;;;; Priorities
9022 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9023 "Regular expression matching the priority indicator.")
9025 (defvar org-remove-priority-next-time nil)
9027 (defun org-priority-up ()
9028 "Increase the priority of the current item."
9029 (interactive)
9030 (org-priority 'up))
9032 (defun org-priority-down ()
9033 "Decrease the priority of the current item."
9034 (interactive)
9035 (org-priority 'down))
9037 (defun org-priority (&optional action)
9038 "Change the priority of an item by ARG.
9039 ACTION can be `set', `up', `down', or a character."
9040 (interactive)
9041 (setq action (or action 'set))
9042 (let (current new news have remove)
9043 (save-excursion
9044 (org-back-to-heading)
9045 (if (looking-at org-priority-regexp)
9046 (setq current (string-to-char (match-string 2))
9047 have t)
9048 (setq current org-default-priority))
9049 (cond
9050 ((or (eq action 'set)
9051 (if (featurep 'xemacs) (characterp action) (integerp action)))
9052 (if (not (eq action 'set))
9053 (setq new action)
9054 (message "Priority %c-%c, SPC to remove: "
9055 org-highest-priority org-lowest-priority)
9056 (setq new (read-char-exclusive)))
9057 (if (and (= (upcase org-highest-priority) org-highest-priority)
9058 (= (upcase org-lowest-priority) org-lowest-priority))
9059 (setq new (upcase new)))
9060 (cond ((equal new ?\ ) (setq remove t))
9061 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9062 (error "Priority must be between `%c' and `%c'"
9063 org-highest-priority org-lowest-priority))))
9064 ((eq action 'up)
9065 (if (and (not have) (eq last-command this-command))
9066 (setq new org-lowest-priority)
9067 (setq new (if (and org-priority-start-cycle-with-default (not have))
9068 org-default-priority (1- current)))))
9069 ((eq action 'down)
9070 (if (and (not have) (eq last-command this-command))
9071 (setq new org-highest-priority)
9072 (setq new (if (and org-priority-start-cycle-with-default (not have))
9073 org-default-priority (1+ current)))))
9074 (t (error "Invalid action")))
9075 (if (or (< (upcase new) org-highest-priority)
9076 (> (upcase new) org-lowest-priority))
9077 (setq remove t))
9078 (setq news (format "%c" new))
9079 (if have
9080 (if remove
9081 (replace-match "" t t nil 1)
9082 (replace-match news t t nil 2))
9083 (if remove
9084 (error "No priority cookie found in line")
9085 (looking-at org-todo-line-regexp)
9086 (if (match-end 2)
9087 (progn
9088 (goto-char (match-end 2))
9089 (insert " [#" news "]"))
9090 (goto-char (match-beginning 3))
9091 (insert "[#" news "] ")))))
9092 (org-preserve-lc (org-set-tags nil 'align))
9093 (if remove
9094 (message "Priority removed")
9095 (message "Priority of current item set to %s" news))))
9098 (defun org-get-priority (s)
9099 "Find priority cookie and return priority."
9100 (save-match-data
9101 (if (not (string-match org-priority-regexp s))
9102 (* 1000 (- org-lowest-priority org-default-priority))
9103 (* 1000 (- org-lowest-priority
9104 (string-to-char (match-string 2 s)))))))
9106 ;;;; Tags
9108 (defvar org-agenda-archives-mode)
9109 (defun org-scan-tags (action matcher &optional todo-only)
9110 "Scan headline tags with inheritance and produce output ACTION.
9112 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9113 or `agenda' to produce an entry list for an agenda view. It can also be
9114 a Lisp form or a function that should be called at each matched headline, in
9115 this case the return value is a list of all return values from these calls.
9117 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9118 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9119 only lines with a TODO keyword are included in the output."
9120 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9121 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9122 (org-re
9123 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9124 (props (list 'face 'default
9125 'done-face 'org-done
9126 'undone-face 'default
9127 'mouse-face 'highlight
9128 'org-not-done-regexp org-not-done-regexp
9129 'org-todo-regexp org-todo-regexp
9130 'keymap org-agenda-keymap
9131 'help-echo
9132 (format "mouse-2 or RET jump to org file %s"
9133 (abbreviate-file-name
9134 (or (buffer-file-name (buffer-base-buffer))
9135 (buffer-name (buffer-base-buffer)))))))
9136 (case-fold-search nil)
9137 lspos tags tags-list
9138 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9139 (llast 0) rtn rtn1 level category i txt
9140 todo marker entry priority)
9141 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9142 (setq action (list 'lambda nil action)))
9143 (save-excursion
9144 (goto-char (point-min))
9145 (when (eq action 'sparse-tree)
9146 (org-overview)
9147 (org-remove-occur-highlights))
9148 (while (re-search-forward re nil t)
9149 (catch :skip
9150 (setq todo (if (match-end 1) (match-string 2))
9151 tags (if (match-end 4) (match-string 4)))
9152 (goto-char (setq lspos (1+ (match-beginning 0))))
9153 (setq level (org-reduced-level (funcall outline-level))
9154 category (org-get-category))
9155 (setq i llast llast level)
9156 ;; remove tag lists from same and sublevels
9157 (while (>= i level)
9158 (when (setq entry (assoc i tags-alist))
9159 (setq tags-alist (delete entry tags-alist)))
9160 (setq i (1- i)))
9161 ;; add the next tags
9162 (when tags
9163 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9164 tags-alist
9165 (cons (cons level tags) tags-alist)))
9166 ;; compile tags for current headline
9167 (setq tags-list
9168 (if org-use-tag-inheritance
9169 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9170 tags))
9171 (when org-use-tag-inheritance
9172 (setcdr (car tags-alist)
9173 (mapcar (lambda (x)
9174 (setq x (copy-sequence x))
9175 (org-add-prop-inherited x))
9176 (cdar tags-alist))))
9177 (when (and tags org-use-tag-inheritance
9178 (not (eq t org-use-tag-inheritance)))
9179 ;; selective inheritance, remove uninherited ones
9180 (setcdr (car tags-alist)
9181 (org-remove-uniherited-tags (cdar tags-alist))))
9182 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9183 (let ((case-fold-search t)) (eval matcher))
9185 (not (member org-archive-tag tags-list))
9186 ;; we have an archive tag, should we use this anyway?
9187 (or (not org-agenda-skip-archived-trees)
9188 (and (eq action 'agenda) org-agenda-archives-mode))))
9189 (unless (eq action 'sparse-tree) (org-agenda-skip))
9191 ;; select this headline
9193 (cond
9194 ((eq action 'sparse-tree)
9195 (and org-highlight-sparse-tree-matches
9196 (org-get-heading) (match-end 0)
9197 (org-highlight-new-match
9198 (match-beginning 0) (match-beginning 1)))
9199 (org-show-context 'tags-tree))
9200 ((eq action 'agenda)
9201 (setq txt (org-format-agenda-item
9203 (concat
9204 (if org-tags-match-list-sublevels
9205 (make-string (1- level) ?.) "")
9206 (org-get-heading))
9207 category tags-list)
9208 priority (org-get-priority txt))
9209 (goto-char lspos)
9210 (setq marker (org-agenda-new-marker))
9211 (org-add-props txt props
9212 'org-marker marker 'org-hd-marker marker 'org-category category
9213 'priority priority 'type "tagsmatch")
9214 (push txt rtn))
9215 ((functionp action)
9216 (save-excursion
9217 (setq rtn1 (funcall action))
9218 (push rtn1 rtn))
9219 (goto-char (point-at-eol)))
9220 (t (error "Invalid action")))
9222 ;; if we are to skip sublevels, jump to end of subtree
9223 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9224 (when (and (eq action 'sparse-tree)
9225 (not org-sparse-tree-open-archived-trees))
9226 (org-hide-archived-subtrees (point-min) (point-max)))
9227 (nreverse rtn)))
9229 (defun org-remove-uniherited-tags (tags)
9230 "Remove all tags that are not inherited from the list TAGS."
9231 (cond
9232 ((eq org-use-tag-inheritance t)
9233 (if org-tags-exclude-from-inheritance
9234 (org-delete-all org-tags-exclude-from-inheritance tags)
9235 tags))
9236 ((not org-use-tag-inheritance) nil)
9237 ((stringp org-use-tag-inheritance)
9238 (delq nil (mapcar
9239 (lambda (x)
9240 (if (and (string-match org-use-tag-inheritance x)
9241 (not (member x org-tags-exclude-from-inheritance)))
9242 x nil))
9243 tags)))
9244 ((listp org-use-tag-inheritance)
9245 (delq nil (mapcar
9246 (lambda (x)
9247 (if (member x org-use-tag-inheritance) x nil))
9248 tags)))))
9250 (defvar todo-only) ;; dynamically scoped
9252 (defun org-tags-sparse-tree (&optional todo-only match)
9253 "Create a sparse tree according to tags string MATCH.
9254 MATCH can contain positive and negative selection of tags, like
9255 \"+WORK+URGENT-WITHBOSS\".
9256 If optional argument TODO-ONLY is non-nil, only select lines that are
9257 also TODO lines."
9258 (interactive "P")
9259 (org-prepare-agenda-buffers (list (current-buffer)))
9260 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9262 (defvar org-cached-props nil)
9263 (defun org-cached-entry-get (pom property)
9264 (if (or (eq t org-use-property-inheritance)
9265 (and (stringp org-use-property-inheritance)
9266 (string-match org-use-property-inheritance property))
9267 (and (listp org-use-property-inheritance)
9268 (member property org-use-property-inheritance)))
9269 ;; Caching is not possible, check it directly
9270 (org-entry-get pom property 'inherit)
9271 ;; Get all properties, so that we can do complicated checks easily
9272 (cdr (assoc property (or org-cached-props
9273 (setq org-cached-props
9274 (org-entry-properties pom)))))))
9276 (defun org-global-tags-completion-table (&optional files)
9277 "Return the list of all tags in all agenda buffer/files."
9278 (save-excursion
9279 (org-uniquify
9280 (delq nil
9281 (apply 'append
9282 (mapcar
9283 (lambda (file)
9284 (set-buffer (find-file-noselect file))
9285 (append (org-get-buffer-tags)
9286 (mapcar (lambda (x) (if (stringp (car-safe x))
9287 (list (car-safe x)) nil))
9288 org-tag-alist)))
9289 (if (and files (car files))
9290 files
9291 (org-agenda-files))))))))
9293 (defun org-make-tags-matcher (match)
9294 "Create the TAGS//TODO matcher form for the selection string MATCH."
9295 ;; todo-only is scoped dynamically into this function, and the function
9296 ;; may change it it the matcher asksk for it.
9297 (unless match
9298 ;; Get a new match request, with completion
9299 (let ((org-last-tags-completion-table
9300 (org-global-tags-completion-table)))
9301 (setq match (org-ido-completing-read
9302 "Match: " 'org-tags-completion-function nil nil nil
9303 'org-tags-history))))
9305 ;; Parse the string and create a lisp form
9306 (let ((match0 match)
9307 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9308 minus tag mm
9309 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9310 orterms term orlist re-p str-p level-p level-op time-p
9311 prop-p pn pv po cat-p gv rest)
9312 (if (string-match "/+" match)
9313 ;; match contains also a todo-matching request
9314 (progn
9315 (setq tagsmatch (substring match 0 (match-beginning 0))
9316 todomatch (substring match (match-end 0)))
9317 (if (string-match "^!" todomatch)
9318 (setq todo-only t todomatch (substring todomatch 1)))
9319 (if (string-match "^\\s-*$" todomatch)
9320 (setq todomatch nil)))
9321 ;; only matching tags
9322 (setq tagsmatch match todomatch nil))
9324 ;; Make the tags matcher
9325 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9326 (setq tagsmatcher t)
9327 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9328 (while (setq term (pop orterms))
9329 (while (and (equal (substring term -1) "\\") orterms)
9330 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9331 (while (string-match re term)
9332 (setq rest (substring term (match-end 0))
9333 minus (and (match-end 1)
9334 (equal (match-string 1 term) "-"))
9335 tag (match-string 2 term)
9336 re-p (equal (string-to-char tag) ?{)
9337 level-p (match-end 4)
9338 prop-p (match-end 5)
9339 mm (cond
9340 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9341 (level-p
9342 (setq level-op (org-op-to-function (match-string 3 term)))
9343 `(,level-op level ,(string-to-number
9344 (match-string 4 term))))
9345 (prop-p
9346 (setq pn (match-string 5 term)
9347 po (match-string 6 term)
9348 pv (match-string 7 term)
9349 cat-p (equal pn "CATEGORY")
9350 re-p (equal (string-to-char pv) ?{)
9351 str-p (equal (string-to-char pv) ?\")
9352 time-p (save-match-data
9353 (string-match "^\"[[<].*[]>]\"$" pv))
9354 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9355 (if time-p (setq pv (org-matcher-time pv)))
9356 (setq po (org-op-to-function po (if time-p 'time str-p)))
9357 (cond
9358 ((equal pn "CATEGORY")
9359 (setq gv '(get-text-property (point) 'org-category)))
9360 ((equal pn "TODO")
9361 (setq gv 'todo))
9363 (setq gv `(org-cached-entry-get nil ,pn))))
9364 (if re-p
9365 (if (eq po 'org<>)
9366 `(not (string-match ,pv (or ,gv "")))
9367 `(string-match ,pv (or ,gv "")))
9368 (if str-p
9369 `(,po (or ,gv "") ,pv)
9370 `(,po (string-to-number (or ,gv ""))
9371 ,(string-to-number pv) ))))
9372 (t `(member ,(downcase tag) tags-list)))
9373 mm (if minus (list 'not mm) mm)
9374 term rest)
9375 (push mm tagsmatcher))
9376 (push (if (> (length tagsmatcher) 1)
9377 (cons 'and tagsmatcher)
9378 (car tagsmatcher))
9379 orlist)
9380 (setq tagsmatcher nil))
9381 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9382 (setq tagsmatcher
9383 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9384 ;; Make the todo matcher
9385 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9386 (setq todomatcher t)
9387 (setq orterms (org-split-string todomatch "|") orlist nil)
9388 (while (setq term (pop orterms))
9389 (while (string-match re term)
9390 (setq minus (and (match-end 1)
9391 (equal (match-string 1 term) "-"))
9392 kwd (match-string 2 term)
9393 re-p (equal (string-to-char kwd) ?{)
9394 term (substring term (match-end 0))
9395 mm (if re-p
9396 `(string-match ,(substring kwd 1 -1) todo)
9397 (list 'equal 'todo kwd))
9398 mm (if minus (list 'not mm) mm))
9399 (push mm todomatcher))
9400 (push (if (> (length todomatcher) 1)
9401 (cons 'and todomatcher)
9402 (car todomatcher))
9403 orlist)
9404 (setq todomatcher nil))
9405 (setq todomatcher (if (> (length orlist) 1)
9406 (cons 'or orlist) (car orlist))))
9408 ;; Return the string and lisp forms of the matcher
9409 (setq matcher (if todomatcher
9410 (list 'and tagsmatcher todomatcher)
9411 tagsmatcher))
9412 (cons match0 matcher)))
9414 (defun org-op-to-function (op &optional stringp)
9415 "Turn an operator into the appropriate function."
9416 (setq op
9417 (cond
9418 ((equal op "<" ) '(< string< org-time<))
9419 ((equal op ">" ) '(> org-string> org-time>))
9420 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9421 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9422 ((member op '("=" "==")) '(= string= org-time=))
9423 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9424 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9426 (defun org<> (a b) (not (= a b)))
9427 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9428 (defun org-string>= (a b) (not (string< a b)))
9429 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9430 (defun org-string<> (a b) (not (string= a b)))
9431 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9432 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9433 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9434 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9435 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9436 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9437 (defun org-2ft (s)
9438 "Convert S to a floating point time.
9439 If S is already a number, just return it. If it is a string, parse
9440 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9441 (cond
9442 ((numberp s) s)
9443 ((stringp s)
9444 (condition-case nil
9445 (float-time (apply 'encode-time (org-parse-time-string s)))
9446 (error 0.)))
9447 (t 0.)))
9449 (defun org-time-today ()
9450 "Time in seconds today at 0:00.
9451 Returns the float number of seconds since the beginning of the
9452 epoch to the beginning of today (00:00)."
9453 (float-time (apply 'encode-time
9454 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9456 (defun org-matcher-time (s)
9457 "Interprete a time comparison value."
9458 (save-match-data
9459 (cond
9460 ((string= s "<now>") (float-time))
9461 ((string= s "<today>") (org-time-today))
9462 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9463 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9464 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9465 (+ (org-time-today)
9466 (* (string-to-number (match-string 1 s))
9467 (cdr (assoc (match-string 2 s)
9468 '(("d" . 86400.0) ("w" . 604800.0)
9469 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9470 (t (org-2ft s)))))
9472 (defun org-match-any-p (re list)
9473 "Does re match any element of list?"
9474 (setq list (mapcar (lambda (x) (string-match re x)) list))
9475 (delq nil list))
9477 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9478 (defvar org-tags-overlay (org-make-overlay 1 1))
9479 (org-detach-overlay org-tags-overlay)
9481 (defun org-get-local-tags-at (&optional pos)
9482 "Get a list of tags defined in the current headline."
9483 (org-get-tags-at pos 'local))
9485 (defun org-get-local-tags ()
9486 "Get a list of tags defined in the current headline."
9487 (org-get-tags-at nil 'local))
9489 (defun org-get-tags-at (&optional pos local)
9490 "Get a list of all headline tags applicable at POS.
9491 POS defaults to point. If tags are inherited, the list contains
9492 the targets in the same sequence as the headlines appear, i.e.
9493 the tags of the current headline come last.
9494 When LOCAL is non-nil, only return tags from the current headline,
9495 ignore inherited ones."
9496 (interactive)
9497 (let (tags ltags lastpos parent)
9498 (save-excursion
9499 (save-restriction
9500 (widen)
9501 (goto-char (or pos (point)))
9502 (save-match-data
9503 (catch 'done
9504 (condition-case nil
9505 (progn
9506 (org-back-to-heading t)
9507 (while (not (equal lastpos (point)))
9508 (setq lastpos (point))
9509 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9510 (setq ltags (org-split-string
9511 (org-match-string-no-properties 1) ":"))
9512 (when parent
9513 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9514 (setq tags (append
9515 (if parent
9516 (org-remove-uniherited-tags ltags)
9517 ltags)
9518 tags)))
9519 (or org-use-tag-inheritance (throw 'done t))
9520 (if local (throw 'done t))
9521 (org-up-heading-all 1)
9522 (setq parent t)))
9523 (error nil)))))
9524 (append (org-remove-uniherited-tags org-file-tags) tags))))
9526 (defun org-add-prop-inherited (s)
9527 (add-text-properties 0 (length s) '(inherited t) s)
9530 (defun org-toggle-tag (tag &optional onoff)
9531 "Toggle the tag TAG for the current line.
9532 If ONOFF is `on' or `off', don't toggle but set to this state."
9533 (let (res current)
9534 (save-excursion
9535 (org-back-to-heading t)
9536 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9537 (point-at-eol) t)
9538 (progn
9539 (setq current (match-string 1))
9540 (replace-match ""))
9541 (setq current ""))
9542 (setq current (nreverse (org-split-string current ":")))
9543 (cond
9544 ((eq onoff 'on)
9545 (setq res t)
9546 (or (member tag current) (push tag current)))
9547 ((eq onoff 'off)
9548 (or (not (member tag current)) (setq current (delete tag current))))
9549 (t (if (member tag current)
9550 (setq current (delete tag current))
9551 (setq res t)
9552 (push tag current))))
9553 (end-of-line 1)
9554 (if current
9555 (progn
9556 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9557 (org-set-tags nil t))
9558 (delete-horizontal-space))
9559 (run-hooks 'org-after-tags-change-hook))
9560 res))
9562 (defun org-align-tags-here (to-col)
9563 ;; Assumes that this is a headline
9564 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9565 (beginning-of-line 1)
9566 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9567 (< pos (match-beginning 2)))
9568 (progn
9569 (setq tags-l (- (match-end 2) (match-beginning 2)))
9570 (goto-char (match-beginning 1))
9571 (insert " ")
9572 (delete-region (point) (1+ (match-beginning 2)))
9573 (setq ncol (max (1+ (current-column))
9574 (1+ col)
9575 (if (> to-col 0)
9576 to-col
9577 (- (abs to-col) tags-l))))
9578 (setq p (point))
9579 (insert (make-string (- ncol (current-column)) ?\ ))
9580 (setq ncol (current-column))
9581 (when indent-tabs-mode (tabify p (point-at-eol)))
9582 (org-move-to-column (min ncol col) t))
9583 (goto-char pos))))
9585 (defun org-set-tags-command (&optional arg just-align)
9586 "Call the set-tags command for the current entry."
9587 (interactive "P")
9588 (if (org-on-heading-p)
9589 (org-set-tags arg just-align)
9590 (save-excursion
9591 (org-back-to-heading t)
9592 (org-set-tags arg just-align))))
9594 (defun org-set-tags (&optional arg just-align)
9595 "Set the tags for the current headline.
9596 With prefix ARG, realign all tags in headings in the current buffer."
9597 (interactive "P")
9598 (let* ((re (concat "^" outline-regexp))
9599 (current (org-get-tags-string))
9600 (col (current-column))
9601 (org-setting-tags t)
9602 table current-tags inherited-tags ; computed below when needed
9603 tags p0 c0 c1 rpl)
9604 (if arg
9605 (save-excursion
9606 (goto-char (point-min))
9607 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9608 (while (re-search-forward re nil t)
9609 (org-set-tags nil t)
9610 (end-of-line 1)))
9611 (message "All tags realigned to column %d" org-tags-column))
9612 (if just-align
9613 (setq tags current)
9614 ;; Get a new set of tags from the user
9615 (save-excursion
9616 (setq table (or org-tag-alist (org-get-buffer-tags))
9617 org-last-tags-completion-table table
9618 current-tags (org-split-string current ":")
9619 inherited-tags (nreverse
9620 (nthcdr (length current-tags)
9621 (nreverse (org-get-tags-at))))
9622 tags
9623 (if (or (eq t org-use-fast-tag-selection)
9624 (and org-use-fast-tag-selection
9625 (delq nil (mapcar 'cdr table))))
9626 (org-fast-tag-selection
9627 current-tags inherited-tags table
9628 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9629 (let ((org-add-colon-after-tag-completion t))
9630 (org-trim
9631 (org-without-partial-completion
9632 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9633 nil nil current 'org-tags-history)))))))
9634 (while (string-match "[-+&]+" tags)
9635 ;; No boolean logic, just a list
9636 (setq tags (replace-match ":" t t tags))))
9638 (if (string-match "\\`[\t ]*\\'" tags)
9639 (setq tags "")
9640 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9641 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9643 ;; Insert new tags at the correct column
9644 (beginning-of-line 1)
9645 (cond
9646 ((and (equal current "") (equal tags "")))
9647 ((re-search-forward
9648 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9649 (point-at-eol) t)
9650 (if (equal tags "")
9651 (setq rpl "")
9652 (goto-char (match-beginning 0))
9653 (setq c0 (current-column) p0 (point)
9654 c1 (max (1+ c0) (if (> org-tags-column 0)
9655 org-tags-column
9656 (- (- org-tags-column) (length tags))))
9657 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9658 (replace-match rpl t t)
9659 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9660 tags)
9661 (t (error "Tags alignment failed")))
9662 (org-move-to-column col)
9663 (unless just-align
9664 (run-hooks 'org-after-tags-change-hook)))))
9666 (defun org-change-tag-in-region (beg end tag off)
9667 "Add or remove TAG for each entry in the region.
9668 This works in the agenda, and also in an org-mode buffer."
9669 (interactive
9670 (list (region-beginning) (region-end)
9671 (let ((org-last-tags-completion-table
9672 (if (org-mode-p)
9673 (org-get-buffer-tags)
9674 (org-global-tags-completion-table))))
9675 (org-ido-completing-read
9676 "Tag: " 'org-tags-completion-function nil nil nil
9677 'org-tags-history))
9678 (progn
9679 (message "[s]et or [r]emove? ")
9680 (equal (read-char-exclusive) ?r))))
9681 (if (fboundp 'deactivate-mark) (deactivate-mark))
9682 (let ((agendap (equal major-mode 'org-agenda-mode))
9683 l1 l2 m buf pos newhead (cnt 0))
9684 (goto-char end)
9685 (setq l2 (1- (org-current-line)))
9686 (goto-char beg)
9687 (setq l1 (org-current-line))
9688 (loop for l from l1 to l2 do
9689 (goto-line l)
9690 (setq m (get-text-property (point) 'org-hd-marker))
9691 (when (or (and (org-mode-p) (org-on-heading-p))
9692 (and agendap m))
9693 (setq buf (if agendap (marker-buffer m) (current-buffer))
9694 pos (if agendap m (point)))
9695 (with-current-buffer buf
9696 (save-excursion
9697 (save-restriction
9698 (goto-char pos)
9699 (setq cnt (1+ cnt))
9700 (org-toggle-tag tag (if off 'off 'on))
9701 (setq newhead (org-get-heading)))))
9702 (and agendap (org-agenda-change-all-lines newhead m))))
9703 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9705 (defun org-tags-completion-function (string predicate &optional flag)
9706 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9707 (confirm (lambda (x) (stringp (car x)))))
9708 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9709 (setq s1 (match-string 1 string)
9710 s2 (match-string 2 string))
9711 (setq s1 "" s2 string))
9712 (cond
9713 ((eq flag nil)
9714 ;; try completion
9715 (setq rtn (try-completion s2 ctable confirm))
9716 (if (stringp rtn)
9717 (setq rtn
9718 (concat s1 s2 (substring rtn (length s2))
9719 (if (and org-add-colon-after-tag-completion
9720 (assoc rtn ctable))
9721 ":" ""))))
9722 rtn)
9723 ((eq flag t)
9724 ;; all-completions
9725 (all-completions s2 ctable confirm)
9727 ((eq flag 'lambda)
9728 ;; exact match?
9729 (assoc s2 ctable)))
9732 (defun org-fast-tag-insert (kwd tags face &optional end)
9733 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9734 (insert (format "%-12s" (concat kwd ":"))
9735 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9736 (or end "")))
9738 (defun org-fast-tag-show-exit (flag)
9739 (save-excursion
9740 (goto-line 3)
9741 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9742 (replace-match ""))
9743 (when flag
9744 (end-of-line 1)
9745 (org-move-to-column (- (window-width) 19) t)
9746 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9748 (defun org-set-current-tags-overlay (current prefix)
9749 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9750 (if (featurep 'xemacs)
9751 (org-overlay-display org-tags-overlay (concat prefix s)
9752 'secondary-selection)
9753 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9754 (org-overlay-display org-tags-overlay (concat prefix s)))))
9756 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9757 "Fast tag selection with single keys.
9758 CURRENT is the current list of tags in the headline, INHERITED is the
9759 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9760 possibly with grouping information. TODO-TABLE is a similar table with
9761 TODO keywords, should these have keys assigned to them.
9762 If the keys are nil, a-z are automatically assigned.
9763 Returns the new tags string, or nil to not change the current settings."
9764 (let* ((fulltable (append table todo-table))
9765 (maxlen (apply 'max (mapcar
9766 (lambda (x)
9767 (if (stringp (car x)) (string-width (car x)) 0))
9768 fulltable)))
9769 (buf (current-buffer))
9770 (expert (eq org-fast-tag-selection-single-key 'expert))
9771 (buffer-tags nil)
9772 (fwidth (+ maxlen 3 1 3))
9773 (ncol (/ (- (window-width) 4) fwidth))
9774 (i-face 'org-done)
9775 (c-face 'org-todo)
9776 tg cnt e c char c1 c2 ntable tbl rtn
9777 ov-start ov-end ov-prefix
9778 (exit-after-next org-fast-tag-selection-single-key)
9779 (done-keywords org-done-keywords)
9780 groups ingroup)
9781 (save-excursion
9782 (beginning-of-line 1)
9783 (if (looking-at
9784 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9785 (setq ov-start (match-beginning 1)
9786 ov-end (match-end 1)
9787 ov-prefix "")
9788 (setq ov-start (1- (point-at-eol))
9789 ov-end (1+ ov-start))
9790 (skip-chars-forward "^\n\r")
9791 (setq ov-prefix
9792 (concat
9793 (buffer-substring (1- (point)) (point))
9794 (if (> (current-column) org-tags-column)
9796 (make-string (- org-tags-column (current-column)) ?\ ))))))
9797 (org-move-overlay org-tags-overlay ov-start ov-end)
9798 (save-window-excursion
9799 (if expert
9800 (set-buffer (get-buffer-create " *Org tags*"))
9801 (delete-other-windows)
9802 (split-window-vertically)
9803 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9804 (erase-buffer)
9805 (org-set-local 'org-done-keywords done-keywords)
9806 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9807 (org-fast-tag-insert "Current" current c-face "\n\n")
9808 (org-fast-tag-show-exit exit-after-next)
9809 (org-set-current-tags-overlay current ov-prefix)
9810 (setq tbl fulltable char ?a cnt 0)
9811 (while (setq e (pop tbl))
9812 (cond
9813 ((equal e '(:startgroup))
9814 (push '() groups) (setq ingroup t)
9815 (when (not (= cnt 0))
9816 (setq cnt 0)
9817 (insert "\n"))
9818 (insert "{ "))
9819 ((equal e '(:endgroup))
9820 (setq ingroup nil cnt 0)
9821 (insert "}\n"))
9823 (setq tg (car e) c2 nil)
9824 (if (cdr e)
9825 (setq c (cdr e))
9826 ;; automatically assign a character.
9827 (setq c1 (string-to-char
9828 (downcase (substring
9829 tg (if (= (string-to-char tg) ?@) 1 0)))))
9830 (if (or (rassoc c1 ntable) (rassoc c1 table))
9831 (while (or (rassoc char ntable) (rassoc char table))
9832 (setq char (1+ char)))
9833 (setq c2 c1))
9834 (setq c (or c2 char)))
9835 (if ingroup (push tg (car groups)))
9836 (setq tg (org-add-props tg nil 'face
9837 (cond
9838 ((not (assoc tg table))
9839 (org-get-todo-face tg))
9840 ((member tg current) c-face)
9841 ((member tg inherited) i-face)
9842 (t nil))))
9843 (if (and (= cnt 0) (not ingroup)) (insert " "))
9844 (insert "[" c "] " tg (make-string
9845 (- fwidth 4 (length tg)) ?\ ))
9846 (push (cons tg c) ntable)
9847 (when (= (setq cnt (1+ cnt)) ncol)
9848 (insert "\n")
9849 (if ingroup (insert " "))
9850 (setq cnt 0)))))
9851 (setq ntable (nreverse ntable))
9852 (insert "\n")
9853 (goto-char (point-min))
9854 (if (not expert) (org-fit-window-to-buffer))
9855 (setq rtn
9856 (catch 'exit
9857 (while t
9858 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9859 (if groups " [!] no groups" " [!]groups")
9860 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9861 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9862 (cond
9863 ((= c ?\r) (throw 'exit t))
9864 ((= c ?!)
9865 (setq groups (not groups))
9866 (goto-char (point-min))
9867 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9868 ((= c ?\C-c)
9869 (if (not expert)
9870 (org-fast-tag-show-exit
9871 (setq exit-after-next (not exit-after-next)))
9872 (setq expert nil)
9873 (delete-other-windows)
9874 (split-window-vertically)
9875 (org-switch-to-buffer-other-window " *Org tags*")
9876 (org-fit-window-to-buffer)))
9877 ((or (= c ?\C-g)
9878 (and (= c ?q) (not (rassoc c ntable))))
9879 (org-detach-overlay org-tags-overlay)
9880 (setq quit-flag t))
9881 ((= c ?\ )
9882 (setq current nil)
9883 (if exit-after-next (setq exit-after-next 'now)))
9884 ((= c ?\t)
9885 (condition-case nil
9886 (setq tg (org-ido-completing-read
9887 "Tag: "
9888 (or buffer-tags
9889 (with-current-buffer buf
9890 (org-get-buffer-tags)))))
9891 (quit (setq tg "")))
9892 (when (string-match "\\S-" tg)
9893 (add-to-list 'buffer-tags (list tg))
9894 (if (member tg current)
9895 (setq current (delete tg current))
9896 (push tg current)))
9897 (if exit-after-next (setq exit-after-next 'now)))
9898 ((setq e (rassoc c todo-table) tg (car e))
9899 (with-current-buffer buf
9900 (save-excursion (org-todo tg)))
9901 (if exit-after-next (setq exit-after-next 'now)))
9902 ((setq e (rassoc c ntable) tg (car e))
9903 (if (member tg current)
9904 (setq current (delete tg current))
9905 (loop for g in groups do
9906 (if (member tg g)
9907 (mapc (lambda (x)
9908 (setq current (delete x current)))
9909 g)))
9910 (push tg current))
9911 (if exit-after-next (setq exit-after-next 'now))))
9913 ;; Create a sorted list
9914 (setq current
9915 (sort current
9916 (lambda (a b)
9917 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9918 (if (eq exit-after-next 'now) (throw 'exit t))
9919 (goto-char (point-min))
9920 (beginning-of-line 2)
9921 (delete-region (point) (point-at-eol))
9922 (org-fast-tag-insert "Current" current c-face)
9923 (org-set-current-tags-overlay current ov-prefix)
9924 (while (re-search-forward
9925 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9926 (setq tg (match-string 1))
9927 (add-text-properties
9928 (match-beginning 1) (match-end 1)
9929 (list 'face
9930 (cond
9931 ((member tg current) c-face)
9932 ((member tg inherited) i-face)
9933 (t (get-text-property (match-beginning 1) 'face))))))
9934 (goto-char (point-min)))))
9935 (org-detach-overlay org-tags-overlay)
9936 (if rtn
9937 (mapconcat 'identity current ":")
9938 nil))))
9940 (defun org-get-tags-string ()
9941 "Get the TAGS string in the current headline."
9942 (unless (org-on-heading-p t)
9943 (error "Not on a heading"))
9944 (save-excursion
9945 (beginning-of-line 1)
9946 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9947 (org-match-string-no-properties 1)
9948 "")))
9950 (defun org-get-tags ()
9951 "Get the list of tags specified in the current headline."
9952 (org-split-string (org-get-tags-string) ":"))
9954 (defun org-get-buffer-tags ()
9955 "Get a table of all tags used in the buffer, for completion."
9956 (let (tags)
9957 (save-excursion
9958 (goto-char (point-min))
9959 (while (re-search-forward
9960 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9961 (when (equal (char-after (point-at-bol 0)) ?*)
9962 (mapc (lambda (x) (add-to-list 'tags x))
9963 (org-split-string (org-match-string-no-properties 1) ":")))))
9964 (mapcar 'list tags)))
9966 ;;;; The mapping API
9968 ;;;###autoload
9969 (defun org-map-entries (func &optional match scope &rest skip)
9970 "Call FUNC at each headline selected by MATCH in SCOPE.
9972 FUNC is a function or a lisp form. The function will be called without
9973 arguments, with the cursor positioned at the beginning of the headline.
9974 The return values of all calls to the function will be collected and
9975 returned as a list.
9977 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9978 Only headlines that are matched by this query will be considered during
9979 the iteration. When MATCH is nil or t, all headlines will be
9980 visited by the iteration.
9982 SCOPE determines the scope of this command. It can be any of:
9984 nil The current buffer, respecting the restriction if any
9985 tree The subtree started with the entry at point
9986 file The current buffer, without restriction
9987 file-with-archives
9988 The current buffer, and any archives associated with it
9989 agenda All agenda files
9990 agenda-with-archives
9991 All agenda files with any archive files associated with them
9992 \(file1 file2 ...)
9993 If this is a list, all files in the list will be scanned
9995 The remaining args are treated as settings for the skipping facilities of
9996 the scanner. The following items can be given here:
9998 archive skip trees with the archive tag.
9999 comment skip trees with the COMMENT keyword
10000 function or Emacs Lisp form:
10001 will be used as value for `org-agenda-skip-function', so whenever
10002 the the function returns t, FUNC will not be called for that
10003 entry and search will continue from the point where the
10004 function leaves it."
10005 (let* ((org-agenda-archives-mode nil) ; just to make sure
10006 (org-agenda-skip-archived-trees (memq 'archive skip))
10007 (org-agenda-skip-comment-trees (memq 'comment skip))
10008 (org-agenda-skip-function
10009 (car (org-delete-all '(comment archive) skip)))
10010 (org-tags-match-list-sublevels t)
10011 matcher pos file res
10012 org-todo-keywords-for-agenda
10013 org-done-keywords-for-agenda
10014 org-todo-keyword-alist-for-agenda
10015 org-tag-alist-for-agenda)
10017 (cond
10018 ((eq match t) (setq matcher t))
10019 ((eq match nil) (setq matcher t))
10020 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10022 (when (eq scope 'tree)
10023 (org-back-to-heading t)
10024 (org-narrow-to-subtree)
10025 (setq scope nil))
10027 (if (not scope)
10028 (progn
10029 (org-prepare-agenda-buffers
10030 (list (buffer-file-name (current-buffer))))
10031 (org-scan-tags func matcher))
10032 ;; Get the right scope
10033 (setq pos (point))
10034 (cond
10035 ((and scope (listp scope) (symbolp (car scope)))
10036 (setq scope (eval scope)))
10037 ((eq scope 'agenda)
10038 (setq scope (org-agenda-files t)))
10039 ((eq scope 'agenda-with-archives)
10040 (setq scope (org-agenda-files t))
10041 (setq scope (org-add-archive-files scope)))
10042 ((eq scope 'file)
10043 (setq scope (list (buffer-file-name))))
10044 ((eq scope 'file-with-archives)
10045 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10046 (org-prepare-agenda-buffers scope)
10047 (while (setq file (pop scope))
10048 (with-current-buffer (org-find-base-buffer-visiting file)
10049 (save-excursion
10050 (save-restriction
10051 (widen)
10052 (goto-char (point-min))
10053 (setq res (append res (org-scan-tags func matcher)))))))
10054 res)))
10056 ;;;; Properties
10058 ;;; Setting and retrieving properties
10060 (defconst org-special-properties
10061 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10062 "TIMESTAMP" "TIMESTAMP_IA")
10063 "The special properties valid in Org-mode.
10065 These are properties that are not defined in the property drawer,
10066 but in some other way.")
10068 (defconst org-default-properties
10069 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10070 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10071 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10072 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10073 "Some properties that are used by Org-mode for various purposes.
10074 Being in this list makes sure that they are offered for completion.")
10076 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10077 "Regular expression matching the first line of a property drawer.")
10079 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10080 "Regular expression matching the first line of a property drawer.")
10082 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10083 "Regular expression matching the first line of a property drawer.")
10085 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10086 "Regular expression matching the first line of a property drawer.")
10088 (defconst org-property-drawer-re
10089 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10090 org-property-end-re "\\)\n?")
10091 "Matches an entire property drawer.")
10093 (defconst org-clock-drawer-re
10094 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10095 org-property-end-re "\\)\n?")
10096 "Matches an entire clock drawer.")
10098 (defun org-property-action ()
10099 "Do an action on properties."
10100 (interactive)
10101 (let (c)
10102 (org-at-property-p)
10103 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10104 (setq c (read-char-exclusive))
10105 (cond
10106 ((equal c ?s)
10107 (call-interactively 'org-set-property))
10108 ((equal c ?d)
10109 (call-interactively 'org-delete-property))
10110 ((equal c ?D)
10111 (call-interactively 'org-delete-property-globally))
10112 ((equal c ?c)
10113 (call-interactively 'org-compute-property-at-point))
10114 (t (error "No such property action %c" c)))))
10116 (defun org-at-property-p ()
10117 "Is the cursor in a property line?"
10118 ;; FIXME: Does not check if we are actually in the drawer.
10119 ;; FIXME: also returns true on any drawers.....
10120 ;; This is used by C-c C-c for property action.
10121 (save-excursion
10122 (beginning-of-line 1)
10123 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10125 (defun org-get-property-block (&optional beg end force)
10126 "Return the (beg . end) range of the body of the property drawer.
10127 BEG and END can be beginning and end of subtree, if not given
10128 they will be found.
10129 If the drawer does not exist and FORCE is non-nil, create the drawer."
10130 (catch 'exit
10131 (save-excursion
10132 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10133 (end (or end (progn (outline-next-heading) (point)))))
10134 (goto-char beg)
10135 (if (re-search-forward org-property-start-re end t)
10136 (setq beg (1+ (match-end 0)))
10137 (if force
10138 (save-excursion
10139 (org-insert-property-drawer)
10140 (setq end (progn (outline-next-heading) (point))))
10141 (throw 'exit nil))
10142 (goto-char beg)
10143 (if (re-search-forward org-property-start-re end t)
10144 (setq beg (1+ (match-end 0)))))
10145 (if (re-search-forward org-property-end-re end t)
10146 (setq end (match-beginning 0))
10147 (or force (throw 'exit nil))
10148 (goto-char beg)
10149 (setq end beg)
10150 (org-indent-line-function)
10151 (insert ":END:\n"))
10152 (cons beg end)))))
10154 (defun org-entry-properties (&optional pom which)
10155 "Get all properties of the entry at point-or-marker POM.
10156 This includes the TODO keyword, the tags, time strings for deadline,
10157 scheduled, and clocking, and any additional properties defined in the
10158 entry. The return value is an alist, keys may occur multiple times
10159 if the property key was used several times.
10160 POM may also be nil, in which case the current entry is used.
10161 If WHICH is nil or `all', get all properties. If WHICH is
10162 `special' or `standard', only get that subclass."
10163 (setq which (or which 'all))
10164 (org-with-point-at pom
10165 (let ((clockstr (substring org-clock-string 0 -1))
10166 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10167 beg end range props sum-props key value string clocksum)
10168 (save-excursion
10169 (when (condition-case nil (org-back-to-heading t) (error nil))
10170 (setq beg (point))
10171 (setq sum-props (get-text-property (point) 'org-summaries))
10172 (setq clocksum (get-text-property (point) :org-clock-minutes))
10173 (outline-next-heading)
10174 (setq end (point))
10175 (when (memq which '(all special))
10176 ;; Get the special properties, like TODO and tags
10177 (goto-char beg)
10178 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10179 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10180 (when (looking-at org-priority-regexp)
10181 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10182 (when (and (setq value (org-get-tags-string))
10183 (string-match "\\S-" value))
10184 (push (cons "TAGS" value) props))
10185 (when (setq value (org-get-tags-at))
10186 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10187 props))
10188 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10189 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10190 string (if (equal key clockstr)
10191 (org-no-properties
10192 (org-trim
10193 (buffer-substring
10194 (match-beginning 3) (goto-char (point-at-eol)))))
10195 (substring (org-match-string-no-properties 3) 1 -1)))
10196 (unless key
10197 (if (= (char-after (match-beginning 3)) ?\[)
10198 (setq key "TIMESTAMP_IA")
10199 (setq key "TIMESTAMP")))
10200 (when (or (equal key clockstr) (not (assoc key props)))
10201 (push (cons key string) props)))
10205 (when (memq which '(all standard))
10206 ;; Get the standard properties, like :PORP: ...
10207 (setq range (org-get-property-block beg end))
10208 (when range
10209 (goto-char (car range))
10210 (while (re-search-forward
10211 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10212 (cdr range) t)
10213 (setq key (org-match-string-no-properties 1)
10214 value (org-trim (or (org-match-string-no-properties 2) "")))
10215 (unless (member key excluded)
10216 (push (cons key (or value "")) props)))))
10217 (if clocksum
10218 (push (cons "CLOCKSUM"
10219 (org-columns-number-to-string (/ (float clocksum) 60.)
10220 'add_times))
10221 props))
10222 (unless (assoc "CATEGORY" props)
10223 (setq value (or (org-get-category)
10224 (progn (org-refresh-category-properties)
10225 (org-get-category))))
10226 (push (cons "CATEGORY" value) props))
10227 (append sum-props (nreverse props)))))))
10229 (defun org-entry-get (pom property &optional inherit)
10230 "Get value of PROPERTY for entry at point-or-marker POM.
10231 If INHERIT is non-nil and the entry does not have the property,
10232 then also check higher levels of the hierarchy.
10233 If INHERIT is the symbol `selective', use inheritance only if the setting
10234 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10235 If the property is present but empty, the return value is the empty string.
10236 If the property is not present at all, nil is returned."
10237 (org-with-point-at pom
10238 (if (and inherit (if (eq inherit 'selective)
10239 (org-property-inherit-p property)
10241 (org-entry-get-with-inheritance property)
10242 (if (member property org-special-properties)
10243 ;; We need a special property. Use brute force, get all properties.
10244 (cdr (assoc property (org-entry-properties nil 'special)))
10245 (let ((range (org-get-property-block)))
10246 (if (and range
10247 (goto-char (car range))
10248 (re-search-forward
10249 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10250 (cdr range) t))
10251 ;; Found the property, return it.
10252 (if (match-end 1)
10253 (org-match-string-no-properties 1)
10254 "")))))))
10256 (defun org-property-or-variable-value (var &optional inherit)
10257 "Check if there is a property fixing the value of VAR.
10258 If yes, return this value. If not, return the current value of the variable."
10259 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10260 (if (and prop (stringp prop) (string-match "\\S-" prop))
10261 (read prop)
10262 (symbol-value var))))
10264 (defun org-entry-delete (pom property)
10265 "Delete the property PROPERTY from entry at point-or-marker POM."
10266 (org-with-point-at pom
10267 (if (member property org-special-properties)
10268 nil ; cannot delete these properties.
10269 (let ((range (org-get-property-block)))
10270 (if (and range
10271 (goto-char (car range))
10272 (re-search-forward
10273 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10274 (cdr range) t))
10275 (progn
10276 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10278 nil)))))
10280 ;; Multi-values properties are properties that contain multiple values
10281 ;; These values are assumed to be single words, separated by whitespace.
10282 (defun org-entry-add-to-multivalued-property (pom property value)
10283 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10284 (let* ((old (org-entry-get pom property))
10285 (values (and old (org-split-string old "[ \t]"))))
10286 (setq value (org-entry-protect-space value))
10287 (unless (member value values)
10288 (setq values (cons value values))
10289 (org-entry-put pom property
10290 (mapconcat 'identity values " ")))))
10292 (defun org-entry-remove-from-multivalued-property (pom property value)
10293 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10294 (let* ((old (org-entry-get pom property))
10295 (values (and old (org-split-string old "[ \t]"))))
10296 (setq value (org-entry-protect-space value))
10297 (when (member value values)
10298 (setq values (delete value values))
10299 (org-entry-put pom property
10300 (mapconcat 'identity values " ")))))
10302 (defun org-entry-member-in-multivalued-property (pom property value)
10303 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10304 (let* ((old (org-entry-get pom property))
10305 (values (and old (org-split-string old "[ \t]"))))
10306 (setq value (org-entry-protect-space value))
10307 (member value values)))
10309 (defun org-entry-get-multivalued-property (pom property)
10310 "Return a list of values in a multivalued property."
10311 (let* ((value (org-entry-get pom property))
10312 (values (and value (org-split-string value "[ \t]"))))
10313 (mapcar 'org-entry-restore-space values)))
10315 (defun org-entry-put-multivalued-property (pom property &rest values)
10316 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10317 VALUES should be a list of strings. Spaces will be protected."
10318 (org-entry-put pom property
10319 (mapconcat 'org-entry-protect-space values " "))
10320 (let* ((value (org-entry-get pom property))
10321 (values (and value (org-split-string value "[ \t]"))))
10322 (mapcar 'org-entry-restore-space values)))
10324 (defun org-entry-protect-space (s)
10325 "Protect spaces and newline in string S."
10326 (while (string-match " " s)
10327 (setq s (replace-match "%20" t t s)))
10328 (while (string-match "\n" s)
10329 (setq s (replace-match "%0A" t t s)))
10332 (defun org-entry-restore-space (s)
10333 "Restore spaces and newline in string S."
10334 (while (string-match "%20" s)
10335 (setq s (replace-match " " t t s)))
10336 (while (string-match "%0A" s)
10337 (setq s (replace-match "\n" t t s)))
10340 (defvar org-entry-property-inherited-from (make-marker)
10341 "Marker pointing to the entry from where a proerty was inherited.
10342 Each call to `org-entry-get-with-inheritance' will set this marker to the
10343 location of the entry where the inheriance search matched. If there was
10344 no match, the marker will point nowhere.
10345 Note that also `org-entry-get' calls this function, if the INHERIT flag
10346 is set.")
10348 (defun org-entry-get-with-inheritance (property)
10349 "Get entry property, and search higher levels if not present."
10350 (move-marker org-entry-property-inherited-from nil)
10351 (let (tmp)
10352 (save-excursion
10353 (save-restriction
10354 (widen)
10355 (catch 'ex
10356 (while t
10357 (when (setq tmp (org-entry-get nil property))
10358 (org-back-to-heading t)
10359 (move-marker org-entry-property-inherited-from (point))
10360 (throw 'ex tmp))
10361 (or (org-up-heading-safe) (throw 'ex nil)))))
10362 (or tmp
10363 (cdr (assoc property org-file-properties))
10364 (cdr (assoc property org-global-properties))
10365 (cdr (assoc property org-global-properties-fixed))))))
10367 (defun org-entry-put (pom property value)
10368 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10369 (org-with-point-at pom
10370 (org-back-to-heading t)
10371 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10372 range)
10373 (cond
10374 ((equal property "TODO")
10375 (when (and (stringp value) (string-match "\\S-" value)
10376 (not (member value org-todo-keywords-1)))
10377 (error "\"%s\" is not a valid TODO state" value))
10378 (if (or (not value)
10379 (not (string-match "\\S-" value)))
10380 (setq value 'none))
10381 (org-todo value)
10382 (org-set-tags nil 'align))
10383 ((equal property "PRIORITY")
10384 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10385 (string-to-char value) ?\ ))
10386 (org-set-tags nil 'align))
10387 ((equal property "SCHEDULED")
10388 (if (re-search-forward org-scheduled-time-regexp end t)
10389 (cond
10390 ((eq value 'earlier) (org-timestamp-change -1 'day))
10391 ((eq value 'later) (org-timestamp-change 1 'day))
10392 (t (call-interactively 'org-schedule)))
10393 (call-interactively 'org-schedule)))
10394 ((equal property "DEADLINE")
10395 (if (re-search-forward org-deadline-time-regexp end t)
10396 (cond
10397 ((eq value 'earlier) (org-timestamp-change -1 'day))
10398 ((eq value 'later) (org-timestamp-change 1 'day))
10399 (t (call-interactively 'org-deadline)))
10400 (call-interactively 'org-deadline)))
10401 ((member property org-special-properties)
10402 (error "The %s property can not yet be set with `org-entry-put'"
10403 property))
10404 (t ; a non-special property
10405 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10406 (setq range (org-get-property-block beg end 'force))
10407 (goto-char (car range))
10408 (if (re-search-forward
10409 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10410 (progn
10411 (delete-region (match-beginning 1) (match-end 1))
10412 (goto-char (match-beginning 1)))
10413 (goto-char (cdr range))
10414 (insert "\n")
10415 (backward-char 1)
10416 (org-indent-line-function)
10417 (insert ":" property ":"))
10418 (and value (insert " " value))
10419 (org-indent-line-function)))))))
10421 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10422 "Get all property keys in the current buffer.
10423 With INCLUDE-SPECIALS, also list the special properties that relect things
10424 like tags and TODO state.
10425 With INCLUDE-DEFAULTS, also include properties that has special meaning
10426 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10427 With INCLUDE-COLUMNS, also include property names given in COLUMN
10428 formats in the current buffer."
10429 (let (rtn range cfmt cols s p)
10430 (save-excursion
10431 (save-restriction
10432 (widen)
10433 (goto-char (point-min))
10434 (while (re-search-forward org-property-start-re nil t)
10435 (setq range (org-get-property-block))
10436 (goto-char (car range))
10437 (while (re-search-forward
10438 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10439 (cdr range) t)
10440 (add-to-list 'rtn (org-match-string-no-properties 1)))
10441 (outline-next-heading))))
10443 (when include-specials
10444 (setq rtn (append org-special-properties rtn)))
10446 (when include-defaults
10447 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10449 (when include-columns
10450 (save-excursion
10451 (save-restriction
10452 (widen)
10453 (goto-char (point-min))
10454 (while (re-search-forward
10455 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10456 nil t)
10457 (setq cfmt (match-string 2) s 0)
10458 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10459 cfmt s)
10460 (setq s (match-end 0)
10461 p (match-string 1 cfmt))
10462 (unless (or (equal p "ITEM")
10463 (member p org-special-properties))
10464 (add-to-list 'rtn (match-string 1 cfmt))))))))
10466 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10468 (defun org-property-values (key)
10469 "Return a list of all values of property KEY."
10470 (save-excursion
10471 (save-restriction
10472 (widen)
10473 (goto-char (point-min))
10474 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10475 values)
10476 (while (re-search-forward re nil t)
10477 (add-to-list 'values (org-trim (match-string 1))))
10478 (delete "" values)))))
10480 (defun org-insert-property-drawer ()
10481 "Insert a property drawer into the current entry."
10482 (interactive)
10483 (org-back-to-heading t)
10484 (looking-at outline-regexp)
10485 (let ((indent (- (match-end 0)(match-beginning 0)))
10486 (beg (point))
10487 (re (concat "^[ \t]*" org-keyword-time-regexp))
10488 end hiddenp)
10489 (outline-next-heading)
10490 (setq end (point))
10491 (goto-char beg)
10492 (while (re-search-forward re end t))
10493 (setq hiddenp (org-invisible-p))
10494 (end-of-line 1)
10495 (and (equal (char-after) ?\n) (forward-char 1))
10496 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10497 (beginning-of-line 2))
10498 (org-skip-over-state-notes)
10499 (skip-chars-backward " \t\n\r")
10500 (if (eq (char-before) ?*) (forward-char 1))
10501 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10502 (beginning-of-line 0)
10503 (org-indent-to-column indent)
10504 (beginning-of-line 2)
10505 (org-indent-to-column indent)
10506 (beginning-of-line 0)
10507 (if hiddenp
10508 (save-excursion
10509 (org-back-to-heading t)
10510 (hide-entry))
10511 (org-flag-drawer t))))
10513 (defun org-set-property (property value)
10514 "In the current entry, set PROPERTY to VALUE.
10515 When called interactively, this will prompt for a property name, offering
10516 completion on existing and default properties. And then it will prompt
10517 for a value, offering competion either on allowed values (via an inherited
10518 xxx_ALL property) or on existing values in other instances of this property
10519 in the current file."
10520 (interactive
10521 (let* ((completion-ignore-case t)
10522 (keys (org-buffer-property-keys nil t t))
10523 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10524 (prop (if (member prop0 keys)
10525 prop0
10526 (or (cdr (assoc (downcase prop0)
10527 (mapcar (lambda (x) (cons (downcase x) x))
10528 keys)))
10529 prop0)))
10530 (cur (org-entry-get nil prop))
10531 (allowed (org-property-get-allowed-values nil prop 'table))
10532 (existing (mapcar 'list (org-property-values prop)))
10533 (val (if allowed
10534 (org-completing-read "Value: " allowed nil 'req-match)
10535 (org-completing-read
10536 (concat "Value" (if (and cur (string-match "\\S-" cur))
10537 (concat "[" cur "]") "")
10538 ": ")
10539 existing nil nil "" nil cur))))
10540 (list prop (if (equal val "") cur val))))
10541 (unless (equal (org-entry-get nil property) value)
10542 (org-entry-put nil property value)))
10544 (defun org-delete-property (property)
10545 "In the current entry, delete PROPERTY."
10546 (interactive
10547 (let* ((completion-ignore-case t)
10548 (prop (org-ido-completing-read
10549 "Property: " (org-entry-properties nil 'standard))))
10550 (list prop)))
10551 (message "Property %s %s" property
10552 (if (org-entry-delete nil property)
10553 "deleted"
10554 "was not present in the entry")))
10556 (defun org-delete-property-globally (property)
10557 "Remove PROPERTY globally, from all entries."
10558 (interactive
10559 (let* ((completion-ignore-case t)
10560 (prop (org-ido-completing-read
10561 "Globally remove property: "
10562 (mapcar 'list (org-buffer-property-keys)))))
10563 (list prop)))
10564 (save-excursion
10565 (save-restriction
10566 (widen)
10567 (goto-char (point-min))
10568 (let ((cnt 0))
10569 (while (re-search-forward
10570 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10571 nil t)
10572 (setq cnt (1+ cnt))
10573 (replace-match ""))
10574 (message "Property \"%s\" removed from %d entries" property cnt)))))
10576 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10578 (defun org-compute-property-at-point ()
10579 "Compute the property at point.
10580 This looks for an enclosing column format, extracts the operator and
10581 then applies it to the proerty in the column format's scope."
10582 (interactive)
10583 (unless (org-at-property-p)
10584 (error "Not at a property"))
10585 (let ((prop (org-match-string-no-properties 2)))
10586 (org-columns-get-format-and-top-level)
10587 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10588 (error "No operator defined for property %s" prop))
10589 (org-columns-compute prop)))
10591 (defun org-property-get-allowed-values (pom property &optional table)
10592 "Get allowed values for the property PROPERTY.
10593 When TABLE is non-nil, return an alist that can directly be used for
10594 completion."
10595 (let (vals)
10596 (cond
10597 ((equal property "TODO")
10598 (setq vals (org-with-point-at pom
10599 (append org-todo-keywords-1 '("")))))
10600 ((equal property "PRIORITY")
10601 (let ((n org-lowest-priority))
10602 (while (>= n org-highest-priority)
10603 (push (char-to-string n) vals)
10604 (setq n (1- n)))))
10605 ((member property org-special-properties))
10607 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10609 (when (and vals (string-match "\\S-" vals))
10610 (setq vals (car (read-from-string (concat "(" vals ")"))))
10611 (setq vals (mapcar (lambda (x)
10612 (cond ((stringp x) x)
10613 ((numberp x) (number-to-string x))
10614 ((symbolp x) (symbol-name x))
10615 (t "???")))
10616 vals)))))
10617 (if table (mapcar 'list vals) vals)))
10619 (defun org-property-previous-allowed-value (&optional previous)
10620 "Switch to the next allowed value for this property."
10621 (interactive)
10622 (org-property-next-allowed-value t))
10624 (defun org-property-next-allowed-value (&optional previous)
10625 "Switch to the next allowed value for this property."
10626 (interactive)
10627 (unless (org-at-property-p)
10628 (error "Not at a property"))
10629 (let* ((key (match-string 2))
10630 (value (match-string 3))
10631 (allowed (or (org-property-get-allowed-values (point) key)
10632 (and (member value '("[ ]" "[-]" "[X]"))
10633 '("[ ]" "[X]"))))
10634 nval)
10635 (unless allowed
10636 (error "Allowed values for this property have not been defined"))
10637 (if previous (setq allowed (reverse allowed)))
10638 (if (member value allowed)
10639 (setq nval (car (cdr (member value allowed)))))
10640 (setq nval (or nval (car allowed)))
10641 (if (equal nval value)
10642 (error "Only one allowed value for this property"))
10643 (org-at-property-p)
10644 (replace-match (concat " :" key ": " nval) t t)
10645 (org-indent-line-function)
10646 (beginning-of-line 1)
10647 (skip-chars-forward " \t")))
10649 (defun org-find-entry-with-id (ident)
10650 "Locate the entry that contains the ID property with exact value IDENT.
10651 IDENT can be a string, a symbol or a number, this function will search for
10652 the string representation of it.
10653 Return the position where this entry starts, or nil if there is no such entry."
10654 (interactive "sID: ")
10655 (let ((id (cond
10656 ((stringp ident) ident)
10657 ((symbol-name ident) (symbol-name ident))
10658 ((numberp ident) (number-to-string ident))
10659 (t (error "IDENT %s must be a string, symbol or number" ident))))
10660 (case-fold-search nil))
10661 (save-excursion
10662 (save-restriction
10663 (widen)
10664 (goto-char (point-min))
10665 (when (re-search-forward
10666 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10667 nil t)
10668 (org-back-to-heading)
10669 (point))))))
10671 ;;;; Timestamps
10673 (defvar org-last-changed-timestamp nil)
10674 (defvar org-last-inserted-timestamp nil
10675 "The last time stamp inserted with `org-insert-time-stamp'.")
10676 (defvar org-time-was-given) ; dynamically scoped parameter
10677 (defvar org-end-time-was-given) ; dynamically scoped parameter
10678 (defvar org-ts-what) ; dynamically scoped parameter
10680 (defun org-time-stamp (arg &optional inactive)
10681 "Prompt for a date/time and insert a time stamp.
10682 If the user specifies a time like HH:MM, or if this command is called
10683 with a prefix argument, the time stamp will contain date and time.
10684 Otherwise, only the date will be included. All parts of a date not
10685 specified by the user will be filled in from the current date/time.
10686 So if you press just return without typing anything, the time stamp
10687 will represent the current date/time. If there is already a timestamp
10688 at the cursor, it will be modified."
10689 (interactive "P")
10690 (let* ((ts nil)
10691 (default-time
10692 ;; Default time is either today, or, when entering a range,
10693 ;; the range start.
10694 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10695 (save-excursion
10696 (re-search-backward
10697 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10698 (- (point) 20) t)))
10699 (apply 'encode-time (org-parse-time-string (match-string 1)))
10700 (current-time)))
10701 (default-input (and ts (org-get-compact-tod ts)))
10702 org-time-was-given org-end-time-was-given time)
10703 (cond
10704 ((and (org-at-timestamp-p t)
10705 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10706 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10707 (insert "--")
10708 (setq time (let ((this-command this-command))
10709 (org-read-date arg 'totime nil nil
10710 default-time default-input)))
10711 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10712 ((org-at-timestamp-p t)
10713 (setq time (let ((this-command this-command))
10714 (org-read-date arg 'totime nil nil default-time default-input)))
10715 (when (org-at-timestamp-p t) ; just to get the match data
10716 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10717 (replace-match "")
10718 (setq org-last-changed-timestamp
10719 (org-insert-time-stamp
10720 time (or org-time-was-given arg)
10721 inactive nil nil (list org-end-time-was-given))))
10722 (message "Timestamp updated"))
10724 (setq time (let ((this-command this-command))
10725 (org-read-date arg 'totime nil nil default-time default-input)))
10726 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10727 nil nil (list org-end-time-was-given))))))
10729 ;; FIXME: can we use this for something else, like computing time differences?
10730 (defun org-get-compact-tod (s)
10731 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10732 (let* ((t1 (match-string 1 s))
10733 (h1 (string-to-number (match-string 2 s)))
10734 (m1 (string-to-number (match-string 3 s)))
10735 (t2 (and (match-end 4) (match-string 5 s)))
10736 (h2 (and t2 (string-to-number (match-string 6 s))))
10737 (m2 (and t2 (string-to-number (match-string 7 s))))
10738 dh dm)
10739 (if (not t2)
10741 (setq dh (- h2 h1) dm (- m2 m1))
10742 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10743 (concat t1 "+" (number-to-string dh)
10744 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10746 (defun org-time-stamp-inactive (&optional arg)
10747 "Insert an inactive time stamp.
10748 An inactive time stamp is enclosed in square brackets instead of angle
10749 brackets. It is inactive in the sense that it does not trigger agenda entries,
10750 does not link to the calendar and cannot be changed with the S-cursor keys.
10751 So these are more for recording a certain time/date."
10752 (interactive "P")
10753 (org-time-stamp arg 'inactive))
10755 (defvar org-date-ovl (org-make-overlay 1 1))
10756 (org-overlay-put org-date-ovl 'face 'org-warning)
10757 (org-detach-overlay org-date-ovl)
10759 (defvar org-ans1) ; dynamically scoped parameter
10760 (defvar org-ans2) ; dynamically scoped parameter
10762 (defvar org-plain-time-of-day-regexp) ; defined below
10764 (defvar org-overriding-default-time nil) ; dynamically scoped
10765 (defvar org-read-date-overlay nil)
10766 (defvar org-dcst nil) ; dynamically scoped
10768 (defun org-read-date (&optional with-time to-time from-string prompt
10769 default-time default-input)
10770 "Read a date, possibly a time, and make things smooth for the user.
10771 The prompt will suggest to enter an ISO date, but you can also enter anything
10772 which will at least partially be understood by `parse-time-string'.
10773 Unrecognized parts of the date will default to the current day, month, year,
10774 hour and minute. If this command is called to replace a timestamp at point,
10775 of to enter the second timestamp of a range, the default time is taken from the
10776 existing stamp. For example,
10777 3-2-5 --> 2003-02-05
10778 feb 15 --> currentyear-02-15
10779 sep 12 9 --> 2009-09-12
10780 12:45 --> today 12:45
10781 22 sept 0:34 --> currentyear-09-22 0:34
10782 12 --> currentyear-currentmonth-12
10783 Fri --> nearest Friday (today or later)
10784 etc.
10786 Furthermore you can specify a relative date by giving, as the *first* thing
10787 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10788 change in days weeks, months, years.
10789 With a single plus or minus, the date is relative to today. With a double
10790 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10791 +4d --> four days from today
10792 +4 --> same as above
10793 +2w --> two weeks from today
10794 ++5 --> five days from default date
10796 The function understands only English month and weekday abbreviations,
10797 but this can be configured with the variables `parse-time-months' and
10798 `parse-time-weekdays'.
10800 While prompting, a calendar is popped up - you can also select the
10801 date with the mouse (button 1). The calendar shows a period of three
10802 months. To scroll it to other months, use the keys `>' and `<'.
10803 If you don't like the calendar, turn it off with
10804 \(setq org-read-date-popup-calendar nil)
10806 With optional argument TO-TIME, the date will immediately be converted
10807 to an internal time.
10808 With an optional argument WITH-TIME, the prompt will suggest to also
10809 insert a time. Note that when WITH-TIME is not set, you can still
10810 enter a time, and this function will inform the calling routine about
10811 this change. The calling routine may then choose to change the format
10812 used to insert the time stamp into the buffer to include the time.
10813 With optional argument FROM-STRING, read from this string instead from
10814 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10815 the time/date that is used for everything that is not specified by the
10816 user."
10817 (require 'parse-time)
10818 (let* ((org-time-stamp-rounding-minutes
10819 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10820 (org-dcst org-display-custom-times)
10821 (ct (org-current-time))
10822 (def (or org-overriding-default-time default-time ct))
10823 (defdecode (decode-time def))
10824 (dummy (progn
10825 (when (< (nth 2 defdecode) org-extend-today-until)
10826 (setcar (nthcdr 2 defdecode) -1)
10827 (setcar (nthcdr 1 defdecode) 59)
10828 (setq def (apply 'encode-time defdecode)
10829 defdecode (decode-time def)))))
10830 (calendar-move-hook nil)
10831 (calendar-view-diary-initially-flag nil)
10832 (view-diary-entries-initially nil)
10833 (calendar-view-holidays-initially-flag nil)
10834 (view-calendar-holidays-initially nil)
10835 (timestr (format-time-string
10836 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10837 (prompt (concat (if prompt (concat prompt " ") "")
10838 (format "Date+time [%s]: " timestr)))
10839 ans (org-ans0 "") org-ans1 org-ans2 final)
10841 (cond
10842 (from-string (setq ans from-string))
10843 (org-read-date-popup-calendar
10844 (save-excursion
10845 (save-window-excursion
10846 (calendar)
10847 (calendar-forward-day (- (time-to-days def)
10848 (calendar-absolute-from-gregorian
10849 (calendar-current-date))))
10850 (org-eval-in-calendar nil t)
10851 (let* ((old-map (current-local-map))
10852 (map (copy-keymap calendar-mode-map))
10853 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10854 (org-defkey map (kbd "RET") 'org-calendar-select)
10855 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10856 'org-calendar-select-mouse)
10857 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10858 'org-calendar-select-mouse)
10859 (org-defkey minibuffer-local-map [(meta shift left)]
10860 (lambda () (interactive)
10861 (org-eval-in-calendar '(calendar-backward-month 1))))
10862 (org-defkey minibuffer-local-map [(meta shift right)]
10863 (lambda () (interactive)
10864 (org-eval-in-calendar '(calendar-forward-month 1))))
10865 (org-defkey minibuffer-local-map [(meta shift up)]
10866 (lambda () (interactive)
10867 (org-eval-in-calendar '(calendar-backward-year 1))))
10868 (org-defkey minibuffer-local-map [(meta shift down)]
10869 (lambda () (interactive)
10870 (org-eval-in-calendar '(calendar-forward-year 1))))
10871 (org-defkey minibuffer-local-map [(shift up)]
10872 (lambda () (interactive)
10873 (org-eval-in-calendar '(calendar-backward-week 1))))
10874 (org-defkey minibuffer-local-map [(shift down)]
10875 (lambda () (interactive)
10876 (org-eval-in-calendar '(calendar-forward-week 1))))
10877 (org-defkey minibuffer-local-map [(shift left)]
10878 (lambda () (interactive)
10879 (org-eval-in-calendar '(calendar-backward-day 1))))
10880 (org-defkey minibuffer-local-map [(shift right)]
10881 (lambda () (interactive)
10882 (org-eval-in-calendar '(calendar-forward-day 1))))
10883 (org-defkey minibuffer-local-map ">"
10884 (lambda () (interactive)
10885 (org-eval-in-calendar '(scroll-calendar-left 1))))
10886 (org-defkey minibuffer-local-map "<"
10887 (lambda () (interactive)
10888 (org-eval-in-calendar '(scroll-calendar-right 1))))
10889 (unwind-protect
10890 (progn
10891 (use-local-map map)
10892 (add-hook 'post-command-hook 'org-read-date-display)
10893 (setq org-ans0 (read-string prompt default-input nil nil))
10894 ;; org-ans0: from prompt
10895 ;; org-ans1: from mouse click
10896 ;; org-ans2: from calendar motion
10897 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10898 (remove-hook 'post-command-hook 'org-read-date-display)
10899 (use-local-map old-map)
10900 (when org-read-date-overlay
10901 (org-delete-overlay org-read-date-overlay)
10902 (setq org-read-date-overlay nil)))))))
10904 (t ; Naked prompt only
10905 (unwind-protect
10906 (setq ans (read-string prompt default-input nil timestr))
10907 (when org-read-date-overlay
10908 (org-delete-overlay org-read-date-overlay)
10909 (setq org-read-date-overlay nil)))))
10911 (setq final (org-read-date-analyze ans def defdecode))
10913 (if to-time
10914 (apply 'encode-time final)
10915 (if (and (boundp 'org-time-was-given) org-time-was-given)
10916 (format "%04d-%02d-%02d %02d:%02d"
10917 (nth 5 final) (nth 4 final) (nth 3 final)
10918 (nth 2 final) (nth 1 final))
10919 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10920 (defvar def)
10921 (defvar defdecode)
10922 (defvar with-time)
10923 (defun org-read-date-display ()
10924 "Display the currrent date prompt interpretation in the minibuffer."
10925 (when org-read-date-display-live
10926 (when org-read-date-overlay
10927 (org-delete-overlay org-read-date-overlay))
10928 (let ((p (point)))
10929 (end-of-line 1)
10930 (while (not (equal (buffer-substring
10931 (max (point-min) (- (point) 4)) (point))
10932 " "))
10933 (insert " "))
10934 (goto-char p))
10935 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10936 " " (or org-ans1 org-ans2)))
10937 (org-end-time-was-given nil)
10938 (f (org-read-date-analyze ans def defdecode))
10939 (fmts (if org-dcst
10940 org-time-stamp-custom-formats
10941 org-time-stamp-formats))
10942 (fmt (if (or with-time
10943 (and (boundp 'org-time-was-given) org-time-was-given))
10944 (cdr fmts)
10945 (car fmts)))
10946 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10947 (when (and org-end-time-was-given
10948 (string-match org-plain-time-of-day-regexp txt))
10949 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10950 org-end-time-was-given
10951 (substring txt (match-end 0)))))
10952 (setq org-read-date-overlay
10953 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10954 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10956 (defun org-read-date-analyze (ans def defdecode)
10957 "Analyze the combined answer of the date prompt."
10958 ;; FIXME: cleanup and comment
10959 (let (delta deltan deltaw deltadef year month day
10960 hour minute second wday pm h2 m2 tl wday1
10961 iso-year iso-weekday iso-week iso-year iso-date)
10963 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10964 (setq ans "+0"))
10966 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10967 (setq ans (replace-match "" t t ans)
10968 deltan (car delta)
10969 deltaw (nth 1 delta)
10970 deltadef (nth 2 delta)))
10972 ;; Check if there is an iso week date in there
10973 ;; If yes, sore the info and ostpone interpreting it until the rest
10974 ;; of the parsing is done
10975 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10976 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10977 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10978 iso-week (string-to-number (match-string 2 ans)))
10979 (setq ans (replace-match "" t t ans)))
10981 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10982 (when (string-match
10983 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10984 (setq year (if (match-end 2)
10985 (string-to-number (match-string 2 ans))
10986 (string-to-number (format-time-string "%Y")))
10987 month (string-to-number (match-string 3 ans))
10988 day (string-to-number (match-string 4 ans)))
10989 (if (< year 100) (setq year (+ 2000 year)))
10990 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10991 t nil ans)))
10992 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10993 ;; If there is a time with am/pm, and *no* time without it, we convert
10994 ;; so that matching will be successful.
10995 (loop for i from 1 to 2 do ; twice, for end time as well
10996 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10997 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10998 (setq hour (string-to-number (match-string 1 ans))
10999 minute (if (match-end 3)
11000 (string-to-number (match-string 3 ans))
11002 pm (equal ?p
11003 (string-to-char (downcase (match-string 4 ans)))))
11004 (if (and (= hour 12) (not pm))
11005 (setq hour 0)
11006 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11007 (setq ans (replace-match (format "%02d:%02d" hour minute)
11008 t t ans))))
11010 ;; Check if a time range is given as a duration
11011 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11012 (setq hour (string-to-number (match-string 1 ans))
11013 h2 (+ hour (string-to-number (match-string 3 ans)))
11014 minute (string-to-number (match-string 2 ans))
11015 m2 (+ minute (if (match-end 5) (string-to-number
11016 (match-string 5 ans))0)))
11017 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11018 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11019 t t ans)))
11021 ;; Check if there is a time range
11022 (when (boundp 'org-end-time-was-given)
11023 (setq org-time-was-given nil)
11024 (when (and (string-match org-plain-time-of-day-regexp ans)
11025 (match-end 8))
11026 (setq org-end-time-was-given (match-string 8 ans))
11027 (setq ans (concat (substring ans 0 (match-beginning 7))
11028 (substring ans (match-end 7))))))
11030 (setq tl (parse-time-string ans)
11031 day (or (nth 3 tl) (nth 3 defdecode))
11032 month (or (nth 4 tl)
11033 (if (and org-read-date-prefer-future
11034 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11035 (1+ (nth 4 defdecode))
11036 (nth 4 defdecode)))
11037 year (or (nth 5 tl)
11038 (if (and org-read-date-prefer-future
11039 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11040 (1+ (nth 5 defdecode))
11041 (nth 5 defdecode)))
11042 hour (or (nth 2 tl) (nth 2 defdecode))
11043 minute (or (nth 1 tl) (nth 1 defdecode))
11044 second (or (nth 0 tl) 0)
11045 wday (nth 6 tl))
11047 ;; Special date definitions below
11048 (cond
11049 (iso-week
11050 ;; There was an iso week
11051 (setq year (or iso-year year)
11052 day (or iso-weekday wday 1)
11053 wday nil ; to make sure that the trigger below does not match
11054 iso-date (calendar-gregorian-from-absolute
11055 (calendar-absolute-from-iso
11056 (list iso-week day year))))
11057 ; FIXME: Should we also push ISO weeks into the future?
11058 ; (when (and org-read-date-prefer-future
11059 ; (not iso-year)
11060 ; (< (calendar-absolute-from-gregorian iso-date)
11061 ; (time-to-days (current-time))))
11062 ; (setq year (1+ year)
11063 ; iso-date (calendar-gregorian-from-absolute
11064 ; (calendar-absolute-from-iso
11065 ; (list iso-week day year)))))
11066 (setq month (car iso-date)
11067 year (nth 2 iso-date)
11068 day (nth 1 iso-date)))
11069 (deltan
11070 (unless deltadef
11071 (let ((now (decode-time (current-time))))
11072 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11073 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11074 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11075 ((equal deltaw "m") (setq month (+ month deltan)))
11076 ((equal deltaw "y") (setq year (+ year deltan)))))
11077 ((and wday (not (nth 3 tl)))
11078 ;; Weekday was given, but no day, so pick that day in the week
11079 ;; on or after the derived date.
11080 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11081 (unless (equal wday wday1)
11082 (setq day (+ day (% (- wday wday1 -7) 7))))))
11083 (if (and (boundp 'org-time-was-given)
11084 (nth 2 tl))
11085 (setq org-time-was-given t))
11086 (if (< year 100) (setq year (+ 2000 year)))
11087 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11088 (list second minute hour day month year)))
11090 (defvar parse-time-weekdays)
11092 (defun org-read-date-get-relative (s today default)
11093 "Check string S for special relative date string.
11094 TODAY and DEFAULT are internal times, for today and for a default.
11095 Return shift list (N what def-flag)
11096 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11097 N is the number of WHATs to shift.
11098 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11099 the DEFAULT date rather than TODAY."
11100 (when (and
11101 (string-match
11102 (concat
11103 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11104 "\\([0-9]+\\)?"
11105 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11106 "\\([ \t]\\|$\\)") s)
11107 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11108 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11109 (string-to-char (substring (match-string 1 s) -1))
11110 ?+))
11111 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11112 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11113 (what (if (match-end 3) (match-string 3 s) "d"))
11114 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11115 (date (if rel default today))
11116 (wday (nth 6 (decode-time date)))
11117 delta)
11118 (if wday1
11119 (progn
11120 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11121 (if (= dir ?-) (setq delta (- delta 7)))
11122 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11123 (list delta "d" rel))
11124 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11126 (defun org-eval-in-calendar (form &optional keepdate)
11127 "Eval FORM in the calendar window and return to current window.
11128 Also, store the cursor date in variable org-ans2."
11129 (let ((sw (selected-window)))
11130 (select-window (get-buffer-window "*Calendar*"))
11131 (eval form)
11132 (when (and (not keepdate) (calendar-cursor-to-date))
11133 (let* ((date (calendar-cursor-to-date))
11134 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11135 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11136 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11137 (select-window sw)))
11139 (defun org-calendar-select ()
11140 "Return to `org-read-date' with the date currently selected.
11141 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11142 (interactive)
11143 (when (calendar-cursor-to-date)
11144 (let* ((date (calendar-cursor-to-date))
11145 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11146 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11147 (if (active-minibuffer-window) (exit-minibuffer))))
11149 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11150 "Insert a date stamp for the date given by the internal TIME.
11151 WITH-HM means, use the stamp format that includes the time of the day.
11152 INACTIVE means use square brackets instead of angular ones, so that the
11153 stamp will not contribute to the agenda.
11154 PRE and POST are optional strings to be inserted before and after the
11155 stamp.
11156 The command returns the inserted time stamp."
11157 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11158 stamp)
11159 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11160 (insert-before-markers (or pre ""))
11161 (insert-before-markers (setq stamp (format-time-string fmt time)))
11162 (when (listp extra)
11163 (setq extra (car extra))
11164 (if (and (stringp extra)
11165 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11166 (setq extra (format "-%02d:%02d"
11167 (string-to-number (match-string 1 extra))
11168 (string-to-number (match-string 2 extra))))
11169 (setq extra nil)))
11170 (when extra
11171 (backward-char 1)
11172 (insert-before-markers extra)
11173 (forward-char 1))
11174 (insert-before-markers (or post ""))
11175 (setq org-last-inserted-timestamp stamp)))
11177 (defun org-toggle-time-stamp-overlays ()
11178 "Toggle the use of custom time stamp formats."
11179 (interactive)
11180 (setq org-display-custom-times (not org-display-custom-times))
11181 (unless org-display-custom-times
11182 (let ((p (point-min)) (bmp (buffer-modified-p)))
11183 (while (setq p (next-single-property-change p 'display))
11184 (if (and (get-text-property p 'display)
11185 (eq (get-text-property p 'face) 'org-date))
11186 (remove-text-properties
11187 p (setq p (next-single-property-change p 'display))
11188 '(display t))))
11189 (set-buffer-modified-p bmp)))
11190 (if (featurep 'xemacs)
11191 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11192 (org-restart-font-lock)
11193 (setq org-table-may-need-update t)
11194 (if org-display-custom-times
11195 (message "Time stamps are overlayed with custom format")
11196 (message "Time stamp overlays removed")))
11198 (defun org-display-custom-time (beg end)
11199 "Overlay modified time stamp format over timestamp between BEG and END."
11200 (let* ((ts (buffer-substring beg end))
11201 t1 w1 with-hm tf time str w2 (off 0))
11202 (save-match-data
11203 (setq t1 (org-parse-time-string ts t))
11204 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11205 (setq off (- (match-end 0) (match-beginning 0)))))
11206 (setq end (- end off))
11207 (setq w1 (- end beg)
11208 with-hm (and (nth 1 t1) (nth 2 t1))
11209 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11210 time (org-fix-decoded-time t1)
11211 str (org-add-props
11212 (format-time-string
11213 (substring tf 1 -1) (apply 'encode-time time))
11214 nil 'mouse-face 'highlight)
11215 w2 (length str))
11216 (if (not (= w2 w1))
11217 (add-text-properties (1+ beg) (+ 2 beg)
11218 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11219 (if (featurep 'xemacs)
11220 (progn
11221 (put-text-property beg end 'invisible t)
11222 (put-text-property beg end 'end-glyph (make-glyph str)))
11223 (put-text-property beg end 'display str))))
11225 (defun org-translate-time (string)
11226 "Translate all timestamps in STRING to custom format.
11227 But do this only if the variable `org-display-custom-times' is set."
11228 (when org-display-custom-times
11229 (save-match-data
11230 (let* ((start 0)
11231 (re org-ts-regexp-both)
11232 t1 with-hm inactive tf time str beg end)
11233 (while (setq start (string-match re string start))
11234 (setq beg (match-beginning 0)
11235 end (match-end 0)
11236 t1 (save-match-data
11237 (org-parse-time-string (substring string beg end) t))
11238 with-hm (and (nth 1 t1) (nth 2 t1))
11239 inactive (equal (substring string beg (1+ beg)) "[")
11240 tf (funcall (if with-hm 'cdr 'car)
11241 org-time-stamp-custom-formats)
11242 time (org-fix-decoded-time t1)
11243 str (format-time-string
11244 (concat
11245 (if inactive "[" "<") (substring tf 1 -1)
11246 (if inactive "]" ">"))
11247 (apply 'encode-time time))
11248 string (replace-match str t t string)
11249 start (+ start (length str)))))))
11250 string)
11252 (defun org-fix-decoded-time (time)
11253 "Set 0 instead of nil for the first 6 elements of time.
11254 Don't touch the rest."
11255 (let ((n 0))
11256 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11258 (defun org-days-to-time (timestamp-string)
11259 "Difference between TIMESTAMP-STRING and now in days."
11260 (- (time-to-days (org-time-string-to-time timestamp-string))
11261 (time-to-days (current-time))))
11263 (defun org-deadline-close (timestamp-string &optional ndays)
11264 "Is the time in TIMESTAMP-STRING close to the current date?"
11265 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11266 (and (< (org-days-to-time timestamp-string) ndays)
11267 (not (org-entry-is-done-p))))
11269 (defun org-get-wdays (ts)
11270 "Get the deadline lead time appropriate for timestring TS."
11271 (cond
11272 ((<= org-deadline-warning-days 0)
11273 ;; 0 or negative, enforce this value no matter what
11274 (- org-deadline-warning-days))
11275 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11276 ;; lead time is specified.
11277 (floor (* (string-to-number (match-string 1 ts))
11278 (cdr (assoc (match-string 2 ts)
11279 '(("d" . 1) ("w" . 7)
11280 ("m" . 30.4) ("y" . 365.25)))))))
11281 ;; go for the default.
11282 (t org-deadline-warning-days)))
11284 (defun org-calendar-select-mouse (ev)
11285 "Return to `org-read-date' with the date currently selected.
11286 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11287 (interactive "e")
11288 (mouse-set-point ev)
11289 (when (calendar-cursor-to-date)
11290 (let* ((date (calendar-cursor-to-date))
11291 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11292 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11293 (if (active-minibuffer-window) (exit-minibuffer))))
11295 (defun org-check-deadlines (ndays)
11296 "Check if there are any deadlines due or past due.
11297 A deadline is considered due if it happens within `org-deadline-warning-days'
11298 days from today's date. If the deadline appears in an entry marked DONE,
11299 it is not shown. The prefix arg NDAYS can be used to test that many
11300 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11301 (interactive "P")
11302 (let* ((org-warn-days
11303 (cond
11304 ((equal ndays '(4)) 100000)
11305 (ndays (prefix-numeric-value ndays))
11306 (t (abs org-deadline-warning-days))))
11307 (case-fold-search nil)
11308 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11309 (callback
11310 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11312 (message "%d deadlines past-due or due within %d days"
11313 (org-occur regexp nil callback)
11314 org-warn-days)))
11316 (defun org-check-before-date (date)
11317 "Check if there are deadlines or scheduled entries before DATE."
11318 (interactive (list (org-read-date)))
11319 (let ((case-fold-search nil)
11320 (regexp (concat "\\<\\(" org-deadline-string
11321 "\\|" org-scheduled-string
11322 "\\) *<\\([^>]+\\)>"))
11323 (callback
11324 (lambda () (time-less-p
11325 (org-time-string-to-time (match-string 2))
11326 (org-time-string-to-time date)))))
11327 (message "%d entries before %s"
11328 (org-occur regexp nil callback) date)))
11330 (defun org-evaluate-time-range (&optional to-buffer)
11331 "Evaluate a time range by computing the difference between start and end.
11332 Normally the result is just printed in the echo area, but with prefix arg
11333 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11334 If the time range is actually in a table, the result is inserted into the
11335 next column.
11336 For time difference computation, a year is assumed to be exactly 365
11337 days in order to avoid rounding problems."
11338 (interactive "P")
11340 (org-clock-update-time-maybe)
11341 (save-excursion
11342 (unless (org-at-date-range-p t)
11343 (goto-char (point-at-bol))
11344 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11345 (if (not (org-at-date-range-p t))
11346 (error "Not at a time-stamp range, and none found in current line")))
11347 (let* ((ts1 (match-string 1))
11348 (ts2 (match-string 2))
11349 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11350 (match-end (match-end 0))
11351 (time1 (org-time-string-to-time ts1))
11352 (time2 (org-time-string-to-time ts2))
11353 (t1 (time-to-seconds time1))
11354 (t2 (time-to-seconds time2))
11355 (diff (abs (- t2 t1)))
11356 (negative (< (- t2 t1) 0))
11357 ;; (ys (floor (* 365 24 60 60)))
11358 (ds (* 24 60 60))
11359 (hs (* 60 60))
11360 (fy "%dy %dd %02d:%02d")
11361 (fy1 "%dy %dd")
11362 (fd "%dd %02d:%02d")
11363 (fd1 "%dd")
11364 (fh "%02d:%02d")
11365 y d h m align)
11366 (if havetime
11367 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11369 d (floor (/ diff ds)) diff (mod diff ds)
11370 h (floor (/ diff hs)) diff (mod diff hs)
11371 m (floor (/ diff 60)))
11372 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11374 d (floor (+ (/ diff ds) 0.5))
11375 h 0 m 0))
11376 (if (not to-buffer)
11377 (message "%s" (org-make-tdiff-string y d h m))
11378 (if (org-at-table-p)
11379 (progn
11380 (goto-char match-end)
11381 (setq align t)
11382 (and (looking-at " *|") (goto-char (match-end 0))))
11383 (goto-char match-end))
11384 (if (looking-at
11385 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11386 (replace-match ""))
11387 (if negative (insert " -"))
11388 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11389 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11390 (insert " " (format fh h m))))
11391 (if align (org-table-align))
11392 (message "Time difference inserted")))))
11394 (defun org-make-tdiff-string (y d h m)
11395 (let ((fmt "")
11396 (l nil))
11397 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11398 l (push y l)))
11399 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11400 l (push d l)))
11401 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11402 l (push h l)))
11403 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11404 l (push m l)))
11405 (apply 'format fmt (nreverse l))))
11407 (defun org-time-string-to-time (s)
11408 (apply 'encode-time (org-parse-time-string s)))
11410 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11411 "Convert a time stamp to an absolute day number.
11412 If there is a specifyer for a cyclic time stamp, get the closest date to
11413 DAYNR.
11414 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11415 (cond
11416 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11417 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11418 daynr
11419 (+ daynr 1000)))
11420 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11421 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11422 (time-to-days (current-time))) (match-string 0 s)
11423 prefer show-all))
11424 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11426 (defun org-days-to-iso-week (days)
11427 "Return the iso week number."
11428 (require 'cal-iso)
11429 (car (calendar-iso-from-absolute days)))
11431 (defun org-small-year-to-year (year)
11432 "Convert 2-digit years into 4-digit years.
11433 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11434 The year 2000 cannot be abbreviated. Any year larger than 99
11435 is returned unchanged."
11436 (if (< year 38)
11437 (setq year (+ 2000 year))
11438 (if (< year 100)
11439 (setq year (+ 1900 year))))
11440 year)
11442 (defun org-time-from-absolute (d)
11443 "Return the time corresponding to date D.
11444 D may be an absolute day number, or a calendar-type list (month day year)."
11445 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11446 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11448 (defun org-calendar-holiday ()
11449 "List of holidays, for Diary display in Org-mode."
11450 (require 'holidays)
11451 (let ((hl (funcall
11452 (if (fboundp 'calendar-check-holidays)
11453 'calendar-check-holidays 'check-calendar-holidays) date)))
11454 (if hl (mapconcat 'identity hl "; "))))
11456 (defun org-diary-sexp-entry (sexp entry date)
11457 "Process a SEXP diary ENTRY for DATE."
11458 (require 'diary-lib)
11459 (let ((result (if calendar-debug-sexp
11460 (let ((stack-trace-on-error t))
11461 (eval (car (read-from-string sexp))))
11462 (condition-case nil
11463 (eval (car (read-from-string sexp)))
11464 (error
11465 (beep)
11466 (message "Bad sexp at line %d in %s: %s"
11467 (org-current-line)
11468 (buffer-file-name) sexp)
11469 (sleep-for 2))))))
11470 (cond ((stringp result) result)
11471 ((and (consp result)
11472 (stringp (cdr result))) (cdr result))
11473 (result entry)
11474 (t nil))))
11476 (defun org-diary-to-ical-string (frombuf)
11477 "Get iCalendar entries from diary entries in buffer FROMBUF.
11478 This uses the icalendar.el library."
11479 (let* ((tmpdir (if (featurep 'xemacs)
11480 (temp-directory)
11481 temporary-file-directory))
11482 (tmpfile (make-temp-name
11483 (expand-file-name "orgics" tmpdir)))
11484 buf rtn b e)
11485 (save-excursion
11486 (set-buffer frombuf)
11487 (icalendar-export-region (point-min) (point-max) tmpfile)
11488 (setq buf (find-buffer-visiting tmpfile))
11489 (set-buffer buf)
11490 (goto-char (point-min))
11491 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11492 (setq b (match-beginning 0)))
11493 (goto-char (point-max))
11494 (if (re-search-backward "^END:VEVENT" nil t)
11495 (setq e (match-end 0)))
11496 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11497 (kill-buffer buf)
11498 (delete-file tmpfile)
11499 rtn))
11501 (defun org-closest-date (start current change prefer show-all)
11502 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11503 When PREFER is `past' return a date that is either CURRENT or past.
11504 When PREFER is `future', return a date that is either CURRENT or future.
11505 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11506 ;; Make the proper lists from the dates
11507 (catch 'exit
11508 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11509 dn dw sday cday n1 n2
11510 d m y y1 y2 date1 date2 nmonths nm ny m2)
11512 (setq start (org-date-to-gregorian start)
11513 current (org-date-to-gregorian
11514 (if show-all
11515 current
11516 (time-to-days (current-time))))
11517 sday (calendar-absolute-from-gregorian start)
11518 cday (calendar-absolute-from-gregorian current))
11520 (if (<= cday sday) (throw 'exit sday))
11522 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11523 (setq dn (string-to-number (match-string 1 change))
11524 dw (cdr (assoc (match-string 2 change) a1)))
11525 (error "Invalid change specifyer: %s" change))
11526 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11527 (cond
11528 ((eq dw 'day)
11529 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11530 n2 (+ n1 dn)))
11531 ((eq dw 'year)
11532 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11533 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11534 (setq date1 (list m d y1)
11535 n1 (calendar-absolute-from-gregorian date1)
11536 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11537 n2 (calendar-absolute-from-gregorian date2)))
11538 ((eq dw 'month)
11539 ;; approx number of month between the two dates
11540 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11541 ;; How often does dn fit in there?
11542 (setq d (nth 1 start) m (car start) y (nth 2 start)
11543 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11544 m (+ m nm)
11545 ny (floor (/ m 12))
11546 y (+ y ny)
11547 m (- m (* ny 12)))
11548 (while (> m 12) (setq m (- m 12) y (1+ y)))
11549 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11550 (setq m2 (+ m dn) y2 y)
11551 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11552 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11553 (while (<= n2 cday)
11554 (setq n1 n2 m m2 y y2)
11555 (setq m2 (+ m dn) y2 y)
11556 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11557 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11558 (if show-all
11559 (cond
11560 ((eq prefer 'past) n1)
11561 ((eq prefer 'future) (if (= cday n1) n1 n2))
11562 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11563 (cond
11564 ((eq prefer 'past) n1)
11565 ((eq prefer 'future) (if (= cday n1) n1 n2))
11566 (t (if (= cday n1) n1 n2)))))))
11568 (defun org-date-to-gregorian (date)
11569 "Turn any specification of DATE into a gregorian date for the calendar."
11570 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11571 ((and (listp date) (= (length date) 3)) date)
11572 ((stringp date)
11573 (setq date (org-parse-time-string date))
11574 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11575 ((listp date)
11576 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11578 (defun org-parse-time-string (s &optional nodefault)
11579 "Parse the standard Org-mode time string.
11580 This should be a lot faster than the normal `parse-time-string'.
11581 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11582 hour and minute fields will be nil if not given."
11583 (if (string-match org-ts-regexp0 s)
11584 (list 0
11585 (if (or (match-beginning 8) (not nodefault))
11586 (string-to-number (or (match-string 8 s) "0")))
11587 (if (or (match-beginning 7) (not nodefault))
11588 (string-to-number (or (match-string 7 s) "0")))
11589 (string-to-number (match-string 4 s))
11590 (string-to-number (match-string 3 s))
11591 (string-to-number (match-string 2 s))
11592 nil nil nil)
11593 (make-list 9 0)))
11595 (defun org-timestamp-up (&optional arg)
11596 "Increase the date item at the cursor by one.
11597 If the cursor is on the year, change the year. If it is on the month or
11598 the day, change that.
11599 With prefix ARG, change by that many units."
11600 (interactive "p")
11601 (org-timestamp-change (prefix-numeric-value arg)))
11603 (defun org-timestamp-down (&optional arg)
11604 "Decrease the date item at the cursor by one.
11605 If the cursor is on the year, change the year. If it is on the month or
11606 the day, change that.
11607 With prefix ARG, change by that many units."
11608 (interactive "p")
11609 (org-timestamp-change (- (prefix-numeric-value arg))))
11611 (defun org-timestamp-up-day (&optional arg)
11612 "Increase the date in the time stamp by one day.
11613 With prefix ARG, change that many days."
11614 (interactive "p")
11615 (if (and (not (org-at-timestamp-p t))
11616 (org-on-heading-p))
11617 (org-todo 'up)
11618 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11620 (defun org-timestamp-down-day (&optional arg)
11621 "Decrease the date in the time stamp by one day.
11622 With prefix ARG, change that many days."
11623 (interactive "p")
11624 (if (and (not (org-at-timestamp-p t))
11625 (org-on-heading-p))
11626 (org-todo 'down)
11627 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11629 (defun org-at-timestamp-p (&optional inactive-ok)
11630 "Determine if the cursor is in or at a timestamp."
11631 (interactive)
11632 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11633 (pos (point))
11634 (ans (or (looking-at tsr)
11635 (save-excursion
11636 (skip-chars-backward "^[<\n\r\t")
11637 (if (> (point) (point-min)) (backward-char 1))
11638 (and (looking-at tsr)
11639 (> (- (match-end 0) pos) -1))))))
11640 (and ans
11641 (boundp 'org-ts-what)
11642 (setq org-ts-what
11643 (cond
11644 ((= pos (match-beginning 0)) 'bracket)
11645 ((= pos (1- (match-end 0))) 'bracket)
11646 ((org-pos-in-match-range pos 2) 'year)
11647 ((org-pos-in-match-range pos 3) 'month)
11648 ((org-pos-in-match-range pos 7) 'hour)
11649 ((org-pos-in-match-range pos 8) 'minute)
11650 ((or (org-pos-in-match-range pos 4)
11651 (org-pos-in-match-range pos 5)) 'day)
11652 ((and (> pos (or (match-end 8) (match-end 5)))
11653 (< pos (match-end 0)))
11654 (- pos (or (match-end 8) (match-end 5))))
11655 (t 'day))))
11656 ans))
11658 (defun org-toggle-timestamp-type ()
11659 "Toggle the type (<active> or [inactive]) of a time stamp."
11660 (interactive)
11661 (when (org-at-timestamp-p t)
11662 (let ((beg (match-beginning 0)) (end (match-end 0))
11663 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11664 (save-excursion
11665 (goto-char beg)
11666 (while (re-search-forward "[][<>]" end t)
11667 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11668 t t)))
11669 (message "Timestamp is now %sactive"
11670 (if (equal (char-after beg) ?<) "" "in")))))
11672 (defun org-timestamp-change (n &optional what)
11673 "Change the date in the time stamp at point.
11674 The date will be changed by N times WHAT. WHAT can be `day', `month',
11675 `year', `minute', `second'. If WHAT is not given, the cursor position
11676 in the timestamp determines what will be changed."
11677 (let ((pos (point))
11678 with-hm inactive
11679 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11680 org-ts-what
11681 extra rem
11682 ts time time0)
11683 (if (not (org-at-timestamp-p t))
11684 (error "Not at a timestamp"))
11685 (if (and (not what) (eq org-ts-what 'bracket))
11686 (org-toggle-timestamp-type)
11687 (if (and (not what) (not (eq org-ts-what 'day))
11688 org-display-custom-times
11689 (get-text-property (point) 'display)
11690 (not (get-text-property (1- (point)) 'display)))
11691 (setq org-ts-what 'day))
11692 (setq org-ts-what (or what org-ts-what)
11693 inactive (= (char-after (match-beginning 0)) ?\[)
11694 ts (match-string 0))
11695 (replace-match "")
11696 (if (string-match
11697 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11699 (setq extra (match-string 1 ts)))
11700 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11701 (setq with-hm t))
11702 (setq time0 (org-parse-time-string ts))
11703 (when (and (eq org-ts-what 'minute)
11704 (eq current-prefix-arg nil))
11705 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11706 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11707 (setcar (cdr time0) (+ (nth 1 time0)
11708 (if (> n 0) (- rem) (- dm rem))))))
11709 (setq time
11710 (encode-time (or (car time0) 0)
11711 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11712 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11713 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11714 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11715 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11716 (nthcdr 6 time0)))
11717 (when (integerp org-ts-what)
11718 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11719 (if (eq what 'calendar)
11720 (let ((cal-date (org-get-date-from-calendar)))
11721 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11722 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11723 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11724 (setcar time0 (or (car time0) 0))
11725 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11726 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11727 (setq time (apply 'encode-time time0))))
11728 (setq org-last-changed-timestamp
11729 (org-insert-time-stamp time with-hm inactive nil nil extra))
11730 (org-clock-update-time-maybe)
11731 (goto-char pos)
11732 ;; Try to recenter the calendar window, if any
11733 (if (and org-calendar-follow-timestamp-change
11734 (get-buffer-window "*Calendar*" t)
11735 (memq org-ts-what '(day month year)))
11736 (org-recenter-calendar (time-to-days time))))))
11738 (defun org-modify-ts-extra (s pos n dm)
11739 "Change the different parts of the lead-time and repeat fields in timestamp."
11740 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11741 ng h m new rem)
11742 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11743 (cond
11744 ((or (org-pos-in-match-range pos 2)
11745 (org-pos-in-match-range pos 3))
11746 (setq m (string-to-number (match-string 3 s))
11747 h (string-to-number (match-string 2 s)))
11748 (if (org-pos-in-match-range pos 2)
11749 (setq h (+ h n))
11750 (setq n (* dm (org-no-warnings (signum n))))
11751 (when (not (= 0 (setq rem (% m dm))))
11752 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11753 (setq m (+ m n)))
11754 (if (< m 0) (setq m (+ m 60) h (1- h)))
11755 (if (> m 59) (setq m (- m 60) h (1+ h)))
11756 (setq h (min 24 (max 0 h)))
11757 (setq ng 1 new (format "-%02d:%02d" h m)))
11758 ((org-pos-in-match-range pos 6)
11759 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11760 ((org-pos-in-match-range pos 5)
11761 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11763 ((org-pos-in-match-range pos 9)
11764 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11765 ((org-pos-in-match-range pos 8)
11766 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11768 (when ng
11769 (setq s (concat
11770 (substring s 0 (match-beginning ng))
11772 (substring s (match-end ng))))))
11775 (defun org-recenter-calendar (date)
11776 "If the calendar is visible, recenter it to DATE."
11777 (let* ((win (selected-window))
11778 (cwin (get-buffer-window "*Calendar*" t))
11779 (calendar-move-hook nil))
11780 (when cwin
11781 (select-window cwin)
11782 (calendar-goto-date (if (listp date) date
11783 (calendar-gregorian-from-absolute date)))
11784 (select-window win))))
11786 (defun org-goto-calendar (&optional arg)
11787 "Go to the Emacs calendar at the current date.
11788 If there is a time stamp in the current line, go to that date.
11789 A prefix ARG can be used to force the current date."
11790 (interactive "P")
11791 (let ((tsr org-ts-regexp) diff
11792 (calendar-move-hook nil)
11793 (calendar-view-holidays-initially-flag nil)
11794 (view-calendar-holidays-initially nil)
11795 (calendar-view-diary-initially-flag nil)
11796 (view-diary-entries-initially nil))
11797 (if (or (org-at-timestamp-p)
11798 (save-excursion
11799 (beginning-of-line 1)
11800 (looking-at (concat ".*" tsr))))
11801 (let ((d1 (time-to-days (current-time)))
11802 (d2 (time-to-days
11803 (org-time-string-to-time (match-string 1)))))
11804 (setq diff (- d2 d1))))
11805 (calendar)
11806 (calendar-goto-today)
11807 (if (and diff (not arg)) (calendar-forward-day diff))))
11809 (defun org-get-date-from-calendar ()
11810 "Return a list (month day year) of date at point in calendar."
11811 (with-current-buffer "*Calendar*"
11812 (save-match-data
11813 (calendar-cursor-to-date))))
11815 (defun org-date-from-calendar ()
11816 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11817 If there is already a time stamp at the cursor position, update it."
11818 (interactive)
11819 (if (org-at-timestamp-p t)
11820 (org-timestamp-change 0 'calendar)
11821 (let ((cal-date (org-get-date-from-calendar)))
11822 (org-insert-time-stamp
11823 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11825 (defun org-minutes-to-hh:mm-string (m)
11826 "Compute H:MM from a number of minutes."
11827 (let ((h (/ m 60)))
11828 (setq m (- m (* 60 h)))
11829 (format org-time-clocksum-format h m)))
11831 (defun org-hh:mm-string-to-minutes (s)
11832 "Convert a string H:MM to a number of minutes."
11833 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11834 (+ (* (string-to-number (match-string 1 s)) 60)
11835 (string-to-number (match-string 2 s)))
11838 ;;;; Agenda files
11840 ;;;###autoload
11841 (defun org-iswitchb (&optional arg)
11842 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11843 With a prefix argument, restrict available to files.
11844 With two prefix arguments, restrict available buffers to agenda files.
11846 Due to some yet unresolved reason, the global function
11847 `iswitchb-mode' needs to be active for this function to work."
11848 (interactive "P")
11849 (require 'iswitchb)
11850 (let ((enabled iswitchb-mode) blist)
11851 (or enabled (iswitchb-mode 1))
11852 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11853 ((equal arg '(16)) (org-buffer-list 'agenda))
11854 (t (org-buffer-list))))
11855 (unwind-protect
11856 (let ((iswitchb-make-buflist-hook
11857 (lambda ()
11858 (setq iswitchb-temp-buflist
11859 (mapcar 'buffer-name blist)))))
11860 (switch-to-buffer
11861 (iswitchb-read-buffer
11862 "Switch-to: " nil t))
11863 (or enabled (iswitchb-mode -1))))))
11865 (defun org-buffer-list (&optional predicate exclude-tmp)
11866 "Return a list of Org buffers.
11867 PREDICATE can be `export', `files' or `agenda'.
11869 export restrict the list to Export buffers.
11870 files restrict the list to buffers visiting Org files.
11871 agenda restrict the list to buffers visiting agenda files.
11873 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11874 (let* ((bfn nil)
11875 (agenda-files (and (eq predicate 'agenda)
11876 (mapcar 'file-truename (org-agenda-files t))))
11877 (filter
11878 (cond
11879 ((eq predicate 'files)
11880 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11881 ((eq predicate 'export)
11882 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11883 ((eq predicate 'agenda)
11884 (lambda (b)
11885 (with-current-buffer b
11886 (and (eq major-mode 'org-mode)
11887 (setq bfn (buffer-file-name b))
11888 (member (file-truename bfn) agenda-files)))))
11889 (t (lambda (b) (with-current-buffer b
11890 (or (eq major-mode 'org-mode)
11891 (string-match "\*Org .*Export"
11892 (buffer-name b)))))))))
11893 (delq nil
11894 (mapcar
11895 (lambda(b)
11896 (if (and (funcall filter b)
11897 (or (not exclude-tmp)
11898 (not (string-match "tmp" (buffer-name b)))))
11900 nil))
11901 (buffer-list)))))
11903 (defun org-agenda-files (&optional unrestricted archives)
11904 "Get the list of agenda files.
11905 Optional UNRESTRICTED means return the full list even if a restriction
11906 is currently in place.
11907 When ARCHIVES is t, include all archive files hat are really being
11908 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11909 `org-agenda-archives-mode' is t."
11910 (let ((files
11911 (cond
11912 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11913 ((stringp org-agenda-files) (org-read-agenda-file-list))
11914 ((listp org-agenda-files) org-agenda-files)
11915 (t (error "Invalid value of `org-agenda-files'")))))
11916 (setq files (apply 'append
11917 (mapcar (lambda (f)
11918 (if (file-directory-p f)
11919 (directory-files
11920 f t org-agenda-file-regexp)
11921 (list f)))
11922 files)))
11923 (when org-agenda-skip-unavailable-files
11924 (setq files (delq nil
11925 (mapcar (function
11926 (lambda (file)
11927 (and (file-readable-p file) file)))
11928 files))))
11929 (when (or (eq archives t)
11930 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11931 (setq files (org-add-archive-files files)))
11932 files))
11934 (defun org-edit-agenda-file-list ()
11935 "Edit the list of agenda files.
11936 Depending on setup, this either uses customize to edit the variable
11937 `org-agenda-files', or it visits the file that is holding the list. In the
11938 latter case, the buffer is set up in a way that saving it automatically kills
11939 the buffer and restores the previous window configuration."
11940 (interactive)
11941 (if (stringp org-agenda-files)
11942 (let ((cw (current-window-configuration)))
11943 (find-file org-agenda-files)
11944 (org-set-local 'org-window-configuration cw)
11945 (org-add-hook 'after-save-hook
11946 (lambda ()
11947 (set-window-configuration
11948 (prog1 org-window-configuration
11949 (kill-buffer (current-buffer))))
11950 (org-install-agenda-files-menu)
11951 (message "New agenda file list installed"))
11952 nil 'local)
11953 (message "%s" (substitute-command-keys
11954 "Edit list and finish with \\[save-buffer]")))
11955 (customize-variable 'org-agenda-files)))
11957 (defun org-store-new-agenda-file-list (list)
11958 "Set new value for the agenda file list and save it correcly."
11959 (if (stringp org-agenda-files)
11960 (let ((f org-agenda-files) b)
11961 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11962 (with-temp-file f
11963 (insert (mapconcat 'identity list "\n") "\n")))
11964 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11965 (setq org-agenda-files list)
11966 (customize-save-variable 'org-agenda-files org-agenda-files))))
11968 (defun org-read-agenda-file-list ()
11969 "Read the list of agenda files from a file."
11970 (when (file-directory-p org-agenda-files)
11971 (error "`org-agenda-files' cannot be a single directory"))
11972 (when (stringp org-agenda-files)
11973 (with-temp-buffer
11974 (insert-file-contents org-agenda-files)
11975 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11978 ;;;###autoload
11979 (defun org-cycle-agenda-files ()
11980 "Cycle through the files in `org-agenda-files'.
11981 If the current buffer visits an agenda file, find the next one in the list.
11982 If the current buffer does not, find the first agenda file."
11983 (interactive)
11984 (let* ((fs (org-agenda-files t))
11985 (files (append fs (list (car fs))))
11986 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11987 file)
11988 (unless files (error "No agenda files"))
11989 (catch 'exit
11990 (while (setq file (pop files))
11991 (if (equal (file-truename file) tcf)
11992 (when (car files)
11993 (find-file (car files))
11994 (throw 'exit t))))
11995 (find-file (car fs)))
11996 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11998 (defun org-agenda-file-to-front (&optional to-end)
11999 "Move/add the current file to the top of the agenda file list.
12000 If the file is not present in the list, it is added to the front. If it is
12001 present, it is moved there. With optional argument TO-END, add/move to the
12002 end of the list."
12003 (interactive "P")
12004 (let ((org-agenda-skip-unavailable-files nil)
12005 (file-alist (mapcar (lambda (x)
12006 (cons (file-truename x) x))
12007 (org-agenda-files t)))
12008 (ctf (file-truename buffer-file-name))
12009 x had)
12010 (setq x (assoc ctf file-alist) had x)
12012 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12013 (if to-end
12014 (setq file-alist (append (delq x file-alist) (list x)))
12015 (setq file-alist (cons x (delq x file-alist))))
12016 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12017 (org-install-agenda-files-menu)
12018 (message "File %s to %s of agenda file list"
12019 (if had "moved" "added") (if to-end "end" "front"))))
12021 (defun org-remove-file (&optional file)
12022 "Remove current file from the list of files in variable `org-agenda-files'.
12023 These are the files which are being checked for agenda entries.
12024 Optional argument FILE means, use this file instead of the current."
12025 (interactive)
12026 (let* ((org-agenda-skip-unavailable-files nil)
12027 (file (or file buffer-file-name))
12028 (true-file (file-truename file))
12029 (afile (abbreviate-file-name file))
12030 (files (delq nil (mapcar
12031 (lambda (x)
12032 (if (equal true-file
12033 (file-truename x))
12034 nil x))
12035 (org-agenda-files t)))))
12036 (if (not (= (length files) (length (org-agenda-files t))))
12037 (progn
12038 (org-store-new-agenda-file-list files)
12039 (org-install-agenda-files-menu)
12040 (message "Removed file: %s" afile))
12041 (message "File was not in list: %s (not removed)" afile))))
12043 (defun org-file-menu-entry (file)
12044 (vector file (list 'find-file file) t))
12046 (defun org-check-agenda-file (file)
12047 "Make sure FILE exists. If not, ask user what to do."
12048 (when (not (file-exists-p file))
12049 (message "non-existent file %s. [R]emove from list or [A]bort?"
12050 (abbreviate-file-name file))
12051 (let ((r (downcase (read-char-exclusive))))
12052 (cond
12053 ((equal r ?r)
12054 (org-remove-file file)
12055 (throw 'nextfile t))
12056 (t (error "Abort"))))))
12058 (defun org-get-agenda-file-buffer (file)
12059 "Get a buffer visiting FILE. If the buffer needs to be created, add
12060 it to the list of buffers which might be released later."
12061 (let ((buf (org-find-base-buffer-visiting file)))
12062 (if buf
12063 buf ; just return it
12064 ;; Make a new buffer and remember it
12065 (setq buf (find-file-noselect file))
12066 (if buf (push buf org-agenda-new-buffers))
12067 buf)))
12069 (defun org-release-buffers (blist)
12070 "Release all buffers in list, asking the user for confirmation when needed.
12071 When a buffer is unmodified, it is just killed. When modified, it is saved
12072 \(if the user agrees) and then killed."
12073 (let (buf file)
12074 (while (setq buf (pop blist))
12075 (setq file (buffer-file-name buf))
12076 (when (and (buffer-modified-p buf)
12077 file
12078 (y-or-n-p (format "Save file %s? " file)))
12079 (with-current-buffer buf (save-buffer)))
12080 (kill-buffer buf))))
12082 (defun org-prepare-agenda-buffers (files)
12083 "Create buffers for all agenda files, protect archived trees and comments."
12084 (interactive)
12085 (let ((pa '(:org-archived t))
12086 (pc '(:org-comment t))
12087 (pall '(:org-archived t :org-comment t))
12088 (inhibit-read-only t)
12089 (rea (concat ":" org-archive-tag ":"))
12090 bmp file re)
12091 (save-excursion
12092 (save-restriction
12093 (while (setq file (pop files))
12094 (if (bufferp file)
12095 (set-buffer file)
12096 (org-check-agenda-file file)
12097 (set-buffer (org-get-agenda-file-buffer file)))
12098 (widen)
12099 (setq bmp (buffer-modified-p))
12100 (org-refresh-category-properties)
12101 (setq org-todo-keywords-for-agenda
12102 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12103 (setq org-done-keywords-for-agenda
12104 (append org-done-keywords-for-agenda org-done-keywords))
12105 (setq org-todo-keyword-alist-for-agenda
12106 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12107 (setq org-tag-alist-for-agenda
12108 (append org-tag-alist-for-agenda org-tag-alist))
12110 (save-excursion
12111 (remove-text-properties (point-min) (point-max) pall)
12112 (when org-agenda-skip-archived-trees
12113 (goto-char (point-min))
12114 (while (re-search-forward rea nil t)
12115 (if (org-on-heading-p t)
12116 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12117 (goto-char (point-min))
12118 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12119 (while (re-search-forward re nil t)
12120 (add-text-properties
12121 (match-beginning 0) (org-end-of-subtree t) pc)))
12122 (set-buffer-modified-p bmp))))
12123 (setq org-todo-keyword-alist-for-agenda
12124 (org-uniquify org-todo-keyword-alist-for-agenda)
12125 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12127 ;;;; Embedded LaTeX
12129 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12130 "Keymap for the minor `org-cdlatex-mode'.")
12132 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12133 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12134 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12135 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12136 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12138 (defvar org-cdlatex-texmathp-advice-is-done nil
12139 "Flag remembering if we have applied the advice to texmathp already.")
12141 (define-minor-mode org-cdlatex-mode
12142 "Toggle the minor `org-cdlatex-mode'.
12143 This mode supports entering LaTeX environment and math in LaTeX fragments
12144 in Org-mode.
12145 \\{org-cdlatex-mode-map}"
12146 nil " OCDL" nil
12147 (when org-cdlatex-mode (require 'cdlatex))
12148 (unless org-cdlatex-texmathp-advice-is-done
12149 (setq org-cdlatex-texmathp-advice-is-done t)
12150 (defadvice texmathp (around org-math-always-on activate)
12151 "Always return t in org-mode buffers.
12152 This is because we want to insert math symbols without dollars even outside
12153 the LaTeX math segments. If Orgmode thinks that point is actually inside
12154 en embedded LaTeX fragement, let texmathp do its job.
12155 \\[org-cdlatex-mode-map]"
12156 (interactive)
12157 (let (p)
12158 (cond
12159 ((not (org-mode-p)) ad-do-it)
12160 ((eq this-command 'cdlatex-math-symbol)
12161 (setq ad-return-value t
12162 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12164 (let ((p (org-inside-LaTeX-fragment-p)))
12165 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12166 (setq ad-return-value t
12167 texmathp-why '("Org-mode embedded math" . 0))
12168 (if p ad-do-it)))))))))
12170 (defun turn-on-org-cdlatex ()
12171 "Unconditionally turn on `org-cdlatex-mode'."
12172 (org-cdlatex-mode 1))
12174 (defun org-inside-LaTeX-fragment-p ()
12175 "Test if point is inside a LaTeX fragment.
12176 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12177 sequence appearing also before point.
12178 Even though the matchers for math are configurable, this function assumes
12179 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12180 delimiters are skipped when they have been removed by customization.
12181 The return value is nil, or a cons cell with the delimiter and
12182 and the position of this delimiter.
12184 This function does a reasonably good job, but can locally be fooled by
12185 for example currency specifications. For example it will assume being in
12186 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12187 fragments that are properly closed, but during editing, we have to live
12188 with the uncertainty caused by missing closing delimiters. This function
12189 looks only before point, not after."
12190 (catch 'exit
12191 (let ((pos (point))
12192 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12193 (lim (progn
12194 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12195 (point)))
12196 dd-on str (start 0) m re)
12197 (goto-char pos)
12198 (when dodollar
12199 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12200 re (nth 1 (assoc "$" org-latex-regexps)))
12201 (while (string-match re str start)
12202 (cond
12203 ((= (match-end 0) (length str))
12204 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12205 ((= (match-end 0) (- (length str) 5))
12206 (throw 'exit nil))
12207 (t (setq start (match-end 0))))))
12208 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12209 (goto-char pos)
12210 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12211 (and (match-beginning 2) (throw 'exit nil))
12212 ;; count $$
12213 (while (re-search-backward "\\$\\$" lim t)
12214 (setq dd-on (not dd-on)))
12215 (goto-char pos)
12216 (if dd-on (cons "$$" m))))))
12219 (defun org-try-cdlatex-tab ()
12220 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12221 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12222 - inside a LaTeX fragment, or
12223 - after the first word in a line, where an abbreviation expansion could
12224 insert a LaTeX environment."
12225 (when org-cdlatex-mode
12226 (cond
12227 ((save-excursion
12228 (skip-chars-backward "a-zA-Z0-9*")
12229 (skip-chars-backward " \t")
12230 (bolp))
12231 (cdlatex-tab) t)
12232 ((org-inside-LaTeX-fragment-p)
12233 (cdlatex-tab) t)
12234 (t nil))))
12236 (defun org-cdlatex-underscore-caret (&optional arg)
12237 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12238 Revert to the normal definition outside of these fragments."
12239 (interactive "P")
12240 (if (org-inside-LaTeX-fragment-p)
12241 (call-interactively 'cdlatex-sub-superscript)
12242 (let (org-cdlatex-mode)
12243 (call-interactively (key-binding (vector last-input-event))))))
12245 (defun org-cdlatex-math-modify (&optional arg)
12246 "Execute `cdlatex-math-modify' in LaTeX fragments.
12247 Revert to the normal definition outside of these fragments."
12248 (interactive "P")
12249 (if (org-inside-LaTeX-fragment-p)
12250 (call-interactively 'cdlatex-math-modify)
12251 (let (org-cdlatex-mode)
12252 (call-interactively (key-binding (vector last-input-event))))))
12254 (defvar org-latex-fragment-image-overlays nil
12255 "List of overlays carrying the images of latex fragments.")
12256 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12258 (defun org-remove-latex-fragment-image-overlays ()
12259 "Remove all overlays with LaTeX fragment images in current buffer."
12260 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12261 (setq org-latex-fragment-image-overlays nil))
12263 (defun org-preview-latex-fragment (&optional subtree)
12264 "Preview the LaTeX fragment at point, or all locally or globally.
12265 If the cursor is in a LaTeX fragment, create the image and overlay
12266 it over the source code. If there is no fragment at point, display
12267 all fragments in the current text, from one headline to the next. With
12268 prefix SUBTREE, display all fragments in the current subtree. With a
12269 double prefix `C-u C-u', or when the cursor is before the first headline,
12270 display all fragments in the buffer.
12271 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12272 (interactive "P")
12273 (org-remove-latex-fragment-image-overlays)
12274 (save-excursion
12275 (save-restriction
12276 (let (beg end at msg)
12277 (cond
12278 ((or (equal subtree '(16))
12279 (not (save-excursion
12280 (re-search-backward (concat "^" outline-regexp) nil t))))
12281 (setq beg (point-min) end (point-max)
12282 msg "Creating images for buffer...%s"))
12283 ((equal subtree '(4))
12284 (org-back-to-heading)
12285 (setq beg (point) end (org-end-of-subtree t)
12286 msg "Creating images for subtree...%s"))
12288 (if (setq at (org-inside-LaTeX-fragment-p))
12289 (goto-char (max (point-min) (- (cdr at) 2)))
12290 (org-back-to-heading))
12291 (setq beg (point) end (progn (outline-next-heading) (point))
12292 msg (if at "Creating image...%s"
12293 "Creating images for entry...%s"))))
12294 (message msg "")
12295 (narrow-to-region beg end)
12296 (goto-char beg)
12297 (org-format-latex
12298 (concat "ltxpng/" (file-name-sans-extension
12299 (file-name-nondirectory
12300 buffer-file-name)))
12301 default-directory 'overlays msg at 'forbuffer)
12302 (message msg "done. Use `C-c C-c' to remove images.")))))
12304 (defvar org-latex-regexps
12305 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12306 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12307 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12308 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12309 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12310 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12311 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12312 "Regular expressions for matching embedded LaTeX.")
12314 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12315 "Replace LaTeX fragments with links to an image, and produce images."
12316 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12317 (let* ((prefixnodir (file-name-nondirectory prefix))
12318 (absprefix (expand-file-name prefix dir))
12319 (todir (file-name-directory absprefix))
12320 (opt org-format-latex-options)
12321 (matchers (plist-get opt :matchers))
12322 (re-list org-latex-regexps)
12323 (cnt 0) txt link beg end re e checkdir
12324 m n block linkfile movefile ov)
12325 ;; Check if there are old images files with this prefix, and remove them
12326 (when (file-directory-p todir)
12327 (mapc 'delete-file
12328 (directory-files
12329 todir 'full
12330 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12331 ;; Check the different regular expressions
12332 (while (setq e (pop re-list))
12333 (setq m (car e) re (nth 1 e) n (nth 2 e)
12334 block (if (nth 3 e) "\n\n" ""))
12335 (when (member m matchers)
12336 (goto-char (point-min))
12337 (while (re-search-forward re nil t)
12338 (when (or (not at) (equal (cdr at) (match-beginning n)))
12339 (setq txt (match-string n)
12340 beg (match-beginning n) end (match-end n)
12341 cnt (1+ cnt)
12342 linkfile (format "%s_%04d.png" prefix cnt)
12343 movefile (format "%s_%04d.png" absprefix cnt)
12344 link (concat block "[[file:" linkfile "]]" block))
12345 (if msg (message msg cnt))
12346 (goto-char beg)
12347 (unless checkdir ; make sure the directory exists
12348 (setq checkdir t)
12349 (or (file-directory-p todir) (make-directory todir)))
12350 (org-create-formula-image
12351 txt movefile opt forbuffer)
12352 (if overlays
12353 (progn
12354 (setq ov (org-make-overlay beg end))
12355 (if (featurep 'xemacs)
12356 (progn
12357 (org-overlay-put ov 'invisible t)
12358 (org-overlay-put
12359 ov 'end-glyph
12360 (make-glyph (vector 'png :file movefile))))
12361 (org-overlay-put
12362 ov 'display
12363 (list 'image :type 'png :file movefile :ascent 'center)))
12364 (push ov org-latex-fragment-image-overlays)
12365 (goto-char end))
12366 (delete-region beg end)
12367 (insert link))))))))
12369 ;; This function borrows from Ganesh Swami's latex2png.el
12370 (defun org-create-formula-image (string tofile options buffer)
12371 (let* ((tmpdir (if (featurep 'xemacs)
12372 (temp-directory)
12373 temporary-file-directory))
12374 (texfilebase (make-temp-name
12375 (expand-file-name "orgtex" tmpdir)))
12376 (texfile (concat texfilebase ".tex"))
12377 (dvifile (concat texfilebase ".dvi"))
12378 (pngfile (concat texfilebase ".png"))
12379 (fnh (if (featurep 'xemacs)
12380 (font-height (get-face-font 'default))
12381 (face-attribute 'default :height nil)))
12382 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12383 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12384 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12385 "Black"))
12386 (bg (or (plist-get options (if buffer :background :html-background))
12387 "Transparent")))
12388 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12389 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12390 (with-temp-file texfile
12391 (insert org-format-latex-header
12392 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12393 (let ((dir default-directory))
12394 (condition-case nil
12395 (progn
12396 (cd tmpdir)
12397 (call-process "latex" nil nil nil texfile))
12398 (error nil))
12399 (cd dir))
12400 (if (not (file-exists-p dvifile))
12401 (progn (message "Failed to create dvi file from %s" texfile) nil)
12402 (condition-case nil
12403 (call-process "dvipng" nil nil nil
12404 "-E" "-fg" fg "-bg" bg
12405 "-D" dpi
12406 ;;"-x" scale "-y" scale
12407 "-T" "tight"
12408 "-o" pngfile
12409 dvifile)
12410 (error nil))
12411 (if (not (file-exists-p pngfile))
12412 (progn (message "Failed to create png file from %s" texfile) nil)
12413 ;; Use the requested file name and clean up
12414 (copy-file pngfile tofile 'replace)
12415 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12416 (delete-file (concat texfilebase e)))
12417 pngfile))))
12419 (defun org-dvipng-color (attr)
12420 "Return an rgb color specification for dvipng."
12421 (apply 'format "rgb %s %s %s"
12422 (mapcar 'org-normalize-color
12423 (color-values (face-attribute 'default attr nil)))))
12425 (defun org-normalize-color (value)
12426 "Return string to be used as color value for an RGB component."
12427 (format "%g" (/ value 65535.0)))
12430 ;;;; Key bindings
12432 ;; Make `C-c C-x' a prefix key
12433 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12435 ;; TAB key with modifiers
12436 (org-defkey org-mode-map "\C-i" 'org-cycle)
12437 (org-defkey org-mode-map [(tab)] 'org-cycle)
12438 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12439 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12440 (org-defkey org-mode-map "\M-\t" 'org-complete)
12441 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12442 ;; The following line is necessary under Suse GNU/Linux
12443 (unless (featurep 'xemacs)
12444 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12445 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12446 (define-key org-mode-map [backtab] 'org-shifttab)
12448 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12449 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12450 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12452 ;; Cursor keys with modifiers
12453 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12454 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12455 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12456 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12458 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12459 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12460 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12461 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12463 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12464 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12465 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12466 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12468 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12469 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12471 ;;; Extra keys for tty access.
12472 ;; We only set them when really needed because otherwise the
12473 ;; menus don't show the simple keys
12475 (when (or org-use-extra-keys
12476 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12477 (not window-system))
12478 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12479 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12480 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12481 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12482 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12483 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12484 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12485 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12486 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12487 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12488 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12489 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12490 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12491 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12492 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12493 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12494 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12495 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12496 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12497 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12498 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12499 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12501 ;; All the other keys
12503 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12504 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12505 (if (boundp 'narrow-map)
12506 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12507 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12508 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12509 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12510 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12511 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12512 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12513 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12514 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12515 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12516 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12517 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12518 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12519 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12520 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12521 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12522 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12523 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12524 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12525 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12526 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12527 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12528 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12529 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12530 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12531 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12532 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12533 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12534 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12535 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12536 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12537 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12538 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12539 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12540 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12541 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12542 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12543 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12544 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12545 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12546 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12547 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12548 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12549 (org-defkey org-mode-map "\C-c^" 'org-sort)
12550 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12551 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12552 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12553 (org-defkey org-mode-map "\C-m" 'org-return)
12554 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12555 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12556 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12557 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12558 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12559 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12560 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12561 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12562 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12563 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12564 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12565 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12566 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12567 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12568 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12569 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12571 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12572 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12573 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12574 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12576 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12577 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12578 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12579 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12580 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12581 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12582 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12583 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12584 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12585 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12586 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12587 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12589 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12590 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12591 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12593 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12595 (when (featurep 'xemacs)
12596 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12598 (defvar org-table-auto-blank-field) ; defined in org-table.el
12599 (defun org-self-insert-command (N)
12600 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12601 If the cursor is in a table looking at whitespace, the whitespace is
12602 overwritten, and the table is not marked as requiring realignment."
12603 (interactive "p")
12604 (if (and (org-table-p)
12605 (progn
12606 ;; check if we blank the field, and if that triggers align
12607 (and (featurep 'org-table) org-table-auto-blank-field
12608 (member last-command
12609 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12610 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12611 ;; got extra space, this field does not determine column width
12612 (let (org-table-may-need-update) (org-table-blank-field))
12613 ;; no extra space, this field may determine column width
12614 (org-table-blank-field)))
12616 (eq N 1)
12617 (looking-at "[^|\n]* |"))
12618 (let (org-table-may-need-update)
12619 (goto-char (1- (match-end 0)))
12620 (delete-backward-char 1)
12621 (goto-char (match-beginning 0))
12622 (self-insert-command N))
12623 (setq org-table-may-need-update t)
12624 (self-insert-command N)
12625 (org-fix-tags-on-the-fly)))
12627 (defun org-fix-tags-on-the-fly ()
12628 (when (and (equal (char-after (point-at-bol)) ?*)
12629 (org-on-heading-p))
12630 (org-align-tags-here org-tags-column)))
12632 (defun org-delete-backward-char (N)
12633 "Like `delete-backward-char', insert whitespace at field end in tables.
12634 When deleting backwards, in tables this function will insert whitespace in
12635 front of the next \"|\" separator, to keep the table aligned. The table will
12636 still be marked for re-alignment if the field did fill the entire column,
12637 because, in this case the deletion might narrow the column."
12638 (interactive "p")
12639 (if (and (org-table-p)
12640 (eq N 1)
12641 (string-match "|" (buffer-substring (point-at-bol) (point)))
12642 (looking-at ".*?|"))
12643 (let ((pos (point))
12644 (noalign (looking-at "[^|\n\r]* |"))
12645 (c org-table-may-need-update))
12646 (backward-delete-char N)
12647 (skip-chars-forward "^|")
12648 (insert " ")
12649 (goto-char (1- pos))
12650 ;; noalign: if there were two spaces at the end, this field
12651 ;; does not determine the width of the column.
12652 (if noalign (setq org-table-may-need-update c)))
12653 (backward-delete-char N)
12654 (org-fix-tags-on-the-fly)))
12656 (defun org-delete-char (N)
12657 "Like `delete-char', but insert whitespace at field end in tables.
12658 When deleting characters, in tables this function will insert whitespace in
12659 front of the next \"|\" separator, to keep the table aligned. The table will
12660 still be marked for re-alignment if the field did fill the entire column,
12661 because, in this case the deletion might narrow the column."
12662 (interactive "p")
12663 (if (and (org-table-p)
12664 (not (bolp))
12665 (not (= (char-after) ?|))
12666 (eq N 1))
12667 (if (looking-at ".*?|")
12668 (let ((pos (point))
12669 (noalign (looking-at "[^|\n\r]* |"))
12670 (c org-table-may-need-update))
12671 (replace-match (concat
12672 (substring (match-string 0) 1 -1)
12673 " |"))
12674 (goto-char pos)
12675 ;; noalign: if there were two spaces at the end, this field
12676 ;; does not determine the width of the column.
12677 (if noalign (setq org-table-may-need-update c)))
12678 (delete-char N))
12679 (delete-char N)
12680 (org-fix-tags-on-the-fly)))
12682 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12683 (put 'org-self-insert-command 'delete-selection t)
12684 (put 'orgtbl-self-insert-command 'delete-selection t)
12685 (put 'org-delete-char 'delete-selection 'supersede)
12686 (put 'org-delete-backward-char 'delete-selection 'supersede)
12688 ;; Make `flyspell-mode' delay after some commands
12689 (put 'org-self-insert-command 'flyspell-delayed t)
12690 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12691 (put 'org-delete-char 'flyspell-delayed t)
12692 (put 'org-delete-backward-char 'flyspell-delayed t)
12694 ;; Make pabbrev-mode expand after org-mode commands
12695 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12696 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12698 ;; How to do this: Measure non-white length of current string
12699 ;; If equal to column width, we should realign.
12701 (defun org-remap (map &rest commands)
12702 "In MAP, remap the functions given in COMMANDS.
12703 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12704 (let (new old)
12705 (while commands
12706 (setq old (pop commands) new (pop commands))
12707 (if (fboundp 'command-remapping)
12708 (org-defkey map (vector 'remap old) new)
12709 (substitute-key-definition old new map global-map)))))
12711 (when (eq org-enable-table-editor 'optimized)
12712 ;; If the user wants maximum table support, we need to hijack
12713 ;; some standard editing functions
12714 (org-remap org-mode-map
12715 'self-insert-command 'org-self-insert-command
12716 'delete-char 'org-delete-char
12717 'delete-backward-char 'org-delete-backward-char)
12718 (org-defkey org-mode-map "|" 'org-force-self-insert))
12720 (defun org-shiftcursor-error ()
12721 "Throw an error because Shift-Cursor command was applied in wrong context."
12722 (error "This command is active in special context like tables, headlines or timestamps"))
12724 (defun org-shifttab (&optional arg)
12725 "Global visibility cycling or move to previous table field.
12726 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12727 on context.
12728 See the individual commands for more information."
12729 (interactive "P")
12730 (cond
12731 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12732 ((integerp arg)
12733 (message "Content view to level: %d" arg)
12734 (org-content (prefix-numeric-value arg))
12735 (setq org-cycle-global-status 'overview))
12736 (t (call-interactively 'org-global-cycle))))
12738 (defun org-shiftmetaleft ()
12739 "Promote subtree or delete table column.
12740 Calls `org-promote-subtree', `org-outdent-item',
12741 or `org-table-delete-column', depending on context.
12742 See the individual commands for more information."
12743 (interactive)
12744 (cond
12745 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12746 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12747 ((org-at-item-p) (call-interactively 'org-outdent-item))
12748 (t (org-shiftcursor-error))))
12750 (defun org-shiftmetaright ()
12751 "Demote subtree or insert table column.
12752 Calls `org-demote-subtree', `org-indent-item',
12753 or `org-table-insert-column', depending on context.
12754 See the individual commands for more information."
12755 (interactive)
12756 (cond
12757 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12758 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12759 ((org-at-item-p) (call-interactively 'org-indent-item))
12760 (t (org-shiftcursor-error))))
12762 (defun org-shiftmetaup (&optional arg)
12763 "Move subtree up or kill table row.
12764 Calls `org-move-subtree-up' or `org-table-kill-row' or
12765 `org-move-item-up' depending on context. See the individual commands
12766 for more information."
12767 (interactive "P")
12768 (cond
12769 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12770 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12771 ((org-at-item-p) (call-interactively 'org-move-item-up))
12772 (t (org-shiftcursor-error))))
12773 (defun org-shiftmetadown (&optional arg)
12774 "Move subtree down or insert table row.
12775 Calls `org-move-subtree-down' or `org-table-insert-row' or
12776 `org-move-item-down', depending on context. See the individual
12777 commands for more information."
12778 (interactive "P")
12779 (cond
12780 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12781 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12782 ((org-at-item-p) (call-interactively 'org-move-item-down))
12783 (t (org-shiftcursor-error))))
12785 (defun org-metaleft (&optional arg)
12786 "Promote heading or move table column to left.
12787 Calls `org-do-promote' or `org-table-move-column', depending on context.
12788 With no specific context, calls the Emacs default `backward-word'.
12789 See the individual commands for more information."
12790 (interactive "P")
12791 (cond
12792 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12793 ((or (org-on-heading-p) (org-region-active-p))
12794 (call-interactively 'org-do-promote))
12795 ((org-at-item-p) (call-interactively 'org-outdent-item))
12796 (t (call-interactively 'backward-word))))
12798 (defun org-metaright (&optional arg)
12799 "Demote subtree or move table column to right.
12800 Calls `org-do-demote' or `org-table-move-column', depending on context.
12801 With no specific context, calls the Emacs default `forward-word'.
12802 See the individual commands for more information."
12803 (interactive "P")
12804 (cond
12805 ((org-at-table-p) (call-interactively 'org-table-move-column))
12806 ((or (org-on-heading-p) (org-region-active-p))
12807 (call-interactively 'org-do-demote))
12808 ((org-at-item-p) (call-interactively 'org-indent-item))
12809 (t (call-interactively 'forward-word))))
12811 (defun org-metaup (&optional arg)
12812 "Move subtree up or move table row up.
12813 Calls `org-move-subtree-up' or `org-table-move-row' or
12814 `org-move-item-up', depending on context. See the individual commands
12815 for more information."
12816 (interactive "P")
12817 (cond
12818 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12819 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12820 ((org-at-item-p) (call-interactively 'org-move-item-up))
12821 (t (transpose-lines 1) (beginning-of-line -1))))
12823 (defun org-metadown (&optional arg)
12824 "Move subtree down or move table row down.
12825 Calls `org-move-subtree-down' or `org-table-move-row' or
12826 `org-move-item-down', depending on context. See the individual
12827 commands for more information."
12828 (interactive "P")
12829 (cond
12830 ((org-at-table-p) (call-interactively 'org-table-move-row))
12831 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12832 ((org-at-item-p) (call-interactively 'org-move-item-down))
12833 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12835 (defun org-shiftup (&optional arg)
12836 "Increase item in timestamp or increase priority of current headline.
12837 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12838 depending on context. See the individual commands for more information."
12839 (interactive "P")
12840 (cond
12841 ((org-at-timestamp-p t)
12842 (call-interactively (if org-edit-timestamp-down-means-later
12843 'org-timestamp-down 'org-timestamp-up)))
12844 ((org-on-heading-p) (call-interactively 'org-priority-up))
12845 ((org-at-item-p) (call-interactively 'org-previous-item))
12846 ((org-clocktable-try-shift 'up arg))
12847 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12849 (defun org-shiftdown (&optional arg)
12850 "Decrease item in timestamp or decrease priority of current headline.
12851 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12852 depending on context. See the individual commands for more information."
12853 (interactive "P")
12854 (cond
12855 ((org-at-timestamp-p t)
12856 (call-interactively (if org-edit-timestamp-down-means-later
12857 'org-timestamp-up 'org-timestamp-down)))
12858 ((org-on-heading-p) (call-interactively 'org-priority-down))
12859 ((org-clocktable-try-shift 'down arg))
12860 (t (call-interactively 'org-next-item))))
12862 (defun org-shiftright (&optional arg)
12863 "Cycle the thing at point or in the current line, depending on context.
12864 Depending on context, this does one of the following:
12866 - switch a timestamp at point one day into the future
12867 - on a headline, switch to the next TODO keyword.
12868 - on an item, switch entire list to the next bullet type
12869 - on a property line, switch to the next allowed value
12870 - on a clocktable definition line, move time block into the future"
12871 (interactive "P")
12872 (cond
12873 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12874 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12875 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12876 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12877 ((org-clocktable-try-shift 'right arg))
12878 (t (org-shiftcursor-error))))
12880 (defun org-shiftleft (&optional arg)
12881 "Cycle the thing at point or in the current line, depending on context.
12882 Depending on context, this does one of the following:
12884 - switch a timestamp at point one day into the past
12885 - on a headline, switch to the previous TODO keyword.
12886 - on an item, switch entire list to the previous bullet type
12887 - on a property line, switch to the previous allowed value
12888 - on a clocktable definition line, move time block into the past"
12889 (interactive "P")
12890 (cond
12891 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12892 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12893 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12894 ((org-at-property-p)
12895 (call-interactively 'org-property-previous-allowed-value))
12896 ((org-clocktable-try-shift 'left arg))
12897 (t (org-shiftcursor-error))))
12899 (defun org-shiftcontrolright ()
12900 "Switch to next TODO set."
12901 (interactive)
12902 (cond
12903 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12904 (t (org-shiftcursor-error))))
12906 (defun org-shiftcontrolleft ()
12907 "Switch to previous TODO set."
12908 (interactive)
12909 (cond
12910 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12911 (t (org-shiftcursor-error))))
12913 (defun org-ctrl-c-ret ()
12914 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12915 (interactive)
12916 (cond
12917 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12918 (t (call-interactively 'org-insert-heading))))
12920 (defun org-copy-special ()
12921 "Copy region in table or copy current subtree.
12922 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12923 See the individual commands for more information."
12924 (interactive)
12925 (call-interactively
12926 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12928 (defun org-cut-special ()
12929 "Cut region in table or cut current subtree.
12930 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12931 See the individual commands for more information."
12932 (interactive)
12933 (call-interactively
12934 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12936 (defun org-paste-special (arg)
12937 "Paste rectangular region into table, or past subtree relative to level.
12938 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12939 See the individual commands for more information."
12940 (interactive "P")
12941 (if (org-at-table-p)
12942 (org-table-paste-rectangle)
12943 (org-paste-subtree arg)))
12945 (defun org-edit-special ()
12946 "Call a special editor for the stuff at point.
12947 When at a table, call the formula editor with `org-table-edit-formulas'.
12948 When at the first line of an src example, call `org-edit-src-code'.
12949 When in an #+include line, visit the include file. Otherwise call
12950 `ffap' to visit the file at point."
12951 (interactive)
12952 (cond
12953 ((org-at-table-p)
12954 (call-interactively 'org-table-edit-formulas))
12955 ((save-excursion
12956 (beginning-of-line 1)
12957 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12958 (find-file (org-trim (match-string 1))))
12959 ((org-edit-src-code))
12960 ((org-edit-fixed-width-region))
12961 (t (call-interactively 'ffap))))
12963 (defun org-ctrl-c-ctrl-c (&optional arg)
12964 "Set tags in headline, or update according to changed information at point.
12966 This command does many different things, depending on context:
12968 - If the cursor is in a headline, prompt for tags and insert them
12969 into the current line, aligned to `org-tags-column'. When called
12970 with prefix arg, realign all tags in the current buffer.
12972 - If the cursor is in one of the special #+KEYWORD lines, this
12973 triggers scanning the buffer for these lines and updating the
12974 information.
12976 - If the cursor is inside a table, realign the table. This command
12977 works even if the automatic table editor has been turned off.
12979 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12980 the entire table.
12982 - If the cursor is a the beginning of a dynamic block, update it.
12984 - If the cursor is inside a table created by the table.el package,
12985 activate that table.
12987 - If the current buffer is a remember buffer, close note and file
12988 it. A prefix argument of 1 files to the default location
12989 without further interaction. A prefix argument of 2 files to
12990 the currently clocking task.
12992 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12993 links in this buffer.
12995 - If the cursor is on a numbered item in a plain list, renumber the
12996 ordered list.
12998 - If the cursor is on a checkbox, toggle it."
12999 (interactive "P")
13000 (let ((org-enable-table-editor t))
13001 (cond
13002 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13003 org-occur-highlights
13004 org-latex-fragment-image-overlays)
13005 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13006 (org-remove-occur-highlights)
13007 (org-remove-latex-fragment-image-overlays)
13008 (message "Temporary highlights/overlays removed from current buffer"))
13009 ((and (local-variable-p 'org-finish-function (current-buffer))
13010 (fboundp org-finish-function))
13011 (funcall org-finish-function))
13012 ((org-at-property-p)
13013 (call-interactively 'org-property-action))
13014 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13015 ((org-on-heading-p) (call-interactively 'org-set-tags))
13016 ((org-at-table.el-p)
13017 (require 'table)
13018 (beginning-of-line 1)
13019 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13020 (call-interactively 'table-recognize-table))
13021 ((org-at-table-p)
13022 (org-table-maybe-eval-formula)
13023 (if arg
13024 (call-interactively 'org-table-recalculate)
13025 (org-table-maybe-recalculate-line))
13026 (call-interactively 'org-table-align))
13027 ((org-at-item-checkbox-p)
13028 (call-interactively 'org-toggle-checkbox))
13029 ((org-at-item-p)
13030 (call-interactively 'org-maybe-renumber-ordered-list))
13031 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13032 ;; Dynamic block
13033 (beginning-of-line 1)
13034 (save-excursion (org-update-dblock)))
13035 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13036 (cond
13037 ((equal (match-string 1) "TBLFM")
13038 ;; Recalculate the table before this line
13039 (save-excursion
13040 (beginning-of-line 1)
13041 (skip-chars-backward " \r\n\t")
13042 (if (org-at-table-p)
13043 (org-call-with-arg 'org-table-recalculate t))))
13045 ; (org-set-regexps-and-options)
13046 ; (org-restart-font-lock)
13047 (let ((org-inhibit-startup t)) (org-mode-restart))
13048 (message "Local setup has been refreshed"))))
13049 (t (error "C-c C-c can do nothing useful at this location.")))))
13051 (defun org-mode-restart ()
13052 "Restart Org-mode, to scan again for special lines.
13053 Also updates the keyword regular expressions."
13054 (interactive)
13055 (org-mode)
13056 (message "Org-mode restarted"))
13058 (defun org-kill-note-or-show-branches ()
13059 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13060 (interactive)
13061 (if (not org-finish-function)
13062 (call-interactively 'show-branches)
13063 (let ((org-note-abort t))
13064 (funcall org-finish-function))))
13066 (defun org-return (&optional indent)
13067 "Goto next table row or insert a newline.
13068 Calls `org-table-next-row' or `newline', depending on context.
13069 See the individual commands for more information."
13070 (interactive)
13071 (cond
13072 ((bobp) (if indent (newline-and-indent) (newline)))
13073 ((and (org-at-heading-p)
13074 (looking-at
13075 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13076 (org-show-entry)
13077 (end-of-line 1)
13078 (newline))
13079 ((org-at-table-p)
13080 (org-table-justify-field-maybe)
13081 (call-interactively 'org-table-next-row))
13082 (t (if indent (newline-and-indent) (newline)))))
13084 (defun org-return-indent ()
13085 "Goto next table row or insert a newline and indent.
13086 Calls `org-table-next-row' or `newline-and-indent', depending on
13087 context. See the individual commands for more information."
13088 (interactive)
13089 (org-return t))
13091 (defun org-ctrl-c-star ()
13092 "Compute table, or change heading status of lines.
13093 Calls `org-table-recalculate' or `org-toggle-region-headings',
13094 depending on context. This will also turn a plain list item or a normal
13095 line into a subheading."
13096 (interactive)
13097 (cond
13098 ((org-at-table-p)
13099 (call-interactively 'org-table-recalculate))
13100 ((org-region-active-p)
13101 ;; Convert all lines in region to list items
13102 (call-interactively 'org-toggle-region-headings))
13103 ((org-on-heading-p)
13104 (org-toggle-region-headings (point-at-bol)
13105 (min (1+ (point-at-eol)) (point-max))))
13106 ((org-at-item-p)
13107 ;; Convert to heading
13108 (let ((level (save-match-data
13109 (save-excursion
13110 (condition-case nil
13111 (progn
13112 (org-back-to-heading t)
13113 (funcall outline-level))
13114 (error 0))))))
13115 (replace-match
13116 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13117 (t (org-toggle-region-headings (point-at-bol)
13118 (min (1+ (point-at-eol)) (point-max))))))
13120 (defun org-ctrl-c-minus ()
13121 "Insert separator line in table or modify bullet status of line.
13122 Also turns a plain line or a region of lines into list items.
13123 Calls `org-table-insert-hline', `org-toggle-region-items', or
13124 `org-cycle-list-bullet', depending on context."
13125 (interactive)
13126 (cond
13127 ((org-at-table-p)
13128 (call-interactively 'org-table-insert-hline))
13129 ((org-on-heading-p)
13130 ;; Convert to item
13131 (save-excursion
13132 (beginning-of-line 1)
13133 (if (looking-at "\\*+ ")
13134 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13135 ((org-region-active-p)
13136 ;; Convert all lines in region to list items
13137 (call-interactively 'org-toggle-region-items))
13138 ((org-in-item-p)
13139 (call-interactively 'org-cycle-list-bullet))
13140 (t (org-toggle-region-items (point-at-bol)
13141 (min (1+ (point-at-eol)) (point-max))))))
13143 (defun org-toggle-region-items (beg end)
13144 "Convert all lines in region to list items.
13145 If the first line is already an item, convert all list items in the region
13146 to normal lines."
13147 (interactive "r")
13148 (let (l2 l)
13149 (save-excursion
13150 (goto-char end)
13151 (setq l2 (org-current-line))
13152 (goto-char beg)
13153 (beginning-of-line 1)
13154 (setq l (1- (org-current-line)))
13155 (if (org-at-item-p)
13156 ;; We already have items, de-itemize
13157 (while (< (setq l (1+ l)) l2)
13158 (when (org-at-item-p)
13159 (goto-char (match-beginning 2))
13160 (delete-region (match-beginning 2) (match-end 2))
13161 (and (looking-at "[ \t]+") (replace-match "")))
13162 (beginning-of-line 2))
13163 (while (< (setq l (1+ l)) l2)
13164 (unless (org-at-item-p)
13165 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13166 (replace-match "\\1- \\2")))
13167 (beginning-of-line 2))))))
13169 (defun org-toggle-region-headings (beg end)
13170 "Convert all lines in region to list items.
13171 If the first line is already an item, convert all list items in the region
13172 to normal lines."
13173 (interactive "r")
13174 (let (l2 l)
13175 (save-excursion
13176 (goto-char end)
13177 (setq l2 (org-current-line))
13178 (goto-char beg)
13179 (beginning-of-line 1)
13180 (setq l (1- (org-current-line)))
13181 (if (org-on-heading-p)
13182 ;; We already have headlines, de-star them
13183 (while (< (setq l (1+ l)) l2)
13184 (when (org-on-heading-p t)
13185 (and (looking-at outline-regexp) (replace-match "")))
13186 (beginning-of-line 2))
13187 (let* ((stars (save-excursion
13188 (re-search-backward org-complex-heading-regexp nil t)
13189 (or (match-string 1) "*")))
13190 (add-stars (if org-odd-levels-only "**" "*"))
13191 (rpl (concat stars add-stars " \\2")))
13192 (while (< (setq l (1+ l)) l2)
13193 (unless (org-on-heading-p)
13194 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13195 (replace-match rpl)))
13196 (beginning-of-line 2)))))))
13198 (defun org-meta-return (&optional arg)
13199 "Insert a new heading or wrap a region in a table.
13200 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13201 See the individual commands for more information."
13202 (interactive "P")
13203 (cond
13204 ((org-at-table-p)
13205 (call-interactively 'org-table-wrap-region))
13206 (t (call-interactively 'org-insert-heading))))
13208 ;;; Menu entries
13210 ;; Define the Org-mode menus
13211 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13212 '("Tbl"
13213 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13214 ["Next Field" org-cycle (org-at-table-p)]
13215 ["Previous Field" org-shifttab (org-at-table-p)]
13216 ["Next Row" org-return (org-at-table-p)]
13217 "--"
13218 ["Blank Field" org-table-blank-field (org-at-table-p)]
13219 ["Edit Field" org-table-edit-field (org-at-table-p)]
13220 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13221 "--"
13222 ("Column"
13223 ["Move Column Left" org-metaleft (org-at-table-p)]
13224 ["Move Column Right" org-metaright (org-at-table-p)]
13225 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13226 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13227 ("Row"
13228 ["Move Row Up" org-metaup (org-at-table-p)]
13229 ["Move Row Down" org-metadown (org-at-table-p)]
13230 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13231 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13232 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13233 "--"
13234 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13235 ("Rectangle"
13236 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13237 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13238 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13239 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13240 "--"
13241 ("Calculate"
13242 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13243 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13244 ["Edit Formulas" org-edit-special (org-at-table-p)]
13245 "--"
13246 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13247 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13248 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13249 "--"
13250 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13251 "--"
13252 ["Sum Column/Rectangle" org-table-sum
13253 (or (org-at-table-p) (org-region-active-p))]
13254 ["Which Column?" org-table-current-column (org-at-table-p)])
13255 ["Debug Formulas"
13256 org-table-toggle-formula-debugger
13257 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13258 ["Show Col/Row Numbers"
13259 org-table-toggle-coordinate-overlays
13260 :style toggle
13261 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13262 "--"
13263 ["Create" org-table-create (and (not (org-at-table-p))
13264 org-enable-table-editor)]
13265 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13266 ["Import from File" org-table-import (not (org-at-table-p))]
13267 ["Export to File" org-table-export (org-at-table-p)]
13268 "--"
13269 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13271 (easy-menu-define org-org-menu org-mode-map "Org menu"
13272 '("Org"
13273 ("Show/Hide"
13274 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13275 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13276 ["Sparse Tree..." org-sparse-tree t]
13277 ["Reveal Context" org-reveal t]
13278 ["Show All" show-all t]
13279 "--"
13280 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13281 "--"
13282 ["New Heading" org-insert-heading t]
13283 ("Navigate Headings"
13284 ["Up" outline-up-heading t]
13285 ["Next" outline-next-visible-heading t]
13286 ["Previous" outline-previous-visible-heading t]
13287 ["Next Same Level" outline-forward-same-level t]
13288 ["Previous Same Level" outline-backward-same-level t]
13289 "--"
13290 ["Jump" org-goto t])
13291 ("Edit Structure"
13292 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13293 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13294 "--"
13295 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13296 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13297 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13298 "--"
13299 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13300 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13301 ["Demote Heading" org-metaright (not (org-at-table-p))]
13302 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13303 "--"
13304 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13305 "--"
13306 ["Convert to odd levels" org-convert-to-odd-levels t]
13307 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13308 ("Editing"
13309 ["Emphasis..." org-emphasize t]
13310 ["Edit Source Example" org-edit-special t])
13311 ("Archive"
13312 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13313 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13314 ; :active t :keys "C-u C-c C-x C-a"]
13315 ["Sparse trees open ARCHIVE trees"
13316 (setq org-sparse-tree-open-archived-trees
13317 (not org-sparse-tree-open-archived-trees))
13318 :style toggle :selected org-sparse-tree-open-archived-trees]
13319 ["Cycling opens ARCHIVE trees"
13320 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13321 :style toggle :selected org-cycle-open-archived-trees]
13322 "--"
13323 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13324 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13325 ; ["Check and Move Children" (org-archive-subtree '(4))
13326 ; :active t :keys "C-u C-c C-x C-s"]
13328 "--"
13329 ("TODO Lists"
13330 ["TODO/DONE/-" org-todo t]
13331 ("Select keyword"
13332 ["Next keyword" org-shiftright (org-on-heading-p)]
13333 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13334 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13335 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13336 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13337 ["Show TODO Tree" org-show-todo-tree t]
13338 ["Global TODO list" org-todo-list t]
13339 "--"
13340 ["Set Priority" org-priority t]
13341 ["Priority Up" org-shiftup t]
13342 ["Priority Down" org-shiftdown t])
13343 ("TAGS and Properties"
13344 ["Set Tags" 'org-set-tags-command t]
13345 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13346 "--"
13347 ["Set property" 'org-set-property t]
13348 ["Column view of properties" org-columns t]
13349 ["Insert Column View DBlock" org-insert-columns-dblock t])
13350 ("Dates and Scheduling"
13351 ["Timestamp" org-time-stamp t]
13352 ["Timestamp (inactive)" org-time-stamp-inactive t]
13353 ("Change Date"
13354 ["1 Day Later" org-shiftright t]
13355 ["1 Day Earlier" org-shiftleft t]
13356 ["1 ... Later" org-shiftup t]
13357 ["1 ... Earlier" org-shiftdown t])
13358 ["Compute Time Range" org-evaluate-time-range t]
13359 ["Schedule Item" org-schedule t]
13360 ["Deadline" org-deadline t]
13361 "--"
13362 ["Custom time format" org-toggle-time-stamp-overlays
13363 :style radio :selected org-display-custom-times]
13364 "--"
13365 ["Goto Calendar" org-goto-calendar t]
13366 ["Date from Calendar" org-date-from-calendar t]
13367 "--"
13368 ["Start/restart timer" org-timer-start t]
13369 ["Insert timer string" org-timer t]
13370 ["Insert timer item" org-timer-item t])
13371 ("Logging work"
13372 ["Clock in" org-clock-in t]
13373 ["Clock out" org-clock-out t]
13374 ["Clock cancel" org-clock-cancel t]
13375 ["Goto running clock" org-clock-goto t]
13376 ["Display times" org-clock-display t]
13377 ["Create clock table" org-clock-report t]
13378 "--"
13379 ["Record DONE time"
13380 (progn (setq org-log-done (not org-log-done))
13381 (message "Switching to %s will %s record a timestamp"
13382 (car org-done-keywords)
13383 (if org-log-done "automatically" "not")))
13384 :style toggle :selected org-log-done])
13385 "--"
13386 ["Agenda Command..." org-agenda t]
13387 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13388 ("File List for Agenda")
13389 ("Special views current file"
13390 ["TODO Tree" org-show-todo-tree t]
13391 ["Check Deadlines" org-check-deadlines t]
13392 ["Timeline" org-timeline t]
13393 ["Tags Tree" org-tags-sparse-tree t])
13394 "--"
13395 ("Hyperlinks"
13396 ["Store Link (Global)" org-store-link t]
13397 ["Insert Link" org-insert-link t]
13398 ["Follow Link" org-open-at-point t]
13399 "--"
13400 ["Next link" org-next-link t]
13401 ["Previous link" org-previous-link t]
13402 "--"
13403 ["Descriptive Links"
13404 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13405 :style radio
13406 :selected (member '(org-link) buffer-invisibility-spec)]
13407 ["Literal Links"
13408 (progn
13409 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13410 :style radio
13411 :selected (not (member '(org-link) buffer-invisibility-spec))])
13412 "--"
13413 ["Export/Publish..." org-export t]
13414 ("LaTeX"
13415 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13416 :selected org-cdlatex-mode]
13417 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13418 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13419 ["Modify math symbol" org-cdlatex-math-modify
13420 (org-inside-LaTeX-fragment-p)]
13421 ["Export LaTeX fragments as images"
13422 (if (featurep 'org-exp)
13423 (setq org-export-with-LaTeX-fragments
13424 (not org-export-with-LaTeX-fragments))
13425 (require 'org-exp))
13426 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13427 org-export-with-LaTeX-fragments)])
13428 "--"
13429 ("Documentation"
13430 ["Show Version" org-version t]
13431 ["Info Documentation" org-info t])
13432 ("Customize"
13433 ["Browse Org Group" org-customize t]
13434 "--"
13435 ["Expand This Menu" org-create-customize-menu
13436 (fboundp 'customize-menu-create)])
13437 "--"
13438 ["Refresh setup" org-mode-restart t]
13441 (defun org-info (&optional node)
13442 "Read documentation for Org-mode in the info system.
13443 With optional NODE, go directly to that node."
13444 (interactive)
13445 (info (format "(org)%s" (or node ""))))
13447 (defun org-install-agenda-files-menu ()
13448 (let ((bl (buffer-list)))
13449 (save-excursion
13450 (while bl
13451 (set-buffer (pop bl))
13452 (if (org-mode-p) (setq bl nil)))
13453 (when (org-mode-p)
13454 (easy-menu-change
13455 '("Org") "File List for Agenda"
13456 (append
13457 (list
13458 ["Edit File List" (org-edit-agenda-file-list) t]
13459 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13460 ["Remove Current File from List" org-remove-file t]
13461 ["Cycle through agenda files" org-cycle-agenda-files t]
13462 ["Occur in all agenda files" org-occur-in-agenda-files t]
13463 "--")
13464 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13466 ;;;; Documentation
13468 ;;;###autoload
13469 (defun org-require-autoloaded-modules ()
13470 (interactive)
13471 (mapc 'require
13472 '(org-agenda org-archive org-clock org-colview
13473 org-exp org-id org-export-latex org-publish
13474 org-remember org-table)))
13476 ;;;###autoload
13477 (defun org-customize ()
13478 "Call the customize function with org as argument."
13479 (interactive)
13480 (org-load-modules-maybe)
13481 (org-require-autoloaded-modules)
13482 (customize-browse 'org))
13484 (defun org-create-customize-menu ()
13485 "Create a full customization menu for Org-mode, insert it into the menu."
13486 (interactive)
13487 (org-load-modules-maybe)
13488 (org-require-autoloaded-modules)
13489 (if (fboundp 'customize-menu-create)
13490 (progn
13491 (easy-menu-change
13492 '("Org") "Customize"
13493 `(["Browse Org group" org-customize t]
13494 "--"
13495 ,(customize-menu-create 'org)
13496 ["Set" Custom-set t]
13497 ["Save" Custom-save t]
13498 ["Reset to Current" Custom-reset-current t]
13499 ["Reset to Saved" Custom-reset-saved t]
13500 ["Reset to Standard Settings" Custom-reset-standard t]))
13501 (message "\"Org\"-menu now contains full customization menu"))
13502 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13504 ;;;; Miscellaneous stuff
13506 ;;; Generally useful functions
13508 (defun org-find-text-property-in-string (prop s)
13509 "Return the first non-nil value of property PROP in string S."
13510 (or (get-text-property 0 prop s)
13511 (get-text-property (or (next-single-property-change 0 prop s) 0)
13512 prop s)))
13514 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13515 "Display the given MESSAGE as a warning."
13516 (if (fboundp 'display-warning)
13517 (display-warning 'org message
13518 (if (featurep 'xemacs)
13519 'warning
13520 :warning))
13521 (let ((buf (get-buffer-create "*Org warnings*")))
13522 (with-current-buffer buf
13523 (goto-char (point-max))
13524 (insert "Warning (Org): " message)
13525 (unless (bolp)
13526 (newline)))
13527 (display-buffer buf)
13528 (sit-for 0))))
13530 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13531 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13532 (if (and marker (marker-buffer marker)
13533 (buffer-live-p (marker-buffer marker)))
13534 (progn
13535 (switch-to-buffer (marker-buffer marker))
13536 (if (or (> marker (point-max)) (< marker (point-min)))
13537 (widen))
13538 (goto-char marker))
13539 (if bookmark
13540 (bookmark-jump bookmark)
13541 (error "Cannot find location"))))
13543 (defun org-quote-csv-field (s)
13544 "Quote field for inclusion in CSV material."
13545 (if (string-match "[\",]" s)
13546 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13549 (defun org-plist-delete (plist property)
13550 "Delete PROPERTY from PLIST.
13551 This is in contrast to merely setting it to 0."
13552 (let (p)
13553 (while plist
13554 (if (not (eq property (car plist)))
13555 (setq p (plist-put p (car plist) (nth 1 plist))))
13556 (setq plist (cddr plist)))
13559 (defun org-force-self-insert (N)
13560 "Needed to enforce self-insert under remapping."
13561 (interactive "p")
13562 (self-insert-command N))
13564 (defun org-string-width (s)
13565 "Compute width of string, ignoring invisible characters.
13566 This ignores character with invisibility property `org-link', and also
13567 characters with property `org-cwidth', because these will become invisible
13568 upon the next fontification round."
13569 (let (b l)
13570 (when (or (eq t buffer-invisibility-spec)
13571 (assq 'org-link buffer-invisibility-spec))
13572 (while (setq b (text-property-any 0 (length s)
13573 'invisible 'org-link s))
13574 (setq s (concat (substring s 0 b)
13575 (substring s (or (next-single-property-change
13576 b 'invisible s) (length s)))))))
13577 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13578 (setq s (concat (substring s 0 b)
13579 (substring s (or (next-single-property-change
13580 b 'org-cwidth s) (length s))))))
13581 (setq l (string-width s) b -1)
13582 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13583 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13586 (defun org-get-indentation (&optional line)
13587 "Get the indentation of the current line, interpreting tabs.
13588 When LINE is given, assume it represents a line and compute its indentation."
13589 (if line
13590 (if (string-match "^ *" (org-remove-tabs line))
13591 (match-end 0))
13592 (save-excursion
13593 (beginning-of-line 1)
13594 (skip-chars-forward " \t")
13595 (current-column))))
13597 (defun org-remove-tabs (s &optional width)
13598 "Replace tabulators in S with spaces.
13599 Assumes that s is a single line, starting in column 0."
13600 (setq width (or width tab-width))
13601 (while (string-match "\t" s)
13602 (setq s (replace-match
13603 (make-string
13604 (- (* width (/ (+ (match-beginning 0) width) width))
13605 (match-beginning 0)) ?\ )
13606 t t s)))
13609 (defun org-fix-indentation (line ind)
13610 "Fix indentation in LINE.
13611 IND is a cons cell with target and minimum indentation.
13612 If the current indenation in LINE is smaller than the minimum,
13613 leave it alone. If it is larger than ind, set it to the target."
13614 (let* ((l (org-remove-tabs line))
13615 (i (org-get-indentation l))
13616 (i1 (car ind)) (i2 (cdr ind)))
13617 (if (>= i i2) (setq l (substring line i2)))
13618 (if (> i1 0)
13619 (concat (make-string i1 ?\ ) l)
13620 l)))
13622 (defun org-base-buffer (buffer)
13623 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13624 (if (not buffer)
13625 buffer
13626 (or (buffer-base-buffer buffer)
13627 buffer)))
13629 (defun org-trim (s)
13630 "Remove whitespace at beginning and end of string."
13631 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13632 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13635 (defun org-wrap (string &optional width lines)
13636 "Wrap string to either a number of lines, or a width in characters.
13637 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13638 that costs. If there is a word longer than WIDTH, the text is actually
13639 wrapped to the length of that word.
13640 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13641 many lines, whatever width that takes.
13642 The return value is a list of lines, without newlines at the end."
13643 (let* ((words (org-split-string string "[ \t\n]+"))
13644 (maxword (apply 'max (mapcar 'org-string-width words)))
13645 w ll)
13646 (cond (width
13647 (org-do-wrap words (max maxword width)))
13648 (lines
13649 (setq w maxword)
13650 (setq ll (org-do-wrap words maxword))
13651 (if (<= (length ll) lines)
13653 (setq ll words)
13654 (while (> (length ll) lines)
13655 (setq w (1+ w))
13656 (setq ll (org-do-wrap words w)))
13657 ll))
13658 (t (error "Cannot wrap this")))))
13660 (defun org-do-wrap (words width)
13661 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13662 (let (lines line)
13663 (while words
13664 (setq line (pop words))
13665 (while (and words (< (+ (length line) (length (car words))) width))
13666 (setq line (concat line " " (pop words))))
13667 (setq lines (push line lines)))
13668 (nreverse lines)))
13670 (defun org-split-string (string &optional separators)
13671 "Splits STRING into substrings at SEPARATORS.
13672 No empty strings are returned if there are matches at the beginning
13673 and end of string."
13674 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13675 (start 0)
13676 notfirst
13677 (list nil))
13678 (while (and (string-match rexp string
13679 (if (and notfirst
13680 (= start (match-beginning 0))
13681 (< start (length string)))
13682 (1+ start) start))
13683 (< (match-beginning 0) (length string)))
13684 (setq notfirst t)
13685 (or (eq (match-beginning 0) 0)
13686 (and (eq (match-beginning 0) (match-end 0))
13687 (eq (match-beginning 0) start))
13688 (setq list
13689 (cons (substring string start (match-beginning 0))
13690 list)))
13691 (setq start (match-end 0)))
13692 (or (eq start (length string))
13693 (setq list
13694 (cons (substring string start)
13695 list)))
13696 (nreverse list)))
13698 (defun org-context ()
13699 "Return a list of contexts of the current cursor position.
13700 If several contexts apply, all are returned.
13701 Each context entry is a list with a symbol naming the context, and
13702 two positions indicating start and end of the context. Possible
13703 contexts are:
13705 :headline anywhere in a headline
13706 :headline-stars on the leading stars in a headline
13707 :todo-keyword on a TODO keyword (including DONE) in a headline
13708 :tags on the TAGS in a headline
13709 :priority on the priority cookie in a headline
13710 :item on the first line of a plain list item
13711 :item-bullet on the bullet/number of a plain list item
13712 :checkbox on the checkbox in a plain list item
13713 :table in an org-mode table
13714 :table-special on a special filed in a table
13715 :table-table in a table.el table
13716 :link on a hyperlink
13717 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13718 :target on a <<target>>
13719 :radio-target on a <<<radio-target>>>
13720 :latex-fragment on a LaTeX fragment
13721 :latex-preview on a LaTeX fragment with overlayed preview image
13723 This function expects the position to be visible because it uses font-lock
13724 faces as a help to recognize the following contexts: :table-special, :link,
13725 and :keyword."
13726 (let* ((f (get-text-property (point) 'face))
13727 (faces (if (listp f) f (list f)))
13728 (p (point)) clist o)
13729 ;; First the large context
13730 (cond
13731 ((org-on-heading-p t)
13732 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13733 (when (progn
13734 (beginning-of-line 1)
13735 (looking-at org-todo-line-tags-regexp))
13736 (push (org-point-in-group p 1 :headline-stars) clist)
13737 (push (org-point-in-group p 2 :todo-keyword) clist)
13738 (push (org-point-in-group p 4 :tags) clist))
13739 (goto-char p)
13740 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13741 (if (looking-at "\\[#[A-Z0-9]\\]")
13742 (push (org-point-in-group p 0 :priority) clist)))
13744 ((org-at-item-p)
13745 (push (org-point-in-group p 2 :item-bullet) clist)
13746 (push (list :item (point-at-bol)
13747 (save-excursion (org-end-of-item) (point)))
13748 clist)
13749 (and (org-at-item-checkbox-p)
13750 (push (org-point-in-group p 0 :checkbox) clist)))
13752 ((org-at-table-p)
13753 (push (list :table (org-table-begin) (org-table-end)) clist)
13754 (if (memq 'org-formula faces)
13755 (push (list :table-special
13756 (previous-single-property-change p 'face)
13757 (next-single-property-change p 'face)) clist)))
13758 ((org-at-table-p 'any)
13759 (push (list :table-table) clist)))
13760 (goto-char p)
13762 ;; Now the small context
13763 (cond
13764 ((org-at-timestamp-p)
13765 (push (org-point-in-group p 0 :timestamp) clist))
13766 ((memq 'org-link faces)
13767 (push (list :link
13768 (previous-single-property-change p 'face)
13769 (next-single-property-change p 'face)) clist))
13770 ((memq 'org-special-keyword faces)
13771 (push (list :keyword
13772 (previous-single-property-change p 'face)
13773 (next-single-property-change p 'face)) clist))
13774 ((org-on-target-p)
13775 (push (org-point-in-group p 0 :target) clist)
13776 (goto-char (1- (match-beginning 0)))
13777 (if (looking-at org-radio-target-regexp)
13778 (push (org-point-in-group p 0 :radio-target) clist))
13779 (goto-char p))
13780 ((setq o (car (delq nil
13781 (mapcar
13782 (lambda (x)
13783 (if (memq x org-latex-fragment-image-overlays) x))
13784 (org-overlays-at (point))))))
13785 (push (list :latex-fragment
13786 (org-overlay-start o) (org-overlay-end o)) clist)
13787 (push (list :latex-preview
13788 (org-overlay-start o) (org-overlay-end o)) clist))
13789 ((org-inside-LaTeX-fragment-p)
13790 ;; FIXME: positions wrong.
13791 (push (list :latex-fragment (point) (point)) clist)))
13793 (setq clist (nreverse (delq nil clist)))
13794 clist))
13796 ;; FIXME: Compare with at-regexp-p Do we need both?
13797 (defun org-in-regexp (re &optional nlines visually)
13798 "Check if point is inside a match of regexp.
13799 Normally only the current line is checked, but you can include NLINES extra
13800 lines both before and after point into the search.
13801 If VISUALLY is set, require that the cursor is not after the match but
13802 really on, so that the block visually is on the match."
13803 (catch 'exit
13804 (let ((pos (point))
13805 (eol (point-at-eol (+ 1 (or nlines 0))))
13806 (inc (if visually 1 0)))
13807 (save-excursion
13808 (beginning-of-line (- 1 (or nlines 0)))
13809 (while (re-search-forward re eol t)
13810 (if (and (<= (match-beginning 0) pos)
13811 (>= (+ inc (match-end 0)) pos))
13812 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13814 (defun org-at-regexp-p (regexp)
13815 "Is point inside a match of REGEXP in the current line?"
13816 (catch 'exit
13817 (save-excursion
13818 (let ((pos (point)) (end (point-at-eol)))
13819 (beginning-of-line 1)
13820 (while (re-search-forward regexp end t)
13821 (if (and (<= (match-beginning 0) pos)
13822 (>= (match-end 0) pos))
13823 (throw 'exit t)))
13824 nil))))
13826 (defun org-occur-in-agenda-files (regexp &optional nlines)
13827 "Call `multi-occur' with buffers for all agenda files."
13828 (interactive "sOrg-files matching: \np")
13829 (let* ((files (org-agenda-files))
13830 (tnames (mapcar 'file-truename files))
13831 (extra org-agenda-text-search-extra-files)
13833 (when (eq (car extra) 'agenda-archives)
13834 (setq extra (cdr extra))
13835 (setq files (org-add-archive-files files)))
13836 (while (setq f (pop extra))
13837 (unless (member (file-truename f) tnames)
13838 (add-to-list 'files f 'append)
13839 (add-to-list 'tnames (file-truename f) 'append)))
13840 (multi-occur
13841 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13842 regexp)))
13844 (if (boundp 'occur-mode-find-occurrence-hook)
13845 ;; Emacs 23
13846 (add-hook 'occur-mode-find-occurrence-hook
13847 (lambda ()
13848 (when (org-mode-p)
13849 (org-reveal))))
13850 ;; Emacs 22
13851 (defadvice occur-mode-goto-occurrence
13852 (after org-occur-reveal activate)
13853 (and (org-mode-p) (org-reveal)))
13854 (defadvice occur-mode-goto-occurrence-other-window
13855 (after org-occur-reveal activate)
13856 (and (org-mode-p) (org-reveal)))
13857 (defadvice occur-mode-display-occurrence
13858 (after org-occur-reveal activate)
13859 (when (org-mode-p)
13860 (let ((pos (occur-mode-find-occurrence)))
13861 (with-current-buffer (marker-buffer pos)
13862 (save-excursion
13863 (goto-char pos)
13864 (org-reveal)))))))
13866 (defun org-uniquify (list)
13867 "Remove duplicate elements from LIST."
13868 (let (res)
13869 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13870 res))
13872 (defun org-delete-all (elts list)
13873 "Remove all elements in ELTS from LIST."
13874 (while elts
13875 (setq list (delete (pop elts) list)))
13876 list)
13878 (defun org-back-over-empty-lines ()
13879 "Move backwards over witespace, to the beginning of the first empty line.
13880 Returns the number of empty lines passed."
13881 (let ((pos (point)))
13882 (skip-chars-backward " \t\n\r")
13883 (beginning-of-line 2)
13884 (goto-char (min (point) pos))
13885 (count-lines (point) pos)))
13887 (defun org-skip-whitespace ()
13888 (skip-chars-forward " \t\n\r"))
13890 (defun org-point-in-group (point group &optional context)
13891 "Check if POINT is in match-group GROUP.
13892 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13893 match. If the match group does ot exist or point is not inside it,
13894 return nil."
13895 (and (match-beginning group)
13896 (>= point (match-beginning group))
13897 (<= point (match-end group))
13898 (if context
13899 (list context (match-beginning group) (match-end group))
13900 t)))
13902 (defun org-switch-to-buffer-other-window (&rest args)
13903 "Switch to buffer in a second window on the current frame.
13904 In particular, do not allow pop-up frames."
13905 (let (pop-up-frames special-display-buffer-names special-display-regexps
13906 special-display-function)
13907 (apply 'switch-to-buffer-other-window args)))
13909 (defun org-combine-plists (&rest plists)
13910 "Create a single property list from all plists in PLISTS.
13911 The process starts by copying the first list, and then setting properties
13912 from the other lists. Settings in the last list are the most significant
13913 ones and overrule settings in the other lists."
13914 (let ((rtn (copy-sequence (pop plists)))
13915 p v ls)
13916 (while plists
13917 (setq ls (pop plists))
13918 (while ls
13919 (setq p (pop ls) v (pop ls))
13920 (setq rtn (plist-put rtn p v))))
13921 rtn))
13923 (defun org-move-line-down (arg)
13924 "Move the current line down. With prefix argument, move it past ARG lines."
13925 (interactive "p")
13926 (let ((col (current-column))
13927 beg end pos)
13928 (beginning-of-line 1) (setq beg (point))
13929 (beginning-of-line 2) (setq end (point))
13930 (beginning-of-line (+ 1 arg))
13931 (setq pos (move-marker (make-marker) (point)))
13932 (insert (delete-and-extract-region beg end))
13933 (goto-char pos)
13934 (org-move-to-column col)))
13936 (defun org-move-line-up (arg)
13937 "Move the current line up. With prefix argument, move it past ARG lines."
13938 (interactive "p")
13939 (let ((col (current-column))
13940 beg end pos)
13941 (beginning-of-line 1) (setq beg (point))
13942 (beginning-of-line 2) (setq end (point))
13943 (beginning-of-line (- arg))
13944 (setq pos (move-marker (make-marker) (point)))
13945 (insert (delete-and-extract-region beg end))
13946 (goto-char pos)
13947 (org-move-to-column col)))
13949 (defun org-replace-escapes (string table)
13950 "Replace %-escapes in STRING with values in TABLE.
13951 TABLE is an association list with keys like \"%a\" and string values.
13952 The sequences in STRING may contain normal field width and padding information,
13953 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13954 so values can contain further %-escapes if they are define later in TABLE."
13955 (let ((case-fold-search nil)
13956 e re rpl)
13957 (while (setq e (pop table))
13958 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13959 (while (string-match re string)
13960 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13961 (cdr e)))
13962 (setq string (replace-match rpl t t string))))
13963 string))
13966 (defun org-sublist (list start end)
13967 "Return a section of LIST, from START to END.
13968 Counting starts at 1."
13969 (let (rtn (c start))
13970 (setq list (nthcdr (1- start) list))
13971 (while (and list (<= c end))
13972 (push (pop list) rtn)
13973 (setq c (1+ c)))
13974 (nreverse rtn)))
13976 (defun org-find-base-buffer-visiting (file)
13977 "Like `find-buffer-visiting' but alway return the base buffer and
13978 not an indirect buffer."
13979 (let ((buf (find-buffer-visiting file)))
13980 (if buf
13981 (or (buffer-base-buffer buf) buf)
13982 nil)))
13984 (defun org-image-file-name-regexp ()
13985 "Return regexp matching the file names of images."
13986 (if (fboundp 'image-file-name-regexp)
13987 (image-file-name-regexp)
13988 (let ((image-file-name-extensions
13989 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13990 "xbm" "xpm" "pbm" "pgm" "ppm")))
13991 (concat "\\."
13992 (regexp-opt (nconc (mapcar 'upcase
13993 image-file-name-extensions)
13994 image-file-name-extensions)
13996 "\\'"))))
13998 (defun org-file-image-p (file)
13999 "Return non-nil if FILE is an image."
14000 (save-match-data
14001 (string-match (org-image-file-name-regexp) file)))
14003 (defun org-get-cursor-date ()
14004 "Return the date at cursor in as a time.
14005 This works in the calendar and in the agenda, anywhere else it just
14006 returns the current time."
14007 (let (date day defd)
14008 (cond
14009 ((eq major-mode 'calendar-mode)
14010 (setq date (calendar-cursor-to-date)
14011 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14012 ((eq major-mode 'org-agenda-mode)
14013 (setq day (get-text-property (point) 'day))
14014 (if day
14015 (setq date (calendar-gregorian-from-absolute day)
14016 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14017 (nth 2 date))))))
14018 (or defd (current-time))))
14020 (defvar org-agenda-action-marker (make-marker)
14021 "Marker pointing to the entry for the next agenda action.")
14023 (defun org-mark-entry-for-agenda-action ()
14024 "Mark the current entry as target of an agenda action.
14025 Agenda actions are actions executed from the agenda with the key `k',
14026 which make use of the date at the cursor."
14027 (interactive)
14028 (move-marker org-agenda-action-marker
14029 (save-excursion (org-back-to-heading t) (point))
14030 (current-buffer))
14031 (message
14032 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14034 ;;; Paragraph filling stuff.
14035 ;; We want this to be just right, so use the full arsenal.
14037 (defun org-indent-line-function ()
14038 "Indent line like previous, but further if previous was headline or item."
14039 (interactive)
14040 (let* ((pos (point))
14041 (itemp (org-at-item-p))
14042 column bpos bcol tpos tcol bullet btype bullet-type)
14043 ;; Find the previous relevant line
14044 (beginning-of-line 1)
14045 (cond
14046 ((looking-at "#") (setq column 0))
14047 ((looking-at "\\*+ ") (setq column 0))
14049 (beginning-of-line 0)
14050 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14051 (beginning-of-line 0))
14052 (cond
14053 ((looking-at "\\*+[ \t]+")
14054 (if (not org-adapt-indentation)
14055 (setq column 0)
14056 (goto-char (match-end 0))
14057 (setq column (current-column))))
14058 ((org-in-item-p)
14059 (org-beginning-of-item)
14060 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14061 (setq bpos (match-beginning 1) tpos (match-end 0)
14062 bcol (progn (goto-char bpos) (current-column))
14063 tcol (progn (goto-char tpos) (current-column))
14064 bullet (match-string 1)
14065 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14066 (if (> tcol (+ bcol org-description-max-indent))
14067 (setq tcol (+ bcol 5)))
14068 (if (not itemp)
14069 (setq column tcol)
14070 (goto-char pos)
14071 (beginning-of-line 1)
14072 (if (looking-at "\\S-")
14073 (progn
14074 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14075 (setq bullet (match-string 1)
14076 btype (if (string-match "[0-9]" bullet) "n" bullet))
14077 (setq column (if (equal btype bullet-type) bcol tcol)))
14078 (setq column (org-get-indentation)))))
14079 (t (setq column (org-get-indentation))))))
14080 (goto-char pos)
14081 (if (<= (current-column) (current-indentation))
14082 (org-indent-line-to column)
14083 (save-excursion (org-indent-line-to column)))
14084 (setq column (current-column))
14085 (beginning-of-line 1)
14086 (if (looking-at
14087 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14088 (replace-match (concat "\\1" (format org-property-format
14089 (match-string 2) (match-string 3)))
14090 t nil))
14091 (org-move-to-column column)))
14093 (defun org-set-autofill-regexps ()
14094 (interactive)
14095 ;; In the paragraph separator we include headlines, because filling
14096 ;; text in a line directly attached to a headline would otherwise
14097 ;; fill the headline as well.
14098 (org-set-local 'comment-start-skip "^#+[ \t]*")
14099 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14100 ;; The paragraph starter includes hand-formatted lists.
14101 (org-set-local 'paragraph-start
14102 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14103 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14104 ;; But only if the user has not turned off tables or fixed-width regions
14105 (org-set-local
14106 'auto-fill-inhibit-regexp
14107 (concat "\\*+ \\|#\\+"
14108 "\\|[ \t]*" org-keyword-time-regexp
14109 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14110 (concat
14111 "\\|[ \t]*["
14112 (if org-enable-table-editor "|" "")
14113 (if org-enable-fixed-width-editor ":" "")
14114 "]"))))
14115 ;; We use our own fill-paragraph function, to make sure that tables
14116 ;; and fixed-width regions are not wrapped. That function will pass
14117 ;; through to `fill-paragraph' when appropriate.
14118 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14119 ; Adaptive filling: To get full control, first make sure that
14120 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14121 (org-set-local 'adaptive-fill-regexp "\000")
14122 (org-set-local 'adaptive-fill-function
14123 'org-adaptive-fill-function)
14124 (org-set-local
14125 'align-mode-rules-list
14126 '((org-in-buffer-settings
14127 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14128 (modes . '(org-mode))))))
14130 (defun org-fill-paragraph (&optional justify)
14131 "Re-align a table, pass through to fill-paragraph if no table."
14132 (let ((table-p (org-at-table-p))
14133 (table.el-p (org-at-table.el-p)))
14134 (cond ((and (equal (char-after (point-at-bol)) ?*)
14135 (save-excursion (goto-char (point-at-bol))
14136 (looking-at outline-regexp)))
14137 t) ; skip headlines
14138 (table.el-p t) ; skip table.el tables
14139 (table-p (org-table-align) t) ; align org-mode tables
14140 (t nil)))) ; call paragraph-fill
14142 ;; For reference, this is the default value of adaptive-fill-regexp
14143 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14145 (defun org-adaptive-fill-function ()
14146 "Return a fill prefix for org-mode files.
14147 In particular, this makes sure hanging paragraphs for hand-formatted lists
14148 work correctly."
14149 (cond ((looking-at "#[ \t]+")
14150 (match-string 0))
14151 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14152 (save-excursion
14153 (if (> (match-end 1) (+ (match-beginning 1)
14154 org-description-max-indent))
14155 (goto-char (+ (match-beginning 1) 5))
14156 (goto-char (match-end 0)))
14157 (make-string (current-column) ?\ )))
14158 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14159 (save-excursion
14160 (goto-char (match-end 0))
14161 (make-string (current-column) ?\ )))
14162 (t nil)))
14164 ;;; Other stuff.
14166 (defun org-toggle-fixed-width-section (arg)
14167 "Toggle the fixed-width export.
14168 If there is no active region, the QUOTE keyword at the current headline is
14169 inserted or removed. When present, it causes the text between this headline
14170 and the next to be exported as fixed-width text, and unmodified.
14171 If there is an active region, this command adds or removes a colon as the
14172 first character of this line. If the first character of a line is a colon,
14173 this line is also exported in fixed-width font."
14174 (interactive "P")
14175 (let* ((cc 0)
14176 (regionp (org-region-active-p))
14177 (beg (if regionp (region-beginning) (point)))
14178 (end (if regionp (region-end)))
14179 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14180 (case-fold-search nil)
14181 (re "[ \t]*\\(:\\)")
14182 off)
14183 (if regionp
14184 (save-excursion
14185 (goto-char beg)
14186 (setq cc (current-column))
14187 (beginning-of-line 1)
14188 (setq off (looking-at re))
14189 (while (> nlines 0)
14190 (setq nlines (1- nlines))
14191 (beginning-of-line 1)
14192 (cond
14193 (arg
14194 (org-move-to-column cc t)
14195 (insert ":\n")
14196 (forward-line -1))
14197 ((and off (looking-at re))
14198 (replace-match "" t t nil 1))
14199 ((not off) (org-move-to-column cc t) (insert ":")))
14200 (forward-line 1)))
14201 (save-excursion
14202 (org-back-to-heading)
14203 (if (looking-at (concat outline-regexp
14204 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14205 (replace-match "" t t nil 1)
14206 (if (looking-at outline-regexp)
14207 (progn
14208 (goto-char (match-end 0))
14209 (insert org-quote-string " "))))))))
14211 ;;;; Functions extending outline functionality
14213 (defun org-beginning-of-line (&optional arg)
14214 "Go to the beginning of the current line. If that is invisible, continue
14215 to a visible line beginning. This makes the function of C-a more intuitive.
14216 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14217 first attempt, and only move to after the tags when the cursor is already
14218 beyond the end of the headline."
14219 (interactive "P")
14220 (let ((pos (point)) refpos)
14221 (beginning-of-line 1)
14222 (if (bobp)
14224 (backward-char 1)
14225 (if (org-invisible-p)
14226 (while (and (not (bobp)) (org-invisible-p))
14227 (backward-char 1)
14228 (beginning-of-line 1))
14229 (forward-char 1)))
14230 (when org-special-ctrl-a/e
14231 (cond
14232 ((and (looking-at org-complex-heading-regexp)
14233 (= (char-after (match-end 1)) ?\ ))
14234 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14235 (point-at-eol)))
14236 (goto-char
14237 (if (eq org-special-ctrl-a/e t)
14238 (cond ((> pos refpos) refpos)
14239 ((= pos (point)) refpos)
14240 (t (point)))
14241 (cond ((> pos (point)) (point))
14242 ((not (eq last-command this-command)) (point))
14243 (t refpos)))))
14244 ((org-at-item-p)
14245 (goto-char
14246 (if (eq org-special-ctrl-a/e t)
14247 (cond ((> pos (match-end 4)) (match-end 4))
14248 ((= pos (point)) (match-end 4))
14249 (t (point)))
14250 (cond ((> pos (point)) (point))
14251 ((not (eq last-command this-command)) (point))
14252 (t (match-end 4))))))))
14253 (org-no-warnings
14254 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14256 (defun org-end-of-line (&optional arg)
14257 "Go to the end of the line.
14258 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14259 first attempt, and only move to after the tags when the cursor is already
14260 beyond the end of the headline."
14261 (interactive "P")
14262 (if (or (not org-special-ctrl-a/e)
14263 (not (org-on-heading-p)))
14264 (end-of-line arg)
14265 (let ((pos (point)))
14266 (beginning-of-line 1)
14267 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14268 (if (eq org-special-ctrl-a/e t)
14269 (if (or (< pos (match-beginning 1))
14270 (= pos (match-end 0)))
14271 (goto-char (match-beginning 1))
14272 (goto-char (match-end 0)))
14273 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14274 (goto-char (match-end 0))
14275 (goto-char (match-beginning 1))))
14276 (end-of-line arg))))
14277 (org-no-warnings
14278 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14281 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14282 (define-key org-mode-map "\C-e" 'org-end-of-line)
14284 (defun org-kill-line (&optional arg)
14285 "Kill line, to tags or end of line."
14286 (interactive "P")
14287 (cond
14288 ((or (not org-special-ctrl-k)
14289 (bolp)
14290 (not (org-on-heading-p)))
14291 (call-interactively 'kill-line))
14292 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14293 (kill-region (point) (match-beginning 1))
14294 (org-set-tags nil t))
14295 (t (kill-region (point) (point-at-eol)))))
14297 (define-key org-mode-map "\C-k" 'org-kill-line)
14299 (defun org-yank (&optional arg)
14300 "Yank. If the kill is a subtree, treat it specially.
14301 This command will look at the current kill and check if is a single
14302 subtree, or a series of subtrees[1]. If it passes the test, and if the
14303 cursor is at the beginning of a line or after the stars of a currently
14304 empty headline, then the yank is handeled specially. How exactly depends
14305 on the value of the following variables, both set by default.
14307 org-yank-folded-subtrees
14308 When set, the subree(s) will be folded after insertion, but only
14309 if doing so would now swallow text after the yanked text.
14311 org-yank-adjusted-subtrees
14312 When set, the subtree will be promoted or demoted in order to
14313 fit into the local outline tree structure, which means that the level
14314 will be adjusted so that it becomes the smaller one of the two
14315 *visible* surrounding headings.
14317 Any prefix to this command will cause `yank' to be called directly with
14318 no special treatment. In particular, a simple `C-u' prefix will just
14319 plainly yank the text as it is.
14321 \[1] Basically, the test checks if the first non-white line is a heading
14322 and if there are no other headings with fewer stars."
14323 (interactive "P")
14324 (setq this-command 'yank)
14325 (if arg
14326 (call-interactively 'yank)
14327 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14328 (and (org-kill-is-subtree-p)
14329 (or (bolp)
14330 (and (looking-at "[ \t]*$")
14331 (string-match
14332 "\\`\\*+\\'"
14333 (buffer-substring (point-at-bol) (point)))))))
14334 swallowp)
14335 (cond
14336 ((and subtreep org-yank-folded-subtrees)
14337 (let ((beg (point))
14338 end)
14339 (if (and subtreep org-yank-adjusted-subtrees)
14340 (org-paste-subtree nil nil 'for-yank)
14341 (call-interactively 'yank))
14342 (setq end (point))
14343 (goto-char beg)
14344 (when (and (bolp) subtreep
14345 (not (setq swallowp
14346 (org-yank-folding-would-swallow-text beg end))))
14347 (or (looking-at outline-regexp)
14348 (re-search-forward (concat "^" outline-regexp) end t))
14349 (while (and (< (point) end) (looking-at outline-regexp))
14350 (hide-subtree)
14351 (org-cycle-show-empty-lines 'folded)
14352 (condition-case nil
14353 (outline-forward-same-level 1)
14354 (error (goto-char end)))))
14355 (when swallowp
14356 (message
14357 "Yanked text not folded because that would swallow text"))
14358 (goto-char end)
14359 (skip-chars-forward " \t\n\r")
14360 (beginning-of-line 1)
14361 (push-mark beg 'nomsg)))
14362 ((and subtreep org-yank-adjusted-subtrees)
14363 (let ((beg (point-at-bol)))
14364 (org-paste-subtree nil nil 'for-yank)
14365 (push-mark beg 'nomsg)))
14367 (call-interactively 'yank))))))
14369 (defun org-yank-folding-would-swallow-text (beg end)
14370 "Would hide-subtree at BEG swallow any text after END?"
14371 (let (level)
14372 (save-excursion
14373 (goto-char beg)
14374 (when (or (looking-at outline-regexp)
14375 (re-search-forward (concat "^" outline-regexp) end t))
14376 (setq level (org-outline-level)))
14377 (goto-char end)
14378 (skip-chars-forward " \t\r\n\v\f")
14379 (if (or (eobp)
14380 (and (bolp) (looking-at org-outline-regexp)
14381 (<= (org-outline-level) level)))
14382 nil ; Nothing would be swallowed
14383 t)))) ; something would swallow
14385 (define-key org-mode-map "\C-y" 'org-yank)
14387 (defun org-invisible-p ()
14388 "Check if point is at a character currently not visible."
14389 ;; Early versions of noutline don't have `outline-invisible-p'.
14390 (if (fboundp 'outline-invisible-p)
14391 (outline-invisible-p)
14392 (get-char-property (point) 'invisible)))
14394 (defun org-invisible-p2 ()
14395 "Check if point is at a character currently not visible."
14396 (save-excursion
14397 (if (and (eolp) (not (bobp))) (backward-char 1))
14398 ;; Early versions of noutline don't have `outline-invisible-p'.
14399 (if (fboundp 'outline-invisible-p)
14400 (outline-invisible-p)
14401 (get-char-property (point) 'invisible))))
14403 (defun org-back-to-heading (&optional invisible-ok)
14404 "Call `outline-back-to-heading', but provide a better error message."
14405 (condition-case nil
14406 (outline-back-to-heading invisible-ok)
14407 (error (error "Before first headline at position %d in buffer %s"
14408 (point) (current-buffer)))))
14410 (defun org-before-first-heading-p ()
14411 "Before first heading?"
14412 (save-excursion
14413 (null (re-search-backward "^\\*+ " nil t))))
14415 (defalias 'org-on-heading-p 'outline-on-heading-p)
14416 (defalias 'org-at-heading-p 'outline-on-heading-p)
14417 (defun org-at-heading-or-item-p ()
14418 (or (org-on-heading-p) (org-at-item-p)))
14420 (defun org-on-target-p ()
14421 (or (org-in-regexp org-radio-target-regexp)
14422 (org-in-regexp org-target-regexp)))
14424 (defun org-up-heading-all (arg)
14425 "Move to the heading line of which the present line is a subheading.
14426 This function considers both visible and invisible heading lines.
14427 With argument, move up ARG levels."
14428 (if (fboundp 'outline-up-heading-all)
14429 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14430 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14432 (defun org-up-heading-safe ()
14433 "Move to the heading line of which the present line is a subheading.
14434 This version will not throw an error. It will return the level of the
14435 headline found, or nil if no higher level is found."
14436 (let (start-level re)
14437 (org-back-to-heading t)
14438 (setq start-level (funcall outline-level))
14439 (if (equal start-level 1)
14441 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14442 (if (re-search-backward re nil t)
14443 (funcall outline-level)))))
14445 (defun org-first-sibling-p ()
14446 "Is this heading the first child of its parents?"
14447 (interactive)
14448 (let ((re (concat "^" outline-regexp))
14449 level l)
14450 (unless (org-at-heading-p t)
14451 (error "Not at a heading"))
14452 (setq level (funcall outline-level))
14453 (save-excursion
14454 (if (not (re-search-backward re nil t))
14456 (setq l (funcall outline-level))
14457 (< l level)))))
14459 (defun org-goto-sibling (&optional previous)
14460 "Goto the next sibling, even if it is invisible.
14461 When PREVIOUS is set, go to the previous sibling instead. Returns t
14462 when a sibling was found. When none is found, return nil and don't
14463 move point."
14464 (let ((fun (if previous 're-search-backward 're-search-forward))
14465 (pos (point))
14466 (re (concat "^" outline-regexp))
14467 level l)
14468 (when (condition-case nil (org-back-to-heading t) (error nil))
14469 (setq level (funcall outline-level))
14470 (catch 'exit
14471 (or previous (forward-char 1))
14472 (while (funcall fun re nil t)
14473 (setq l (funcall outline-level))
14474 (when (< l level) (goto-char pos) (throw 'exit nil))
14475 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14476 (goto-char pos)
14477 nil))))
14479 (defun org-show-siblings ()
14480 "Show all siblings of the current headline."
14481 (save-excursion
14482 (while (org-goto-sibling) (org-flag-heading nil)))
14483 (save-excursion
14484 (while (org-goto-sibling 'previous)
14485 (org-flag-heading nil))))
14487 (defun org-show-hidden-entry ()
14488 "Show an entry where even the heading is hidden."
14489 (save-excursion
14490 (org-show-entry)))
14492 (defun org-flag-heading (flag &optional entry)
14493 "Flag the current heading. FLAG non-nil means make invisible.
14494 When ENTRY is non-nil, show the entire entry."
14495 (save-excursion
14496 (org-back-to-heading t)
14497 ;; Check if we should show the entire entry
14498 (if entry
14499 (progn
14500 (org-show-entry)
14501 (save-excursion
14502 (and (outline-next-heading)
14503 (org-flag-heading nil))))
14504 (outline-flag-region (max (point-min) (1- (point)))
14505 (save-excursion (outline-end-of-heading) (point))
14506 flag))))
14508 (defun org-forward-same-level (arg)
14509 "Move forward to the ARG'th subheading at same level as this one.
14510 Stop at the first and last subheadings of a superior heading.
14511 This is like outline-forward-same-level, but invisible headings are ok."
14512 (interactive "p")
14513 (org-back-to-heading t)
14514 (while (> arg 0)
14515 (let ((point-to-move-to (save-excursion
14516 (org-get-next-sibling))))
14517 (if point-to-move-to
14518 (progn
14519 (goto-char point-to-move-to)
14520 (setq arg (1- arg)))
14521 (progn
14522 (setq arg 0)
14523 (error "No following same-level heading"))))))
14525 (defun org-get-next-sibling ()
14526 "Move to next heading of the same level, and return point.
14527 If there is no such heading, return nil.
14528 This is like outline-next-sibling, but invisible headings are ok."
14529 (let ((level (funcall outline-level)))
14530 (outline-next-heading)
14531 (while (and (not (eobp)) (> (funcall outline-level) level))
14532 (outline-next-heading))
14533 (if (or (eobp) (< (funcall outline-level) level))
14535 (point))))
14537 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14538 ;; This is an exact copy of the original function, but it uses
14539 ;; `org-back-to-heading', to make it work also in invisible
14540 ;; trees. And is uses an invisible-OK argument.
14541 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14542 (org-back-to-heading invisible-OK)
14543 (let ((first t)
14544 (level (funcall outline-level)))
14545 (while (and (not (eobp))
14546 (or first (> (funcall outline-level) level)))
14547 (setq first nil)
14548 (outline-next-heading))
14549 (unless to-heading
14550 (if (memq (preceding-char) '(?\n ?\^M))
14551 (progn
14552 ;; Go to end of line before heading
14553 (forward-char -1)
14554 (if (memq (preceding-char) '(?\n ?\^M))
14555 ;; leave blank line before heading
14556 (forward-char -1))))))
14557 (point))
14559 (defun org-show-subtree ()
14560 "Show everything after this heading at deeper levels."
14561 (outline-flag-region
14562 (point)
14563 (save-excursion
14564 (outline-end-of-subtree) (outline-next-heading) (point))
14565 nil))
14567 (defun org-show-entry ()
14568 "Show the body directly following this heading.
14569 Show the heading too, if it is currently invisible."
14570 (interactive)
14571 (save-excursion
14572 (condition-case nil
14573 (progn
14574 (org-back-to-heading t)
14575 (outline-flag-region
14576 (max (point-min) (1- (point)))
14577 (save-excursion
14578 (re-search-forward
14579 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14580 (or (match-beginning 1) (point-max)))
14581 nil))
14582 (error nil))))
14584 (defun org-make-options-regexp (kwds)
14585 "Make a regular expression for keyword lines."
14586 (concat
14588 "#?[ \t]*\\+\\("
14589 (mapconcat 'regexp-quote kwds "\\|")
14590 "\\):[ \t]*"
14591 "\\(.+\\)"))
14593 ;; Make isearch reveal the necessary context
14594 (defun org-isearch-end ()
14595 "Reveal context after isearch exits."
14596 (when isearch-success ; only if search was successful
14597 (if (featurep 'xemacs)
14598 ;; Under XEmacs, the hook is run in the correct place,
14599 ;; we directly show the context.
14600 (org-show-context 'isearch)
14601 ;; In Emacs the hook runs *before* restoring the overlays.
14602 ;; So we have to use a one-time post-command-hook to do this.
14603 ;; (Emacs 22 has a special variable, see function `org-mode')
14604 (unless (and (boundp 'isearch-mode-end-hook-quit)
14605 isearch-mode-end-hook-quit)
14606 ;; Only when the isearch was not quitted.
14607 (org-add-hook 'post-command-hook 'org-isearch-post-command
14608 'append 'local)))))
14610 (defun org-isearch-post-command ()
14611 "Remove self from hook, and show context."
14612 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14613 (org-show-context 'isearch))
14616 ;;;; Integration with and fixes for other packages
14618 ;;; Imenu support
14620 (defvar org-imenu-markers nil
14621 "All markers currently used by Imenu.")
14622 (make-variable-buffer-local 'org-imenu-markers)
14624 (defun org-imenu-new-marker (&optional pos)
14625 "Return a new marker for use by Imenu, and remember the marker."
14626 (let ((m (make-marker)))
14627 (move-marker m (or pos (point)))
14628 (push m org-imenu-markers)
14631 (defun org-imenu-get-tree ()
14632 "Produce the index for Imenu."
14633 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14634 (setq org-imenu-markers nil)
14635 (let* ((n org-imenu-depth)
14636 (re (concat "^" outline-regexp))
14637 (subs (make-vector (1+ n) nil))
14638 (last-level 0)
14639 m tree level head)
14640 (save-excursion
14641 (save-restriction
14642 (widen)
14643 (goto-char (point-max))
14644 (while (re-search-backward re nil t)
14645 (setq level (org-reduced-level (funcall outline-level)))
14646 (when (<= level n)
14647 (looking-at org-complex-heading-regexp)
14648 (setq head (org-link-display-format
14649 (org-match-string-no-properties 4))
14650 m (org-imenu-new-marker))
14651 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14652 (if (>= level last-level)
14653 (push (cons head m) (aref subs level))
14654 (push (cons head (aref subs (1+ level))) (aref subs level))
14655 (loop for i from (1+ level) to n do (aset subs i nil)))
14656 (setq last-level level)))))
14657 (aref subs 1)))
14659 (eval-after-load "imenu"
14660 '(progn
14661 (add-hook 'imenu-after-jump-hook
14662 (lambda ()
14663 (if (eq major-mode 'org-mode)
14664 (org-show-context 'org-goto))))))
14666 (defun org-link-display-format (link)
14667 "Replace a link with either the description, or the link target
14668 if no description is present"
14669 (save-match-data
14670 (if (string-match org-bracket-link-analytic-regexp link)
14671 (replace-match (or (match-string 5 link)
14672 (concat (match-string 1 link)
14673 (match-string 3 link)))
14674 nil nil link)
14675 link)))
14677 ;; Speedbar support
14679 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14680 "Overlay marking the agenda restriction line in speedbar.")
14681 (org-overlay-put org-speedbar-restriction-lock-overlay
14682 'face 'org-agenda-restriction-lock)
14683 (org-overlay-put org-speedbar-restriction-lock-overlay
14684 'help-echo "Agendas are currently limited to this item.")
14685 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14687 (defun org-speedbar-set-agenda-restriction ()
14688 "Restrict future agenda commands to the location at point in speedbar.
14689 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14690 (interactive)
14691 (require 'org-agenda)
14692 (let (p m tp np dir txt w)
14693 (cond
14694 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14695 'org-imenu t))
14696 (setq m (get-text-property p 'org-imenu-marker))
14697 (save-excursion
14698 (save-restriction
14699 (set-buffer (marker-buffer m))
14700 (goto-char m)
14701 (org-agenda-set-restriction-lock 'subtree))))
14702 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14703 'speedbar-function 'speedbar-find-file))
14704 (setq tp (previous-single-property-change
14705 (1+ p) 'speedbar-function)
14706 np (next-single-property-change
14707 tp 'speedbar-function)
14708 dir (speedbar-line-directory)
14709 txt (buffer-substring-no-properties (or tp (point-min))
14710 (or np (point-max))))
14711 (save-excursion
14712 (save-restriction
14713 (set-buffer (find-file-noselect
14714 (let ((default-directory dir))
14715 (expand-file-name txt))))
14716 (unless (org-mode-p)
14717 (error "Cannot restrict to non-Org-mode file"))
14718 (org-agenda-set-restriction-lock 'file))))
14719 (t (error "Don't know how to restrict Org-mode's agenda")))
14720 (org-move-overlay org-speedbar-restriction-lock-overlay
14721 (point-at-bol) (point-at-eol))
14722 (setq current-prefix-arg nil)
14723 (org-agenda-maybe-redo)))
14725 (eval-after-load "speedbar"
14726 '(progn
14727 (speedbar-add-supported-extension ".org")
14728 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14729 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14730 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14731 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14732 (add-hook 'speedbar-visiting-tag-hook
14733 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14736 ;;; Fixes and Hacks for problems with other packages
14738 ;; Make flyspell not check words in links, to not mess up our keymap
14739 (defun org-mode-flyspell-verify ()
14740 "Don't let flyspell put overlays at active buttons."
14741 (not (get-text-property (point) 'keymap)))
14743 ;; Make `bookmark-jump' show the jump location if it was hidden.
14744 (eval-after-load "bookmark"
14745 '(if (boundp 'bookmark-after-jump-hook)
14746 ;; We can use the hook
14747 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14748 ;; Hook not available, use advice
14749 (defadvice bookmark-jump (after org-make-visible activate)
14750 "Make the position visible."
14751 (org-bookmark-jump-unhide))))
14753 ;; Make sure saveplace show the location if it was hidden
14754 (eval-after-load "saveplace"
14755 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14756 "Make the position visible."
14757 (org-bookmark-jump-unhide)))
14759 (defun org-bookmark-jump-unhide ()
14760 "Unhide the current position, to show the bookmark location."
14761 (and (org-mode-p)
14762 (or (org-invisible-p)
14763 (save-excursion (goto-char (max (point-min) (1- (point))))
14764 (org-invisible-p)))
14765 (org-show-context 'bookmark-jump)))
14767 ;; Make session.el ignore our circular variable
14768 (eval-after-load "session"
14769 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14771 ;;;; Experimental code
14773 (defun org-closed-in-range ()
14774 "Sparse tree of items closed in a certain time range.
14775 Still experimental, may disappear in the future."
14776 (interactive)
14777 ;; Get the time interval from the user.
14778 (let* ((time1 (time-to-seconds
14779 (org-read-date nil 'to-time nil "Starting date: ")))
14780 (time2 (time-to-seconds
14781 (org-read-date nil 'to-time nil "End date:")))
14782 ;; callback function
14783 (callback (lambda ()
14784 (let ((time
14785 (time-to-seconds
14786 (apply 'encode-time
14787 (org-parse-time-string
14788 (match-string 1))))))
14789 ;; check if time in interval
14790 (and (>= time time1) (<= time time2))))))
14791 ;; make tree, check each match with the callback
14792 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14795 ;;;; Finish up
14797 (provide 'org)
14799 (run-hooks 'org-load-hook)
14801 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14803 ;;; org.el ends here