Changelog entry for org-gnus patch.
[org-mode/org-tableheadings.git] / lisp / org.el
blob29e586bccc6e0c21bf9e99b9f1fc9a342cda630c
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.14trans
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.14trans"
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-reverse-note-order nil
1321 "Non-nil means, store new notes at the beginning of a file or entry.
1322 When nil, new notes will be filed to the end of a file or entry.
1323 This can also be a list with cons cells of regular expressions that
1324 are matched against file names, and values."
1325 :group 'org-remember
1326 :group 'org-refile
1327 :type '(choice
1328 (const :tag "Reverse always" t)
1329 (const :tag "Reverse never" nil)
1330 (repeat :tag "By file name regexp"
1331 (cons regexp boolean))))
1333 (defcustom org-refile-targets nil
1334 "Targets for refiling entries with \\[org-refile].
1335 This is list of cons cells. Each cell contains:
1336 - a specification of the files to be considered, either a list of files,
1337 or a symbol whose function or variable value will be used to retrieve
1338 a file name or a list of file names. Nil means, refile to a different
1339 heading in the current buffer.
1340 - A specification of how to find candidate refile targets. This may be
1341 any of
1342 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1343 This tag has to be present in all target headlines, inheritance will
1344 not be considered.
1345 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1346 todo keyword.
1347 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1348 headlines that are refiling targets.
1349 - a cons cell (:level . N). Any headline of level N is considered a target.
1350 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1352 When this variable is nil, all top-level headlines in the current buffer
1353 are used, equivalent to the value `((nil . (:level . 1))'."
1354 :group 'org-refile
1355 :type '(repeat
1356 (cons
1357 (choice :value org-agenda-files
1358 (const :tag "All agenda files" org-agenda-files)
1359 (const :tag "Current buffer" nil)
1360 (function) (variable) (file))
1361 (choice :tag "Identify target headline by"
1362 (cons :tag "Specific tag" (const :value :tag) (string))
1363 (cons :tag "TODO keyword" (const :value :todo) (string))
1364 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1365 (cons :tag "Level number" (const :value :level) (integer))
1366 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1368 (defcustom org-refile-use-outline-path nil
1369 "Non-nil means, provide refile targets as paths.
1370 So a level 3 headline will be available as level1/level2/level3.
1371 When the value is `file', also include the file name (without directory)
1372 into the path. When `full-file-path', include the full file path."
1373 :group 'org-refile
1374 :type '(choice
1375 (const :tag "Not" nil)
1376 (const :tag "Yes" t)
1377 (const :tag "Start with file name" file)
1378 (const :tag "Start with full file path" full-file-path)))
1380 (defcustom org-outline-path-complete-in-steps t
1381 "Non-nil means, complete the outline path in hierarchical steps.
1382 When Org-mode uses the refile interface to select an outline path
1383 \(see variable `org-refile-use-outline-path'), the completion of
1384 the path can be done is a single go, or if can be done in steps down
1385 the headline hierarchy. Going in steps is probably the best if you
1386 do not use a special completion package like `ido' or `icicles'.
1387 However, when using these packages, going in one step can be very
1388 fast, while still showing the whole path to the entry."
1389 :group 'org-refile
1390 :type 'boolean)
1392 (defgroup org-todo nil
1393 "Options concerning TODO items in Org-mode."
1394 :tag "Org TODO"
1395 :group 'org)
1397 (defgroup org-progress nil
1398 "Options concerning Progress logging in Org-mode."
1399 :tag "Org Progress"
1400 :group 'org-time)
1402 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1403 "List of TODO entry keyword sequences and their interpretation.
1404 \\<org-mode-map>This is a list of sequences.
1406 Each sequence starts with a symbol, either `sequence' or `type',
1407 indicating if the keywords should be interpreted as a sequence of
1408 action steps, or as different types of TODO items. The first
1409 keywords are states requiring action - these states will select a headline
1410 for inclusion into the global TODO list Org-mode produces. If one of
1411 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1412 signify that no further action is necessary. If \"|\" is not found,
1413 the last keyword is treated as the only DONE state of the sequence.
1415 The command \\[org-todo] cycles an entry through these states, and one
1416 additional state where no keyword is present. For details about this
1417 cycling, see the manual.
1419 TODO keywords and interpretation can also be set on a per-file basis with
1420 the special #+SEQ_TODO and #+TYP_TODO lines.
1422 Each keyword can optionally specify a character for fast state selection
1423 \(in combination with the variable `org-use-fast-todo-selection')
1424 and specifiers for state change logging, using the same syntax
1425 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1426 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1427 indicates to record a time stamp each time this state is selected.
1429 Each keyword may also specify if a timestamp or a note should be
1430 recorded when entering or leaving the state, by adding additional
1431 characters in the parenthesis after the keyword. This looks like this:
1432 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1433 record only the time of the state change. With X and Y being either
1434 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1435 Y when leaving the state if and only if the *target* state does not
1436 define X. You may omit any of the fast-selection key or X or /Y,
1437 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1439 For backward compatibility, this variable may also be just a list
1440 of keywords - in this case the interptetation (sequence or type) will be
1441 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1442 :group 'org-todo
1443 :group 'org-keywords
1444 :type '(choice
1445 (repeat :tag "Old syntax, just keywords"
1446 (string :tag "Keyword"))
1447 (repeat :tag "New syntax"
1448 (cons
1449 (choice
1450 :tag "Interpretation"
1451 (const :tag "Sequence (cycling hits every state)" sequence)
1452 (const :tag "Type (cycling directly to DONE)" type))
1453 (repeat
1454 (string :tag "Keyword"))))))
1456 (defvar org-todo-keywords-1 nil
1457 "All TODO and DONE keywords active in a buffer.")
1458 (make-variable-buffer-local 'org-todo-keywords-1)
1459 (defvar org-todo-keywords-for-agenda nil)
1460 (defvar org-done-keywords-for-agenda nil)
1461 (defvar org-todo-keyword-alist-for-agenda nil)
1462 (defvar org-tag-alist-for-agenda nil)
1463 (defvar org-agenda-contributing-files nil)
1464 (defvar org-not-done-keywords nil)
1465 (make-variable-buffer-local 'org-not-done-keywords)
1466 (defvar org-done-keywords nil)
1467 (make-variable-buffer-local 'org-done-keywords)
1468 (defvar org-todo-heads nil)
1469 (make-variable-buffer-local 'org-todo-heads)
1470 (defvar org-todo-sets nil)
1471 (make-variable-buffer-local 'org-todo-sets)
1472 (defvar org-todo-log-states nil)
1473 (make-variable-buffer-local 'org-todo-log-states)
1474 (defvar org-todo-kwd-alist nil)
1475 (make-variable-buffer-local 'org-todo-kwd-alist)
1476 (defvar org-todo-key-alist nil)
1477 (make-variable-buffer-local 'org-todo-key-alist)
1478 (defvar org-todo-key-trigger nil)
1479 (make-variable-buffer-local 'org-todo-key-trigger)
1481 (defcustom org-todo-interpretation 'sequence
1482 "Controls how TODO keywords are interpreted.
1483 This variable is in principle obsolete and is only used for
1484 backward compatibility, if the interpretation of todo keywords is
1485 not given already in `org-todo-keywords'. See that variable for
1486 more information."
1487 :group 'org-todo
1488 :group 'org-keywords
1489 :type '(choice (const sequence)
1490 (const type)))
1492 (defcustom org-use-fast-todo-selection 'prefix
1493 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1494 This variable describes if and under what circumstances the cycling
1495 mechanism for TODO keywords will be replaced by a single-key, direct
1496 selection scheme.
1498 When nil, fast selection is never used.
1500 When the symbol `prefix', it will be used when `org-todo' is called with
1501 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1502 in an agenda buffer.
1504 When t, fast selection is used by default. In this case, the prefix
1505 argument forces cycling instead.
1507 In all cases, the special interface is only used if access keys have actually
1508 been assigned by the user, i.e. if keywords in the configuration are followed
1509 by a letter in parenthesis, like TODO(t)."
1510 :group 'org-todo
1511 :type '(choice
1512 (const :tag "Never" nil)
1513 (const :tag "By default" t)
1514 (const :tag "Only with C-u C-c C-t" prefix)))
1516 (defcustom org-provide-todo-statistics t
1517 "Non-nil means, update todo statistics after insert and toggle.
1518 When this is set, todo statistics is updated in the parent of the current
1519 entry each time a todo state is changed."
1520 :group 'org-todo
1521 :type 'boolean)
1523 (defcustom org-after-todo-state-change-hook nil
1524 "Hook which is run after the state of a TODO item was changed.
1525 The new state (a string with a TODO keyword, or nil) is available in the
1526 Lisp variable `state'."
1527 :group 'org-todo
1528 :type 'hook)
1530 (defcustom org-todo-state-tags-triggers nil
1531 "Tag changes that should be triggered by TODO state changes.
1532 This is a list. Each entry is
1534 (state-change (tag . flag) .......)
1536 State-change can be a string with a state, and empty string to indicate the
1537 state that has no TODO keyword, or it can be one of the symbols `todo'
1538 or `done', meaning any not-done or done state, respectively."
1539 :group 'org-todo
1540 :group 'org-tags
1541 :type '(repeat
1542 (cons (choice :tag "When changing to"
1543 (const :tag "Not-done state" todo)
1544 (const :tag "Done state" done)
1545 (string :tag "State"))
1546 (repeat
1547 (cons :tag "Tag action"
1548 (string :tag "Tag")
1549 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1551 (defcustom org-log-done nil
1552 "Information to record when a task moves to the DONE state.
1554 Possible values are:
1556 nil Don't add anything, just change the keyword
1557 time Add a time stamp to the task
1558 note Prompt a closing note and add it with template `org-log-note-headings'
1560 This option can also be set with on a per-file-basis with
1562 #+STARTUP: nologdone
1563 #+STARTUP: logdone
1564 #+STARTUP: lognotedone
1566 You can have local logging settings for a subtree by setting the LOGGING
1567 property to one or more of these keywords."
1568 :group 'org-todo
1569 :group 'org-progress
1570 :type '(choice
1571 (const :tag "No logging" nil)
1572 (const :tag "Record CLOSED timestamp" time)
1573 (const :tag "Record CLOSED timestamp with closing note." note)))
1575 ;; Normalize old uses of org-log-done.
1576 (cond
1577 ((eq org-log-done t) (setq org-log-done 'time))
1578 ((and (listp org-log-done) (memq 'done org-log-done))
1579 (setq org-log-done 'note)))
1581 (defcustom org-log-note-clock-out nil
1582 "Non-nil means, record a note when clocking out of an item.
1583 This can also be configured on a per-file basis by adding one of
1584 the following lines anywhere in the buffer:
1586 #+STARTUP: lognoteclock-out
1587 #+STARTUP: nolognoteclock-out"
1588 :group 'org-todo
1589 :group 'org-progress
1590 :type 'boolean)
1592 (defcustom org-log-done-with-time t
1593 "Non-nil means, the CLOSED time stamp will contain date and time.
1594 When nil, only the date will be recorded."
1595 :group 'org-progress
1596 :type 'boolean)
1598 (defcustom org-log-note-headings
1599 '((done . "CLOSING NOTE %t")
1600 (state . "State %-12s %t")
1601 (note . "Note taken on %t")
1602 (clock-out . ""))
1603 "Headings for notes added to entries.
1604 The value is an alist, with the car being a symbol indicating the note
1605 context, and the cdr is the heading to be used. The heading may also be the
1606 empty string.
1607 %t in the heading will be replaced by a time stamp.
1608 %s will be replaced by the new TODO state, in double quotes.
1609 %u will be replaced by the user name.
1610 %U will be replaced by the full user name."
1611 :group 'org-todo
1612 :group 'org-progress
1613 :type '(list :greedy t
1614 (cons (const :tag "Heading when closing an item" done) string)
1615 (cons (const :tag
1616 "Heading when changing todo state (todo sequence only)"
1617 state) string)
1618 (cons (const :tag "Heading when just taking a note" note) string)
1619 (cons (const :tag "Heading when clocking out" clock-out) string)))
1621 (unless (assq 'note org-log-note-headings)
1622 (push '(note . "%t") org-log-note-headings))
1624 (defcustom org-log-state-notes-insert-after-drawers nil
1625 "Non-nil means, insert state change notes after any drawers in entry.
1626 Only the drawers that *immediately* follow the headline and the
1627 deadline/scheduled line are skipped.
1628 When nil, insert notes right after the heading and perhaps the line
1629 with deadline/scheduling if present."
1630 :group 'org-todo
1631 :group 'org-progress
1632 :type 'boolean)
1634 (defcustom org-log-states-order-reversed t
1635 "Non-nil means, the latest state change note will be directly after heading.
1636 When nil, the notes will be orderer according to time."
1637 :group 'org-todo
1638 :group 'org-progress
1639 :type 'boolean)
1641 (defcustom org-log-repeat 'time
1642 "Non-nil means, record moving through the DONE state when triggering repeat.
1643 An auto-repeating tasks is immediately switched back to TODO when marked
1644 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1645 the TODO keyword definition, or recording a closing note by setting
1646 `org-log-done', there will be no record of the task moving through DONE.
1647 This variable forces taking a note anyway. Possible values are:
1649 nil Don't force a record
1650 time Record a time stamp
1651 note Record a note
1653 This option can also be set with on a per-file-basis with
1655 #+STARTUP: logrepeat
1656 #+STARTUP: lognoterepeat
1657 #+STARTUP: nologrepeat
1659 You can have local logging settings for a subtree by setting the LOGGING
1660 property to one or more of these keywords."
1661 :group 'org-todo
1662 :group 'org-progress
1663 :type '(choice
1664 (const :tag "Don't force a record" nil)
1665 (const :tag "Force recording the DONE state" time)
1666 (const :tag "Force recording a note with the DONE state" note)))
1669 (defgroup org-priorities nil
1670 "Priorities in Org-mode."
1671 :tag "Org Priorities"
1672 :group 'org-todo)
1674 (defcustom org-highest-priority ?A
1675 "The highest priority of TODO items. A character like ?A, ?B etc.
1676 Must have a smaller ASCII number than `org-lowest-priority'."
1677 :group 'org-priorities
1678 :type 'character)
1680 (defcustom org-lowest-priority ?C
1681 "The lowest priority of TODO items. A character like ?A, ?B etc.
1682 Must have a larger ASCII number than `org-highest-priority'."
1683 :group 'org-priorities
1684 :type 'character)
1686 (defcustom org-default-priority ?B
1687 "The default priority of TODO items.
1688 This is the priority an item get if no explicit priority is given."
1689 :group 'org-priorities
1690 :type 'character)
1692 (defcustom org-priority-start-cycle-with-default t
1693 "Non-nil means, start with default priority when starting to cycle.
1694 When this is nil, the first step in the cycle will be (depending on the
1695 command used) one higher or lower that the default priority."
1696 :group 'org-priorities
1697 :type 'boolean)
1699 (defgroup org-time nil
1700 "Options concerning time stamps and deadlines in Org-mode."
1701 :tag "Org Time"
1702 :group 'org)
1704 (defcustom org-insert-labeled-timestamps-at-point nil
1705 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1706 When nil, these labeled time stamps are forces into the second line of an
1707 entry, just after the headline. When scheduling from the global TODO list,
1708 the time stamp will always be forced into the second line."
1709 :group 'org-time
1710 :type 'boolean)
1712 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1713 "Formats for `format-time-string' which are used for time stamps.
1714 It is not recommended to change this constant.")
1716 (defcustom org-time-stamp-rounding-minutes '(0 5)
1717 "Number of minutes to round time stamps to.
1718 These are two values, the first applies when first creating a time stamp.
1719 The second applies when changing it with the commands `S-up' and `S-down'.
1720 When changing the time stamp, this means that it will change in steps
1721 of N minutes, as given by the second value.
1723 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1724 numbers should be factors of 60, so for example 5, 10, 15.
1726 When this is larger than 1, you can still force an exact time-stamp by using
1727 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1728 and by using a prefix arg to `S-up/down' to specify the exact number
1729 of minutes to shift."
1730 :group 'org-time
1731 :get '(lambda (var) ; Make sure all entries have 5 elements
1732 (if (integerp (default-value var))
1733 (list (default-value var) 5)
1734 (default-value var)))
1735 :type '(list
1736 (integer :tag "when inserting times")
1737 (integer :tag "when modifying times")))
1739 ;; Normalize old customizations of this variable.
1740 (when (integerp org-time-stamp-rounding-minutes)
1741 (setq org-time-stamp-rounding-minutes
1742 (list org-time-stamp-rounding-minutes
1743 org-time-stamp-rounding-minutes)))
1745 (defcustom org-display-custom-times nil
1746 "Non-nil means, overlay custom formats over all time stamps.
1747 The formats are defined through the variable `org-time-stamp-custom-formats'.
1748 To turn this on on a per-file basis, insert anywhere in the file:
1749 #+STARTUP: customtime"
1750 :group 'org-time
1751 :set 'set-default
1752 :type 'sexp)
1753 (make-variable-buffer-local 'org-display-custom-times)
1755 (defcustom org-time-stamp-custom-formats
1756 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1757 "Custom formats for time stamps. See `format-time-string' for the syntax.
1758 These are overlayed over the default ISO format if the variable
1759 `org-display-custom-times' is set. Time like %H:%M should be at the
1760 end of the second format."
1761 :group 'org-time
1762 :type 'sexp)
1764 (defun org-time-stamp-format (&optional long inactive)
1765 "Get the right format for a time string."
1766 (let ((f (if long (cdr org-time-stamp-formats)
1767 (car org-time-stamp-formats))))
1768 (if inactive
1769 (concat "[" (substring f 1 -1) "]")
1770 f)))
1772 (defcustom org-time-clocksum-format "%d:%02d"
1773 "The format string used when creating CLOCKSUM lines, or when
1774 org-mode generates a time duration."
1775 :group 'org-time
1776 :type 'string)
1778 (defcustom org-deadline-warning-days 14
1779 "No. of days before expiration during which a deadline becomes active.
1780 This variable governs the display in sparse trees and in the agenda.
1781 When 0 or negative, it means use this number (the absolute value of it)
1782 even if a deadline has a different individual lead time specified."
1783 :group 'org-time
1784 :group 'org-agenda-daily/weekly
1785 :type 'number)
1787 (defcustom org-read-date-prefer-future t
1788 "Non-nil means, assume future for incomplete date input from user.
1789 This affects the following situations:
1790 1. The user gives a day, but no month.
1791 For example, if today is the 15th, and you enter \"3\", Org-mode will
1792 read this as the third of *next* month. However, if you enter \"17\",
1793 it will be considered as *this* month.
1794 2. The user gives a month but not a year.
1795 For example, if it is april and you enter \"feb 2\", this will be read
1796 as feb 2, *next* year. \"May 5\", however, will be this year.
1798 Currently this does not work for ISO week specifications.
1800 When this option is nil, the current month and year will always be used
1801 as defaults."
1802 :group 'org-time
1803 :type 'boolean)
1805 (defcustom org-read-date-display-live t
1806 "Non-nil means, display current interpretation of date prompt live.
1807 This display will be in an overlay, in the minibuffer."
1808 :group 'org-time
1809 :type 'boolean)
1811 (defcustom org-read-date-popup-calendar t
1812 "Non-nil means, pop up a calendar when prompting for a date.
1813 In the calendar, the date can be selected with mouse-1. However, the
1814 minibuffer will also be active, and you can simply enter the date as well.
1815 When nil, only the minibuffer will be available."
1816 :group 'org-time
1817 :type 'boolean)
1818 (if (fboundp 'defvaralias)
1819 (defvaralias 'org-popup-calendar-for-date-prompt
1820 'org-read-date-popup-calendar))
1822 (defcustom org-extend-today-until 0
1823 "The hour when your day really ends. Must be an integer.
1824 This has influence for the following applications:
1825 - When switching the agenda to \"today\". It it is still earlier than
1826 the time given here, the day recognized as TODAY is actually yesterday.
1827 - When a date is read from the user and it is still before the time given
1828 here, the current date and time will be assumed to be yesterday, 23:59.
1829 Also, timestamps inserted in remember templates follow this rule.
1831 IMPORTANT: This is a feature whose implementation is and likely will
1832 remain incomplete. Really, it is only here because past midnight seems to
1833 be the favorite working time of John Wiegley :-)"
1834 :group 'org-time
1835 :type 'number)
1837 (defcustom org-edit-timestamp-down-means-later nil
1838 "Non-nil means, S-down will increase the time in a time stamp.
1839 When nil, S-up will increase."
1840 :group 'org-time
1841 :type 'boolean)
1843 (defcustom org-calendar-follow-timestamp-change t
1844 "Non-nil means, make the calendar window follow timestamp changes.
1845 When a timestamp is modified and the calendar window is visible, it will be
1846 moved to the new date."
1847 :group 'org-time
1848 :type 'boolean)
1850 (defgroup org-tags nil
1851 "Options concerning tags in Org-mode."
1852 :tag "Org Tags"
1853 :group 'org)
1855 (defcustom org-tag-alist nil
1856 "List of tags allowed in Org-mode files.
1857 When this list is nil, Org-mode will base TAG input on what is already in the
1858 buffer.
1859 The value of this variable is an alist, the car of each entry must be a
1860 keyword as a string, the cdr may be a character that is used to select
1861 that tag through the fast-tag-selection interface.
1862 See the manual for details."
1863 :group 'org-tags
1864 :type '(repeat
1865 (choice
1866 (cons (string :tag "Tag name")
1867 (character :tag "Access char"))
1868 (const :tag "Start radio group" (:startgroup))
1869 (const :tag "End radio group" (:endgroup)))))
1871 (defvar org-file-tags nil
1872 "List of tags that can be inherited by all entries in the file.
1873 The tags will be inherited if the variable `org-use-tag-inheritance'
1874 says they should be.
1875 This variable is populated from #+TAG lines.")
1877 (defcustom org-use-fast-tag-selection 'auto
1878 "Non-nil means, use fast tag selection scheme.
1879 This is a special interface to select and deselect tags with single keys.
1880 When nil, fast selection is never used.
1881 When the symbol `auto', fast selection is used if and only if selection
1882 characters for tags have been configured, either through the variable
1883 `org-tag-alist' or through a #+TAGS line in the buffer.
1884 When t, fast selection is always used and selection keys are assigned
1885 automatically if necessary."
1886 :group 'org-tags
1887 :type '(choice
1888 (const :tag "Always" t)
1889 (const :tag "Never" nil)
1890 (const :tag "When selection characters are configured" 'auto)))
1892 (defcustom org-fast-tag-selection-single-key nil
1893 "Non-nil means, fast tag selection exits after first change.
1894 When nil, you have to press RET to exit it.
1895 During fast tag selection, you can toggle this flag with `C-c'.
1896 This variable can also have the value `expert'. In this case, the window
1897 displaying the tags menu is not even shown, until you press C-c again."
1898 :group 'org-tags
1899 :type '(choice
1900 (const :tag "No" nil)
1901 (const :tag "Yes" t)
1902 (const :tag "Expert" expert)))
1904 (defvar org-fast-tag-selection-include-todo nil
1905 "Non-nil means, fast tags selection interface will also offer TODO states.
1906 This is an undocumented feature, you should not rely on it.")
1908 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1909 "The column to which tags should be indented in a headline.
1910 If this number is positive, it specifies the column. If it is negative,
1911 it means that the tags should be flushright to that column. For example,
1912 -80 works well for a normal 80 character screen."
1913 :group 'org-tags
1914 :type 'integer)
1916 (defcustom org-auto-align-tags t
1917 "Non-nil means, realign tags after pro/demotion of TODO state change.
1918 These operations change the length of a headline and therefore shift
1919 the tags around. With this options turned on, after each such operation
1920 the tags are again aligned to `org-tags-column'."
1921 :group 'org-tags
1922 :type 'boolean)
1924 (defcustom org-use-tag-inheritance t
1925 "Non-nil means, tags in levels apply also for sublevels.
1926 When nil, only the tags directly given in a specific line apply there.
1927 This may also be a list of tags that should be inherited, or a regexp that
1928 matches tags that should be inherited. Additional control is possible
1929 with the variable `org-tags-exclude-from-inheritance' which gives an
1930 explicit list of tags to be excluded from inheritance., even if the value of
1931 `org-use-tag-inheritance' would select it for inheritance.
1933 If this option is t, a match early-on in a tree can lead to a large
1934 number of matches in the subtree when constructing the agenda or creating
1935 a sparse tree. If you only want to see the first match in a tree during
1936 a search, check out the variable `org-tags-match-list-sublevels'."
1937 :group 'org-tags
1938 :type '(choice
1939 (const :tag "Not" nil)
1940 (const :tag "Always" t)
1941 (repeat :tag "Specific tags" (string :tag "Tag"))
1942 (regexp :tag "Tags matched by regexp")))
1944 (defcustom org-tags-exclude-from-inheritance nil
1945 "List of tags that should never be inherited.
1946 This is a way to exclude a few tags from inheritance. For way to do
1947 the opposite, to actively allow inheritance for selected tags,
1948 see the variable `org-use-tag-inheritance'."
1949 :group 'org-tags
1950 :type '(repeat (string :tag "Tag")))
1952 (defun org-tag-inherit-p (tag)
1953 "Check if TAG is one that should be inherited."
1954 (cond
1955 ((member tag org-tags-exclude-from-inheritance) nil)
1956 ((eq org-use-tag-inheritance t) t)
1957 ((not org-use-tag-inheritance) nil)
1958 ((stringp org-use-tag-inheritance)
1959 (string-match org-use-tag-inheritance tag))
1960 ((listp org-use-tag-inheritance)
1961 (member tag org-use-tag-inheritance))
1962 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1964 (defcustom org-tags-match-list-sublevels t
1965 "Non-nil means list also sublevels of headlines matching tag search.
1966 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1967 the sublevels of a headline matching a tag search often also match
1968 the same search. Listing all of them can create very long lists.
1969 Setting this variable to nil causes subtrees of a match to be skipped.
1970 This option is off by default, because inheritance in on. If you turn
1971 inheritance off, you very likely want to turn this option on.
1973 As a special case, if the tag search is restricted to TODO items, the
1974 value of this variable is ignored and sublevels are always checked, to
1975 make sure all corresponding TODO items find their way into the list.
1977 This variable is semi-obsolete and probably should always be true. It
1978 is better to limit inheritance to certain tags using the variables
1979 `org-use-tag-inheritanc'e and `org-tags-exclude-from-inheritance'."
1980 :group 'org-tags
1981 :type 'boolean)
1983 (defvar org-tags-history nil
1984 "History of minibuffer reads for tags.")
1985 (defvar org-last-tags-completion-table nil
1986 "The last used completion table for tags.")
1987 (defvar org-after-tags-change-hook nil
1988 "Hook that is run after the tags in a line have changed.")
1990 (defgroup org-properties nil
1991 "Options concerning properties in Org-mode."
1992 :tag "Org Properties"
1993 :group 'org)
1995 (defcustom org-property-format "%-10s %s"
1996 "How property key/value pairs should be formatted by `indent-line'.
1997 When `indent-line' hits a property definition, it will format the line
1998 according to this format, mainly to make sure that the values are
1999 lined-up with respect to each other."
2000 :group 'org-properties
2001 :type 'string)
2003 (defcustom org-use-property-inheritance nil
2004 "Non-nil means, properties apply also for sublevels.
2006 This setting is chiefly used during property searches. Turning it on can
2007 cause significant overhead when doing a search, which is why it is not
2008 on by default.
2010 When nil, only the properties directly given in the current entry count.
2011 When t, every property is inherited. The value may also be a list of
2012 properties that should have inheritance, or a regular expression matching
2013 properties that should be inherited.
2015 However, note that some special properties use inheritance under special
2016 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2017 and the properties ending in \"_ALL\" when they are used as descriptor
2018 for valid values of a property.
2020 Note for programmers:
2021 When querying an entry with `org-entry-get', you can control if inheritance
2022 should be used. By default, `org-entry-get' looks only at the local
2023 properties. You can request inheritance by setting the inherit argument
2024 to t (to force inheritance) or to `selective' (to respect the setting
2025 in this variable)."
2026 :group 'org-properties
2027 :type '(choice
2028 (const :tag "Not" nil)
2029 (const :tag "Always" t)
2030 (repeat :tag "Specific properties" (string :tag "Property"))
2031 (regexp :tag "Properties matched by regexp")))
2033 (defun org-property-inherit-p (property)
2034 "Check if PROPERTY is one that should be inherited."
2035 (cond
2036 ((eq org-use-property-inheritance t) t)
2037 ((not org-use-property-inheritance) nil)
2038 ((stringp org-use-property-inheritance)
2039 (string-match org-use-property-inheritance property))
2040 ((listp org-use-property-inheritance)
2041 (member property org-use-property-inheritance))
2042 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2044 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2045 "The default column format, if no other format has been defined.
2046 This variable can be set on the per-file basis by inserting a line
2048 #+COLUMNS: %25ITEM ....."
2049 :group 'org-properties
2050 :type 'string)
2052 (defcustom org-columns-ellipses ".."
2053 "The ellipses to be used when a field in column view is truncated.
2054 When this is the empty string, as many characters as possible are shown,
2055 but then there will be no visual indication that the field has been truncated.
2056 When this is a string of length N, the last N characters of a truncated
2057 field are replaced by this string. If the column is narrower than the
2058 ellipses string, only part of the ellipses string will be shown."
2059 :group 'org-properties
2060 :type 'string)
2062 (defcustom org-columns-modify-value-for-display-function nil
2063 "Function that modifies values for display in column view.
2064 For example, it can be used to cut out a certain part from a time stamp.
2065 The function must take 2 arguments:
2067 column-title The tite of the column (*not* the property name)
2068 value The value that should be modified.
2070 The function should return the value that should be displayed,
2071 or nil if the normal value should be used."
2072 :group 'org-properties
2073 :type 'function)
2075 (defcustom org-effort-property "Effort"
2076 "The property that is being used to keep track of effort estimates.
2077 Effort estimates given in this property need to have the format H:MM."
2078 :group 'org-properties
2079 :group 'org-progress
2080 :type '(string :tag "Property"))
2082 (defconst org-global-properties-fixed
2083 '(("VISIBILITY_ALL" . "folded children content all"))
2084 "List of property/value pairs that can be inherited by any entry.
2085 These are fixed values, for the preset properties.")
2088 (defcustom org-global-properties nil
2089 "List of property/value pairs that can be inherited by any entry.
2090 You can set buffer-local values for the same purpose in the variable
2091 `org-file-properties' this by adding lines like
2093 #+PROPERTY: NAME VALUE"
2094 :group 'org-properties
2095 :type '(repeat
2096 (cons (string :tag "Property")
2097 (string :tag "Value"))))
2099 (defvar org-file-properties nil
2100 "List of property/value pairs that can be inherited by any entry.
2101 Valid for the current buffer.
2102 This variable is populated from #+PROPERTY lines.")
2103 (make-variable-buffer-local 'org-file-properties)
2105 (defgroup org-agenda nil
2106 "Options concerning agenda views in Org-mode."
2107 :tag "Org Agenda"
2108 :group 'org)
2110 (defvar org-category nil
2111 "Variable used by org files to set a category for agenda display.
2112 Such files should use a file variable to set it, for example
2114 # -*- mode: org; org-category: \"ELisp\"
2116 or contain a special line
2118 #+CATEGORY: ELisp
2120 If the file does not specify a category, then file's base name
2121 is used instead.")
2122 (make-variable-buffer-local 'org-category)
2123 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2125 (defcustom org-agenda-files nil
2126 "The files to be used for agenda display.
2127 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2128 \\[org-remove-file]. You can also use customize to edit the list.
2130 If an entry is a directory, all files in that directory that are matched by
2131 `org-agenda-file-regexp' will be part of the file list.
2133 If the value of the variable is not a list but a single file name, then
2134 the list of agenda files is actually stored and maintained in that file, one
2135 agenda file per line."
2136 :group 'org-agenda
2137 :type '(choice
2138 (repeat :tag "List of files and directories" file)
2139 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2141 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2142 "Regular expression to match files for `org-agenda-files'.
2143 If any element in the list in that variable contains a directory instead
2144 of a normal file, all files in that directory that are matched by this
2145 regular expression will be included."
2146 :group 'org-agenda
2147 :type 'regexp)
2149 (defcustom org-agenda-text-search-extra-files nil
2150 "List of extra files to be searched by text search commands.
2151 These files will be search in addition to the agenda files by the
2152 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2153 Note that these files will only be searched for text search commands,
2154 not for the other agenda views like todo lists, tag searches or the weekly
2155 agenda. This variable is intended to list notes and possibly archive files
2156 that should also be searched by these two commands.
2157 In fact, if the first element in the list is the symbol `agenda-archives',
2158 than all archive files of all agenda files will be added to the search
2159 scope."
2160 :group 'org-agenda
2161 :type '(set :greedy t
2162 (const :tag "Agenda Archives" agenda-archives)
2163 (repeat :inline t (file))))
2165 (if (fboundp 'defvaralias)
2166 (defvaralias 'org-agenda-multi-occur-extra-files
2167 'org-agenda-text-search-extra-files))
2169 (defcustom org-agenda-skip-unavailable-files nil
2170 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2171 A nil value means to remove them, after a query, from the list."
2172 :group 'org-agenda
2173 :type 'boolean)
2175 (defcustom org-calendar-to-agenda-key [?c]
2176 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2177 The command `org-calendar-goto-agenda' will be bound to this key. The
2178 default is the character `c' because then `c' can be used to switch back and
2179 forth between agenda and calendar."
2180 :group 'org-agenda
2181 :type 'sexp)
2183 (defcustom org-calendar-agenda-action-key [?k]
2184 "The key to be installed in `calendar-mode-map' for agenda-action.
2185 The command `org-agenda-action' will be bound to this key. The
2186 default is the character `k' because we use the same key in the agenda."
2187 :group 'org-agenda
2188 :type 'sexp)
2190 (eval-after-load "calendar"
2191 '(progn
2192 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2193 'org-calendar-goto-agenda)
2194 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2195 'org-agenda-action)))
2197 (defgroup org-latex nil
2198 "Options for embedding LaTeX code into Org-mode."
2199 :tag "Org LaTeX"
2200 :group 'org)
2202 (defcustom org-format-latex-options
2203 '(:foreground default :background default :scale 1.0
2204 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2205 :matchers ("begin" "$" "$$" "\\(" "\\["))
2206 "Options for creating images from LaTeX fragments.
2207 This is a property list with the following properties:
2208 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2209 `default' means use the foreground of the default face.
2210 :background the background color, or \"Transparent\".
2211 `default' means use the background of the default face.
2212 :scale a scaling factor for the size of the images.
2213 :html-foreground, :html-background, :html-scale
2214 the same numbers for HTML export.
2215 :matchers a list indicating which matchers should be used to
2216 find LaTeX fragments. Valid members of this list are:
2217 \"begin\" find environments
2218 \"$\" find math expressions surrounded by $...$
2219 \"$$\" find math expressions surrounded by $$....$$
2220 \"\\(\" find math expressions surrounded by \\(...\\)
2221 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2222 :group 'org-latex
2223 :type 'plist)
2225 (defcustom org-format-latex-header "\\documentclass{article}
2226 \\usepackage{fullpage} % do not remove
2227 \\usepackage{amssymb}
2228 \\usepackage[usenames]{color}
2229 \\usepackage{amsmath}
2230 \\usepackage{latexsym}
2231 \\usepackage[mathscr]{eucal}
2232 \\pagestyle{empty} % do not remove"
2233 "The document header used for processing LaTeX fragments."
2234 :group 'org-latex
2235 :type 'string)
2238 (defgroup org-font-lock nil
2239 "Font-lock settings for highlighting in Org-mode."
2240 :tag "Org Font Lock"
2241 :group 'org)
2243 (defcustom org-level-color-stars-only nil
2244 "Non-nil means fontify only the stars in each headline.
2245 When nil, the entire headline is fontified.
2246 Changing it requires restart of `font-lock-mode' to become effective
2247 also in regions already fontified."
2248 :group 'org-font-lock
2249 :type 'boolean)
2251 (defcustom org-hide-leading-stars nil
2252 "Non-nil means, hide the first N-1 stars in a headline.
2253 This works by using the face `org-hide' for these stars. This
2254 face is white for a light background, and black for a dark
2255 background. You may have to customize the face `org-hide' to
2256 make this work.
2257 Changing it requires restart of `font-lock-mode' to become effective
2258 also in regions already fontified.
2259 You may also set this on a per-file basis by adding one of the following
2260 lines to the buffer:
2262 #+STARTUP: hidestars
2263 #+STARTUP: showstars"
2264 :group 'org-font-lock
2265 :type 'boolean)
2267 (defcustom org-fontify-done-headline nil
2268 "Non-nil means, change the face of a headline if it is marked DONE.
2269 Normally, only the TODO/DONE keyword indicates the state of a headline.
2270 When this is non-nil, the headline after the keyword is set to the
2271 `org-headline-done' as an additional indication."
2272 :group 'org-font-lock
2273 :type 'boolean)
2275 (defcustom org-fontify-emphasized-text t
2276 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2277 Changing this variable requires a restart of Emacs to take effect."
2278 :group 'org-font-lock
2279 :type 'boolean)
2281 (defcustom org-highlight-latex-fragments-and-specials nil
2282 "Non-nil means, fontify what is treated specially by the exporters."
2283 :group 'org-font-lock
2284 :type 'boolean)
2286 (defcustom org-hide-emphasis-markers nil
2287 "Non-nil mean font-lock should hide the emphasis marker characters."
2288 :group 'org-font-lock
2289 :type 'boolean)
2291 (defvar org-emph-re nil
2292 "Regular expression for matching emphasis.")
2293 (defvar org-verbatim-re nil
2294 "Regular expression for matching verbatim text.")
2295 (defvar org-emphasis-regexp-components) ; defined just below
2296 (defvar org-emphasis-alist) ; defined just below
2297 (defun org-set-emph-re (var val)
2298 "Set variable and compute the emphasis regular expression."
2299 (set var val)
2300 (when (and (boundp 'org-emphasis-alist)
2301 (boundp 'org-emphasis-regexp-components)
2302 org-emphasis-alist org-emphasis-regexp-components)
2303 (let* ((e org-emphasis-regexp-components)
2304 (pre (car e))
2305 (post (nth 1 e))
2306 (border (nth 2 e))
2307 (body (nth 3 e))
2308 (nl (nth 4 e))
2309 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2310 (body1 (concat body "*?"))
2311 (markers (mapconcat 'car org-emphasis-alist ""))
2312 (vmarkers (mapconcat
2313 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2314 org-emphasis-alist "")))
2315 ;; make sure special characters appear at the right position in the class
2316 (if (string-match "\\^" markers)
2317 (setq markers (concat (replace-match "" t t markers) "^")))
2318 (if (string-match "-" markers)
2319 (setq markers (concat (replace-match "" t t markers) "-")))
2320 (if (string-match "\\^" vmarkers)
2321 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2322 (if (string-match "-" vmarkers)
2323 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2324 (if (> nl 0)
2325 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2326 (int-to-string nl) "\\}")))
2327 ;; Make the regexp
2328 (setq org-emph-re
2329 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2330 "\\("
2331 "\\([" markers "]\\)"
2332 "\\("
2333 "[^" border "]\\|"
2334 "[^" border (if (and nil stacked) markers) "]"
2335 body1
2336 "[^" border (if (and nil stacked) markers) "]"
2337 "\\)"
2338 "\\3\\)"
2339 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2340 (setq org-verbatim-re
2341 (concat "\\([" pre "]\\|^\\)"
2342 "\\("
2343 "\\([" vmarkers "]\\)"
2344 "\\("
2345 "[^" border "]\\|"
2346 "[^" border "]"
2347 body1
2348 "[^" border "]"
2349 "\\)"
2350 "\\3\\)"
2351 "\\([" post "]\\|$\\)")))))
2353 (defcustom org-emphasis-regexp-components
2354 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2355 "Components used to build the regular expression for emphasis.
2356 This is a list with 6 entries. Terminology: In an emphasis string
2357 like \" *strong word* \", we call the initial space PREMATCH, the final
2358 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2359 and \"trong wor\" is the body. The different components in this variable
2360 specify what is allowed/forbidden in each part:
2362 pre Chars allowed as prematch. Beginning of line will be allowed too.
2363 post Chars allowed as postmatch. End of line will be allowed too.
2364 border The chars *forbidden* as border characters.
2365 body-regexp A regexp like \".\" to match a body character. Don't use
2366 non-shy groups here, and don't allow newline here.
2367 newline The maximum number of newlines allowed in an emphasis exp.
2369 Use customize to modify this, or restart Emacs after changing it."
2370 :group 'org-font-lock
2371 :set 'org-set-emph-re
2372 :type '(list
2373 (sexp :tag "Allowed chars in pre ")
2374 (sexp :tag "Allowed chars in post ")
2375 (sexp :tag "Forbidden chars in border ")
2376 (sexp :tag "Regexp for body ")
2377 (integer :tag "number of newlines allowed")
2378 (option (boolean :tag "Please ignore this button"))))
2380 (defcustom org-emphasis-alist
2381 `(("*" bold "<b>" "</b>")
2382 ("/" italic "<i>" "</i>")
2383 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2384 ("=" org-code "<code>" "</code>" verbatim)
2385 ("~" org-verbatim "<code>" "</code>" verbatim)
2386 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2387 "<del>" "</del>")
2389 "Special syntax for emphasized text.
2390 Text starting and ending with a special character will be emphasized, for
2391 example *bold*, _underlined_ and /italic/. This variable sets the marker
2392 characters, the face to be used by font-lock for highlighting in Org-mode
2393 Emacs buffers, and the HTML tags to be used for this.
2394 Use customize to modify this, or restart Emacs after changing it."
2395 :group 'org-font-lock
2396 :set 'org-set-emph-re
2397 :type '(repeat
2398 (list
2399 (string :tag "Marker character")
2400 (choice
2401 (face :tag "Font-lock-face")
2402 (plist :tag "Face property list"))
2403 (string :tag "HTML start tag")
2404 (string :tag "HTML end tag")
2405 (option (const verbatim)))))
2407 ;;; Miscellaneous options
2409 (defgroup org-completion nil
2410 "Completion in Org-mode."
2411 :tag "Org Completion"
2412 :group 'org)
2414 (defcustom org-completion-use-ido nil
2415 "Non-nil means, use ido completion wherever possible."
2416 :group 'org-completion
2417 :type 'boolean)
2419 (defcustom org-completion-fallback-command 'hippie-expand
2420 "The expansion command called by \\[org-complete] in normal context.
2421 Normal means, no org-mode-specific context."
2422 :group 'org-completion
2423 :type 'function)
2425 ;;; Functions and variables from ther packages
2426 ;; Declared here to avoid compiler warnings
2428 ;; XEmacs only
2429 (defvar outline-mode-menu-heading)
2430 (defvar outline-mode-menu-show)
2431 (defvar outline-mode-menu-hide)
2432 (defvar zmacs-regions) ; XEmacs regions
2434 ;; Emacs only
2435 (defvar mark-active)
2437 ;; Various packages
2438 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2439 (declare-function calendar-forward-day "cal-move" (arg))
2440 (declare-function calendar-goto-date "cal-move" (date))
2441 (declare-function calendar-goto-today "cal-move" ())
2442 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2443 (defvar calc-embedded-close-formula)
2444 (defvar calc-embedded-open-formula)
2445 (declare-function cdlatex-tab "ext:cdlatex" ())
2446 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2447 (defvar font-lock-unfontify-region-function)
2448 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2449 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2450 (defvar iswitchb-temp-buflist)
2451 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2452 (declare-function org-agenda-skip "org-agenda" ())
2453 (declare-function org-format-agenda-item "org-agenda"
2454 (extra txt &optional category tags dotime noprefix remove-re))
2455 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2456 (declare-function org-agenda-change-all-lines "org-agenda"
2457 (newhead hdmarker &optional fixface just-this))
2458 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2459 (declare-function org-agenda-maybe-redo "org-agenda" ())
2460 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2461 (beg end))
2462 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2463 (declare-function parse-time-string "parse-time" (string))
2464 (declare-function remember "remember" (&optional initial))
2465 (declare-function remember-buffer-desc "remember" ())
2466 (declare-function remember-finalize "remember" ())
2467 (defvar remember-save-after-remembering)
2468 (defvar remember-data-file)
2469 (defvar remember-register)
2470 (defvar remember-buffer)
2471 (defvar remember-handler-functions)
2472 (defvar remember-annotation-functions)
2473 (defvar texmathp-why)
2474 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2475 (declare-function table--at-cell-p "table" (position &optional object at-column))
2477 (defvar w3m-current-url)
2478 (defvar w3m-current-title)
2480 (defvar org-latex-regexps)
2482 ;;; Autoload and prepare some org modules
2484 ;; Some table stuff that needs to be defined here, because it is used
2485 ;; by the functions setting up org-mode or checking for table context.
2487 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2488 "Detects an org-type or table-type table.")
2489 (defconst org-table-line-regexp "^[ \t]*|"
2490 "Detects an org-type table line.")
2491 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2492 "Detects an org-type table line.")
2493 (defconst org-table-hline-regexp "^[ \t]*|-"
2494 "Detects an org-type table hline.")
2495 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2496 "Detects a table-type table hline.")
2497 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2498 "Searching from within a table (any type) this finds the first line
2499 outside the table.")
2501 ;; Autoload the functions in org-table.el that are needed by functions here.
2503 (eval-and-compile
2504 (org-autoload "org-table"
2505 '(org-table-align org-table-begin org-table-blank-field
2506 org-table-convert org-table-convert-region org-table-copy-down
2507 org-table-copy-region org-table-create
2508 org-table-create-or-convert-from-region
2509 org-table-create-with-table.el org-table-current-dline
2510 org-table-cut-region org-table-delete-column org-table-edit-field
2511 org-table-edit-formulas org-table-end org-table-eval-formula
2512 org-table-export org-table-field-info
2513 org-table-get-stored-formulas org-table-goto-column
2514 org-table-hline-and-move org-table-import org-table-insert-column
2515 org-table-insert-hline org-table-insert-row org-table-iterate
2516 org-table-justify-field-maybe org-table-kill-row
2517 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2518 org-table-move-column org-table-move-column-left
2519 org-table-move-column-right org-table-move-row
2520 org-table-move-row-down org-table-move-row-up
2521 org-table-next-field org-table-next-row org-table-paste-rectangle
2522 org-table-previous-field org-table-recalculate
2523 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2524 org-table-toggle-coordinate-overlays
2525 org-table-toggle-formula-debugger org-table-wrap-region
2526 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2528 (defun org-at-table-p (&optional table-type)
2529 "Return t if the cursor is inside an org-type table.
2530 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2531 (if org-enable-table-editor
2532 (save-excursion
2533 (beginning-of-line 1)
2534 (looking-at (if table-type org-table-any-line-regexp
2535 org-table-line-regexp)))
2536 nil))
2537 (defsubst org-table-p () (org-at-table-p))
2539 (defun org-at-table.el-p ()
2540 "Return t if and only if we are at a table.el table."
2541 (and (org-at-table-p 'any)
2542 (save-excursion
2543 (goto-char (org-table-begin 'any))
2544 (looking-at org-table1-hline-regexp))))
2545 (defun org-table-recognize-table.el ()
2546 "If there is a table.el table nearby, recognize it and move into it."
2547 (if org-table-tab-recognizes-table.el
2548 (if (org-at-table.el-p)
2549 (progn
2550 (beginning-of-line 1)
2551 (if (looking-at org-table-dataline-regexp)
2553 (if (looking-at org-table1-hline-regexp)
2554 (progn
2555 (beginning-of-line 2)
2556 (if (looking-at org-table-any-border-regexp)
2557 (beginning-of-line -1)))))
2558 (if (re-search-forward "|" (org-table-end t) t)
2559 (progn
2560 (require 'table)
2561 (if (table--at-cell-p (point))
2563 (message "recognizing table.el table...")
2564 (table-recognize-table)
2565 (message "recognizing table.el table...done")))
2566 (error "This should not happen..."))
2568 nil)
2569 nil))
2571 (defun org-at-table-hline-p ()
2572 "Return t if the cursor is inside a hline in a table."
2573 (if org-enable-table-editor
2574 (save-excursion
2575 (beginning-of-line 1)
2576 (looking-at org-table-hline-regexp))
2577 nil))
2579 (defvar org-table-clean-did-remove-column nil)
2581 (defun org-table-map-tables (function)
2582 "Apply FUNCTION to the start of all tables in the buffer."
2583 (save-excursion
2584 (save-restriction
2585 (widen)
2586 (goto-char (point-min))
2587 (while (re-search-forward org-table-any-line-regexp nil t)
2588 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2589 (beginning-of-line 1)
2590 (if (looking-at org-table-line-regexp)
2591 (save-excursion (funcall function)))
2592 (re-search-forward org-table-any-border-regexp nil 1))))
2593 (message "Mapping tables: done"))
2595 ;; Declare and autoload functions from org-exp.el
2597 (declare-function org-default-export-plist "org-exp")
2598 (declare-function org-infile-export-plist "org-exp")
2599 (declare-function org-get-current-options "org-exp")
2600 (eval-and-compile
2601 (org-autoload "org-exp"
2602 '(org-export org-export-as-ascii org-export-visible
2603 org-insert-export-options-template org-export-as-html-and-open
2604 org-export-as-html-batch org-export-as-html-to-buffer
2605 org-replace-region-by-html org-export-region-as-html
2606 org-export-as-html org-export-icalendar-this-file
2607 org-export-icalendar-all-agenda-files
2608 org-table-clean-before-export
2609 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2611 ;; Declare and autoload functions from org-agenda.el
2613 (eval-and-compile
2614 (org-autoload "org-agenda"
2615 '(org-agenda org-agenda-list org-search-view
2616 org-todo-list org-tags-view org-agenda-list-stuck-projects
2617 org-diary org-agenda-to-appt)))
2619 ;; Autoload org-remember
2621 (eval-and-compile
2622 (org-autoload "org-remember"
2623 '(org-remember-insinuate org-remember-annotation
2624 org-remember-apply-template org-remember org-remember-handler)))
2626 ;; Autoload org-clock.el
2629 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2630 (beg end))
2631 (declare-function org-update-mode-line "org-clock" ())
2632 (defvar org-clock-start-time)
2633 (defvar org-clock-marker (make-marker)
2634 "Marker recording the last clock-in.")
2636 (eval-and-compile
2637 (org-autoload
2638 "org-clock"
2639 '(org-clock-in org-clock-out org-clock-cancel
2640 org-clock-goto org-clock-sum org-clock-display
2641 org-remove-clock-overlays org-clock-report
2642 org-clocktable-shift org-dblock-write:clocktable
2643 org-get-clocktable)))
2645 (defun org-clock-update-time-maybe ()
2646 "If this is a CLOCK line, update it and return t.
2647 Otherwise, return nil."
2648 (interactive)
2649 (save-excursion
2650 (beginning-of-line 1)
2651 (skip-chars-forward " \t")
2652 (when (looking-at org-clock-string)
2653 (let ((re (concat "[ \t]*" org-clock-string
2654 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2655 "\\([ \t]*=>.*\\)?\\)?"))
2656 ts te h m s neg)
2657 (cond
2658 ((not (looking-at re))
2659 nil)
2660 ((not (match-end 2))
2661 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2662 (> org-clock-marker (point))
2663 (<= org-clock-marker (point-at-eol)))
2664 ;; The clock is running here
2665 (setq org-clock-start-time
2666 (apply 'encode-time
2667 (org-parse-time-string (match-string 1))))
2668 (org-update-mode-line)))
2670 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2671 (end-of-line 1)
2672 (setq ts (match-string 1)
2673 te (match-string 3))
2674 (setq s (- (time-to-seconds
2675 (apply 'encode-time (org-parse-time-string te)))
2676 (time-to-seconds
2677 (apply 'encode-time (org-parse-time-string ts))))
2678 neg (< s 0)
2679 s (abs s)
2680 h (floor (/ s 3600))
2681 s (- s (* 3600 h))
2682 m (floor (/ s 60))
2683 s (- s (* 60 s)))
2684 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2685 t))))))
2687 (defun org-check-running-clock ()
2688 "Check if the current buffer contains the running clock.
2689 If yes, offer to stop it and to save the buffer with the changes."
2690 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2691 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2692 (buffer-name))))
2693 (org-clock-out)
2694 (when (y-or-n-p "Save changed buffer?")
2695 (save-buffer))))
2697 (defun org-clocktable-try-shift (dir n)
2698 "Check if this line starts a clock table, if yes, shift the time block."
2699 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2700 (org-clocktable-shift dir n)))
2702 ;; Autoload org-timer.el
2704 ;(declare-function org-timer "org-timer")
2706 (eval-and-compile
2707 (org-autoload
2708 "org-timer"
2709 '(org-timer-start org-timer org-timer-item
2710 org-timer-change-times-in-region)))
2713 ;; Autoload archiving code
2714 ;; The stuff that is needed for cycling and tags has to be defined here.
2716 (defgroup org-archive nil
2717 "Options concerning archiving in Org-mode."
2718 :tag "Org Archive"
2719 :group 'org-structure)
2721 (defcustom org-archive-location "%s_archive::"
2722 "The location where subtrees should be archived.
2724 The value of this variable is a string, consisting of two parts,
2725 separated by a double-colon. The first part is a filename and
2726 the second part is a headline.
2728 When the filename is omitted, archiving happens in the same file.
2729 %s in the filename will be replaced by the current file
2730 name (without the directory part). Archiving to a different file
2731 is useful to keep archived entries from contributing to the
2732 Org-mode Agenda.
2734 The archived entries will be filed as subtrees of the specified
2735 headline. When the headline is omitted, the subtrees are simply
2736 filed away at the end of the file, as top-level entries.
2738 Here are a few examples:
2739 \"%s_archive::\"
2740 If the current file is Projects.org, archive in file
2741 Projects.org_archive, as top-level trees. This is the default.
2743 \"::* Archived Tasks\"
2744 Archive in the current file, under the top-level headline
2745 \"* Archived Tasks\".
2747 \"~/org/archive.org::\"
2748 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2750 \"basement::** Finished Tasks\"
2751 Archive in file ./basement (relative path), as level 3 trees
2752 below the level 2 heading \"** Finished Tasks\".
2754 You may set this option on a per-file basis by adding to the buffer a
2755 line like
2757 #+ARCHIVE: basement::** Finished Tasks
2759 You may also define it locally for a subtree by setting an ARCHIVE property
2760 in the entry. If such a property is found in an entry, or anywhere up
2761 the hierarchy, it will be used."
2762 :group 'org-archive
2763 :type 'string)
2765 (defcustom org-archive-tag "ARCHIVE"
2766 "The tag that marks a subtree as archived.
2767 An archived subtree does not open during visibility cycling, and does
2768 not contribute to the agenda listings.
2769 After changing this, font-lock must be restarted in the relevant buffers to
2770 get the proper fontification."
2771 :group 'org-archive
2772 :group 'org-keywords
2773 :type 'string)
2775 (defcustom org-agenda-skip-archived-trees t
2776 "Non-nil means, the agenda will skip any items located in archived trees.
2777 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2778 variable is no longer recommended, you should leave it at the value t.
2779 Instead, use the key `v' to cycle the archives-mode in the agenda."
2780 :group 'org-archive
2781 :group 'org-agenda-skip
2782 :type 'boolean)
2784 (defcustom org-cycle-open-archived-trees nil
2785 "Non-nil means, `org-cycle' will open archived trees.
2786 An archived tree is a tree marked with the tag ARCHIVE.
2787 When nil, archived trees will stay folded. You can still open them with
2788 normal outline commands like `show-all', but not with the cycling commands."
2789 :group 'org-archive
2790 :group 'org-cycle
2791 :type 'boolean)
2793 (defcustom org-sparse-tree-open-archived-trees nil
2794 "Non-nil means sparse tree construction shows matches in archived trees.
2795 When nil, matches in these trees are highlighted, but the trees are kept in
2796 collapsed state."
2797 :group 'org-archive
2798 :group 'org-sparse-trees
2799 :type 'boolean)
2801 (defun org-cycle-hide-archived-subtrees (state)
2802 "Re-hide all archived subtrees after a visibility state change."
2803 (when (and (not org-cycle-open-archived-trees)
2804 (not (memq state '(overview folded))))
2805 (save-excursion
2806 (let* ((globalp (memq state '(contents all)))
2807 (beg (if globalp (point-min) (point)))
2808 (end (if globalp (point-max) (org-end-of-subtree t))))
2809 (org-hide-archived-subtrees beg end)
2810 (goto-char beg)
2811 (if (looking-at (concat ".*:" org-archive-tag ":"))
2812 (message "%s" (substitute-command-keys
2813 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2815 (defun org-force-cycle-archived ()
2816 "Cycle subtree even if it is archived."
2817 (interactive)
2818 (setq this-command 'org-cycle)
2819 (let ((org-cycle-open-archived-trees t))
2820 (call-interactively 'org-cycle)))
2822 (defun org-hide-archived-subtrees (beg end)
2823 "Re-hide all archived subtrees after a visibility state change."
2824 (save-excursion
2825 (let* ((re (concat ":" org-archive-tag ":")))
2826 (goto-char beg)
2827 (while (re-search-forward re end t)
2828 (and (org-on-heading-p) (hide-subtree))
2829 (org-end-of-subtree t)))))
2831 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2833 (eval-and-compile
2834 (org-autoload "org-archive"
2835 '(org-add-archive-files org-archive-subtree
2836 org-archive-to-archive-sibling org-toggle-archive-tag)))
2838 ;; Autoload Column View Code
2840 (declare-function org-columns-number-to-string "org-colview")
2841 (declare-function org-columns-get-format-and-top-level "org-colview")
2842 (declare-function org-columns-compute "org-colview")
2844 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2845 '(org-columns-number-to-string org-columns-get-format-and-top-level
2846 org-columns-compute org-agenda-columns org-columns-remove-overlays
2847 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2849 ;; Autoload ID code
2851 (declare-function org-id-store-link "org-id")
2852 (org-autoload "org-id"
2853 '(org-id-get-create org-id-new org-id-copy org-id-get
2854 org-id-get-with-outline-path-completion
2855 org-id-get-with-outline-drilling
2856 org-id-goto org-id-find org-id-store-link))
2858 ;;; Variables for pre-computed regular expressions, all buffer local
2860 (defvar org-drawer-regexp nil
2861 "Matches first line of a hidden block.")
2862 (make-variable-buffer-local 'org-drawer-regexp)
2863 (defvar org-todo-regexp nil
2864 "Matches any of the TODO state keywords.")
2865 (make-variable-buffer-local 'org-todo-regexp)
2866 (defvar org-not-done-regexp nil
2867 "Matches any of the TODO state keywords except the last one.")
2868 (make-variable-buffer-local 'org-not-done-regexp)
2869 (defvar org-todo-line-regexp nil
2870 "Matches a headline and puts TODO state into group 2 if present.")
2871 (make-variable-buffer-local 'org-todo-line-regexp)
2872 (defvar org-complex-heading-regexp nil
2873 "Matches a headline and puts everything into groups:
2874 group 1: the stars
2875 group 2: The todo keyword, maybe
2876 group 3: Priority cookie
2877 group 4: True headline
2878 group 5: Tags")
2879 (make-variable-buffer-local 'org-complex-heading-regexp)
2880 (defvar org-todo-line-tags-regexp nil
2881 "Matches a headline and puts TODO state into group 2 if present.
2882 Also put tags into group 4 if tags are present.")
2883 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2884 (defvar org-nl-done-regexp nil
2885 "Matches newline followed by a headline with the DONE keyword.")
2886 (make-variable-buffer-local 'org-nl-done-regexp)
2887 (defvar org-looking-at-done-regexp nil
2888 "Matches the DONE keyword a point.")
2889 (make-variable-buffer-local 'org-looking-at-done-regexp)
2890 (defvar org-ds-keyword-length 12
2891 "Maximum length of the Deadline and SCHEDULED keywords.")
2892 (make-variable-buffer-local 'org-ds-keyword-length)
2893 (defvar org-deadline-regexp nil
2894 "Matches the DEADLINE keyword.")
2895 (make-variable-buffer-local 'org-deadline-regexp)
2896 (defvar org-deadline-time-regexp nil
2897 "Matches the DEADLINE keyword together with a time stamp.")
2898 (make-variable-buffer-local 'org-deadline-time-regexp)
2899 (defvar org-deadline-line-regexp nil
2900 "Matches the DEADLINE keyword and the rest of the line.")
2901 (make-variable-buffer-local 'org-deadline-line-regexp)
2902 (defvar org-scheduled-regexp nil
2903 "Matches the SCHEDULED keyword.")
2904 (make-variable-buffer-local 'org-scheduled-regexp)
2905 (defvar org-scheduled-time-regexp nil
2906 "Matches the SCHEDULED keyword together with a time stamp.")
2907 (make-variable-buffer-local 'org-scheduled-time-regexp)
2908 (defvar org-closed-time-regexp nil
2909 "Matches the CLOSED keyword together with a time stamp.")
2910 (make-variable-buffer-local 'org-closed-time-regexp)
2912 (defvar org-keyword-time-regexp nil
2913 "Matches any of the 4 keywords, together with the time stamp.")
2914 (make-variable-buffer-local 'org-keyword-time-regexp)
2915 (defvar org-keyword-time-not-clock-regexp nil
2916 "Matches any of the 3 keywords, together with the time stamp.")
2917 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2918 (defvar org-maybe-keyword-time-regexp nil
2919 "Matches a timestamp, possibly preceeded by a keyword.")
2920 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2921 (defvar org-planning-or-clock-line-re nil
2922 "Matches a line with planning or clock info.")
2923 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2925 (defconst org-plain-time-of-day-regexp
2926 (concat
2927 "\\(\\<[012]?[0-9]"
2928 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2929 "\\(--?"
2930 "\\(\\<[012]?[0-9]"
2931 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2932 "\\)?")
2933 "Regular expression to match a plain time or time range.
2934 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2935 groups carry important information:
2936 0 the full match
2937 1 the first time, range or not
2938 8 the second time, if it is a range.")
2940 (defconst org-plain-time-extension-regexp
2941 (concat
2942 "\\(\\<[012]?[0-9]"
2943 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2944 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2945 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2946 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2947 groups carry important information:
2948 0 the full match
2949 7 hours of duration
2950 9 minutes of duration")
2952 (defconst org-stamp-time-of-day-regexp
2953 (concat
2954 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2955 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2956 "\\(--?"
2957 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2958 "Regular expression to match a timestamp time or time range.
2959 After a match, the following groups carry important information:
2960 0 the full match
2961 1 date plus weekday, for backreferencing to make sure both times on same day
2962 2 the first time, range or not
2963 4 the second time, if it is a range.")
2965 (defconst org-startup-options
2966 '(("fold" org-startup-folded t)
2967 ("overview" org-startup-folded t)
2968 ("nofold" org-startup-folded nil)
2969 ("showall" org-startup-folded nil)
2970 ("content" org-startup-folded content)
2971 ("hidestars" org-hide-leading-stars t)
2972 ("showstars" org-hide-leading-stars nil)
2973 ("odd" org-odd-levels-only t)
2974 ("oddeven" org-odd-levels-only nil)
2975 ("align" org-startup-align-all-tables t)
2976 ("noalign" org-startup-align-all-tables nil)
2977 ("customtime" org-display-custom-times t)
2978 ("logdone" org-log-done time)
2979 ("lognotedone" org-log-done note)
2980 ("nologdone" org-log-done nil)
2981 ("lognoteclock-out" org-log-note-clock-out t)
2982 ("nolognoteclock-out" org-log-note-clock-out nil)
2983 ("logrepeat" org-log-repeat state)
2984 ("lognoterepeat" org-log-repeat note)
2985 ("nologrepeat" org-log-repeat nil)
2986 ("constcgs" constants-unit-system cgs)
2987 ("constSI" constants-unit-system SI))
2988 "Variable associated with STARTUP options for org-mode.
2989 Each element is a list of three items: The startup options as written
2990 in the #+STARTUP line, the corresponding variable, and the value to
2991 set this variable to if the option is found. An optional forth element PUSH
2992 means to push this value onto the list in the variable.")
2994 (defun org-set-regexps-and-options ()
2995 "Precompute regular expressions for current buffer."
2996 (when (org-mode-p)
2997 (org-set-local 'org-todo-kwd-alist nil)
2998 (org-set-local 'org-todo-key-alist nil)
2999 (org-set-local 'org-todo-key-trigger nil)
3000 (org-set-local 'org-todo-keywords-1 nil)
3001 (org-set-local 'org-done-keywords nil)
3002 (org-set-local 'org-todo-heads nil)
3003 (org-set-local 'org-todo-sets nil)
3004 (org-set-local 'org-todo-log-states nil)
3005 (org-set-local 'org-file-properties nil)
3006 (org-set-local 'org-file-tags nil)
3007 (let ((re (org-make-options-regexp
3008 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3009 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3010 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3011 (splitre "[ \t]+")
3012 kwds kws0 kwsa key log value cat arch tags const links hw dws
3013 tail sep kws1 prio props ftags drawers
3014 ext-setup-or-nil setup-contents (start 0))
3015 (save-excursion
3016 (save-restriction
3017 (widen)
3018 (goto-char (point-min))
3019 (while (or (and ext-setup-or-nil
3020 (string-match re ext-setup-or-nil start)
3021 (setq start (match-end 0)))
3022 (and (setq ext-setup-or-nil nil start 0)
3023 (re-search-forward re nil t)))
3024 (setq key (upcase (match-string 1 ext-setup-or-nil))
3025 value (org-match-string-no-properties 2 ext-setup-or-nil))
3026 (cond
3027 ((equal key "CATEGORY")
3028 (if (string-match "[ \t]+$" value)
3029 (setq value (replace-match "" t t value)))
3030 (setq cat value))
3031 ((member key '("SEQ_TODO" "TODO"))
3032 (push (cons 'sequence (org-split-string value splitre)) kwds))
3033 ((equal key "TYP_TODO")
3034 (push (cons 'type (org-split-string value splitre)) kwds))
3035 ((equal key "TAGS")
3036 (setq tags (append tags (org-split-string value splitre))))
3037 ((equal key "COLUMNS")
3038 (org-set-local 'org-columns-default-format value))
3039 ((equal key "LINK")
3040 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3041 (push (cons (match-string 1 value)
3042 (org-trim (match-string 2 value)))
3043 links)))
3044 ((equal key "PRIORITIES")
3045 (setq prio (org-split-string value " +")))
3046 ((equal key "PROPERTY")
3047 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3048 (push (cons (match-string 1 value) (match-string 2 value))
3049 props)))
3050 ((equal key "FILETAGS")
3051 (when (string-match "\\S-" value)
3052 (setq ftags
3053 (append
3054 ftags
3055 (apply 'append
3056 (mapcar (lambda (x) (org-split-string x ":"))
3057 (org-split-string value)))))))
3058 ((equal key "DRAWERS")
3059 (setq drawers (org-split-string value splitre)))
3060 ((equal key "CONSTANTS")
3061 (setq const (append const (org-split-string value splitre))))
3062 ((equal key "STARTUP")
3063 (let ((opts (org-split-string value splitre))
3064 l var val)
3065 (while (setq l (pop opts))
3066 (when (setq l (assoc l org-startup-options))
3067 (setq var (nth 1 l) val (nth 2 l))
3068 (if (not (nth 3 l))
3069 (set (make-local-variable var) val)
3070 (if (not (listp (symbol-value var)))
3071 (set (make-local-variable var) nil))
3072 (set (make-local-variable var) (symbol-value var))
3073 (add-to-list var val))))))
3074 ((equal key "ARCHIVE")
3075 (string-match " *$" value)
3076 (setq arch (replace-match "" t t value))
3077 (remove-text-properties 0 (length arch)
3078 '(face t fontified t) arch))
3079 ((equal key "SETUPFILE")
3080 (setq setup-contents (org-file-contents
3081 (expand-file-name
3082 (org-remove-double-quotes value))
3083 'noerror))
3084 (if (not ext-setup-or-nil)
3085 (setq ext-setup-or-nil setup-contents start 0)
3086 (setq ext-setup-or-nil
3087 (concat (substring ext-setup-or-nil 0 start)
3088 "\n" setup-contents "\n"
3089 (substring ext-setup-or-nil start)))))
3090 ))))
3091 (when cat
3092 (org-set-local 'org-category (intern cat))
3093 (push (cons "CATEGORY" cat) props))
3094 (when prio
3095 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3096 (setq prio (mapcar 'string-to-char prio))
3097 (org-set-local 'org-highest-priority (nth 0 prio))
3098 (org-set-local 'org-lowest-priority (nth 1 prio))
3099 (org-set-local 'org-default-priority (nth 2 prio)))
3100 (and props (org-set-local 'org-file-properties (nreverse props)))
3101 (and ftags (org-set-local 'org-file-tags ftags))
3102 (and drawers (org-set-local 'org-drawers drawers))
3103 (and arch (org-set-local 'org-archive-location arch))
3104 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3105 ;; Process the TODO keywords
3106 (unless kwds
3107 ;; Use the global values as if they had been given locally.
3108 (setq kwds (default-value 'org-todo-keywords))
3109 (if (stringp (car kwds))
3110 (setq kwds (list (cons org-todo-interpretation
3111 (default-value 'org-todo-keywords)))))
3112 (setq kwds (reverse kwds)))
3113 (setq kwds (nreverse kwds))
3114 (let (inter kws kw)
3115 (while (setq kws (pop kwds))
3116 (setq inter (pop kws) sep (member "|" kws)
3117 kws0 (delete "|" (copy-sequence kws))
3118 kwsa nil
3119 kws1 (mapcar
3120 (lambda (x)
3121 ;; 1 2
3122 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3123 (progn
3124 (setq kw (match-string 1 x)
3125 key (and (match-end 2) (match-string 2 x))
3126 log (org-extract-log-state-settings x))
3127 (push (cons kw (and key (string-to-char key))) kwsa)
3128 (and log (push log org-todo-log-states))
3130 (error "Invalid TODO keyword %s" x)))
3131 kws0)
3132 kwsa (if kwsa (append '((:startgroup))
3133 (nreverse kwsa)
3134 '((:endgroup))))
3135 hw (car kws1)
3136 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3137 tail (list inter hw (car dws) (org-last dws)))
3138 (add-to-list 'org-todo-heads hw 'append)
3139 (push kws1 org-todo-sets)
3140 (setq org-done-keywords (append org-done-keywords dws nil))
3141 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3142 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3143 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3144 (setq org-todo-sets (nreverse org-todo-sets)
3145 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3146 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3147 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3148 ;; Process the constants
3149 (when const
3150 (let (e cst)
3151 (while (setq e (pop const))
3152 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3153 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3154 (setq org-table-formula-constants-local cst)))
3156 ;; Process the tags.
3157 (when tags
3158 (let (e tgs)
3159 (while (setq e (pop tags))
3160 (cond
3161 ((equal e "{") (push '(:startgroup) tgs))
3162 ((equal e "}") (push '(:endgroup) tgs))
3163 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3164 (push (cons (match-string 1 e)
3165 (string-to-char (match-string 2 e)))
3166 tgs))
3167 (t (push (list e) tgs))))
3168 (org-set-local 'org-tag-alist nil)
3169 (while (setq e (pop tgs))
3170 (or (and (stringp (car e))
3171 (assoc (car e) org-tag-alist))
3172 (push e org-tag-alist)))))
3174 ;; Compute the regular expressions and other local variables
3175 (if (not org-done-keywords)
3176 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3177 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3178 (length org-scheduled-string)
3179 (length org-clock-string)
3180 (length org-closed-string)))
3181 org-drawer-regexp
3182 (concat "^[ \t]*:\\("
3183 (mapconcat 'regexp-quote org-drawers "\\|")
3184 "\\):[ \t]*$")
3185 org-not-done-keywords
3186 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3187 org-todo-regexp
3188 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3189 "\\|") "\\)\\>")
3190 org-not-done-regexp
3191 (concat "\\<\\("
3192 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3193 "\\)\\>")
3194 org-todo-line-regexp
3195 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3196 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3197 "\\)\\>\\)?[ \t]*\\(.*\\)")
3198 org-complex-heading-regexp
3199 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3200 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3201 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3202 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3203 org-nl-done-regexp
3204 (concat "\n\\*+[ \t]+"
3205 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3206 "\\)" "\\>")
3207 org-todo-line-tags-regexp
3208 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3209 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3210 (org-re
3211 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3212 org-looking-at-done-regexp
3213 (concat "^" "\\(?:"
3214 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3215 "\\>")
3216 org-deadline-regexp (concat "\\<" org-deadline-string)
3217 org-deadline-time-regexp
3218 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3219 org-deadline-line-regexp
3220 (concat "\\<\\(" org-deadline-string "\\).*")
3221 org-scheduled-regexp
3222 (concat "\\<" org-scheduled-string)
3223 org-scheduled-time-regexp
3224 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3225 org-closed-time-regexp
3226 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3227 org-keyword-time-regexp
3228 (concat "\\<\\(" org-scheduled-string
3229 "\\|" org-deadline-string
3230 "\\|" org-closed-string
3231 "\\|" org-clock-string "\\)"
3232 " *[[<]\\([^]>]+\\)[]>]")
3233 org-keyword-time-not-clock-regexp
3234 (concat "\\<\\(" org-scheduled-string
3235 "\\|" org-deadline-string
3236 "\\|" org-closed-string
3237 "\\)"
3238 " *[[<]\\([^]>]+\\)[]>]")
3239 org-maybe-keyword-time-regexp
3240 (concat "\\(\\<\\(" org-scheduled-string
3241 "\\|" org-deadline-string
3242 "\\|" org-closed-string
3243 "\\|" org-clock-string "\\)\\)?"
3244 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3245 org-planning-or-clock-line-re
3246 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3247 "\\|" org-deadline-string
3248 "\\|" org-closed-string "\\|" org-clock-string
3249 "\\)\\>\\)")
3251 (org-compute-latex-and-specials-regexp)
3252 (org-set-font-lock-defaults))))
3254 (defun org-file-contents (file &optional noerror)
3255 "Return the contents of FILE, as a string."
3256 (if (or (not file)
3257 (not (file-readable-p file)))
3258 (if noerror
3259 (progn
3260 (message "Cannot read file %s" file)
3261 (ding) (sit-for 2)
3263 (error "Cannot read file %s" file))
3264 (with-temp-buffer
3265 (insert-file-contents file)
3266 (buffer-string))))
3268 (defun org-extract-log-state-settings (x)
3269 "Extract the log state setting from a TODO keyword string.
3270 This will extract info from a string like \"WAIT(w@/!)\"."
3271 (let (kw key log1 log2)
3272 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3273 (setq kw (match-string 1 x)
3274 key (and (match-end 2) (match-string 2 x))
3275 log1 (and (match-end 3) (match-string 3 x))
3276 log2 (and (match-end 4) (match-string 4 x)))
3277 (and (or log1 log2)
3278 (list kw
3279 (and log1 (if (equal log1 "!") 'time 'note))
3280 (and log2 (if (equal log2 "!") 'time 'note)))))))
3282 (defun org-remove-keyword-keys (list)
3283 "Remove a pair of parenthesis at the end of each string in LIST."
3284 (mapcar (lambda (x)
3285 (if (string-match "(.*)$" x)
3286 (substring x 0 (match-beginning 0))
3288 list))
3290 ;; FIXME: this could be done much better, using second characters etc.
3291 (defun org-assign-fast-keys (alist)
3292 "Assign fast keys to a keyword-key alist.
3293 Respect keys that are already there."
3294 (let (new e k c c1 c2 (char ?a))
3295 (while (setq e (pop alist))
3296 (cond
3297 ((equal e '(:startgroup)) (push e new))
3298 ((equal e '(:endgroup)) (push e new))
3300 (setq k (car e) c2 nil)
3301 (if (cdr e)
3302 (setq c (cdr e))
3303 ;; automatically assign a character.
3304 (setq c1 (string-to-char
3305 (downcase (substring
3306 k (if (= (string-to-char k) ?@) 1 0)))))
3307 (if (or (rassoc c1 new) (rassoc c1 alist))
3308 (while (or (rassoc char new) (rassoc char alist))
3309 (setq char (1+ char)))
3310 (setq c2 c1))
3311 (setq c (or c2 char)))
3312 (push (cons k c) new))))
3313 (nreverse new)))
3315 ;;; Some variables used in various places
3317 (defvar org-window-configuration nil
3318 "Used in various places to store a window configuration.")
3319 (defvar org-finish-function nil
3320 "Function to be called when `C-c C-c' is used.
3321 This is for getting out of special buffers like remember.")
3324 ;; FIXME: Occasionally check by commenting these, to make sure
3325 ;; no other functions uses these, forgetting to let-bind them.
3326 (defvar entry)
3327 (defvar state)
3328 (defvar last-state)
3329 (defvar date)
3330 (defvar description)
3332 ;; Defined somewhere in this file, but used before definition.
3333 (defvar org-html-entities)
3334 (defvar org-struct-menu)
3335 (defvar org-org-menu)
3336 (defvar org-tbl-menu)
3337 (defvar org-agenda-keymap)
3339 ;;;; Define the Org-mode
3341 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3342 (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."))
3345 ;; We use a before-change function to check if a table might need
3346 ;; an update.
3347 (defvar org-table-may-need-update t
3348 "Indicates that a table might need an update.
3349 This variable is set by `org-before-change-function'.
3350 `org-table-align' sets it back to nil.")
3351 (defun org-before-change-function (beg end)
3352 "Every change indicates that a table might need an update."
3353 (setq org-table-may-need-update t))
3354 (defvar org-mode-map)
3355 (defvar org-mode-hook nil)
3356 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3357 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3358 (defvar org-table-buffer-is-an nil)
3359 (defconst org-outline-regexp "\\*+ ")
3361 ;;;###autoload
3362 (define-derived-mode org-mode outline-mode "Org"
3363 "Outline-based notes management and organizer, alias
3364 \"Carsten's outline-mode for keeping track of everything.\"
3366 Org-mode develops organizational tasks around a NOTES file which
3367 contains information about projects as plain text. Org-mode is
3368 implemented on top of outline-mode, which is ideal to keep the content
3369 of large files well structured. It supports ToDo items, deadlines and
3370 time stamps, which magically appear in the diary listing of the Emacs
3371 calendar. Tables are easily created with a built-in table editor.
3372 Plain text URL-like links connect to websites, emails (VM), Usenet
3373 messages (Gnus), BBDB entries, and any files related to the project.
3374 For printing and sharing of notes, an Org-mode file (or a part of it)
3375 can be exported as a structured ASCII or HTML file.
3377 The following commands are available:
3379 \\{org-mode-map}"
3381 ;; Get rid of Outline menus, they are not needed
3382 ;; Need to do this here because define-derived-mode sets up
3383 ;; the keymap so late. Still, it is a waste to call this each time
3384 ;; we switch another buffer into org-mode.
3385 (if (featurep 'xemacs)
3386 (when (boundp 'outline-mode-menu-heading)
3387 ;; Assume this is Greg's port, it used easymenu
3388 (easy-menu-remove outline-mode-menu-heading)
3389 (easy-menu-remove outline-mode-menu-show)
3390 (easy-menu-remove outline-mode-menu-hide))
3391 (define-key org-mode-map [menu-bar headings] 'undefined)
3392 (define-key org-mode-map [menu-bar hide] 'undefined)
3393 (define-key org-mode-map [menu-bar show] 'undefined))
3395 (org-load-modules-maybe)
3396 (easy-menu-add org-org-menu)
3397 (easy-menu-add org-tbl-menu)
3398 (org-install-agenda-files-menu)
3399 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3400 (org-add-to-invisibility-spec '(org-cwidth))
3401 (when (featurep 'xemacs)
3402 (org-set-local 'line-move-ignore-invisible t))
3403 (org-set-local 'outline-regexp org-outline-regexp)
3404 (org-set-local 'outline-level 'org-outline-level)
3405 (when (and org-ellipsis
3406 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3407 (fboundp 'make-glyph-code))
3408 (unless org-display-table
3409 (setq org-display-table (make-display-table)))
3410 (set-display-table-slot
3411 org-display-table 4
3412 (vconcat (mapcar
3413 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3414 org-ellipsis)))
3415 (if (stringp org-ellipsis) org-ellipsis "..."))))
3416 (setq buffer-display-table org-display-table))
3417 (org-set-regexps-and-options)
3418 ;; Calc embedded
3419 (org-set-local 'calc-embedded-open-mode "# ")
3420 (modify-syntax-entry ?# "<")
3421 (modify-syntax-entry ?@ "w")
3422 (if org-startup-truncated (setq truncate-lines t))
3423 (org-set-local 'font-lock-unfontify-region-function
3424 'org-unfontify-region)
3425 ;; Activate before-change-function
3426 (org-set-local 'org-table-may-need-update t)
3427 (org-add-hook 'before-change-functions 'org-before-change-function nil
3428 'local)
3429 ;; Check for running clock before killing a buffer
3430 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3431 ;; Paragraphs and auto-filling
3432 (org-set-autofill-regexps)
3433 (setq indent-line-function 'org-indent-line-function)
3434 (org-update-radio-target-regexp)
3436 ;; Comment characters
3437 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3438 (org-set-local 'comment-padding " ")
3440 ;; Align options lines
3441 (org-set-local
3442 'align-mode-rules-list
3443 '((org-in-buffer-settings
3444 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3445 (modes . '(org-mode)))))
3447 ;; Imenu
3448 (org-set-local 'imenu-create-index-function
3449 'org-imenu-get-tree)
3451 ;; Make isearch reveal context
3452 (if (or (featurep 'xemacs)
3453 (not (boundp 'outline-isearch-open-invisible-function)))
3454 ;; Emacs 21 and XEmacs make use of the hook
3455 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3456 ;; Emacs 22 deals with this through a special variable
3457 (org-set-local 'outline-isearch-open-invisible-function
3458 (lambda (&rest ignore) (org-show-context 'isearch))))
3460 ;; If empty file that did not turn on org-mode automatically, make it to.
3461 (if (and org-insert-mode-line-in-empty-file
3462 (interactive-p)
3463 (= (point-min) (point-max)))
3464 (insert "# -*- mode: org -*-\n\n"))
3466 (unless org-inhibit-startup
3467 (when org-startup-align-all-tables
3468 (let ((bmp (buffer-modified-p)))
3469 (org-table-map-tables 'org-table-align)
3470 (set-buffer-modified-p bmp)))
3471 (org-set-startup-visibility)))
3473 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3475 (defun org-current-time ()
3476 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3477 (if (> (car org-time-stamp-rounding-minutes) 1)
3478 (let ((r (car org-time-stamp-rounding-minutes))
3479 (time (decode-time)))
3480 (apply 'encode-time
3481 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3482 (nthcdr 2 time))))
3483 (current-time)))
3485 ;;;; Font-Lock stuff, including the activators
3487 (defvar org-mouse-map (make-sparse-keymap))
3488 (org-defkey org-mouse-map
3489 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3490 (org-defkey org-mouse-map
3491 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3492 (when org-mouse-1-follows-link
3493 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3494 (when org-tab-follows-link
3495 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3496 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3497 (when org-return-follows-link
3498 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3499 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3501 (require 'font-lock)
3503 (defconst org-non-link-chars "]\t\n\r<>")
3504 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3505 "shell" "elisp"))
3506 (defvar org-link-types-re nil
3507 "Matches a link that has a url-like prefix like \"http:\"")
3508 (defvar org-link-re-with-space nil
3509 "Matches a link with spaces, optional angular brackets around it.")
3510 (defvar org-link-re-with-space2 nil
3511 "Matches a link with spaces, optional angular brackets around it.")
3512 (defvar org-link-re-with-space3 nil
3513 "Matches a link with spaces, only for internal part in bracket links.")
3514 (defvar org-angle-link-re nil
3515 "Matches link with angular brackets, spaces are allowed.")
3516 (defvar org-plain-link-re nil
3517 "Matches plain link, without spaces.")
3518 (defvar org-bracket-link-regexp nil
3519 "Matches a link in double brackets.")
3520 (defvar org-bracket-link-analytic-regexp nil
3521 "Regular expression used to analyze links.
3522 Here is what the match groups contain after a match:
3523 1: http:
3524 2: http
3525 3: path
3526 4: [desc]
3527 5: desc")
3528 (defvar org-any-link-re nil
3529 "Regular expression matching any link.")
3531 (defun org-make-link-regexps ()
3532 "Update the link regular expressions.
3533 This should be called after the variable `org-link-types' has changed."
3534 (setq org-link-types-re
3535 (concat
3536 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3537 org-link-re-with-space
3538 (concat
3539 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3540 "\\([^" org-non-link-chars " ]"
3541 "[^" org-non-link-chars "]*"
3542 "[^" org-non-link-chars " ]\\)>?")
3543 org-link-re-with-space2
3544 (concat
3545 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3546 "\\([^" org-non-link-chars " ]"
3547 "[^\t\n\r]*"
3548 "[^" org-non-link-chars " ]\\)>?")
3549 org-link-re-with-space3
3550 (concat
3551 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3552 "\\([^" org-non-link-chars " ]"
3553 "[^\t\n\r]*\\)")
3554 org-angle-link-re
3555 (concat
3556 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3557 "\\([^" org-non-link-chars " ]"
3558 "[^" org-non-link-chars "]*"
3559 "\\)>")
3560 org-plain-link-re
3561 (concat
3562 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3563 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3564 org-bracket-link-regexp
3565 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3566 org-bracket-link-analytic-regexp
3567 (concat
3568 "\\[\\["
3569 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3570 "\\([^]]+\\)"
3571 "\\]"
3572 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3573 "\\]")
3574 org-any-link-re
3575 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3576 org-angle-link-re "\\)\\|\\("
3577 org-plain-link-re "\\)")))
3579 (org-make-link-regexps)
3581 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3582 "Regular expression for fast time stamp matching.")
3583 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3584 "Regular expression for fast time stamp matching.")
3585 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3586 "Regular expression matching time strings for analysis.
3587 This one does not require the space after the date, so it can be used
3588 on a string that terminates immediately after the date.")
3589 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3590 "Regular expression matching time strings for analysis.")
3591 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3592 "Regular expression matching time stamps, with groups.")
3593 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3594 "Regular expression matching time stamps (also [..]), with groups.")
3595 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3596 "Regular expression matching a time stamp range.")
3597 (defconst org-tr-regexp-both
3598 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3599 "Regular expression matching a time stamp range.")
3600 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3601 org-ts-regexp "\\)?")
3602 "Regular expression matching a time stamp or time stamp range.")
3603 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3604 org-ts-regexp-both "\\)?")
3605 "Regular expression matching a time stamp or time stamp range.
3606 The time stamps may be either active or inactive.")
3608 (defvar org-emph-face nil)
3610 (defun org-do-emphasis-faces (limit)
3611 "Run through the buffer and add overlays to links."
3612 (let (rtn)
3613 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3614 (if (not (= (char-after (match-beginning 3))
3615 (char-after (match-beginning 4))))
3616 (progn
3617 (setq rtn t)
3618 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3619 'face
3620 (nth 1 (assoc (match-string 3)
3621 org-emphasis-alist)))
3622 (add-text-properties (match-beginning 2) (match-end 2)
3623 '(font-lock-multiline t))
3624 (when org-hide-emphasis-markers
3625 (add-text-properties (match-end 4) (match-beginning 5)
3626 '(invisible org-link))
3627 (add-text-properties (match-beginning 3) (match-end 3)
3628 '(invisible org-link)))))
3629 (backward-char 1))
3630 rtn))
3632 (defun org-emphasize (&optional char)
3633 "Insert or change an emphasis, i.e. a font like bold or italic.
3634 If there is an active region, change that region to a new emphasis.
3635 If there is no region, just insert the marker characters and position
3636 the cursor between them.
3637 CHAR should be either the marker character, or the first character of the
3638 HTML tag associated with that emphasis. If CHAR is a space, the means
3639 to remove the emphasis of the selected region.
3640 If char is not given (for example in an interactive call) it
3641 will be prompted for."
3642 (interactive)
3643 (let ((eal org-emphasis-alist) e det
3644 (erc org-emphasis-regexp-components)
3645 (prompt "")
3646 (string "") beg end move tag c s)
3647 (if (org-region-active-p)
3648 (setq beg (region-beginning) end (region-end)
3649 string (buffer-substring beg end))
3650 (setq move t))
3652 (while (setq e (pop eal))
3653 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3654 c (aref tag 0))
3655 (push (cons c (string-to-char (car e))) det)
3656 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3657 (substring tag 1)))))
3658 (setq det (nreverse det))
3659 (unless char
3660 (message "%s" (concat "Emphasis marker or tag:" prompt))
3661 (setq char (read-char-exclusive)))
3662 (setq char (or (cdr (assoc char det)) char))
3663 (if (equal char ?\ )
3664 (setq s "" move nil)
3665 (unless (assoc (char-to-string char) org-emphasis-alist)
3666 (error "No such emphasis marker: \"%c\"" char))
3667 (setq s (char-to-string char)))
3668 (while (and (> (length string) 1)
3669 (equal (substring string 0 1) (substring string -1))
3670 (assoc (substring string 0 1) org-emphasis-alist))
3671 (setq string (substring string 1 -1)))
3672 (setq string (concat s string s))
3673 (if beg (delete-region beg end))
3674 (unless (or (bolp)
3675 (string-match (concat "[" (nth 0 erc) "\n]")
3676 (char-to-string (char-before (point)))))
3677 (insert " "))
3678 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3679 (char-to-string (char-after (point))))
3680 (insert " ") (backward-char 1))
3681 (insert string)
3682 (and move (backward-char 1))))
3684 (defconst org-nonsticky-props
3685 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3688 (defun org-activate-plain-links (limit)
3689 "Run through the buffer and add overlays to links."
3690 (catch 'exit
3691 (let (f)
3692 (while (re-search-forward org-plain-link-re limit t)
3693 (setq f (get-text-property (match-beginning 0) 'face))
3694 (if (or (eq f 'org-tag)
3695 (and (listp f) (memq 'org-tag f)))
3697 (add-text-properties (match-beginning 0) (match-end 0)
3698 (list 'mouse-face 'highlight
3699 'rear-nonsticky org-nonsticky-props
3700 'keymap org-mouse-map
3702 (throw 'exit t))))))
3704 (defun org-activate-code (limit)
3705 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3706 (progn
3707 (remove-text-properties (match-beginning 0) (match-end 0)
3708 '(display t invisible t intangible t))
3709 t)))
3711 (defun org-activate-angle-links (limit)
3712 "Run through the buffer and add overlays to links."
3713 (if (re-search-forward org-angle-link-re limit t)
3714 (progn
3715 (add-text-properties (match-beginning 0) (match-end 0)
3716 (list 'mouse-face 'highlight
3717 'rear-nonsticky org-nonsticky-props
3718 'keymap org-mouse-map
3720 t)))
3722 (defun org-activate-bracket-links (limit)
3723 "Run through the buffer and add overlays to bracketed links."
3724 (if (re-search-forward org-bracket-link-regexp limit t)
3725 (let* ((help (concat "LINK: "
3726 (org-match-string-no-properties 1)))
3727 ;; FIXME: above we should remove the escapes.
3728 ;; but that requires another match, protecting match data,
3729 ;; a lot of overhead for font-lock.
3730 (ip (org-maybe-intangible
3731 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3732 'keymap org-mouse-map 'mouse-face 'highlight
3733 'font-lock-multiline t 'help-echo help)))
3734 (vp (list 'rear-nonsticky org-nonsticky-props
3735 'keymap org-mouse-map 'mouse-face 'highlight
3736 ' font-lock-multiline t 'help-echo help)))
3737 ;; We need to remove the invisible property here. Table narrowing
3738 ;; may have made some of this invisible.
3739 (remove-text-properties (match-beginning 0) (match-end 0)
3740 '(invisible nil))
3741 (if (match-end 3)
3742 (progn
3743 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3744 (add-text-properties (match-beginning 3) (match-end 3) vp)
3745 (add-text-properties (match-end 3) (match-end 0) ip))
3746 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3747 (add-text-properties (match-beginning 1) (match-end 1) vp)
3748 (add-text-properties (match-end 1) (match-end 0) ip))
3749 t)))
3751 (defun org-activate-dates (limit)
3752 "Run through the buffer and add overlays to dates."
3753 (if (re-search-forward org-tsr-regexp-both limit t)
3754 (progn
3755 (add-text-properties (match-beginning 0) (match-end 0)
3756 (list 'mouse-face 'highlight
3757 'rear-nonsticky org-nonsticky-props
3758 'keymap org-mouse-map))
3759 (when org-display-custom-times
3760 (if (match-end 3)
3761 (org-display-custom-time (match-beginning 3) (match-end 3)))
3762 (org-display-custom-time (match-beginning 1) (match-end 1)))
3763 t)))
3765 (defvar org-target-link-regexp nil
3766 "Regular expression matching radio targets in plain text.")
3767 (make-variable-buffer-local 'org-target-link-regexp)
3768 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3769 "Regular expression matching a link target.")
3770 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3771 "Regular expression matching a radio target.")
3772 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3773 "Regular expression matching any target.")
3775 (defun org-activate-target-links (limit)
3776 "Run through the buffer and add overlays to target matches."
3777 (when org-target-link-regexp
3778 (let ((case-fold-search t))
3779 (if (re-search-forward org-target-link-regexp limit t)
3780 (progn
3781 (add-text-properties (match-beginning 0) (match-end 0)
3782 (list 'mouse-face 'highlight
3783 'rear-nonsticky org-nonsticky-props
3784 'keymap org-mouse-map
3785 'help-echo "Radio target link"
3786 'org-linked-text t))
3787 t)))))
3789 (defun org-update-radio-target-regexp ()
3790 "Find all radio targets in this file and update the regular expression."
3791 (interactive)
3792 (when (memq 'radio org-activate-links)
3793 (setq org-target-link-regexp
3794 (org-make-target-link-regexp (org-all-targets 'radio)))
3795 (org-restart-font-lock)))
3797 (defun org-hide-wide-columns (limit)
3798 (let (s e)
3799 (setq s (text-property-any (point) (or limit (point-max))
3800 'org-cwidth t))
3801 (when s
3802 (setq e (next-single-property-change s 'org-cwidth))
3803 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3804 (goto-char e)
3805 t)))
3807 (defvar org-latex-and-specials-regexp nil
3808 "Regular expression for highlighting export special stuff.")
3809 (defvar org-match-substring-regexp)
3810 (defvar org-match-substring-with-braces-regexp)
3811 (defvar org-export-html-special-string-regexps)
3813 (defun org-compute-latex-and-specials-regexp ()
3814 "Compute regular expression for stuff treated specially by exporters."
3815 (if (not org-highlight-latex-fragments-and-specials)
3816 (org-set-local 'org-latex-and-specials-regexp nil)
3817 (require 'org-exp)
3818 (let*
3819 ((matchers (plist-get org-format-latex-options :matchers))
3820 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3821 org-latex-regexps)))
3822 (options (org-combine-plists (org-default-export-plist)
3823 (org-infile-export-plist)))
3824 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3825 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3826 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3827 (org-export-html-expand (plist-get options :expand-quoted-html))
3828 (org-export-with-special-strings (plist-get options :special-strings))
3829 (re-sub
3830 (cond
3831 ((equal org-export-with-sub-superscripts '{})
3832 (list org-match-substring-with-braces-regexp))
3833 (org-export-with-sub-superscripts
3834 (list org-match-substring-regexp))
3835 (t nil)))
3836 (re-latex
3837 (if org-export-with-LaTeX-fragments
3838 (mapcar (lambda (x) (nth 1 x)) latexs)))
3839 (re-macros
3840 (if org-export-with-TeX-macros
3841 (list (concat "\\\\"
3842 (regexp-opt
3843 (append (mapcar 'car org-html-entities)
3844 (if (boundp 'org-latex-entities)
3845 org-latex-entities nil))
3846 'words))) ; FIXME
3848 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3849 (re-special (if org-export-with-special-strings
3850 (mapcar (lambda (x) (car x))
3851 org-export-html-special-string-regexps)))
3852 (re-rest
3853 (delq nil
3854 (list
3855 (if org-export-html-expand "@<[^>\n]+>")
3856 ))))
3857 (org-set-local
3858 'org-latex-and-specials-regexp
3859 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3860 re-rest) "\\|")))))
3862 (defun org-do-latex-and-special-faces (limit)
3863 "Run through the buffer and add overlays to links."
3864 (when org-latex-and-specials-regexp
3865 (let (rtn d)
3866 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3867 limit t))
3868 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3869 'face))
3870 '(org-code org-verbatim underline)))
3871 (progn
3872 (setq rtn t
3873 d (cond ((member (char-after (1+ (match-beginning 0)))
3874 '(?_ ?^)) 1)
3875 (t 0)))
3876 (font-lock-prepend-text-property
3877 (+ d (match-beginning 0)) (match-end 0)
3878 'face 'org-latex-and-export-specials)
3879 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3880 '(font-lock-multiline t)))))
3881 rtn)))
3883 (defun org-restart-font-lock ()
3884 "Restart font-lock-mode, to force refontification."
3885 (when (and (boundp 'font-lock-mode) font-lock-mode)
3886 (font-lock-mode -1)
3887 (font-lock-mode 1)))
3889 (defun org-all-targets (&optional radio)
3890 "Return a list of all targets in this file.
3891 With optional argument RADIO, only find radio targets."
3892 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3893 rtn)
3894 (save-excursion
3895 (goto-char (point-min))
3896 (while (re-search-forward re nil t)
3897 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3898 rtn)))
3900 (defun org-make-target-link-regexp (targets)
3901 "Make regular expression matching all strings in TARGETS.
3902 The regular expression finds the targets also if there is a line break
3903 between words."
3904 (and targets
3905 (concat
3906 "\\<\\("
3907 (mapconcat
3908 (lambda (x)
3909 (while (string-match " +" x)
3910 (setq x (replace-match "\\s-+" t t x)))
3912 targets
3913 "\\|")
3914 "\\)\\>")))
3916 (defun org-activate-tags (limit)
3917 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3918 (progn
3919 (add-text-properties (match-beginning 1) (match-end 1)
3920 (list 'mouse-face 'highlight
3921 'rear-nonsticky org-nonsticky-props
3922 'keymap org-mouse-map))
3923 t)))
3925 (defun org-outline-level ()
3926 (save-excursion
3927 (looking-at outline-regexp)
3928 (if (match-beginning 1)
3929 (+ (org-get-string-indentation (match-string 1)) 1000)
3930 (1- (- (match-end 0) (match-beginning 0))))))
3932 (defvar org-font-lock-keywords nil)
3934 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3935 "Regular expression matching a property line.")
3937 (defvar org-font-lock-hook nil
3938 "Functions to be called for special font lock stuff.")
3940 (defun org-font-lock-hook (limit)
3941 (run-hook-with-args 'org-font-lock-hook limit))
3943 (defun org-set-font-lock-defaults ()
3944 (let* ((em org-fontify-emphasized-text)
3945 (lk org-activate-links)
3946 (org-font-lock-extra-keywords
3947 (list
3948 ;; Call the hook
3949 '(org-font-lock-hook)
3950 ;; Headlines
3951 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3952 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3953 ;; Table lines
3954 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3955 (1 'org-table t))
3956 ;; Table internals
3957 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3958 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3959 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3960 ;; Drawers
3961 (list org-drawer-regexp '(0 'org-special-keyword t))
3962 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3963 ;; Properties
3964 (list org-property-re
3965 '(1 'org-special-keyword t)
3966 '(3 'org-property-value t))
3967 (if org-format-transports-properties-p
3968 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3969 ;; Links
3970 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3971 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3972 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3973 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3974 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3975 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3976 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3977 '(org-hide-wide-columns (0 nil append))
3978 ;; TODO lines
3979 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3980 '(1 (org-get-todo-face 1) t))
3981 ;; DONE
3982 (if org-fontify-done-headline
3983 (list (concat "^[*]+ +\\<\\("
3984 (mapconcat 'regexp-quote org-done-keywords "\\|")
3985 "\\)\\(.*\\)")
3986 '(2 'org-headline-done t))
3987 nil)
3988 ;; Priorities
3989 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3990 ;; Tags
3991 '(org-font-lock-add-tag-faces)
3992 ;; Special keywords
3993 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3994 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3995 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3996 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3997 ;; Emphasis
3998 (if em
3999 (if (featurep 'xemacs)
4000 '(org-do-emphasis-faces (0 nil append))
4001 '(org-do-emphasis-faces)))
4002 ;; Checkboxes
4003 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4004 2 'bold prepend)
4005 (if org-provide-checkbox-statistics
4006 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4007 (0 (org-get-checkbox-statistics-face) t)))
4008 ;; Description list items
4009 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4010 2 'bold prepend)
4011 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4012 '(1 'org-archived prepend))
4013 ;; Specials
4014 '(org-do-latex-and-special-faces)
4015 ;; Code
4016 '(org-activate-code (1 'org-code t))
4017 ;; COMMENT
4018 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4019 "\\|" org-quote-string "\\)\\>")
4020 '(1 'org-special-keyword t))
4021 '("^#.*" (0 'font-lock-comment-face t))
4023 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4024 ;; Now set the full font-lock-keywords
4025 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4026 (org-set-local 'font-lock-defaults
4027 '(org-font-lock-keywords t nil nil backward-paragraph))
4028 (kill-local-variable 'font-lock-keywords) nil))
4030 (defvar org-m nil)
4031 (defvar org-l nil)
4032 (defvar org-f nil)
4033 (defun org-get-level-face (n)
4034 "Get the right face for match N in font-lock matching of healdines."
4035 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4036 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4037 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4038 (cond
4039 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4040 ((eq n 2) org-f)
4041 (t (if org-level-color-stars-only nil org-f))))
4043 (defun org-get-todo-face (kwd)
4044 "Get the right face for a TODO keyword KWD.
4045 If KWD is a number, get the corresponding match group."
4046 (if (numberp kwd) (setq kwd (match-string kwd)))
4047 (or (cdr (assoc kwd org-todo-keyword-faces))
4048 (and (member kwd org-done-keywords) 'org-done)
4049 'org-todo))
4051 (defun org-font-lock-add-tag-faces (limit)
4052 "Add the special tag faces."
4053 (when (and org-tag-faces org-tags-special-faces-re)
4054 (while (re-search-forward org-tags-special-faces-re limit t)
4055 (add-text-properties (match-beginning 1) (match-end 1)
4056 (list 'face (org-get-tag-face 1)
4057 'font-lock-fontified t))
4058 (backward-char 1))))
4060 (defun org-get-tag-face (kwd)
4061 "Get the right face for a TODO keyword KWD.
4062 If KWD is a number, get the corresponding match group."
4063 (if (numberp kwd) (setq kwd (match-string kwd)))
4064 (or (cdr (assoc kwd org-tag-faces))
4065 'org-tag))
4067 (defun org-unfontify-region (beg end &optional maybe_loudly)
4068 "Remove fontification and activation overlays from links."
4069 (font-lock-default-unfontify-region beg end)
4070 (let* ((buffer-undo-list t)
4071 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4072 (inhibit-modification-hooks t)
4073 deactivate-mark buffer-file-name buffer-file-truename)
4074 (remove-text-properties beg end
4075 '(mouse-face t keymap t org-linked-text t
4076 invisible t intangible t))))
4078 ;;;; Visibility cycling, including org-goto and indirect buffer
4080 ;;; Cycling
4082 (defvar org-cycle-global-status nil)
4083 (make-variable-buffer-local 'org-cycle-global-status)
4084 (defvar org-cycle-subtree-status nil)
4085 (make-variable-buffer-local 'org-cycle-subtree-status)
4087 ;;;###autoload
4088 (defun org-cycle (&optional arg)
4089 "Visibility cycling for Org-mode.
4091 - When this function is called with a prefix argument, rotate the entire
4092 buffer through 3 states (global cycling)
4093 1. OVERVIEW: Show only top-level headlines.
4094 2. CONTENTS: Show all headlines of all levels, but no body text.
4095 3. SHOW ALL: Show everything.
4096 When called with two C-u C-u prefixes, switch to the startup visibility,
4097 determined by the variable `org-startup-folded', and by any VISIBILITY
4098 properties in the buffer.
4099 When called with three C-u C-u C-u prefixed, show the entire buffer,
4100 including drawers.
4102 - When point is at the beginning of a headline, rotate the subtree started
4103 by this line through 3 different states (local cycling)
4104 1. FOLDED: Only the main headline is shown.
4105 2. CHILDREN: The main headline and the direct children are shown.
4106 From this state, you can move to one of the children
4107 and zoom in further.
4108 3. SUBTREE: Show the entire subtree, including body text.
4110 - When there is a numeric prefix, go up to a heading with level ARG, do
4111 a `show-subtree' and return to the previous cursor position. If ARG
4112 is negative, go up that many levels.
4114 - When point is not at the beginning of a headline, execute the global
4115 binding for TAB, which is re-indenting the line. See the option
4116 `org-cycle-emulate-tab' for details.
4118 - Special case: if point is at the beginning of the buffer and there is
4119 no headline in line 1, this function will act as if called with prefix arg.
4120 But only if also the variable `org-cycle-global-at-bob' is t."
4121 (interactive "P")
4122 (org-load-modules-maybe)
4123 (let* ((outline-regexp
4124 (if (and (org-mode-p) org-cycle-include-plain-lists)
4125 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4126 outline-regexp))
4127 (bob-special (and org-cycle-global-at-bob (bobp)
4128 (not (looking-at outline-regexp))))
4129 (org-cycle-hook
4130 (if bob-special
4131 (delq 'org-optimize-window-after-visibility-change
4132 (copy-sequence org-cycle-hook))
4133 org-cycle-hook))
4134 (pos (point)))
4136 (if (or bob-special (equal arg '(4)))
4137 ;; special case: use global cycling
4138 (setq arg t))
4140 (cond
4142 ((equal arg '(16))
4143 (org-set-startup-visibility)
4144 (message "Startup visibility, plus VISIBILITY properties"))
4146 ((equal arg '(64))
4147 (show-all)
4148 (message "Entire buffer visible, including drawers"))
4150 ((org-at-table-p 'any)
4151 ;; Enter the table or move to the next field in the table
4152 (or (org-table-recognize-table.el)
4153 (progn
4154 (if arg (org-table-edit-field t)
4155 (org-table-justify-field-maybe)
4156 (call-interactively 'org-table-next-field)))))
4158 ((eq arg t) ;; Global cycling
4160 (cond
4161 ((and (eq last-command this-command)
4162 (eq org-cycle-global-status 'overview))
4163 ;; We just created the overview - now do table of contents
4164 ;; This can be slow in very large buffers, so indicate action
4165 (message "CONTENTS...")
4166 (org-content)
4167 (message "CONTENTS...done")
4168 (setq org-cycle-global-status 'contents)
4169 (run-hook-with-args 'org-cycle-hook 'contents))
4171 ((and (eq last-command this-command)
4172 (eq org-cycle-global-status 'contents))
4173 ;; We just showed the table of contents - now show everything
4174 (show-all)
4175 (message "SHOW ALL")
4176 (setq org-cycle-global-status 'all)
4177 (run-hook-with-args 'org-cycle-hook 'all))
4180 ;; Default action: go to overview
4181 (org-overview)
4182 (message "OVERVIEW")
4183 (setq org-cycle-global-status 'overview)
4184 (run-hook-with-args 'org-cycle-hook 'overview))))
4186 ((and org-drawers org-drawer-regexp
4187 (save-excursion
4188 (beginning-of-line 1)
4189 (looking-at org-drawer-regexp)))
4190 ;; Toggle block visibility
4191 (org-flag-drawer
4192 (not (get-char-property (match-end 0) 'invisible))))
4194 ((integerp arg)
4195 ;; Show-subtree, ARG levels up from here.
4196 (save-excursion
4197 (org-back-to-heading)
4198 (outline-up-heading (if (< arg 0) (- arg)
4199 (- (funcall outline-level) arg)))
4200 (org-show-subtree)))
4202 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4203 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4204 ;; At a heading: rotate between three different views
4205 (org-back-to-heading)
4206 (let ((goal-column 0) eoh eol eos)
4207 ;; First, some boundaries
4208 (save-excursion
4209 (org-back-to-heading)
4210 (save-excursion
4211 (beginning-of-line 2)
4212 (while (and (not (eobp)) ;; this is like `next-line'
4213 (get-char-property (1- (point)) 'invisible))
4214 (beginning-of-line 2)) (setq eol (point)))
4215 (outline-end-of-heading) (setq eoh (point))
4216 (org-end-of-subtree t)
4217 (unless (eobp)
4218 (skip-chars-forward " \t\n")
4219 (beginning-of-line 1) ; in case this is an item
4221 (setq eos (1- (point))))
4222 ;; Find out what to do next and set `this-command'
4223 (cond
4224 ((= eos eoh)
4225 ;; Nothing is hidden behind this heading
4226 (message "EMPTY ENTRY")
4227 (setq org-cycle-subtree-status nil)
4228 (save-excursion
4229 (goto-char eos)
4230 (outline-next-heading)
4231 (if (org-invisible-p) (org-flag-heading nil))))
4232 ((or (>= eol eos)
4233 (not (string-match "\\S-" (buffer-substring eol eos))))
4234 ;; Entire subtree is hidden in one line: open it
4235 (org-show-entry)
4236 (show-children)
4237 (message "CHILDREN")
4238 (save-excursion
4239 (goto-char eos)
4240 (outline-next-heading)
4241 (if (org-invisible-p) (org-flag-heading nil)))
4242 (setq org-cycle-subtree-status 'children)
4243 (run-hook-with-args 'org-cycle-hook 'children))
4244 ((and (eq last-command this-command)
4245 (eq org-cycle-subtree-status 'children))
4246 ;; We just showed the children, now show everything.
4247 (org-show-subtree)
4248 (message "SUBTREE")
4249 (setq org-cycle-subtree-status 'subtree)
4250 (run-hook-with-args 'org-cycle-hook 'subtree))
4252 ;; Default action: hide the subtree.
4253 (hide-subtree)
4254 (message "FOLDED")
4255 (setq org-cycle-subtree-status 'folded)
4256 (run-hook-with-args 'org-cycle-hook 'folded)))))
4258 ;; TAB emulation and template completion
4259 (buffer-read-only (org-back-to-heading))
4261 ((org-try-structure-completion))
4263 ((org-try-cdlatex-tab))
4265 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4266 (or (not (bolp))
4267 (not (looking-at outline-regexp))))
4268 (call-interactively (global-key-binding "\t")))
4270 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4271 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4272 (or (and (eq org-cycle-emulate-tab 'white)
4273 (= (match-end 0) (point-at-eol)))
4274 (and (eq org-cycle-emulate-tab 'whitestart)
4275 (>= (match-end 0) pos))))
4277 (eq org-cycle-emulate-tab t))
4278 (call-interactively (global-key-binding "\t")))
4280 (t (save-excursion
4281 (org-back-to-heading)
4282 (org-cycle))))))
4284 ;;;###autoload
4285 (defun org-global-cycle (&optional arg)
4286 "Cycle the global visibility. For details see `org-cycle'.
4287 With C-u prefix arg, switch to startup visibility.
4288 With a numeric prefix, show all headlines up to that level."
4289 (interactive "P")
4290 (let ((org-cycle-include-plain-lists
4291 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4292 (cond
4293 ((integerp arg)
4294 (show-all)
4295 (hide-sublevels arg)
4296 (setq org-cycle-global-status 'contents))
4297 ((equal arg '(4))
4298 (org-set-startup-visibility)
4299 (message "Startup visibility, plus VISIBILITY properties."))
4301 (org-cycle '(4))))))
4303 (defun org-set-startup-visibility ()
4304 "Set the visibility required by startup options and properties."
4305 (cond
4306 ((eq org-startup-folded t)
4307 (org-cycle '(4)))
4308 ((eq org-startup-folded 'content)
4309 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4310 (org-cycle '(4)) (org-cycle '(4)))))
4311 (org-set-visibility-according-to-property 'no-cleanup)
4312 (org-cycle-hide-archived-subtrees 'all)
4313 (org-cycle-hide-drawers 'all)
4314 (org-cycle-show-empty-lines 'all))
4316 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4317 "Switch subtree visibilities according to :VISIBILITY: property."
4318 (interactive)
4319 (let (state)
4320 (save-excursion
4321 (goto-char (point-min))
4322 (while (re-search-forward
4323 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4324 nil t)
4325 (setq state (match-string 1))
4326 (save-excursion
4327 (org-back-to-heading t)
4328 (hide-subtree)
4329 (org-reveal)
4330 (cond
4331 ((equal state '("fold" "folded"))
4332 (hide-subtree))
4333 ((equal state "children")
4334 (org-show-hidden-entry)
4335 (show-children))
4336 ((equal state "content")
4337 (save-excursion
4338 (save-restriction
4339 (org-narrow-to-subtree)
4340 (org-content))))
4341 ((member state '("all" "showall"))
4342 (show-subtree)))))
4343 (unless no-cleanup
4344 (org-cycle-hide-archived-subtrees 'all)
4345 (org-cycle-hide-drawers 'all)
4346 (org-cycle-show-empty-lines 'all)))))
4348 (defun org-overview ()
4349 "Switch to overview mode, shoing only top-level headlines.
4350 Really, this shows all headlines with level equal or greater than the level
4351 of the first headline in the buffer. This is important, because if the
4352 first headline is not level one, then (hide-sublevels 1) gives confusing
4353 results."
4354 (interactive)
4355 (let ((level (save-excursion
4356 (goto-char (point-min))
4357 (if (re-search-forward (concat "^" outline-regexp) nil t)
4358 (progn
4359 (goto-char (match-beginning 0))
4360 (funcall outline-level))))))
4361 (and level (hide-sublevels level))))
4363 (defun org-content (&optional arg)
4364 "Show all headlines in the buffer, like a table of contents.
4365 With numerical argument N, show content up to level N."
4366 (interactive "P")
4367 (save-excursion
4368 ;; Visit all headings and show their offspring
4369 (and (integerp arg) (org-overview))
4370 (goto-char (point-max))
4371 (catch 'exit
4372 (while (and (progn (condition-case nil
4373 (outline-previous-visible-heading 1)
4374 (error (goto-char (point-min))))
4376 (looking-at outline-regexp))
4377 (if (integerp arg)
4378 (show-children (1- arg))
4379 (show-branches))
4380 (if (bobp) (throw 'exit nil))))))
4383 (defun org-optimize-window-after-visibility-change (state)
4384 "Adjust the window after a change in outline visibility.
4385 This function is the default value of the hook `org-cycle-hook'."
4386 (when (get-buffer-window (current-buffer))
4387 (cond
4388 ; ((eq state 'overview) (org-first-headline-recenter 1))
4389 ; ((eq state 'overview) (org-beginning-of-line))
4390 ((eq state 'content) nil)
4391 ((eq state 'all) nil)
4392 ((eq state 'folded) nil)
4393 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4394 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4396 (defun org-compact-display-after-subtree-move ()
4397 (let (beg end)
4398 (save-excursion
4399 (if (org-up-heading-safe)
4400 (progn
4401 (hide-subtree)
4402 (show-entry)
4403 (show-children)
4404 (org-cycle-show-empty-lines 'children)
4405 (org-cycle-hide-drawers 'children))
4406 (org-overview)))))
4408 (defun org-cycle-show-empty-lines (state)
4409 "Show empty lines above all visible headlines.
4410 The region to be covered depends on STATE when called through
4411 `org-cycle-hook'. Lisp program can use t for STATE to get the
4412 entire buffer covered. Note that an empty line is only shown if there
4413 are at least `org-cycle-separator-lines' empty lines before the headeline."
4414 (when (> org-cycle-separator-lines 0)
4415 (save-excursion
4416 (let* ((n org-cycle-separator-lines)
4417 (re (cond
4418 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4419 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4420 (t (let ((ns (number-to-string (- n 2))))
4421 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4422 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4423 beg end)
4424 (cond
4425 ((memq state '(overview contents t))
4426 (setq beg (point-min) end (point-max)))
4427 ((memq state '(children folded))
4428 (setq beg (point) end (progn (org-end-of-subtree t t)
4429 (beginning-of-line 2)
4430 (point)))))
4431 (when beg
4432 (goto-char beg)
4433 (while (re-search-forward re end t)
4434 (if (not (get-char-property (match-end 1) 'invisible))
4435 (outline-flag-region
4436 (match-beginning 1) (match-end 1) nil)))))))
4437 ;; Never hide empty lines at the end of the file.
4438 (save-excursion
4439 (goto-char (point-max))
4440 (outline-previous-heading)
4441 (outline-end-of-heading)
4442 (if (and (looking-at "[ \t\n]+")
4443 (= (match-end 0) (point-max)))
4444 (outline-flag-region (point) (match-end 0) nil))))
4446 (defun org-show-empty-lines-in-parent ()
4447 "Move to the parent and re-show empty lines before visible headlines."
4448 (save-excursion
4449 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4450 (org-cycle-show-empty-lines context))))
4452 (defun org-cycle-hide-drawers (state)
4453 "Re-hide all drawers after a visibility state change."
4454 (when (and (org-mode-p)
4455 (not (memq state '(overview folded))))
4456 (save-excursion
4457 (let* ((globalp (memq state '(contents all)))
4458 (beg (if globalp (point-min) (point)))
4459 (end (if globalp (point-max) (org-end-of-subtree t))))
4460 (goto-char beg)
4461 (while (re-search-forward org-drawer-regexp end t)
4462 (org-flag-drawer t))))))
4464 (defun org-flag-drawer (flag)
4465 (save-excursion
4466 (beginning-of-line 1)
4467 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4468 (let ((b (match-end 0))
4469 (outline-regexp org-outline-regexp))
4470 (if (re-search-forward
4471 "^[ \t]*:END:"
4472 (save-excursion (outline-next-heading) (point)) t)
4473 (outline-flag-region b (point-at-eol) flag)
4474 (error ":END: line missing"))))))
4476 (defun org-subtree-end-visible-p ()
4477 "Is the end of the current subtree visible?"
4478 (pos-visible-in-window-p
4479 (save-excursion (org-end-of-subtree t) (point))))
4481 (defun org-first-headline-recenter (&optional N)
4482 "Move cursor to the first headline and recenter the headline.
4483 Optional argument N means, put the headline into the Nth line of the window."
4484 (goto-char (point-min))
4485 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4486 (beginning-of-line)
4487 (recenter (prefix-numeric-value N))))
4489 ;;; Org-goto
4491 (defvar org-goto-window-configuration nil)
4492 (defvar org-goto-marker nil)
4493 (defvar org-goto-map
4494 (let ((map (make-sparse-keymap)))
4495 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4496 (while (setq cmd (pop cmds))
4497 (substitute-key-definition cmd cmd map global-map)))
4498 (suppress-keymap map)
4499 (org-defkey map "\C-m" 'org-goto-ret)
4500 (org-defkey map [(return)] 'org-goto-ret)
4501 (org-defkey map [(left)] 'org-goto-left)
4502 (org-defkey map [(right)] 'org-goto-right)
4503 (org-defkey map [(control ?g)] 'org-goto-quit)
4504 (org-defkey map "\C-i" 'org-cycle)
4505 (org-defkey map [(tab)] 'org-cycle)
4506 (org-defkey map [(down)] 'outline-next-visible-heading)
4507 (org-defkey map [(up)] 'outline-previous-visible-heading)
4508 (if org-goto-auto-isearch
4509 (if (fboundp 'define-key-after)
4510 (define-key-after map [t] 'org-goto-local-auto-isearch)
4511 nil)
4512 (org-defkey map "q" 'org-goto-quit)
4513 (org-defkey map "n" 'outline-next-visible-heading)
4514 (org-defkey map "p" 'outline-previous-visible-heading)
4515 (org-defkey map "f" 'outline-forward-same-level)
4516 (org-defkey map "b" 'outline-backward-same-level)
4517 (org-defkey map "u" 'outline-up-heading))
4518 (org-defkey map "/" 'org-occur)
4519 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4520 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4521 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4522 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4523 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4524 map))
4526 (defconst org-goto-help
4527 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4528 RET=jump to location [Q]uit and return to previous location
4529 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4531 (defvar org-goto-start-pos) ; dynamically scoped parameter
4533 ;; FIXME: Docstring doe not mention both interfaces
4534 (defun org-goto (&optional alternative-interface)
4535 "Look up a different location in the current file, keeping current visibility.
4537 When you want look-up or go to a different location in a document, the
4538 fastest way is often to fold the entire buffer and then dive into the tree.
4539 This method has the disadvantage, that the previous location will be folded,
4540 which may not be what you want.
4542 This command works around this by showing a copy of the current buffer
4543 in an indirect buffer, in overview mode. You can dive into the tree in
4544 that copy, use org-occur and incremental search to find a location.
4545 When pressing RET or `Q', the command returns to the original buffer in
4546 which the visibility is still unchanged. After RET is will also jump to
4547 the location selected in the indirect buffer and expose the
4548 the headline hierarchy above."
4549 (interactive "P")
4550 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4551 (org-refile-use-outline-path t)
4552 (interface
4553 (if (not alternative-interface)
4554 org-goto-interface
4555 (if (eq org-goto-interface 'outline)
4556 'outline-path-completion
4557 'outline)))
4558 (org-goto-start-pos (point))
4559 (selected-point
4560 (if (eq interface 'outline)
4561 (car (org-get-location (current-buffer) org-goto-help))
4562 (nth 3 (org-refile-get-location "Goto: ")))))
4563 (if selected-point
4564 (progn
4565 (org-mark-ring-push org-goto-start-pos)
4566 (goto-char selected-point)
4567 (if (or (org-invisible-p) (org-invisible-p2))
4568 (org-show-context 'org-goto)))
4569 (message "Quit"))))
4571 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4572 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4573 (defvar org-goto-local-auto-isearch-map) ; defined below
4575 (defun org-get-location (buf help)
4576 "Let the user select a location in the Org-mode buffer BUF.
4577 This function uses a recursive edit. It returns the selected position
4578 or nil."
4579 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4580 (isearch-hide-immediately nil)
4581 (isearch-search-fun-function
4582 (lambda () 'org-goto-local-search-headings))
4583 (org-goto-selected-point org-goto-exit-command))
4584 (save-excursion
4585 (save-window-excursion
4586 (delete-other-windows)
4587 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4588 (switch-to-buffer
4589 (condition-case nil
4590 (make-indirect-buffer (current-buffer) "*org-goto*")
4591 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4592 (with-output-to-temp-buffer "*Help*"
4593 (princ help))
4594 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4595 (setq buffer-read-only nil)
4596 (let ((org-startup-truncated t)
4597 (org-startup-folded nil)
4598 (org-startup-align-all-tables nil))
4599 (org-mode)
4600 (org-overview))
4601 (setq buffer-read-only t)
4602 (if (and (boundp 'org-goto-start-pos)
4603 (integer-or-marker-p org-goto-start-pos))
4604 (let ((org-show-hierarchy-above t)
4605 (org-show-siblings t)
4606 (org-show-following-heading t))
4607 (goto-char org-goto-start-pos)
4608 (and (org-invisible-p) (org-show-context)))
4609 (goto-char (point-min)))
4610 (org-beginning-of-line)
4611 (message "Select location and press RET")
4612 (use-local-map org-goto-map)
4613 (recursive-edit)
4615 (kill-buffer "*org-goto*")
4616 (cons org-goto-selected-point org-goto-exit-command)))
4618 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4619 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4620 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4621 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4623 (defun org-goto-local-search-headings (string bound noerror)
4624 "Search and make sure that any matches are in headlines."
4625 (catch 'return
4626 (while (if isearch-forward
4627 (search-forward string bound noerror)
4628 (search-backward string bound noerror))
4629 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4630 (and (member :headline context)
4631 (not (member :tags context))))
4632 (throw 'return (point))))))
4634 (defun org-goto-local-auto-isearch ()
4635 "Start isearch."
4636 (interactive)
4637 (goto-char (point-min))
4638 (let ((keys (this-command-keys)))
4639 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4640 (isearch-mode t)
4641 (isearch-process-search-char (string-to-char keys)))))
4643 (defun org-goto-ret (&optional arg)
4644 "Finish `org-goto' by going to the new location."
4645 (interactive "P")
4646 (setq org-goto-selected-point (point)
4647 org-goto-exit-command 'return)
4648 (throw 'exit nil))
4650 (defun org-goto-left ()
4651 "Finish `org-goto' by going to the new location."
4652 (interactive)
4653 (if (org-on-heading-p)
4654 (progn
4655 (beginning-of-line 1)
4656 (setq org-goto-selected-point (point)
4657 org-goto-exit-command 'left)
4658 (throw 'exit nil))
4659 (error "Not on a heading")))
4661 (defun org-goto-right ()
4662 "Finish `org-goto' by going to the new location."
4663 (interactive)
4664 (if (org-on-heading-p)
4665 (progn
4666 (setq org-goto-selected-point (point)
4667 org-goto-exit-command 'right)
4668 (throw 'exit nil))
4669 (error "Not on a heading")))
4671 (defun org-goto-quit ()
4672 "Finish `org-goto' without cursor motion."
4673 (interactive)
4674 (setq org-goto-selected-point nil)
4675 (setq org-goto-exit-command 'quit)
4676 (throw 'exit nil))
4678 ;;; Indirect buffer display of subtrees
4680 (defvar org-indirect-dedicated-frame nil
4681 "This is the frame being used for indirect tree display.")
4682 (defvar org-last-indirect-buffer nil)
4684 (defun org-tree-to-indirect-buffer (&optional arg)
4685 "Create indirect buffer and narrow it to current subtree.
4686 With numerical prefix ARG, go up to this level and then take that tree.
4687 If ARG is negative, go up that many levels.
4688 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4689 indirect buffer previously made with this command, to avoid proliferation of
4690 indirect buffers. However, when you call the command with a `C-u' prefix, or
4691 when `org-indirect-buffer-display' is `new-frame', the last buffer
4692 is kept so that you can work with several indirect buffers at the same time.
4693 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4694 requests that a new frame be made for the new buffer, so that the dedicated
4695 frame is not changed."
4696 (interactive "P")
4697 (let ((cbuf (current-buffer))
4698 (cwin (selected-window))
4699 (pos (point))
4700 beg end level heading ibuf)
4701 (save-excursion
4702 (org-back-to-heading t)
4703 (when (numberp arg)
4704 (setq level (org-outline-level))
4705 (if (< arg 0) (setq arg (+ level arg)))
4706 (while (> (setq level (org-outline-level)) arg)
4707 (outline-up-heading 1 t)))
4708 (setq beg (point)
4709 heading (org-get-heading))
4710 (org-end-of-subtree t) (setq end (point)))
4711 (if (and (buffer-live-p org-last-indirect-buffer)
4712 (not (eq org-indirect-buffer-display 'new-frame))
4713 (not arg))
4714 (kill-buffer org-last-indirect-buffer))
4715 (setq ibuf (org-get-indirect-buffer cbuf)
4716 org-last-indirect-buffer ibuf)
4717 (cond
4718 ((or (eq org-indirect-buffer-display 'new-frame)
4719 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4720 (select-frame (make-frame))
4721 (delete-other-windows)
4722 (switch-to-buffer ibuf)
4723 (org-set-frame-title heading))
4724 ((eq org-indirect-buffer-display 'dedicated-frame)
4725 (raise-frame
4726 (select-frame (or (and org-indirect-dedicated-frame
4727 (frame-live-p org-indirect-dedicated-frame)
4728 org-indirect-dedicated-frame)
4729 (setq org-indirect-dedicated-frame (make-frame)))))
4730 (delete-other-windows)
4731 (switch-to-buffer ibuf)
4732 (org-set-frame-title (concat "Indirect: " heading)))
4733 ((eq org-indirect-buffer-display 'current-window)
4734 (switch-to-buffer ibuf))
4735 ((eq org-indirect-buffer-display 'other-window)
4736 (pop-to-buffer ibuf))
4737 (t (error "Invalid value.")))
4738 (if (featurep 'xemacs)
4739 (save-excursion (org-mode) (turn-on-font-lock)))
4740 (narrow-to-region beg end)
4741 (show-all)
4742 (goto-char pos)
4743 (and (window-live-p cwin) (select-window cwin))))
4745 (defun org-get-indirect-buffer (&optional buffer)
4746 (setq buffer (or buffer (current-buffer)))
4747 (let ((n 1) (base (buffer-name buffer)) bname)
4748 (while (buffer-live-p
4749 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4750 (setq n (1+ n)))
4751 (condition-case nil
4752 (make-indirect-buffer buffer bname 'clone)
4753 (error (make-indirect-buffer buffer bname)))))
4755 (defun org-set-frame-title (title)
4756 "Set the title of the current frame to the string TITLE."
4757 ;; FIXME: how to name a single frame in XEmacs???
4758 (unless (featurep 'xemacs)
4759 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4761 ;;;; Structure editing
4763 ;;; Inserting headlines
4765 (defun org-insert-heading (&optional force-heading)
4766 "Insert a new heading or item with same depth at point.
4767 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4768 If point is at the beginning of a headline, insert a sibling before the
4769 current headline. If point is not at the beginning, do not split the line,
4770 but create the new headline after the current line."
4771 (interactive "P")
4772 (if (= (buffer-size) 0)
4773 (insert "\n* ")
4774 (when (or force-heading (not (org-insert-item)))
4775 (let* ((head (save-excursion
4776 (condition-case nil
4777 (progn
4778 (org-back-to-heading)
4779 (match-string 0))
4780 (error "*"))))
4781 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4782 pos hide-previous previous-pos)
4783 (cond
4784 ((and (org-on-heading-p) (bolp)
4785 (or (bobp)
4786 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4787 ;; insert before the current line
4788 (open-line (if blank 2 1)))
4789 ((and (bolp)
4790 (or (bobp)
4791 (save-excursion
4792 (backward-char 1) (not (org-invisible-p)))))
4793 ;; insert right here
4794 nil)
4796 ;; somewhere in the line
4797 (save-excursion
4798 (setq previous-pos (point-at-bol))
4799 (end-of-line)
4800 (setq hide-previous (org-invisible-p)))
4801 (and org-insert-heading-respect-content (org-show-subtree))
4802 (let ((split
4803 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4804 (save-excursion
4805 (let ((p (point)))
4806 (goto-char (point-at-bol))
4807 (and (looking-at org-complex-heading-regexp)
4808 (> p (match-beginning 4)))))))
4809 tags pos)
4810 (cond
4811 (org-insert-heading-respect-content
4812 (org-end-of-subtree nil t)
4813 (or (bolp) (newline))
4814 (open-line 1))
4815 ((org-on-heading-p)
4816 (when hide-previous
4817 (show-children)
4818 (org-show-entry))
4819 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4820 (setq tags (and (match-end 2) (match-string 2)))
4821 (and (match-end 1)
4822 (delete-region (match-beginning 1) (match-end 1)))
4823 (setq pos (point-at-bol))
4824 (or split (end-of-line 1))
4825 (delete-horizontal-space)
4826 (newline (if blank 2 1))
4827 (when tags
4828 (save-excursion
4829 (goto-char pos)
4830 (end-of-line 1)
4831 (insert " " tags)
4832 (org-set-tags nil 'align))))
4834 (or split (end-of-line 1))
4835 (newline (if blank 2 1)))))))
4836 (insert head) (just-one-space)
4837 (setq pos (point))
4838 (end-of-line 1)
4839 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4840 (when (and org-insert-heading-respect-content hide-previous)
4841 (save-excursion
4842 (goto-char previous-pos)
4843 (hide-subtree)))
4844 (run-hooks 'org-insert-heading-hook)))))
4846 (defun org-get-heading (&optional no-tags)
4847 "Return the heading of the current entry, without the stars."
4848 (save-excursion
4849 (org-back-to-heading t)
4850 (if (looking-at
4851 (if no-tags
4852 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4853 "\\*+[ \t]+\\([^\r\n]*\\)"))
4854 (match-string 1) "")))
4856 (defun org-insert-heading-after-current ()
4857 "Insert a new heading with same level as current, after current subtree."
4858 (interactive)
4859 (org-back-to-heading)
4860 (org-insert-heading)
4861 (org-move-subtree-down)
4862 (end-of-line 1))
4864 (defun org-insert-heading-respect-content ()
4865 (interactive)
4866 (let ((org-insert-heading-respect-content t))
4867 (org-insert-heading t)))
4869 (defun org-insert-todo-heading-respect-content (&optional force-state)
4870 (interactive "P")
4871 (let ((org-insert-heading-respect-content t))
4872 (org-insert-todo-heading force-state t)))
4874 (defun org-insert-todo-heading (arg &optional force-heading)
4875 "Insert a new heading with the same level and TODO state as current heading.
4876 If the heading has no TODO state, or if the state is DONE, use the first
4877 state (TODO by default). Also with prefix arg, force first state."
4878 (interactive "P")
4879 (when (or force-heading (not (org-insert-item 'checkbox)))
4880 (org-insert-heading force-heading)
4881 (save-excursion
4882 (org-back-to-heading)
4883 (outline-previous-heading)
4884 (looking-at org-todo-line-regexp))
4885 (if (or arg
4886 (not (match-beginning 2))
4887 (member (match-string 2) org-done-keywords))
4888 (insert (car org-todo-keywords-1) " ")
4889 (insert (match-string 2) " "))
4890 (when org-provide-todo-statistics
4891 (org-update-parent-todo-statistics))))
4893 (defun org-insert-subheading (arg)
4894 "Insert a new subheading and demote it.
4895 Works for outline headings and for plain lists alike."
4896 (interactive "P")
4897 (org-insert-heading arg)
4898 (cond
4899 ((org-on-heading-p) (org-do-demote))
4900 ((org-at-item-p) (org-indent-item 1))))
4902 (defun org-insert-todo-subheading (arg)
4903 "Insert a new subheading with TODO keyword or checkbox and demote it.
4904 Works for outline headings and for plain lists alike."
4905 (interactive "P")
4906 (org-insert-todo-heading arg)
4907 (cond
4908 ((org-on-heading-p) (org-do-demote))
4909 ((org-at-item-p) (org-indent-item 1))))
4911 ;;; Promotion and Demotion
4913 (defun org-promote-subtree ()
4914 "Promote the entire subtree.
4915 See also `org-promote'."
4916 (interactive)
4917 (save-excursion
4918 (org-map-tree 'org-promote))
4919 (org-fix-position-after-promote))
4921 (defun org-demote-subtree ()
4922 "Demote the entire subtree. See `org-demote'.
4923 See also `org-promote'."
4924 (interactive)
4925 (save-excursion
4926 (org-map-tree 'org-demote))
4927 (org-fix-position-after-promote))
4930 (defun org-do-promote ()
4931 "Promote the current heading higher up the tree.
4932 If the region is active in `transient-mark-mode', promote all headings
4933 in the region."
4934 (interactive)
4935 (save-excursion
4936 (if (org-region-active-p)
4937 (org-map-region 'org-promote (region-beginning) (region-end))
4938 (org-promote)))
4939 (org-fix-position-after-promote))
4941 (defun org-do-demote ()
4942 "Demote the current heading lower down the tree.
4943 If the region is active in `transient-mark-mode', demote all headings
4944 in the region."
4945 (interactive)
4946 (save-excursion
4947 (if (org-region-active-p)
4948 (org-map-region 'org-demote (region-beginning) (region-end))
4949 (org-demote)))
4950 (org-fix-position-after-promote))
4952 (defun org-fix-position-after-promote ()
4953 "Make sure that after pro/demotion cursor position is right."
4954 (let ((pos (point)))
4955 (when (save-excursion
4956 (beginning-of-line 1)
4957 (looking-at org-todo-line-regexp)
4958 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4959 (cond ((eobp) (insert " "))
4960 ((eolp) (insert " "))
4961 ((equal (char-after) ?\ ) (forward-char 1))))))
4963 (defun org-reduced-level (l)
4964 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4966 (defun org-get-valid-level (level &optional change)
4967 "Rectify a level change under the influence of `org-odd-levels-only'
4968 LEVEL is a current level, CHANGE is by how much the level should be
4969 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4970 even level numbers will become the next higher odd number."
4971 (if org-odd-levels-only
4972 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4973 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4974 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4975 (max 1 (+ level change))))
4977 (if (boundp 'define-obsolete-function-alias)
4978 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4979 (define-obsolete-function-alias 'org-get-legal-level
4980 'org-get-valid-level)
4981 (define-obsolete-function-alias 'org-get-legal-level
4982 'org-get-valid-level "23.1")))
4984 (defun org-promote ()
4985 "Promote the current heading higher up the tree.
4986 If the region is active in `transient-mark-mode', promote all headings
4987 in the region."
4988 (org-back-to-heading t)
4989 (let* ((level (save-match-data (funcall outline-level)))
4990 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4991 (diff (abs (- level (length up-head) -1))))
4992 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4993 (replace-match up-head nil t)
4994 ;; Fixup tag positioning
4995 (and org-auto-align-tags (org-set-tags nil t))
4996 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4998 (defun org-demote ()
4999 "Demote the current heading lower down the tree.
5000 If the region is active in `transient-mark-mode', demote all headings
5001 in the region."
5002 (org-back-to-heading t)
5003 (let* ((level (save-match-data (funcall outline-level)))
5004 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5005 (diff (abs (- level (length down-head) -1))))
5006 (replace-match down-head nil t)
5007 ;; Fixup tag positioning
5008 (and org-auto-align-tags (org-set-tags nil t))
5009 (if org-adapt-indentation (org-fixup-indentation diff))))
5011 (defun org-map-tree (fun)
5012 "Call FUN for every heading underneath the current one."
5013 (org-back-to-heading)
5014 (let ((level (funcall outline-level)))
5015 (save-excursion
5016 (funcall fun)
5017 (while (and (progn
5018 (outline-next-heading)
5019 (> (funcall outline-level) level))
5020 (not (eobp)))
5021 (funcall fun)))))
5023 (defun org-map-region (fun beg end)
5024 "Call FUN for every heading between BEG and END."
5025 (let ((org-ignore-region t))
5026 (save-excursion
5027 (setq end (copy-marker end))
5028 (goto-char beg)
5029 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5030 (< (point) end))
5031 (funcall fun))
5032 (while (and (progn
5033 (outline-next-heading)
5034 (< (point) end))
5035 (not (eobp)))
5036 (funcall fun)))))
5038 (defun org-fixup-indentation (diff)
5039 "Change the indentation in the current entry by DIFF
5040 However, if any line in the current entry has no indentation, or if it
5041 would end up with no indentation after the change, nothing at all is done."
5042 (save-excursion
5043 (let ((end (save-excursion (outline-next-heading)
5044 (point-marker)))
5045 (prohibit (if (> diff 0)
5046 "^\\S-"
5047 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5048 col)
5049 (unless (save-excursion (end-of-line 1)
5050 (re-search-forward prohibit end t))
5051 (while (and (< (point) end)
5052 (re-search-forward "^[ \t]+" end t))
5053 (goto-char (match-end 0))
5054 (setq col (current-column))
5055 (if (< diff 0) (replace-match ""))
5056 (org-indent-to-column (+ diff col))))
5057 (move-marker end nil))))
5059 (defun org-convert-to-odd-levels ()
5060 "Convert an org-mode file with all levels allowed to one with odd levels.
5061 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5062 level 5 etc."
5063 (interactive)
5064 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5065 (let ((org-odd-levels-only nil) n)
5066 (save-excursion
5067 (goto-char (point-min))
5068 (while (re-search-forward "^\\*\\*+ " nil t)
5069 (setq n (- (length (match-string 0)) 2))
5070 (while (>= (setq n (1- n)) 0)
5071 (org-demote))
5072 (end-of-line 1))))))
5075 (defun org-convert-to-oddeven-levels ()
5076 "Convert an org-mode file with only odd levels to one with odd and even levels.
5077 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5078 section with an even level, conversion would destroy the structure of the file. An error
5079 is signaled in this case."
5080 (interactive)
5081 (goto-char (point-min))
5082 ;; First check if there are no even levels
5083 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5084 (org-show-context t)
5085 (error "Not all levels are odd in this file. Conversion not possible."))
5086 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5087 (let ((org-odd-levels-only nil) n)
5088 (save-excursion
5089 (goto-char (point-min))
5090 (while (re-search-forward "^\\*\\*+ " nil t)
5091 (setq n (/ (1- (length (match-string 0))) 2))
5092 (while (>= (setq n (1- n)) 0)
5093 (org-promote))
5094 (end-of-line 1))))))
5096 (defun org-tr-level (n)
5097 "Make N odd if required."
5098 (if org-odd-levels-only (1+ (/ n 2)) n))
5100 ;;; Vertical tree motion, cutting and pasting of subtrees
5102 (defun org-move-subtree-up (&optional arg)
5103 "Move the current subtree up past ARG headlines of the same level."
5104 (interactive "p")
5105 (org-move-subtree-down (- (prefix-numeric-value arg))))
5107 (defun org-move-subtree-down (&optional arg)
5108 "Move the current subtree down past ARG headlines of the same level."
5109 (interactive "p")
5110 (setq arg (prefix-numeric-value arg))
5111 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5112 'outline-get-last-sibling))
5113 (ins-point (make-marker))
5114 (cnt (abs arg))
5115 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5116 ;; Select the tree
5117 (org-back-to-heading)
5118 (setq beg0 (point))
5119 (save-excursion
5120 (setq ne-beg (org-back-over-empty-lines))
5121 (setq beg (point)))
5122 (save-match-data
5123 (save-excursion (outline-end-of-heading)
5124 (setq folded (org-invisible-p)))
5125 (outline-end-of-subtree))
5126 (outline-next-heading)
5127 (setq ne-end (org-back-over-empty-lines))
5128 (setq end (point))
5129 (goto-char beg0)
5130 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5131 ;; include less whitespace
5132 (save-excursion
5133 (goto-char beg)
5134 (forward-line (- ne-beg ne-end))
5135 (setq beg (point))))
5136 ;; Find insertion point, with error handling
5137 (while (> cnt 0)
5138 (or (and (funcall movfunc) (looking-at outline-regexp))
5139 (progn (goto-char beg0)
5140 (error "Cannot move past superior level or buffer limit")))
5141 (setq cnt (1- cnt)))
5142 (if (> arg 0)
5143 ;; Moving forward - still need to move over subtree
5144 (progn (org-end-of-subtree t t)
5145 (save-excursion
5146 (org-back-over-empty-lines)
5147 (or (bolp) (newline)))))
5148 (setq ne-ins (org-back-over-empty-lines))
5149 (move-marker ins-point (point))
5150 (setq txt (buffer-substring beg end))
5151 (org-save-markers-in-region beg end)
5152 (delete-region beg end)
5153 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5154 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5155 (let ((bbb (point)))
5156 (insert-before-markers txt)
5157 (org-reinstall-markers-in-region bbb)
5158 (move-marker ins-point bbb))
5159 (or (bolp) (insert "\n"))
5160 (setq ins-end (point))
5161 (goto-char ins-point)
5162 (org-skip-whitespace)
5163 (when (and (< arg 0)
5164 (org-first-sibling-p)
5165 (> ne-ins ne-beg))
5166 ;; Move whitespace back to beginning
5167 (save-excursion
5168 (goto-char ins-end)
5169 (let ((kill-whole-line t))
5170 (kill-line (- ne-ins ne-beg)) (point)))
5171 (insert (make-string (- ne-ins ne-beg) ?\n)))
5172 (move-marker ins-point nil)
5173 (org-compact-display-after-subtree-move)
5174 (org-show-empty-lines-in-parent)
5175 (unless folded
5176 (org-show-entry)
5177 (show-children)
5178 (org-cycle-hide-drawers 'children))))
5180 (defvar org-subtree-clip ""
5181 "Clipboard for cut and paste of subtrees.
5182 This is actually only a copy of the kill, because we use the normal kill
5183 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5185 (defvar org-subtree-clip-folded nil
5186 "Was the last copied subtree folded?
5187 This is used to fold the tree back after pasting.")
5189 (defun org-cut-subtree (&optional n)
5190 "Cut the current subtree into the clipboard.
5191 With prefix arg N, cut this many sequential subtrees.
5192 This is a short-hand for marking the subtree and then cutting it."
5193 (interactive "p")
5194 (org-copy-subtree n 'cut))
5196 (defun org-copy-subtree (&optional n cut force-store-markers)
5197 "Cut the current subtree into the clipboard.
5198 With prefix arg N, cut this many sequential subtrees.
5199 This is a short-hand for marking the subtree and then copying it.
5200 If CUT is non-nil, actually cut the subtree.
5201 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5202 of some markers in the region, even if CUT is non-nil. This is
5203 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5204 (interactive "p")
5205 (let (beg end folded (beg0 (point)))
5206 (if (interactive-p)
5207 (org-back-to-heading nil) ; take what looks like a subtree
5208 (org-back-to-heading t)) ; take what is really there
5209 (org-back-over-empty-lines)
5210 (setq beg (point))
5211 (skip-chars-forward " \t\r\n")
5212 (save-match-data
5213 (save-excursion (outline-end-of-heading)
5214 (setq folded (org-invisible-p)))
5215 (condition-case nil
5216 (outline-forward-same-level (1- n))
5217 (error nil))
5218 (org-end-of-subtree t t))
5219 (org-back-over-empty-lines)
5220 (setq end (point))
5221 (goto-char beg0)
5222 (when (> end beg)
5223 (setq org-subtree-clip-folded folded)
5224 (when (or cut force-store-markers)
5225 (org-save-markers-in-region beg end))
5226 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5227 (setq org-subtree-clip (current-kill 0))
5228 (message "%s: Subtree(s) with %d characters"
5229 (if cut "Cut" "Copied")
5230 (length org-subtree-clip)))))
5232 (defun org-paste-subtree (&optional level tree for-yank)
5233 "Paste the clipboard as a subtree, with modification of headline level.
5234 The entire subtree is promoted or demoted in order to match a new headline
5235 level.
5237 If the cursor is at the beginning of a headline, the same level as
5238 that headline is used to paste the tree
5240 If not, the new level is derived from the *visible* headings
5241 before and after the insertion point, and taken to be the inferior headline
5242 level of the two. So if the previous visible heading is level 3 and the
5243 next is level 4 (or vice versa), level 4 will be used for insertion.
5244 This makes sure that the subtree remains an independent subtree and does
5245 not swallow low level entries.
5247 You can also force a different level, either by using a numeric prefix
5248 argument, or by inserting the heading marker by hand. For example, if the
5249 cursor is after \"*****\", then the tree will be shifted to level 5.
5251 If optional TREE is given, use this text instead of the kill ring.
5253 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5254 move back over whitespace before inserting, and move point to the end of
5255 the inserted text when done."
5256 (interactive "P")
5257 (unless (org-kill-is-subtree-p tree)
5258 (error "%s"
5259 (substitute-command-keys
5260 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5261 (let* ((visp (not (org-invisible-p)))
5262 (txt (or tree (and kill-ring (current-kill 0))))
5263 (^re (concat "^\\(" outline-regexp "\\)"))
5264 (re (concat "\\(" outline-regexp "\\)"))
5265 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5267 (old-level (if (string-match ^re txt)
5268 (- (match-end 0) (match-beginning 0) 1)
5269 -1))
5270 (force-level (cond (level (prefix-numeric-value level))
5271 ((and (looking-at "[ \t]*$")
5272 (string-match
5273 ^re_ (buffer-substring
5274 (point-at-bol) (point))))
5275 (- (match-end 1) (match-beginning 1)))
5276 ((and (bolp)
5277 (looking-at org-outline-regexp))
5278 (- (match-end 0) (point) 1))
5279 (t nil)))
5280 (previous-level (save-excursion
5281 (condition-case nil
5282 (progn
5283 (outline-previous-visible-heading 1)
5284 (if (looking-at re)
5285 (- (match-end 0) (match-beginning 0) 1)
5287 (error 1))))
5288 (next-level (save-excursion
5289 (condition-case nil
5290 (progn
5291 (or (looking-at outline-regexp)
5292 (outline-next-visible-heading 1))
5293 (if (looking-at re)
5294 (- (match-end 0) (match-beginning 0) 1)
5296 (error 1))))
5297 (new-level (or force-level (max previous-level next-level)))
5298 (shift (if (or (= old-level -1)
5299 (= new-level -1)
5300 (= old-level new-level))
5302 (- new-level old-level)))
5303 (delta (if (> shift 0) -1 1))
5304 (func (if (> shift 0) 'org-demote 'org-promote))
5305 (org-odd-levels-only nil)
5306 beg end newend)
5307 ;; Remove the forced level indicator
5308 (if force-level
5309 (delete-region (point-at-bol) (point)))
5310 ;; Paste
5311 (beginning-of-line 1)
5312 (unless for-yank (org-back-over-empty-lines))
5313 (setq beg (point))
5314 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5315 (insert-before-markers txt)
5316 (unless (string-match "\n\\'" txt) (insert "\n"))
5317 (setq newend (point))
5318 (org-reinstall-markers-in-region beg)
5319 (setq end (point))
5320 (goto-char beg)
5321 (skip-chars-forward " \t\n\r")
5322 (setq beg (point))
5323 (if (and (org-invisible-p) visp)
5324 (save-excursion (outline-show-heading)))
5325 ;; Shift if necessary
5326 (unless (= shift 0)
5327 (save-restriction
5328 (narrow-to-region beg end)
5329 (while (not (= shift 0))
5330 (org-map-region func (point-min) (point-max))
5331 (setq shift (+ delta shift)))
5332 (goto-char (point-min))
5333 (setq newend (point-max))))
5334 (when (or (interactive-p) for-yank)
5335 (message "Clipboard pasted as level %d subtree" new-level))
5336 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5337 kill-ring
5338 (eq org-subtree-clip (current-kill 0))
5339 org-subtree-clip-folded)
5340 ;; The tree was folded before it was killed/copied
5341 (hide-subtree))
5342 (and for-yank (goto-char newend))))
5344 (defun org-kill-is-subtree-p (&optional txt)
5345 "Check if the current kill is an outline subtree, or a set of trees.
5346 Returns nil if kill does not start with a headline, or if the first
5347 headline level is not the largest headline level in the tree.
5348 So this will actually accept several entries of equal levels as well,
5349 which is OK for `org-paste-subtree'.
5350 If optional TXT is given, check this string instead of the current kill."
5351 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5352 (start-level (and kill
5353 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5354 org-outline-regexp "\\)")
5355 kill)
5356 (- (match-end 2) (match-beginning 2) 1)))
5357 (re (concat "^" org-outline-regexp))
5358 (start (1+ (or (match-beginning 2) -1))))
5359 (if (not start-level)
5360 (progn
5361 nil) ;; does not even start with a heading
5362 (catch 'exit
5363 (while (setq start (string-match re kill (1+ start)))
5364 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5365 (throw 'exit nil)))
5366 t))))
5368 (defvar org-markers-to-move nil
5369 "Markers that should be moved with a cut-and-paste operation.
5370 Those markers are stored together with their positions relative to
5371 the start of the region.")
5373 (defun org-save-markers-in-region (beg end)
5374 "Check markers in region.
5375 If these markers are between BEG and END, record their position relative
5376 to BEG, so that after moving the block of text, we can put the markers back
5377 into place.
5378 This function gets called just before an entry or tree gets cut from the
5379 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5380 called immediately, to move the markers with the entries."
5381 (setq org-markers-to-move nil)
5382 (when (featurep 'org-clock)
5383 (org-clock-save-markers-for-cut-and-paste beg end))
5384 (when (featurep 'org-agenda)
5385 (org-agenda-save-markers-for-cut-and-paste beg end)))
5387 (defun org-check-and-save-marker (marker beg end)
5388 "Check if MARKER is between BEG and END.
5389 If yes, remember the marker and the distance to BEG."
5390 (when (and (marker-buffer marker)
5391 (equal (marker-buffer marker) (current-buffer)))
5392 (if (and (>= marker beg) (< marker end))
5393 (push (cons marker (- marker beg)) org-markers-to-move))))
5395 (defun org-reinstall-markers-in-region (beg)
5396 "Move all remembered markers to their position relative to BEG."
5397 (mapc (lambda (x)
5398 (move-marker (car x) (+ beg (cdr x))))
5399 org-markers-to-move)
5400 (setq org-markers-to-move nil))
5402 (defun org-narrow-to-subtree ()
5403 "Narrow buffer to the current subtree."
5404 (interactive)
5405 (save-excursion
5406 (save-match-data
5407 (narrow-to-region
5408 (progn (org-back-to-heading) (point))
5409 (progn (org-end-of-subtree t) (point))))))
5412 ;;; Outline Sorting
5414 (defun org-sort (with-case)
5415 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5416 Optional argument WITH-CASE means sort case-sensitively."
5417 (interactive "P")
5418 (if (org-at-table-p)
5419 (org-call-with-arg 'org-table-sort-lines with-case)
5420 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5422 (defun org-sort-remove-invisible (s)
5423 (remove-text-properties 0 (length s) org-rm-props s)
5424 (while (string-match org-bracket-link-regexp s)
5425 (setq s (replace-match (if (match-end 2)
5426 (match-string 3 s)
5427 (match-string 1 s)) t t s)))
5430 (defvar org-priority-regexp) ; defined later in the file
5432 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5433 "Sort entries on a certain level of an outline tree.
5434 If there is an active region, the entries in the region are sorted.
5435 Else, if the cursor is before the first entry, sort the top-level items.
5436 Else, the children of the entry at point are sorted.
5438 Sorting can be alphabetically, numerically, and by date/time as given by
5439 the first time stamp in the entry. The command prompts for the sorting
5440 type unless it has been given to the function through the SORTING-TYPE
5441 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5442 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5443 called with point at the beginning of the record. It must return either
5444 a string or a number that should serve as the sorting key for that record.
5446 Comparing entries ignores case by default. However, with an optional argument
5447 WITH-CASE, the sorting considers case as well."
5448 (interactive "P")
5449 (let ((case-func (if with-case 'identity 'downcase))
5450 start beg end stars re re2
5451 txt what tmp plain-list-p)
5452 ;; Find beginning and end of region to sort
5453 (cond
5454 ((org-region-active-p)
5455 ;; we will sort the region
5456 (setq end (region-end)
5457 what "region")
5458 (goto-char (region-beginning))
5459 (if (not (org-on-heading-p)) (outline-next-heading))
5460 (setq start (point)))
5461 ((org-at-item-p)
5462 ;; we will sort this plain list
5463 (org-beginning-of-item-list) (setq start (point))
5464 (org-end-of-item-list) (setq end (point))
5465 (goto-char start)
5466 (setq plain-list-p t
5467 what "plain list"))
5468 ((or (org-on-heading-p)
5469 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5470 ;; we will sort the children of the current headline
5471 (org-back-to-heading)
5472 (setq start (point)
5473 end (progn (org-end-of-subtree t t)
5474 (org-back-over-empty-lines)
5475 (point))
5476 what "children")
5477 (goto-char start)
5478 (show-subtree)
5479 (outline-next-heading))
5481 ;; we will sort the top-level entries in this file
5482 (goto-char (point-min))
5483 (or (org-on-heading-p) (outline-next-heading))
5484 (setq start (point) end (point-max) what "top-level")
5485 (goto-char start)
5486 (show-all)))
5488 (setq beg (point))
5489 (if (>= beg end) (error "Nothing to sort"))
5491 (unless plain-list-p
5492 (looking-at "\\(\\*+\\)")
5493 (setq stars (match-string 1)
5494 re (concat "^" (regexp-quote stars) " +")
5495 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5496 txt (buffer-substring beg end))
5497 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5498 (if (and (not (equal stars "*")) (string-match re2 txt))
5499 (error "Region to sort contains a level above the first entry")))
5501 (unless sorting-type
5502 (message
5503 (if plain-list-p
5504 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5505 "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:")
5506 what)
5507 (setq sorting-type (read-char-exclusive))
5509 (and (= (downcase sorting-type) ?f)
5510 (setq getkey-func
5511 (org-ido-completing-read "Sort using function: "
5512 obarray 'fboundp t nil nil))
5513 (setq getkey-func (intern getkey-func)))
5515 (and (= (downcase sorting-type) ?r)
5516 (setq property
5517 (org-ido-completing-read "Property: "
5518 (mapcar 'list (org-buffer-property-keys t))
5519 nil t))))
5521 (message "Sorting entries...")
5523 (save-restriction
5524 (narrow-to-region start end)
5526 (let ((dcst (downcase sorting-type))
5527 (now (current-time)))
5528 (sort-subr
5529 (/= dcst sorting-type)
5530 ;; This function moves to the beginning character of the "record" to
5531 ;; be sorted.
5532 (if plain-list-p
5533 (lambda nil
5534 (if (org-at-item-p) t (goto-char (point-max))))
5535 (lambda nil
5536 (if (re-search-forward re nil t)
5537 (goto-char (match-beginning 0))
5538 (goto-char (point-max)))))
5539 ;; This function moves to the last character of the "record" being
5540 ;; sorted.
5541 (if plain-list-p
5542 'org-end-of-item
5543 (lambda nil
5544 (save-match-data
5545 (condition-case nil
5546 (outline-forward-same-level 1)
5547 (error
5548 (goto-char (point-max)))))))
5550 ;; This function returns the value that gets sorted against.
5551 (if plain-list-p
5552 (lambda nil
5553 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5554 (cond
5555 ((= dcst ?n)
5556 (string-to-number (buffer-substring (match-end 0)
5557 (point-at-eol))))
5558 ((= dcst ?a)
5559 (buffer-substring (match-end 0) (point-at-eol)))
5560 ((= dcst ?t)
5561 (if (re-search-forward org-ts-regexp
5562 (point-at-eol) t)
5563 (org-time-string-to-time (match-string 0))
5564 now))
5565 ((= dcst ?f)
5566 (if getkey-func
5567 (progn
5568 (setq tmp (funcall getkey-func))
5569 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5570 tmp)
5571 (error "Invalid key function `%s'" getkey-func)))
5572 (t (error "Invalid sorting type `%c'" sorting-type)))))
5573 (lambda nil
5574 (cond
5575 ((= dcst ?n)
5576 (if (looking-at org-complex-heading-regexp)
5577 (string-to-number (match-string 4))
5578 nil))
5579 ((= dcst ?a)
5580 (if (looking-at org-complex-heading-regexp)
5581 (funcall case-func (match-string 4))
5582 nil))
5583 ((= dcst ?t)
5584 (if (re-search-forward org-ts-regexp
5585 (save-excursion
5586 (forward-line 2)
5587 (point)) t)
5588 (org-time-string-to-time (match-string 0))
5589 now))
5590 ((= dcst ?p)
5591 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5592 (string-to-char (match-string 2))
5593 org-default-priority))
5594 ((= dcst ?r)
5595 (or (org-entry-get nil property) ""))
5596 ((= dcst ?o)
5597 (if (looking-at org-complex-heading-regexp)
5598 (- 9999 (length (member (match-string 2)
5599 org-todo-keywords-1)))))
5600 ((= dcst ?f)
5601 (if getkey-func
5602 (progn
5603 (setq tmp (funcall getkey-func))
5604 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5605 tmp)
5606 (error "Invalid key function `%s'" getkey-func)))
5607 (t (error "Invalid sorting type `%c'" sorting-type)))))
5609 (cond
5610 ((= dcst ?a) 'string<)
5611 ((= dcst ?t) 'time-less-p)
5612 (t nil)))))
5613 (message "Sorting entries...done")))
5615 (defun org-do-sort (table what &optional with-case sorting-type)
5616 "Sort TABLE of WHAT according to SORTING-TYPE.
5617 The user will be prompted for the SORTING-TYPE if the call to this
5618 function does not specify it. WHAT is only for the prompt, to indicate
5619 what is being sorted. The sorting key will be extracted from
5620 the car of the elements of the table.
5621 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5622 (unless sorting-type
5623 (message
5624 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5625 what)
5626 (setq sorting-type (read-char-exclusive)))
5627 (let ((dcst (downcase sorting-type))
5628 extractfun comparefun)
5629 ;; Define the appropriate functions
5630 (cond
5631 ((= dcst ?n)
5632 (setq extractfun 'string-to-number
5633 comparefun (if (= dcst sorting-type) '< '>)))
5634 ((= dcst ?a)
5635 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5636 (lambda(x) (downcase (org-sort-remove-invisible x))))
5637 comparefun (if (= dcst sorting-type)
5638 'string<
5639 (lambda (a b) (and (not (string< a b))
5640 (not (string= a b)))))))
5641 ((= dcst ?t)
5642 (setq extractfun
5643 (lambda (x)
5644 (if (string-match org-ts-regexp x)
5645 (time-to-seconds
5646 (org-time-string-to-time (match-string 0 x)))
5648 comparefun (if (= dcst sorting-type) '< '>)))
5649 (t (error "Invalid sorting type `%c'" sorting-type)))
5651 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5652 table)
5653 (lambda (a b) (funcall comparefun (car a) (car b))))))
5655 ;;; Editing source examples
5657 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5658 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5659 (defvar org-edit-src-force-single-line nil)
5660 (defvar org-edit-src-from-org-mode nil)
5661 (defvar org-edit-src-picture nil)
5663 (define-minor-mode org-exit-edit-mode
5664 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5666 (defun org-edit-src-code ()
5667 "Edit the source code example at point.
5668 An indirect buffer is created, and that buffer is then narrowed to the
5669 example at point and switched to the correct language mode. When done,
5670 exit by killing the buffer with \\[org-edit-src-exit]."
5671 (interactive)
5672 (let ((line (org-current-line))
5673 (case-fold-search t)
5674 (msg (substitute-command-keys
5675 "Edit, then exit with C-c ' (C-c and single quote)"))
5676 (info (org-edit-src-find-region-and-lang))
5677 (org-mode-p (eq major-mode 'org-mode))
5678 beg end lang lang-f single)
5679 (if (not info)
5681 (setq beg (nth 0 info)
5682 end (nth 1 info)
5683 lang (nth 2 info)
5684 single (nth 3 info)
5685 lang-f (intern (concat lang "-mode")))
5686 (unless (functionp lang-f)
5687 (error "No such language mode: %s" lang-f))
5688 (goto-line line)
5689 (if (get-buffer "*Org Edit Src Example*")
5690 (kill-buffer "*Org Edit Src Example*"))
5691 (switch-to-buffer (make-indirect-buffer (current-buffer)
5692 "*Org Edit Src Example*"))
5693 (narrow-to-region beg end)
5694 (remove-text-properties beg end '(display nil invisible nil
5695 intangible nil))
5696 (let ((org-inhibit-startup t))
5697 (funcall lang-f))
5698 (set (make-local-variable 'org-edit-src-force-single-line) single)
5699 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5700 (when org-mode-p
5701 (goto-char (point-min))
5702 (while (re-search-forward "^," nil t)
5703 (replace-match "")))
5704 (goto-line line)
5705 (org-exit-edit-mode)
5706 (org-set-local 'header-line-format msg)
5707 (message "%s" msg)
5708 t)))
5710 (defun org-edit-fixed-width-region ()
5711 "Edit the fixed-width ascii drawing at point.
5712 This must be a region where each line starts with ca colon followed by
5713 a space character.
5714 An indirect buffer is created, and that buffer is then narrowed to the
5715 example at point and switched to artist-mode. When done,
5716 exit by killing the buffer with \\[org-edit-src-exit]."
5717 (interactive)
5718 (let ((line (org-current-line))
5719 (case-fold-search t)
5720 (msg (substitute-command-keys
5721 "Edit, then exit with C-c ' (C-c and single quote)"))
5722 (org-mode-p (eq major-mode 'org-mode))
5723 beg end lang lang-f)
5724 (beginning-of-line 1)
5725 (if (looking-at "[ \t]*[^:\n \t]")
5727 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5728 (setq beg (point) end beg)
5729 (save-excursion
5730 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5731 (setq beg (point-at-bol 2))
5732 (setq beg (point))))
5733 (save-excursion
5734 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5735 (setq end (1- (match-beginning 0)))
5736 (setq end (point))))
5737 (goto-line line))
5738 (if (get-buffer "*Org Edit Picture*")
5739 (kill-buffer "*Org Edit Picture*"))
5740 (switch-to-buffer (make-indirect-buffer (current-buffer)
5741 "*Org Edit Picture*"))
5742 (narrow-to-region beg end)
5743 (remove-text-properties beg end '(display nil invisible nil
5744 intangible nil))
5745 (when (fboundp 'font-lock-unfontify-region)
5746 (font-lock-unfontify-region (point-min) (point-max)))
5747 (cond
5748 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5749 (fundamental-mode)
5750 (artist-mode 1))
5751 (t (funcall org-edit-fixed-width-region-mode)))
5752 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5753 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5754 (set (make-local-variable 'org-edit-src-picture) t)
5755 (goto-char (point-min))
5756 (while (re-search-forward "^[ \t]*: ?" nil t)
5757 (replace-match ""))
5758 (goto-line line)
5759 (org-exit-edit-mode)
5760 (org-set-local 'header-line-format msg)
5761 (message "%s" msg)
5762 t)))
5765 (defun org-edit-src-find-region-and-lang ()
5766 "Find the region and language for a local edit.
5767 Return a list with beginning and end of the region, a string representing
5768 the language, a switch telling of the content should be in a single line."
5769 (let ((re-list
5770 (append
5771 org-edit-src-region-extra
5773 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5774 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5775 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5776 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5777 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5778 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5779 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5780 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5781 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5782 ("^#\\+html:" "\n" "html" single-line)
5783 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5784 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5785 ("^#\\+latex:" "\n" "latex" single-line)
5786 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5787 ("^#\\+ascii:" "\n" "ascii" single-line)
5789 (pos (point))
5790 re re1 re2 single beg end lang)
5791 (catch 'exit
5792 (while (setq entry (pop re-list))
5793 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5794 single (nth 3 entry))
5795 (save-excursion
5796 (if (or (looking-at re1)
5797 (re-search-backward re1 nil t))
5798 (progn
5799 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5800 (if (and (re-search-forward re2 nil t)
5801 (>= (match-end 0) pos))
5802 (throw 'exit (list beg (match-beginning 0) lang single))))
5803 (if (or (looking-at re2)
5804 (re-search-forward re2 nil t))
5805 (progn
5806 (setq end (match-beginning 0))
5807 (if (and (re-search-backward re1 nil t)
5808 (<= (match-beginning 0) pos))
5809 (throw 'exit
5810 (list (match-end 0) end
5811 (org-edit-src-get-lang lang) single)))))))))))
5813 (defun org-edit-src-get-lang (lang)
5814 "Extract the src language."
5815 (let ((m (match-string 0)))
5816 (cond
5817 ((stringp lang) lang)
5818 ((integerp lang) (match-string lang))
5819 ((and (eq lang 'lang)
5820 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5821 (match-string 1 m))
5822 ((and (eq lang 'style)
5823 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5824 (match-string 1 m))
5825 (t "fundamental"))))
5827 (defun org-edit-src-exit ()
5828 "Exit special edit and protect problematic lines."
5829 (interactive)
5830 (unless (buffer-base-buffer (current-buffer))
5831 (error "This is not an indirect buffer, something is wrong..."))
5832 (unless (> (point-min) 1)
5833 (error "This buffer is not narrowed, something is wrong..."))
5834 (goto-char (point-min))
5835 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5836 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5837 (when (org-bound-and-true-p org-edit-src-force-single-line)
5838 (goto-char (point-min))
5839 (while (re-search-forward "\n" nil t)
5840 (replace-match " "))
5841 (goto-char (point-min))
5842 (if (looking-at "\\s-*") (replace-match " "))
5843 (if (re-search-forward "\\s-+\\'" nil t)
5844 (replace-match "")))
5845 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5846 (goto-char (point-min))
5847 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5848 (replace-match ",\\1"))
5849 (when font-lock-mode
5850 (font-lock-unfontify-region (point-min) (point-max)))
5851 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5852 (when (org-bound-and-true-p org-edit-src-picture)
5853 (untabify (point-min) (point-max))
5854 (goto-char (point-min))
5855 (while (re-search-forward "^" nil t)
5856 (replace-match ": "))
5857 (when font-lock-mode
5858 (font-lock-unfontify-region (point-min) (point-max)))
5859 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5860 (kill-buffer (current-buffer))
5861 (and (org-mode-p) (org-restart-font-lock)))
5864 ;;; The orgstruct minor mode
5866 ;; Define a minor mode which can be used in other modes in order to
5867 ;; integrate the org-mode structure editing commands.
5869 ;; This is really a hack, because the org-mode structure commands use
5870 ;; keys which normally belong to the major mode. Here is how it
5871 ;; works: The minor mode defines all the keys necessary to operate the
5872 ;; structure commands, but wraps the commands into a function which
5873 ;; tests if the cursor is currently at a headline or a plain list
5874 ;; item. If that is the case, the structure command is used,
5875 ;; temporarily setting many Org-mode variables like regular
5876 ;; expressions for filling etc. However, when any of those keys is
5877 ;; used at a different location, function uses `key-binding' to look
5878 ;; up if the key has an associated command in another currently active
5879 ;; keymap (minor modes, major mode, global), and executes that
5880 ;; command. There might be problems if any of the keys is otherwise
5881 ;; used as a prefix key.
5883 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5884 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5885 ;; addresses this by checking explicitly for both bindings.
5887 (defvar orgstruct-mode-map (make-sparse-keymap)
5888 "Keymap for the minor `orgstruct-mode'.")
5890 (defvar org-local-vars nil
5891 "List of local variables, for use by `orgstruct-mode'")
5893 ;;;###autoload
5894 (define-minor-mode orgstruct-mode
5895 "Toggle the minor more `orgstruct-mode'.
5896 This mode is for using Org-mode structure commands in other modes.
5897 The following key behave as if Org-mode was active, if the cursor
5898 is on a headline, or on a plain list item (both in the definition
5899 of Org-mode).
5901 M-up Move entry/item up
5902 M-down Move entry/item down
5903 M-left Promote
5904 M-right Demote
5905 M-S-up Move entry/item up
5906 M-S-down Move entry/item down
5907 M-S-left Promote subtree
5908 M-S-right Demote subtree
5909 M-q Fill paragraph and items like in Org-mode
5910 C-c ^ Sort entries
5911 C-c - Cycle list bullet
5912 TAB Cycle item visibility
5913 M-RET Insert new heading/item
5914 S-M-RET Insert new TODO heading / Chekbox item
5915 C-c C-c Set tags / toggle checkbox"
5916 nil " OrgStruct" nil
5917 (org-load-modules-maybe)
5918 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5920 ;;;###autoload
5921 (defun turn-on-orgstruct ()
5922 "Unconditionally turn on `orgstruct-mode'."
5923 (orgstruct-mode 1))
5925 ;;;###autoload
5926 (defun turn-on-orgstruct++ ()
5927 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5928 In addition to setting orgstruct-mode, this also exports all indentation and
5929 autofilling variables from org-mode into the buffer. Note that turning
5930 off orgstruct-mode will *not* remove these additional settings."
5931 (orgstruct-mode 1)
5932 (let (var val)
5933 (mapc
5934 (lambda (x)
5935 (when (string-match
5936 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5937 (symbol-name (car x)))
5938 (setq var (car x) val (nth 1 x))
5939 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5940 org-local-vars)))
5942 (defun orgstruct-error ()
5943 "Error when there is no default binding for a structure key."
5944 (interactive)
5945 (error "This key has no function outside structure elements"))
5947 (defun orgstruct-setup ()
5948 "Setup orgstruct keymaps."
5949 (let ((nfunc 0)
5950 (bindings
5951 (list
5952 '([(meta up)] org-metaup)
5953 '([(meta down)] org-metadown)
5954 '([(meta left)] org-metaleft)
5955 '([(meta right)] org-metaright)
5956 '([(meta shift up)] org-shiftmetaup)
5957 '([(meta shift down)] org-shiftmetadown)
5958 '([(meta shift left)] org-shiftmetaleft)
5959 '([(meta shift right)] org-shiftmetaright)
5960 '([(shift up)] org-shiftup)
5961 '([(shift down)] org-shiftdown)
5962 '([(shift left)] org-shiftleft)
5963 '([(shift right)] org-shiftright)
5964 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5965 '("\M-q" fill-paragraph)
5966 '("\C-c^" org-sort)
5967 '("\C-c-" org-cycle-list-bullet)))
5968 elt key fun cmd)
5969 (while (setq elt (pop bindings))
5970 (setq nfunc (1+ nfunc))
5971 (setq key (org-key (car elt))
5972 fun (nth 1 elt)
5973 cmd (orgstruct-make-binding fun nfunc key))
5974 (org-defkey orgstruct-mode-map key cmd))
5976 ;; Special treatment needed for TAB and RET
5977 (org-defkey orgstruct-mode-map [(tab)]
5978 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5979 (org-defkey orgstruct-mode-map "\C-i"
5980 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5982 (org-defkey orgstruct-mode-map "\M-\C-m"
5983 (orgstruct-make-binding 'org-insert-heading 105
5984 "\M-\C-m" [(meta return)]))
5985 (org-defkey orgstruct-mode-map [(meta return)]
5986 (orgstruct-make-binding 'org-insert-heading 106
5987 [(meta return)] "\M-\C-m"))
5989 (org-defkey orgstruct-mode-map [(shift meta return)]
5990 (orgstruct-make-binding 'org-insert-todo-heading 107
5991 [(meta return)] "\M-\C-m"))
5993 (unless org-local-vars
5994 (setq org-local-vars (org-get-local-variables)))
5998 (defun orgstruct-make-binding (fun n &rest keys)
5999 "Create a function for binding in the structure minor mode.
6000 FUN is the command to call inside a table. N is used to create a unique
6001 command name. KEYS are keys that should be checked in for a command
6002 to execute outside of tables."
6003 (eval
6004 (list 'defun
6005 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6006 '(arg)
6007 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6008 "Outside of structure, run the binding of `"
6009 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6010 "'.")
6011 '(interactive "p")
6012 (list 'if
6013 '(org-context-p 'headline 'item)
6014 (list 'org-run-like-in-org-mode (list 'quote fun))
6015 (list 'let '(orgstruct-mode)
6016 (list 'call-interactively
6017 (append '(or)
6018 (mapcar (lambda (k)
6019 (list 'key-binding k))
6020 keys)
6021 '('orgstruct-error))))))))
6023 (defun org-context-p (&rest contexts)
6024 "Check if local context is any of CONTEXTS.
6025 Possible values in the list of contexts are `table', `headline', and `item'."
6026 (let ((pos (point)))
6027 (goto-char (point-at-bol))
6028 (prog1 (or (and (memq 'table contexts)
6029 (looking-at "[ \t]*|"))
6030 (and (memq 'headline contexts)
6031 ;;????????? (looking-at "\\*+"))
6032 (looking-at outline-regexp))
6033 (and (memq 'item contexts)
6034 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6035 (goto-char pos))))
6037 (defun org-get-local-variables ()
6038 "Return a list of all local variables in an org-mode buffer."
6039 (let (varlist)
6040 (with-current-buffer (get-buffer-create "*Org tmp*")
6041 (erase-buffer)
6042 (org-mode)
6043 (setq varlist (buffer-local-variables)))
6044 (kill-buffer "*Org tmp*")
6045 (delq nil
6046 (mapcar
6047 (lambda (x)
6048 (setq x
6049 (if (symbolp x)
6050 (list x)
6051 (list (car x) (list 'quote (cdr x)))))
6052 (if (string-match
6053 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6054 (symbol-name (car x)))
6055 x nil))
6056 varlist))))
6058 ;;;###autoload
6059 (defun org-run-like-in-org-mode (cmd)
6060 (org-load-modules-maybe)
6061 (unless org-local-vars
6062 (setq org-local-vars (org-get-local-variables)))
6063 (eval (list 'let org-local-vars
6064 (list 'call-interactively (list 'quote cmd)))))
6066 ;;;; Archiving
6068 (defun org-get-category (&optional pos)
6069 "Get the category applying to position POS."
6070 (get-text-property (or pos (point)) 'org-category))
6072 (defun org-refresh-category-properties ()
6073 "Refresh category text properties in the buffer."
6074 (let ((def-cat (cond
6075 ((null org-category)
6076 (if buffer-file-name
6077 (file-name-sans-extension
6078 (file-name-nondirectory buffer-file-name))
6079 "???"))
6080 ((symbolp org-category) (symbol-name org-category))
6081 (t org-category)))
6082 beg end cat pos optionp)
6083 (org-unmodified
6084 (save-excursion
6085 (save-restriction
6086 (widen)
6087 (goto-char (point-min))
6088 (put-text-property (point) (point-max) 'org-category def-cat)
6089 (while (re-search-forward
6090 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6091 (setq pos (match-end 0)
6092 optionp (equal (char-after (match-beginning 0)) ?#)
6093 cat (org-trim (match-string 2)))
6094 (if optionp
6095 (setq beg (point-at-bol) end (point-max))
6096 (org-back-to-heading t)
6097 (setq beg (point) end (org-end-of-subtree t t)))
6098 (put-text-property beg end 'org-category cat)
6099 (goto-char pos)))))))
6102 ;;;; Link Stuff
6104 ;;; Link abbreviations
6106 (defun org-link-expand-abbrev (link)
6107 "Apply replacements as defined in `org-link-abbrev-alist."
6108 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6109 (let* ((key (match-string 1 link))
6110 (as (or (assoc key org-link-abbrev-alist-local)
6111 (assoc key org-link-abbrev-alist)))
6112 (tag (and (match-end 2) (match-string 3 link)))
6113 rpl)
6114 (if (not as)
6115 link
6116 (setq rpl (cdr as))
6117 (cond
6118 ((symbolp rpl) (funcall rpl tag))
6119 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6120 ((string-match "%h" rpl)
6121 (replace-match (url-hexify-string (or tag "")) t t rpl))
6122 (t (concat rpl tag)))))
6123 link))
6125 ;;; Storing and inserting links
6127 (defvar org-insert-link-history nil
6128 "Minibuffer history for links inserted with `org-insert-link'.")
6130 (defvar org-stored-links nil
6131 "Contains the links stored with `org-store-link'.")
6133 (defvar org-store-link-plist nil
6134 "Plist with info about the most recently link created with `org-store-link'.")
6136 (defvar org-link-protocols nil
6137 "Link protocols added to Org-mode using `org-add-link-type'.")
6139 (defvar org-store-link-functions nil
6140 "List of functions that are called to create and store a link.
6141 Each function will be called in turn until one returns a non-nil
6142 value. Each function should check if it is responsible for creating
6143 this link (for example by looking at the major mode).
6144 If not, it must exit and return nil.
6145 If yes, it should return a non-nil value after a calling
6146 `org-store-link-props' with a list of properties and values.
6147 Special properties are:
6149 :type The link prefix. like \"http\". This must be given.
6150 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6151 This is obligatory as well.
6152 :description Optional default description for the second pair
6153 of brackets in an Org-mode link. The user can still change
6154 this when inserting this link into an Org-mode buffer.
6156 In addition to these, any additional properties can be specified
6157 and then used in remember templates.")
6159 (defun org-add-link-type (type &optional follow export)
6160 "Add TYPE to the list of `org-link-types'.
6161 Re-compute all regular expressions depending on `org-link-types'
6163 FOLLOW and EXPORT are two functions.
6165 FOLLOW should take the link path as the single argument and do whatever
6166 is necessary to follow the link, for example find a file or display
6167 a mail message.
6169 EXPORT should format the link path for export to one of the export formats.
6170 It should be a function accepting three arguments:
6172 path the path of the link, the text after the prefix (like \"http:\")
6173 desc the description of the link, if any, nil if there was no descripton
6174 format the export format, a symbol like `html' or `latex'.
6176 The function may use the FORMAT information to return different values
6177 depending on the format. The return value will be put literally into
6178 the exported file.
6179 Org-mode has a built-in default for exporting links. If you are happy with
6180 this default, there is no need to define an export function for the link
6181 type. For a simple example of an export function, see `org-bbdb.el'."
6182 (add-to-list 'org-link-types type t)
6183 (org-make-link-regexps)
6184 (if (assoc type org-link-protocols)
6185 (setcdr (assoc type org-link-protocols) (list follow export))
6186 (push (list type follow export) org-link-protocols)))
6188 ;;;###autoload
6189 (defun org-store-link (arg)
6190 "\\<org-mode-map>Store an org-link to the current location.
6191 This link is added to `org-stored-links' and can later be inserted
6192 into an org-buffer with \\[org-insert-link].
6194 For some link types, a prefix arg is interpreted:
6195 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6196 For file links, arg negates `org-context-in-file-links'."
6197 (interactive "P")
6198 (org-load-modules-maybe)
6199 (setq org-store-link-plist nil) ; reset
6200 (let (link cpltxt desc description search txt)
6201 (cond
6203 ((run-hook-with-args-until-success 'org-store-link-functions)
6204 (setq link (plist-get org-store-link-plist :link)
6205 desc (or (plist-get org-store-link-plist :description) link)))
6207 ((eq major-mode 'calendar-mode)
6208 (let ((cd (calendar-cursor-to-date)))
6209 (setq link
6210 (format-time-string
6211 (car org-time-stamp-formats)
6212 (apply 'encode-time
6213 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6214 nil nil nil))))
6215 (org-store-link-props :type "calendar" :date cd)))
6217 ((eq major-mode 'w3-mode)
6218 (setq cpltxt (url-view-url t)
6219 link (org-make-link cpltxt))
6220 (org-store-link-props :type "w3" :url (url-view-url t)))
6222 ((eq major-mode 'w3m-mode)
6223 (setq cpltxt (or w3m-current-title w3m-current-url)
6224 link (org-make-link w3m-current-url))
6225 (org-store-link-props :type "w3m" :url (url-view-url t)))
6227 ((setq search (run-hook-with-args-until-success
6228 'org-create-file-search-functions))
6229 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6230 "::" search))
6231 (setq cpltxt (or description link)))
6233 ((eq major-mode 'image-mode)
6234 (setq cpltxt (concat "file:"
6235 (abbreviate-file-name buffer-file-name))
6236 link (org-make-link cpltxt))
6237 (org-store-link-props :type "image" :file buffer-file-name))
6239 ((eq major-mode 'dired-mode)
6240 ;; link to the file in the current line
6241 (setq cpltxt (concat "file:"
6242 (abbreviate-file-name
6243 (expand-file-name
6244 (dired-get-filename nil t))))
6245 link (org-make-link cpltxt)))
6247 ((and buffer-file-name (org-mode-p))
6248 (cond
6249 ((org-in-regexp "<<\\(.*?\\)>>")
6250 (setq cpltxt
6251 (concat "file:"
6252 (abbreviate-file-name buffer-file-name)
6253 "::" (match-string 1))
6254 link (org-make-link cpltxt)))
6255 ((and (featurep 'org-id)
6256 (or (eq org-link-to-org-use-id t)
6257 (and (eq org-link-to-org-use-id 'create-if-interactive)
6258 (interactive-p))
6259 (and org-link-to-org-use-id
6260 (condition-case nil
6261 (org-entry-get nil "ID")
6262 (error nil)))))
6263 ;; We can make a link using the ID.
6264 (setq link (condition-case nil
6265 (org-id-store-link)
6266 (error
6267 ;; probably before first headling, link to file only
6268 (concat "file:"
6269 (abbreviate-file-name buffer-file-name))))))
6271 ;; Just link to current headline
6272 (setq cpltxt (concat "file:"
6273 (abbreviate-file-name buffer-file-name)))
6274 ;; Add a context search string
6275 (when (org-xor org-context-in-file-links arg)
6276 (setq txt (cond
6277 ((org-on-heading-p) nil)
6278 ((org-region-active-p)
6279 (buffer-substring (region-beginning) (region-end)))
6280 (t nil)))
6281 (when (or (null txt) (string-match "\\S-" txt))
6282 (setq cpltxt
6283 (concat cpltxt "::"
6284 (condition-case nil
6285 (org-make-org-heading-search-string txt)
6286 (error "")))
6287 desc "NONE")))
6288 (if (string-match "::\\'" cpltxt)
6289 (setq cpltxt (substring cpltxt 0 -2)))
6290 (setq link (org-make-link cpltxt)))))
6292 ((buffer-file-name (buffer-base-buffer))
6293 ;; Just link to this file here.
6294 (setq cpltxt (concat "file:"
6295 (abbreviate-file-name
6296 (buffer-file-name (buffer-base-buffer)))))
6297 ;; Add a context string
6298 (when (org-xor org-context-in-file-links arg)
6299 (setq txt (if (org-region-active-p)
6300 (buffer-substring (region-beginning) (region-end))
6301 (buffer-substring (point-at-bol) (point-at-eol))))
6302 ;; Only use search option if there is some text.
6303 (when (string-match "\\S-" txt)
6304 (setq cpltxt
6305 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6306 desc "NONE")))
6307 (setq link (org-make-link cpltxt)))
6309 ((interactive-p)
6310 (error "Cannot link to a buffer which is not visiting a file"))
6312 (t (setq link nil)))
6314 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6315 (setq link (or link cpltxt)
6316 desc (or desc cpltxt))
6317 (if (equal desc "NONE") (setq desc nil))
6319 (if (and (interactive-p) link)
6320 (progn
6321 (setq org-stored-links
6322 (cons (list link desc) org-stored-links))
6323 (message "Stored: %s" (or desc link)))
6324 (and link (org-make-link-string link desc)))))
6326 (defun org-store-link-props (&rest plist)
6327 "Store link properties, extract names and addresses."
6328 (let (x adr)
6329 (when (setq x (plist-get plist :from))
6330 (setq adr (mail-extract-address-components x))
6331 (setq plist (plist-put plist :fromname (car adr)))
6332 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6333 (when (setq x (plist-get plist :to))
6334 (setq adr (mail-extract-address-components x))
6335 (setq plist (plist-put plist :toname (car adr)))
6336 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6337 (let ((from (plist-get plist :from))
6338 (to (plist-get plist :to)))
6339 (when (and from to org-from-is-user-regexp)
6340 (setq plist
6341 (plist-put plist :fromto
6342 (if (string-match org-from-is-user-regexp from)
6343 (concat "to %t")
6344 (concat "from %f"))))))
6345 (setq org-store-link-plist plist))
6347 (defun org-add-link-props (&rest plist)
6348 "Add these properties to the link property list."
6349 (let (key value)
6350 (while plist
6351 (setq key (pop plist) value (pop plist))
6352 (setq org-store-link-plist
6353 (plist-put org-store-link-plist key value)))))
6355 (defun org-email-link-description (&optional fmt)
6356 "Return the description part of an email link.
6357 This takes information from `org-store-link-plist' and formats it
6358 according to FMT (default from `org-email-link-description-format')."
6359 (setq fmt (or fmt org-email-link-description-format))
6360 (let* ((p org-store-link-plist)
6361 (to (plist-get p :toaddress))
6362 (from (plist-get p :fromaddress))
6363 (table
6364 (list
6365 (cons "%c" (plist-get p :fromto))
6366 (cons "%F" (plist-get p :from))
6367 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6368 (cons "%T" (plist-get p :to))
6369 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6370 (cons "%s" (plist-get p :subject))
6371 (cons "%m" (plist-get p :message-id)))))
6372 (when (string-match "%c" fmt)
6373 ;; Check if the user wrote this message
6374 (if (and org-from-is-user-regexp from to
6375 (save-match-data (string-match org-from-is-user-regexp from)))
6376 (setq fmt (replace-match "to %t" t t fmt))
6377 (setq fmt (replace-match "from %f" t t fmt))))
6378 (org-replace-escapes fmt table)))
6380 (defun org-make-org-heading-search-string (&optional string heading)
6381 "Make search string for STRING or current headline."
6382 (interactive)
6383 (let ((s (or string (org-get-heading))))
6384 (unless (and string (not heading))
6385 ;; We are using a headline, clean up garbage in there.
6386 (if (string-match org-todo-regexp s)
6387 (setq s (replace-match "" t t s)))
6388 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6389 (setq s (replace-match "" t t s)))
6390 (setq s (org-trim s))
6391 (if (string-match (concat "^\\(" org-quote-string "\\|"
6392 org-comment-string "\\)") s)
6393 (setq s (replace-match "" t t s)))
6394 (while (string-match org-ts-regexp s)
6395 (setq s (replace-match "" t t s))))
6396 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6397 (setq s (replace-match " " t t s)))
6398 (or string (setq s (concat "*" s))) ; Add * for headlines
6399 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6401 (defun org-make-link (&rest strings)
6402 "Concatenate STRINGS."
6403 (apply 'concat strings))
6405 (defun org-make-link-string (link &optional description)
6406 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6407 (unless (string-match "\\S-" link)
6408 (error "Empty link"))
6409 (when (stringp description)
6410 ;; Remove brackets from the description, they are fatal.
6411 (while (string-match "\\[" description)
6412 (setq description (replace-match "{" t t description)))
6413 (while (string-match "\\]" description)
6414 (setq description (replace-match "}" t t description))))
6415 (when (equal (org-link-escape link) description)
6416 ;; No description needed, it is identical
6417 (setq description nil))
6418 (when (and (not description)
6419 (not (equal link (org-link-escape link))))
6420 (setq description (org-extract-attributes link)))
6421 (concat "[[" (org-link-escape link) "]"
6422 (if description (concat "[" description "]") "")
6423 "]"))
6425 (defconst org-link-escape-chars
6426 '((?\ . "%20")
6427 (?\[ . "%5B")
6428 (?\] . "%5D")
6429 (?\340 . "%E0") ; `a
6430 (?\342 . "%E2") ; ^a
6431 (?\347 . "%E7") ; ,c
6432 (?\350 . "%E8") ; `e
6433 (?\351 . "%E9") ; 'e
6434 (?\352 . "%EA") ; ^e
6435 (?\356 . "%EE") ; ^i
6436 (?\364 . "%F4") ; ^o
6437 (?\371 . "%F9") ; `u
6438 (?\373 . "%FB") ; ^u
6439 (?\; . "%3B")
6440 (?? . "%3F")
6441 (?= . "%3D")
6442 (?+ . "%2B")
6444 "Association list of escapes for some characters problematic in links.
6445 This is the list that is used for internal purposes.")
6447 (defconst org-link-escape-chars-browser
6448 '((?\ . "%20")) ; 32 for the SPC char
6449 "Association list of escapes for some characters problematic in links.
6450 This is the list that is used before handing over to the browser.")
6452 (defun org-link-escape (text &optional table)
6453 "Escape characters in TEXT that are problematic for links."
6454 (setq table (or table org-link-escape-chars))
6455 (when text
6456 (let ((re (mapconcat (lambda (x) (regexp-quote
6457 (char-to-string (car x))))
6458 table "\\|")))
6459 (while (string-match re text)
6460 (setq text
6461 (replace-match
6462 (cdr (assoc (string-to-char (match-string 0 text))
6463 table))
6464 t t text)))
6465 text)))
6467 (defun org-link-unescape (text &optional table)
6468 "Reverse the action of `org-link-escape'."
6469 (setq table (or table org-link-escape-chars))
6470 (when text
6471 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6472 table "\\|")))
6473 (while (string-match re text)
6474 (setq text
6475 (replace-match
6476 (char-to-string (car (rassoc (match-string 0 text) table)))
6477 t t text)))
6478 text)))
6480 (defun org-xor (a b)
6481 "Exclusive or."
6482 (if a (not b) b))
6484 (defun org-get-header (header)
6485 "Find a header field in the current buffer."
6486 (save-excursion
6487 (goto-char (point-min))
6488 (let ((case-fold-search t) s)
6489 (cond
6490 ((eq header 'from)
6491 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6492 (setq s (match-string 1)))
6493 (while (string-match "\"" s)
6494 (setq s (replace-match "" t t s)))
6495 (if (string-match "[<(].*" s)
6496 (setq s (replace-match "" t t s))))
6497 ((eq header 'message-id)
6498 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6499 (setq s (match-string 1))))
6500 ((eq header 'subject)
6501 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6502 (setq s (match-string 1)))))
6503 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6504 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6505 s)))
6508 (defun org-fixup-message-id-for-http (s)
6509 "Replace special characters in a message id, so it can be used in an http query."
6510 (while (string-match "<" s)
6511 (setq s (replace-match "%3C" t t s)))
6512 (while (string-match ">" s)
6513 (setq s (replace-match "%3E" t t s)))
6514 (while (string-match "@" s)
6515 (setq s (replace-match "%40" t t s)))
6518 ;;;###autoload
6519 (defun org-insert-link-global ()
6520 "Insert a link like Org-mode does.
6521 This command can be called in any mode to insert a link in Org-mode syntax."
6522 (interactive)
6523 (org-load-modules-maybe)
6524 (org-run-like-in-org-mode 'org-insert-link))
6526 (defun org-insert-link (&optional complete-file link-location)
6527 "Insert a link. At the prompt, enter the link.
6529 Completion can be used to insert any of the link protocol prefixes like
6530 http or ftp in use.
6532 The history can be used to select a link previously stored with
6533 `org-store-link'. When the empty string is entered (i.e. if you just
6534 press RET at the prompt), the link defaults to the most recently
6535 stored link. As SPC triggers completion in the minibuffer, you need to
6536 use M-SPC or C-q SPC to force the insertion of a space character.
6538 You will also be prompted for a description, and if one is given, it will
6539 be displayed in the buffer instead of the link.
6541 If there is already a link at point, this command will allow you to edit link
6542 and description parts.
6544 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6545 be selected using completion. The path to the file will be relative to the
6546 current directory if the file is in the current directory or a subdirectory.
6547 Otherwise, the link will be the absolute path as completed in the minibuffer
6548 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6549 option `org-link-file-path-type'.
6551 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6552 the current directory or below.
6554 With three \\[universal-argument] prefixes, negate the meaning of
6555 `org-keep-stored-link-after-insertion'.
6557 If `org-make-link-description-function' is non-nil, this function will be
6558 called with the link target, and the result will be the default
6559 link description.
6561 If the LINK-LOCATION parameter is non-nil, this value will be
6562 used as the link location instead of reading one interactively."
6563 (interactive "P")
6564 (let* ((wcf (current-window-configuration))
6565 (region (if (org-region-active-p)
6566 (buffer-substring (region-beginning) (region-end))))
6567 (remove (and region (list (region-beginning) (region-end))))
6568 (desc region)
6569 tmphist ; byte-compile incorrectly complains about this
6570 (link link-location)
6571 entry file)
6572 (cond
6573 (link-location) ; specified by arg, just use it.
6574 ((org-in-regexp org-bracket-link-regexp 1)
6575 ;; We do have a link at point, and we are going to edit it.
6576 (setq remove (list (match-beginning 0) (match-end 0)))
6577 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6578 (setq link (read-string "Link: "
6579 (org-link-unescape
6580 (org-match-string-no-properties 1)))))
6581 ((or (org-in-regexp org-angle-link-re)
6582 (org-in-regexp org-plain-link-re))
6583 ;; Convert to bracket link
6584 (setq remove (list (match-beginning 0) (match-end 0))
6585 link (read-string "Link: "
6586 (org-remove-angle-brackets (match-string 0)))))
6587 ((member complete-file '((4) (16)))
6588 ;; Completing read for file names.
6589 (setq file (read-file-name "File: "))
6590 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6591 (pwd1 (file-name-as-directory (abbreviate-file-name
6592 (expand-file-name ".")))))
6593 (cond
6594 ((equal complete-file '(16))
6595 (setq link (org-make-link
6596 "file:"
6597 (abbreviate-file-name (expand-file-name file)))))
6598 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6599 (setq link (org-make-link "file:" (match-string 1 file))))
6600 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6601 (expand-file-name file))
6602 (setq link (org-make-link
6603 "file:" (match-string 1 (expand-file-name file)))))
6604 (t (setq link (org-make-link "file:" file))))))
6606 ;; Read link, with completion for stored links.
6607 (with-output-to-temp-buffer "*Org Links*"
6608 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6609 (when org-stored-links
6610 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6611 (princ (mapconcat
6612 (lambda (x)
6613 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6614 (reverse org-stored-links) "\n"))))
6615 (let ((cw (selected-window)))
6616 (select-window (get-buffer-window "*Org Links*"))
6617 (org-fit-window-to-buffer)
6618 (setq truncate-lines t)
6619 (select-window cw))
6620 ;; Fake a link history, containing the stored links.
6621 (setq tmphist (append (mapcar 'car org-stored-links)
6622 org-insert-link-history))
6623 (unwind-protect
6624 (setq link (org-completing-read
6625 "Link: "
6626 (append
6627 (mapcar (lambda (x) (list (concat (car x) ":")))
6628 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6629 (mapcar (lambda (x) (list (concat x ":")))
6630 org-link-types))
6631 nil nil nil
6632 'tmphist
6633 (or (car (car org-stored-links)))))
6634 (set-window-configuration wcf)
6635 (kill-buffer "*Org Links*"))
6636 (setq entry (assoc link org-stored-links))
6637 (or entry (push link org-insert-link-history))
6638 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6639 (not org-keep-stored-link-after-insertion))
6640 (setq org-stored-links (delq (assoc link org-stored-links)
6641 org-stored-links)))
6642 (setq desc (or desc (nth 1 entry)))))
6644 (if (string-match org-plain-link-re link)
6645 ;; URL-like link, normalize the use of angular brackets.
6646 (setq link (org-make-link (org-remove-angle-brackets link))))
6648 ;; Check if we are linking to the current file with a search option
6649 ;; If yes, simplify the link by using only the search option.
6650 (when (and buffer-file-name
6651 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6652 (let* ((path (match-string 1 link))
6653 (case-fold-search nil)
6654 (search (match-string 2 link)))
6655 (save-match-data
6656 (if (equal (file-truename buffer-file-name) (file-truename path))
6657 ;; We are linking to this same file, with a search option
6658 (setq link search)))))
6660 ;; Check if we can/should use a relative path. If yes, simplify the link
6661 (when (string-match "^file:\\(.*\\)" link)
6662 (let* ((path (match-string 1 link))
6663 (origpath path)
6664 (case-fold-search nil))
6665 (cond
6666 ((or (eq org-link-file-path-type 'absolute)
6667 (equal complete-file '(16)))
6668 (setq path (abbreviate-file-name (expand-file-name path))))
6669 ((eq org-link-file-path-type 'noabbrev)
6670 (setq path (expand-file-name path)))
6671 ((eq org-link-file-path-type 'relative)
6672 (setq path (file-relative-name path)))
6674 (save-match-data
6675 (if (string-match (concat "^" (regexp-quote
6676 (file-name-as-directory
6677 (expand-file-name "."))))
6678 (expand-file-name path))
6679 ;; We are linking a file with relative path name.
6680 (setq path (substring (expand-file-name path)
6681 (match-end 0)))
6682 (setq path (abbreviate-file-name (expand-file-name path)))))))
6683 (setq link (concat "file:" path))
6684 (if (equal desc origpath)
6685 (setq desc path))))
6687 (if org-make-link-description-function
6688 (setq desc (funcall org-make-link-description-function link desc)))
6690 (setq desc (read-string "Description: " desc))
6691 (unless (string-match "\\S-" desc) (setq desc nil))
6692 (if remove (apply 'delete-region remove))
6693 (insert (org-make-link-string link desc))))
6695 (defun org-completing-read (&rest args)
6696 "Completing-read with SPACE being a normal character."
6697 (let ((minibuffer-local-completion-map
6698 (copy-keymap minibuffer-local-completion-map)))
6699 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6700 (apply 'org-ido-completing-read args)))
6702 (defun org-ido-completing-read (&rest args)
6703 "Completing-read using `ido-mode' speedups if available"
6704 (if (and org-completion-use-ido
6705 (fboundp 'ido-completing-read)
6706 (boundp 'ido-mode) ido-mode
6707 (listp (second args)))
6708 (apply 'ido-completing-read (concat (car args)) (cdr args))
6709 (apply 'completing-read args)))
6711 (defun org-extract-attributes (s)
6712 "Extract the attributes cookie from a string and set as text property."
6713 (let (a attr (start 0) key value)
6714 (save-match-data
6715 (when (string-match "{{\\([^}]+\\)}}$" s)
6716 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6717 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6718 (setq key (match-string 1 a) value (match-string 2 a)
6719 start (match-end 0)
6720 attr (plist-put attr (intern key) value))))
6721 (org-add-props s nil 'org-attr attr))
6724 (defun org-attributes-to-string (plist)
6725 "Format a property list into an HTML attribute list."
6726 (let ((s "") key value)
6727 (while plist
6728 (setq key (pop plist) value (pop plist))
6729 (and value
6730 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6733 ;;; Opening/following a link
6735 (defvar org-link-search-failed nil)
6737 (defun org-next-link ()
6738 "Move forward to the next link.
6739 If the link is in hidden text, expose it."
6740 (interactive)
6741 (when (and org-link-search-failed (eq this-command last-command))
6742 (goto-char (point-min))
6743 (message "Link search wrapped back to beginning of buffer"))
6744 (setq org-link-search-failed nil)
6745 (let* ((pos (point))
6746 (ct (org-context))
6747 (a (assoc :link ct)))
6748 (if a (goto-char (nth 2 a)))
6749 (if (re-search-forward org-any-link-re nil t)
6750 (progn
6751 (goto-char (match-beginning 0))
6752 (if (org-invisible-p) (org-show-context)))
6753 (goto-char pos)
6754 (setq org-link-search-failed t)
6755 (error "No further link found"))))
6757 (defun org-previous-link ()
6758 "Move backward to the previous link.
6759 If the link is in hidden text, expose it."
6760 (interactive)
6761 (when (and org-link-search-failed (eq this-command last-command))
6762 (goto-char (point-max))
6763 (message "Link search wrapped back to end of buffer"))
6764 (setq org-link-search-failed nil)
6765 (let* ((pos (point))
6766 (ct (org-context))
6767 (a (assoc :link ct)))
6768 (if a (goto-char (nth 1 a)))
6769 (if (re-search-backward org-any-link-re nil t)
6770 (progn
6771 (goto-char (match-beginning 0))
6772 (if (org-invisible-p) (org-show-context)))
6773 (goto-char pos)
6774 (setq org-link-search-failed t)
6775 (error "No further link found"))))
6777 (defun org-translate-link (s)
6778 "Translate a link string if a translation function has been defined."
6779 (if (and org-link-translation-function
6780 (fboundp org-link-translation-function)
6781 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6782 (progn
6783 (setq s (funcall org-link-translation-function
6784 (match-string 1) (match-string 2)))
6785 (concat (car s) ":" (cdr s)))
6788 (defun org-translate-link-from-planner (type path)
6789 "Translate a link from Emacs Planner syntax so that Org can follow it.
6790 This is still an experimental function, your mileage may vary."
6791 (cond
6792 ((member type '("http" "https" "news" "ftp"))
6793 ;; standard Internet links are the same.
6794 nil)
6795 ((and (equal type "irc") (string-match "^//" path))
6796 ;; Planner has two / at the beginning of an irc link, we have 1.
6797 ;; We should have zero, actually....
6798 (setq path (substring path 1)))
6799 ((and (equal type "lisp") (string-match "^/" path))
6800 ;; Planner has a slash, we do not.
6801 (setq type "elisp" path (substring path 1)))
6802 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6803 ;; A typical message link. Planner has the id after the fina slash,
6804 ;; we separate it with a hash mark
6805 (setq path (concat (match-string 1 path) "#"
6806 (org-remove-angle-brackets (match-string 2 path)))))
6808 (cons type path))
6810 (defun org-find-file-at-mouse (ev)
6811 "Open file link or URL at mouse."
6812 (interactive "e")
6813 (mouse-set-point ev)
6814 (org-open-at-point 'in-emacs))
6816 (defun org-open-at-mouse (ev)
6817 "Open file link or URL at mouse."
6818 (interactive "e")
6819 (mouse-set-point ev)
6820 (if (eq major-mode 'org-agenda-mode)
6821 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6822 (org-open-at-point))
6824 (defvar org-window-config-before-follow-link nil
6825 "The window configuration before following a link.
6826 This is saved in case the need arises to restore it.")
6828 (defvar org-open-link-marker (make-marker)
6829 "Marker pointing to the location where `org-open-at-point; was called.")
6831 ;;;###autoload
6832 (defun org-open-at-point-global ()
6833 "Follow a link like Org-mode does.
6834 This command can be called in any mode to follow a link that has
6835 Org-mode syntax."
6836 (interactive)
6837 (org-run-like-in-org-mode 'org-open-at-point))
6839 ;;;###autoload
6840 (defun org-open-link-from-string (s &optional arg)
6841 "Open a link in the string S, as if it was in Org-mode."
6842 (interactive "sLink: \nP")
6843 (with-temp-buffer
6844 (let ((org-inhibit-startup t))
6845 (org-mode)
6846 (insert s)
6847 (goto-char (point-min))
6848 (org-open-at-point arg))))
6850 (defun org-open-at-point (&optional in-emacs)
6851 "Open link at or after point.
6852 If there is no link at point, this function will search forward up to
6853 the end of the current subtree.
6854 Normally, files will be opened by an appropriate application. If the
6855 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6856 With a double prefix argument, try to open outside of Emacs, in the
6857 application the system uses for this file type."
6858 (interactive "P")
6859 (org-load-modules-maybe)
6860 (move-marker org-open-link-marker (point))
6861 (setq org-window-config-before-follow-link (current-window-configuration))
6862 (org-remove-occur-highlights nil nil t)
6863 (if (org-at-timestamp-p t)
6864 (org-follow-timestamp-link)
6865 (let (type path link line search (pos (point)))
6866 (catch 'match
6867 (save-excursion
6868 (skip-chars-forward "^]\n\r")
6869 (when (org-in-regexp org-bracket-link-regexp)
6870 (setq link (org-extract-attributes
6871 (org-link-unescape (org-match-string-no-properties 1))))
6872 (while (string-match " *\n *" link)
6873 (setq link (replace-match " " t t link)))
6874 (setq link (org-link-expand-abbrev link))
6875 (cond
6876 ((or (file-name-absolute-p link)
6877 (string-match "^\\.\\.?/" link))
6878 (setq type "file" path link))
6879 ((string-match org-link-re-with-space3 link)
6880 (setq type (match-string 1 link) path (match-string 2 link)))
6881 (t (setq type "thisfile" path link)))
6882 (throw 'match t)))
6884 (when (get-text-property (point) 'org-linked-text)
6885 (setq type "thisfile"
6886 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6887 (1+ (point)) (point))
6888 path (buffer-substring
6889 (previous-single-property-change pos 'org-linked-text)
6890 (next-single-property-change pos 'org-linked-text)))
6891 (throw 'match t))
6893 (save-excursion
6894 (when (or (org-in-regexp org-angle-link-re)
6895 (org-in-regexp org-plain-link-re))
6896 (setq type (match-string 1) path (match-string 2))
6897 (throw 'match t)))
6898 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6899 (setq type "tree-match"
6900 path (match-string 1))
6901 (throw 'match t))
6902 (save-excursion
6903 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6904 (setq type "tags"
6905 path (match-string 1))
6906 (while (string-match ":" path)
6907 (setq path (replace-match "+" t t path)))
6908 (throw 'match t))))
6909 (unless path
6910 (error "No link found"))
6911 ;; Remove any trailing spaces in path
6912 (if (string-match " +\\'" path)
6913 (setq path (replace-match "" t t path)))
6914 (if (and org-link-translation-function
6915 (fboundp org-link-translation-function))
6916 ;; Check if we need to translate the link
6917 (let ((tmp (funcall org-link-translation-function type path)))
6918 (setq type (car tmp) path (cdr tmp))))
6920 (cond
6922 ((assoc type org-link-protocols)
6923 (funcall (nth 1 (assoc type org-link-protocols)) path))
6925 ((equal type "mailto")
6926 (let ((cmd (car org-link-mailto-program))
6927 (args (cdr org-link-mailto-program)) args1
6928 (address path) (subject "") a)
6929 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6930 (setq address (match-string 1 path)
6931 subject (org-link-escape (match-string 2 path))))
6932 (while args
6933 (cond
6934 ((not (stringp (car args))) (push (pop args) args1))
6935 (t (setq a (pop args))
6936 (if (string-match "%a" a)
6937 (setq a (replace-match address t t a)))
6938 (if (string-match "%s" a)
6939 (setq a (replace-match subject t t a)))
6940 (push a args1))))
6941 (apply cmd (nreverse args1))))
6943 ((member type '("http" "https" "ftp" "news"))
6944 (browse-url (concat type ":" (org-link-escape
6945 path org-link-escape-chars-browser))))
6947 ((member type '("message"))
6948 (browse-url (concat type ":" path)))
6950 ((string= type "tags")
6951 (org-tags-view in-emacs path))
6952 ((string= type "thisfile")
6953 (if in-emacs
6954 (switch-to-buffer-other-window
6955 (org-get-buffer-for-internal-link (current-buffer)))
6956 (org-mark-ring-push))
6957 (let ((cmd `(org-link-search
6958 ,path
6959 ,(cond ((equal in-emacs '(4)) 'occur)
6960 ((equal in-emacs '(16)) 'org-occur)
6961 (t nil))
6962 ,pos)))
6963 (condition-case nil (eval cmd)
6964 (error (progn (widen) (eval cmd))))))
6966 ((string= type "tree-match")
6967 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6969 ((string= type "file")
6970 (if (string-match "::\\([0-9]+\\)\\'" path)
6971 (setq line (string-to-number (match-string 1 path))
6972 path (substring path 0 (match-beginning 0)))
6973 (if (string-match "::\\(.+\\)\\'" path)
6974 (setq search (match-string 1 path)
6975 path (substring path 0 (match-beginning 0)))))
6976 (if (string-match "[*?{]" (file-name-nondirectory path))
6977 (dired path)
6978 (org-open-file path in-emacs line search)))
6980 ((string= type "news")
6981 (require 'org-gnus)
6982 (org-gnus-follow-link path))
6984 ((string= type "shell")
6985 (let ((cmd path))
6986 (if (or (not org-confirm-shell-link-function)
6987 (funcall org-confirm-shell-link-function
6988 (format "Execute \"%s\" in shell? "
6989 (org-add-props cmd nil
6990 'face 'org-warning))))
6991 (progn
6992 (message "Executing %s" cmd)
6993 (shell-command cmd))
6994 (error "Abort"))))
6996 ((string= type "elisp")
6997 (let ((cmd path))
6998 (if (or (not org-confirm-elisp-link-function)
6999 (funcall org-confirm-elisp-link-function
7000 (format "Execute \"%s\" as elisp? "
7001 (org-add-props cmd nil
7002 'face 'org-warning))))
7003 (message "%s => %s" cmd
7004 (if (equal (string-to-char cmd) ?\()
7005 (eval (read cmd))
7006 (call-interactively (read cmd))))
7007 (error "Abort"))))
7010 (browse-url-at-point)))))
7011 (move-marker org-open-link-marker nil)
7012 (run-hook-with-args 'org-follow-link-hook))
7014 ;;;; Time estimates
7016 (defun org-get-effort (&optional pom)
7017 "Get the effort estimate for the current entry."
7018 (org-entry-get pom org-effort-property))
7020 ;;; File search
7022 (defvar org-create-file-search-functions nil
7023 "List of functions to construct the right search string for a file link.
7024 These functions are called in turn with point at the location to
7025 which the link should point.
7027 A function in the hook should first test if it would like to
7028 handle this file type, for example by checking the major-mode or
7029 the file extension. If it decides not to handle this file, it
7030 should just return nil to give other functions a chance. If it
7031 does handle the file, it must return the search string to be used
7032 when following the link. The search string will be part of the
7033 file link, given after a double colon, and `org-open-at-point'
7034 will automatically search for it. If special measures must be
7035 taken to make the search successful, another function should be
7036 added to the companion hook `org-execute-file-search-functions',
7037 which see.
7039 A function in this hook may also use `setq' to set the variable
7040 `description' to provide a suggestion for the descriptive text to
7041 be used for this link when it gets inserted into an Org-mode
7042 buffer with \\[org-insert-link].")
7044 (defvar org-execute-file-search-functions nil
7045 "List of functions to execute a file search triggered by a link.
7047 Functions added to this hook must accept a single argument, the
7048 search string that was part of the file link, the part after the
7049 double colon. The function must first check if it would like to
7050 handle this search, for example by checking the major-mode or the
7051 file extension. If it decides not to handle this search, it
7052 should just return nil to give other functions a chance. If it
7053 does handle the search, it must return a non-nil value to keep
7054 other functions from trying.
7056 Each function can access the current prefix argument through the
7057 variable `current-prefix-argument'. Note that a single prefix is
7058 used to force opening a link in Emacs, so it may be good to only
7059 use a numeric or double prefix to guide the search function.
7061 In case this is needed, a function in this hook can also restore
7062 the window configuration before `org-open-at-point' was called using:
7064 (set-window-configuration org-window-config-before-follow-link)")
7066 (defun org-link-search (s &optional type avoid-pos)
7067 "Search for a link search option.
7068 If S is surrounded by forward slashes, it is interpreted as a
7069 regular expression. In org-mode files, this will create an `org-occur'
7070 sparse tree. In ordinary files, `occur' will be used to list matches.
7071 If the current buffer is in `dired-mode', grep will be used to search
7072 in all files. If AVOID-POS is given, ignore matches near that position."
7073 (let ((case-fold-search t)
7074 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7075 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7076 (append '(("") (" ") ("\t") ("\n"))
7077 org-emphasis-alist)
7078 "\\|") "\\)"))
7079 (pos (point))
7080 (pre nil) (post nil)
7081 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7082 (cond
7083 ;; First check if there are any special
7084 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7085 ;; Now try the builtin stuff
7086 ((save-excursion
7087 (goto-char (point-min))
7088 (and
7089 (re-search-forward
7090 (concat "<<" (regexp-quote s0) ">>") nil t)
7091 (setq type 'dedicated
7092 pos (match-beginning 0))))
7093 ;; There is an exact target for this
7094 (goto-char pos))
7095 ((string-match "^/\\(.*\\)/$" s)
7096 ;; A regular expression
7097 (cond
7098 ((org-mode-p)
7099 (org-occur (match-string 1 s)))
7100 ;;((eq major-mode 'dired-mode)
7101 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7102 (t (org-do-occur (match-string 1 s)))))
7104 ;; A normal search strings
7105 (when (equal (string-to-char s) ?*)
7106 ;; Anchor on headlines, post may include tags.
7107 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7108 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7109 s (substring s 1)))
7110 (remove-text-properties
7111 0 (length s)
7112 '(face nil mouse-face nil keymap nil fontified nil) s)
7113 ;; Make a series of regular expressions to find a match
7114 (setq words (org-split-string s "[ \n\r\t]+")
7116 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7117 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7118 "\\)" markers)
7119 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7120 re2a (concat "[ \t\r\n]" re2a_)
7121 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7122 re4 (concat "[^a-zA-Z_]" re4_)
7124 re1 (concat pre re2 post)
7125 re3 (concat pre (if pre re4_ re4) post)
7126 re5 (concat pre ".*" re4)
7127 re2 (concat pre re2)
7128 re2a (concat pre (if pre re2a_ re2a))
7129 re4 (concat pre (if pre re4_ re4))
7130 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7131 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7132 re5 "\\)"
7134 (cond
7135 ((eq type 'org-occur) (org-occur reall))
7136 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7137 (t (goto-char (point-min))
7138 (setq type 'fuzzy)
7139 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7140 (org-search-not-self 1 re1 nil t)
7141 (org-search-not-self 1 re2 nil t)
7142 (org-search-not-self 1 re2a nil t)
7143 (org-search-not-self 1 re3 nil t)
7144 (org-search-not-self 1 re4 nil t)
7145 (org-search-not-self 1 re5 nil t)
7147 (goto-char (match-beginning 1))
7148 (goto-char pos)
7149 (error "No match")))))
7151 ;; Normal string-search
7152 (goto-char (point-min))
7153 (if (search-forward s nil t)
7154 (goto-char (match-beginning 0))
7155 (error "No match"))))
7156 (and (org-mode-p) (org-show-context 'link-search))
7157 type))
7159 (defun org-search-not-self (group &rest args)
7160 "Execute `re-search-forward', but only accept matches that do not
7161 enclose the position of `org-open-link-marker'."
7162 (let ((m org-open-link-marker))
7163 (catch 'exit
7164 (while (apply 're-search-forward args)
7165 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7166 (goto-char (match-end group))
7167 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7168 (> (match-beginning 0) (marker-position m))
7169 (< (match-end 0) (marker-position m)))
7170 (save-match-data
7171 (or (not (org-in-regexp
7172 org-bracket-link-analytic-regexp 1))
7173 (not (match-end 4)) ; no description
7174 (and (<= (match-beginning 4) (point))
7175 (>= (match-end 4) (point))))))
7176 (throw 'exit (point))))))))
7178 (defun org-get-buffer-for-internal-link (buffer)
7179 "Return a buffer to be used for displaying the link target of internal links."
7180 (cond
7181 ((not org-display-internal-link-with-indirect-buffer)
7182 buffer)
7183 ((string-match "(Clone)$" (buffer-name buffer))
7184 (message "Buffer is already a clone, not making another one")
7185 ;; we also do not modify visibility in this case
7186 buffer)
7187 (t ; make a new indirect buffer for displaying the link
7188 (let* ((bn (buffer-name buffer))
7189 (ibn (concat bn "(Clone)"))
7190 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7191 (with-current-buffer ib (org-overview))
7192 ib))))
7194 (defun org-do-occur (regexp &optional cleanup)
7195 "Call the Emacs command `occur'.
7196 If CLEANUP is non-nil, remove the printout of the regular expression
7197 in the *Occur* buffer. This is useful if the regex is long and not useful
7198 to read."
7199 (occur regexp)
7200 (when cleanup
7201 (let ((cwin (selected-window)) win beg end)
7202 (when (setq win (get-buffer-window "*Occur*"))
7203 (select-window win))
7204 (goto-char (point-min))
7205 (when (re-search-forward "match[a-z]+" nil t)
7206 (setq beg (match-end 0))
7207 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7208 (setq end (1- (match-beginning 0)))))
7209 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7210 (goto-char (point-min))
7211 (select-window cwin))))
7213 ;;; The mark ring for links jumps
7215 (defvar org-mark-ring nil
7216 "Mark ring for positions before jumps in Org-mode.")
7217 (defvar org-mark-ring-last-goto nil
7218 "Last position in the mark ring used to go back.")
7219 ;; Fill and close the ring
7220 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7221 (loop for i from 1 to org-mark-ring-length do
7222 (push (make-marker) org-mark-ring))
7223 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7224 org-mark-ring)
7226 (defun org-mark-ring-push (&optional pos buffer)
7227 "Put the current position or POS into the mark ring and rotate it."
7228 (interactive)
7229 (setq pos (or pos (point)))
7230 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7231 (move-marker (car org-mark-ring)
7232 (or pos (point))
7233 (or buffer (current-buffer)))
7234 (message "%s"
7235 (substitute-command-keys
7236 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7238 (defun org-mark-ring-goto (&optional n)
7239 "Jump to the previous position in the mark ring.
7240 With prefix arg N, jump back that many stored positions. When
7241 called several times in succession, walk through the entire ring.
7242 Org-mode commands jumping to a different position in the current file,
7243 or to another Org-mode file, automatically push the old position
7244 onto the ring."
7245 (interactive "p")
7246 (let (p m)
7247 (if (eq last-command this-command)
7248 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7249 (setq p org-mark-ring))
7250 (setq org-mark-ring-last-goto p)
7251 (setq m (car p))
7252 (switch-to-buffer (marker-buffer m))
7253 (goto-char m)
7254 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7256 (defun org-remove-angle-brackets (s)
7257 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7258 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7260 (defun org-add-angle-brackets (s)
7261 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7262 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7264 (defun org-remove-double-quotes (s)
7265 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7266 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7269 ;;; Following specific links
7271 (defun org-follow-timestamp-link ()
7272 (cond
7273 ((org-at-date-range-p t)
7274 (let ((org-agenda-start-on-weekday)
7275 (t1 (match-string 1))
7276 (t2 (match-string 2)))
7277 (setq t1 (time-to-days (org-time-string-to-time t1))
7278 t2 (time-to-days (org-time-string-to-time t2)))
7279 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7280 ((org-at-timestamp-p t)
7281 (org-agenda-list nil (time-to-days (org-time-string-to-time
7282 (substring (match-string 1) 0 10)))
7284 (t (error "This should not happen"))))
7287 ;;; Following file links
7288 (defvar org-wait nil)
7289 (defun org-open-file (path &optional in-emacs line search)
7290 "Open the file at PATH.
7291 First, this expands any special file name abbreviations. Then the
7292 configuration variable `org-file-apps' is checked if it contains an
7293 entry for this file type, and if yes, the corresponding command is launched.
7295 If no application is found, Emacs simply visits the file.
7297 With optional prefix argument IN-EMACS, Emacs will visit the file.
7298 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7299 and o use an external application to visit the file.
7301 Optional LINE specifies a line to go to, optional SEARCH a string to
7302 search for. If LINE or SEARCH is given, the file will always be
7303 opened in Emacs.
7304 If the file does not exist, an error is thrown."
7305 (setq in-emacs (or in-emacs line search))
7306 (let* ((file (if (equal path "")
7307 buffer-file-name
7308 (substitute-in-file-name (expand-file-name path))))
7309 (apps (append org-file-apps (org-default-apps)))
7310 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7311 (dirp (if remp nil (file-directory-p file)))
7312 (file (if (and dirp org-open-directory-means-index-dot-org)
7313 (concat (file-name-as-directory file) "index.org")
7314 file))
7315 (a-m-a-p (assq 'auto-mode apps))
7316 (dfile (downcase file))
7317 (old-buffer (current-buffer))
7318 (old-pos (point))
7319 (old-mode major-mode)
7320 ext cmd)
7321 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7322 (setq ext (match-string 1 dfile))
7323 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7324 (setq ext (match-string 1 dfile))))
7325 (cond
7326 ((equal in-emacs '(16))
7327 (setq cmd (cdr (assoc 'system apps))))
7328 (in-emacs (setq cmd 'emacs))
7330 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7331 (and dirp (cdr (assoc 'directory apps)))
7332 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7333 'string-match)
7334 (cdr (assoc ext apps))
7335 (cdr (assoc t apps))))))
7336 (when (eq cmd 'system)
7337 (setq cmd (cdr (assoc 'system apps))))
7338 (when (eq cmd 'default)
7339 (setq cmd (cdr (assoc t apps))))
7340 (when (eq cmd 'mailcap)
7341 (require 'mailcap)
7342 (mailcap-parse-mailcaps)
7343 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7344 (command (mailcap-mime-info mime-type)))
7345 (if (stringp command)
7346 (setq cmd command)
7347 (setq cmd 'emacs))))
7348 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7349 (not (file-exists-p file))
7350 (not org-open-non-existing-files))
7351 (error "No such file: %s" file))
7352 (cond
7353 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7354 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7355 (while (string-match "['\"]%s['\"]" cmd)
7356 (setq cmd (replace-match "%s" t t cmd)))
7357 (while (string-match "%s" cmd)
7358 (setq cmd (replace-match
7359 (save-match-data
7360 (shell-quote-argument
7361 (convert-standard-filename file)))
7362 t t cmd)))
7363 (save-window-excursion
7364 (start-process-shell-command cmd nil cmd)
7365 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7367 ((or (stringp cmd)
7368 (eq cmd 'emacs))
7369 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7370 (widen)
7371 (if line (goto-line line)
7372 (if search (org-link-search search))))
7373 ((consp cmd)
7374 (let ((file (convert-standard-filename file)))
7375 (eval cmd)))
7376 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7377 (and (org-mode-p) (eq old-mode 'org-mode)
7378 (or (not (equal old-buffer (current-buffer)))
7379 (not (equal old-pos (point))))
7380 (org-mark-ring-push old-pos old-buffer))))
7382 (defun org-default-apps ()
7383 "Return the default applications for this operating system."
7384 (cond
7385 ((eq system-type 'darwin)
7386 org-file-apps-defaults-macosx)
7387 ((eq system-type 'windows-nt)
7388 org-file-apps-defaults-windowsnt)
7389 (t org-file-apps-defaults-gnu)))
7391 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7392 "Convert extensions to regular expressions in the cars of LIST.
7393 Also, weed out any non-string entries, because the return value is used
7394 only for regexp matching.
7395 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7396 point to the symbol `emacs', indicating that the file should
7397 be opened in Emacs."
7398 (append
7399 (delq nil
7400 (mapcar (lambda (x)
7401 (if (not (stringp (car x)))
7403 (if (string-match "\\W" (car x))
7405 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7406 list))
7407 (if add-auto-mode
7408 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7410 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7411 (defun org-file-remote-p (file)
7412 "Test whether FILE specifies a location on a remote system.
7413 Return non-nil if the location is indeed remote.
7415 For example, the filename \"/user@host:/foo\" specifies a location
7416 on the system \"/user@host:\"."
7417 (cond ((fboundp 'file-remote-p)
7418 (file-remote-p file))
7419 ((fboundp 'tramp-handle-file-remote-p)
7420 (tramp-handle-file-remote-p file))
7421 ((and (boundp 'ange-ftp-name-format)
7422 (string-match (car ange-ftp-name-format) file))
7424 (t nil)))
7427 ;;;; Refiling
7429 (defun org-get-org-file ()
7430 "Read a filename, with default directory `org-directory'."
7431 (let ((default (or org-default-notes-file remember-data-file)))
7432 (read-file-name (format "File name [%s]: " default)
7433 (file-name-as-directory org-directory)
7434 default)))
7436 (defun org-notes-order-reversed-p ()
7437 "Check if the current file should receive notes in reversed order."
7438 (cond
7439 ((not org-reverse-note-order) nil)
7440 ((eq t org-reverse-note-order) t)
7441 ((not (listp org-reverse-note-order)) nil)
7442 (t (catch 'exit
7443 (let ((all org-reverse-note-order)
7444 entry)
7445 (while (setq entry (pop all))
7446 (if (string-match (car entry) buffer-file-name)
7447 (throw 'exit (cdr entry))))
7448 nil)))))
7450 (defvar org-refile-target-table nil
7451 "The list of refile targets, created by `org-refile'.")
7453 (defvar org-agenda-new-buffers nil
7454 "Buffers created to visit agenda files.")
7456 (defun org-get-refile-targets (&optional default-buffer)
7457 "Produce a table with refile targets."
7458 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7459 targets txt re files f desc descre)
7460 (with-current-buffer (or default-buffer (current-buffer))
7461 (while (setq entry (pop entries))
7462 (setq files (car entry) desc (cdr entry))
7463 (cond
7464 ((null files) (setq files (list (current-buffer))))
7465 ((eq files 'org-agenda-files)
7466 (setq files (org-agenda-files 'unrestricted)))
7467 ((and (symbolp files) (fboundp files))
7468 (setq files (funcall files)))
7469 ((and (symbolp files) (boundp files))
7470 (setq files (symbol-value files))))
7471 (if (stringp files) (setq files (list files)))
7472 (cond
7473 ((eq (car desc) :tag)
7474 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7475 ((eq (car desc) :todo)
7476 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7477 ((eq (car desc) :regexp)
7478 (setq descre (cdr desc)))
7479 ((eq (car desc) :level)
7480 (setq descre (concat "^\\*\\{" (number-to-string
7481 (if org-odd-levels-only
7482 (1- (* 2 (cdr desc)))
7483 (cdr desc)))
7484 "\\}[ \t]")))
7485 ((eq (car desc) :maxlevel)
7486 (setq descre (concat "^\\*\\{1," (number-to-string
7487 (if org-odd-levels-only
7488 (1- (* 2 (cdr desc)))
7489 (cdr desc)))
7490 "\\}[ \t]")))
7491 (t (error "Bad refiling target description %s" desc)))
7492 (while (setq f (pop files))
7493 (save-excursion
7494 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7495 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7496 (save-excursion
7497 (save-restriction
7498 (widen)
7499 (goto-char (point-min))
7500 (while (re-search-forward descre nil t)
7501 (goto-char (point-at-bol))
7502 (when (looking-at org-complex-heading-regexp)
7503 (setq txt (org-link-display-format (match-string 4))
7504 re (concat "^" (regexp-quote
7505 (buffer-substring (match-beginning 1)
7506 (match-end 4)))))
7507 (if (match-end 5) (setq re (concat re "[ \t]+"
7508 (regexp-quote
7509 (match-string 5)))))
7510 (setq re (concat re "[ \t]*$"))
7511 (when org-refile-use-outline-path
7512 (setq txt (mapconcat 'org-protect-slash
7513 (append
7514 (if (eq org-refile-use-outline-path 'file)
7515 (list (file-name-nondirectory
7516 (buffer-file-name (buffer-base-buffer))))
7517 (if (eq org-refile-use-outline-path 'full-file-path)
7518 (list (buffer-file-name (buffer-base-buffer)))))
7519 (org-get-outline-path)
7520 (list txt))
7521 "/")))
7522 (push (list txt f re (point)) targets))
7523 (goto-char (point-at-eol))))))))
7524 (nreverse targets))))
7526 (defun org-protect-slash (s)
7527 (while (string-match "/" s)
7528 (setq s (replace-match "\\" t t s)))
7531 (defun org-get-outline-path ()
7532 "Return the outline path to the current entry, as a list."
7533 (let (rtn)
7534 (save-excursion
7535 (while (org-up-heading-safe)
7536 (when (looking-at org-complex-heading-regexp)
7537 (push (org-match-string-no-properties 4) rtn)))
7538 rtn)))
7540 (defvar org-refile-history nil
7541 "History for refiling operations.")
7543 (defun org-refile (&optional goto default-buffer)
7544 "Move the entry at point to another heading.
7545 The list of target headings is compiled using the information in
7546 `org-refile-targets', which see. This list is created before each use
7547 and will therefore always be up-to-date.
7549 At the target location, the entry is filed as a subitem of the target heading.
7550 Depending on `org-reverse-note-order', the new subitem will either be the
7551 first or the last subitem.
7553 If there is an active region, all entries in that region will be moved.
7554 However, the region must fulfil the requirement that the first heading
7555 is the first one sets the top-level of the moved text - at most siblings
7556 below it are allowed.
7558 With prefix arg GOTO, the command will only visit the target location,
7559 not actually move anything.
7560 With a double prefix `C-u C-u', go to the location where the last refiling
7561 operation has put the subtree."
7562 (interactive "P")
7563 (let* ((cbuf (current-buffer))
7564 (regionp (org-region-active-p))
7565 (region-start (and regionp (region-beginning)))
7566 (region-end (and regionp (region-end)))
7567 (region-length (and regionp (- region-end region-start)))
7568 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7569 pos it nbuf file re level reversed)
7570 (when regionp (goto-char region-start)
7571 (unless (org-kill-is-subtree-p
7572 (buffer-substring region-start region-end))
7573 (error "The region is not a (sequence of) subtree(s)")))
7574 (if (equal goto '(16))
7575 (org-refile-goto-last-stored)
7576 (when (setq it (org-refile-get-location
7577 (if goto "Goto: " "Refile to: ") default-buffer))
7578 (setq file (nth 1 it)
7579 re (nth 2 it)
7580 pos (nth 3 it))
7581 (setq nbuf (or (find-buffer-visiting file)
7582 (find-file-noselect file)))
7583 (if goto
7584 (progn
7585 (switch-to-buffer nbuf)
7586 (goto-char pos)
7587 (org-show-context 'org-goto))
7588 (if regionp
7589 (progn
7590 (kill-new (buffer-substring region-start region-end))
7591 (org-save-markers-in-region region-start region-end))
7592 (org-copy-subtree 1 nil t))
7593 (save-excursion
7594 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7595 (find-file-noselect file))))
7596 (setq reversed (org-notes-order-reversed-p))
7597 (save-excursion
7598 (save-restriction
7599 (widen)
7600 (goto-char pos)
7601 (looking-at outline-regexp)
7602 (setq level (org-get-valid-level (funcall outline-level) 1))
7603 (goto-char
7604 (if reversed
7605 (or (outline-next-heading) (point-max))
7606 (or (save-excursion (outline-get-next-sibling))
7607 (org-end-of-subtree t t)
7608 (point-max))))
7609 (if (not (bolp)) (newline))
7610 (bookmark-set "org-refile-last-stored")
7611 (org-paste-subtree level))))
7612 (if regionp
7613 (delete-region (point) (+ (point) region-length))
7614 (org-cut-subtree))
7615 (setq org-markers-to-move nil)
7616 (message "Refiled to \"%s\"" (car it)))))))
7618 (defun org-refile-goto-last-stored ()
7619 "Go to the location where the last refile was stored."
7620 (interactive)
7621 (bookmark-jump "org-refile-last-stored")
7622 (message "This is the location of the last refile"))
7624 (defun org-refile-get-location (&optional prompt default-buffer)
7625 "Prompt the user for a refile location, using PROMPT."
7626 (let ((org-refile-targets org-refile-targets)
7627 (org-refile-use-outline-path org-refile-use-outline-path))
7628 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7629 (unless org-refile-target-table
7630 (error "No refile targets"))
7631 (let* ((cbuf (current-buffer))
7632 (cfunc (if (and org-refile-use-outline-path
7633 org-outline-path-complete-in-steps)
7634 'org-olpath-completing-read
7635 'org-ido-completing-read))
7636 (extra (if org-refile-use-outline-path "/" ""))
7637 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7638 (fname (and filename (file-truename filename)))
7639 (tbl (mapcar
7640 (lambda (x)
7641 (if (not (equal fname (file-truename (nth 1 x))))
7642 (cons (concat (car x) extra " ("
7643 (file-name-nondirectory (nth 1 x)) ")")
7644 (cdr x))
7645 (cons (concat (car x) extra) (cdr x))))
7646 org-refile-target-table))
7647 (completion-ignore-case t))
7648 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7649 tbl)))
7651 (defun org-olpath-completing-read (prompt collection &rest args)
7652 "Read an outline path like a file name."
7653 (let ((thetable collection))
7654 (apply
7655 'org-ido-completing-read prompt
7656 (lambda (string predicate &optional flag)
7657 (let (rtn r s f (l (length string)))
7658 (cond
7659 ((eq flag nil)
7660 ;; try completion
7661 (try-completion string thetable))
7662 ((eq flag t)
7663 ;; all-completions
7664 (setq rtn (all-completions string thetable predicate))
7665 (mapcar
7666 (lambda (x)
7667 (setq r (substring x l))
7668 (if (string-match " ([^)]*)$" x)
7669 (setq f (match-string 0 x))
7670 (setq f ""))
7671 (if (string-match "/" r)
7672 (concat string (substring r 0 (match-end 0)) f)
7674 rtn))
7675 ((eq flag 'lambda)
7676 ;; exact match?
7677 (assoc string thetable)))
7679 args)))
7681 ;;;; Dynamic blocks
7683 (defun org-find-dblock (name)
7684 "Find the first dynamic block with name NAME in the buffer.
7685 If not found, stay at current position and return nil."
7686 (let (pos)
7687 (save-excursion
7688 (goto-char (point-min))
7689 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7690 nil t)
7691 (match-beginning 0))))
7692 (if pos (goto-char pos))
7693 pos))
7695 (defconst org-dblock-start-re
7696 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7697 "Matches the startline of a dynamic block, with parameters.")
7699 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7700 "Matches the end of a dyhamic block.")
7702 (defun org-create-dblock (plist)
7703 "Create a dynamic block section, with parameters taken from PLIST.
7704 PLIST must containe a :name entry which is used as name of the block."
7705 (unless (bolp) (newline))
7706 (let ((name (plist-get plist :name)))
7707 (insert "#+BEGIN: " name)
7708 (while plist
7709 (if (eq (car plist) :name)
7710 (setq plist (cddr plist))
7711 (insert " " (prin1-to-string (pop plist)))))
7712 (insert "\n\n#+END:\n")
7713 (beginning-of-line -2)))
7715 (defun org-prepare-dblock ()
7716 "Prepare dynamic block for refresh.
7717 This empties the block, puts the cursor at the insert position and returns
7718 the property list including an extra property :name with the block name."
7719 (unless (looking-at org-dblock-start-re)
7720 (error "Not at a dynamic block"))
7721 (let* ((begdel (1+ (match-end 0)))
7722 (name (org-no-properties (match-string 1)))
7723 (params (append (list :name name)
7724 (read (concat "(" (match-string 3) ")")))))
7725 (unless (re-search-forward org-dblock-end-re nil t)
7726 (error "Dynamic block not terminated"))
7727 (setq params
7728 (append params
7729 (list :content (buffer-substring
7730 begdel (match-beginning 0)))))
7731 (delete-region begdel (match-beginning 0))
7732 (goto-char begdel)
7733 (open-line 1)
7734 params))
7736 (defun org-map-dblocks (&optional command)
7737 "Apply COMMAND to all dynamic blocks in the current buffer.
7738 If COMMAND is not given, use `org-update-dblock'."
7739 (let ((cmd (or command 'org-update-dblock))
7740 pos)
7741 (save-excursion
7742 (goto-char (point-min))
7743 (while (re-search-forward org-dblock-start-re nil t)
7744 (goto-char (setq pos (match-beginning 0)))
7745 (condition-case nil
7746 (funcall cmd)
7747 (error (message "Error during update of dynamic block")))
7748 (goto-char pos)
7749 (unless (re-search-forward org-dblock-end-re nil t)
7750 (error "Dynamic block not terminated"))))))
7752 (defun org-dblock-update (&optional arg)
7753 "User command for updating dynamic blocks.
7754 Update the dynamic block at point. With prefix ARG, update all dynamic
7755 blocks in the buffer."
7756 (interactive "P")
7757 (if arg
7758 (org-update-all-dblocks)
7759 (or (looking-at org-dblock-start-re)
7760 (org-beginning-of-dblock))
7761 (org-update-dblock)))
7763 (defun org-update-dblock ()
7764 "Update the dynamic block at point
7765 This means to empty the block, parse for parameters and then call
7766 the correct writing function."
7767 (save-window-excursion
7768 (let* ((pos (point))
7769 (line (org-current-line))
7770 (params (org-prepare-dblock))
7771 (name (plist-get params :name))
7772 (cmd (intern (concat "org-dblock-write:" name))))
7773 (message "Updating dynamic block `%s' at line %d..." name line)
7774 (funcall cmd params)
7775 (message "Updating dynamic block `%s' at line %d...done" name line)
7776 (goto-char pos))))
7778 (defun org-beginning-of-dblock ()
7779 "Find the beginning of the dynamic block at point.
7780 Error if there is no scuh block at point."
7781 (let ((pos (point))
7782 beg)
7783 (end-of-line 1)
7784 (if (and (re-search-backward org-dblock-start-re nil t)
7785 (setq beg (match-beginning 0))
7786 (re-search-forward org-dblock-end-re nil t)
7787 (> (match-end 0) pos))
7788 (goto-char beg)
7789 (goto-char pos)
7790 (error "Not in a dynamic block"))))
7792 (defun org-update-all-dblocks ()
7793 "Update all dynamic blocks in the buffer.
7794 This function can be used in a hook."
7795 (when (org-mode-p)
7796 (org-map-dblocks 'org-update-dblock)))
7799 ;;;; Completion
7801 (defconst org-additional-option-like-keywords
7802 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7803 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7804 "BEGIN_EXAMPLE" "END_EXAMPLE"
7805 "BEGIN_QUOTE" "END_QUOTE"
7806 "BEGIN_VERSE" "END_VERSE"
7807 "BEGIN_SRC" "END_SRC"
7808 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7810 (defcustom org-structure-template-alist
7812 ("s" "#+begin_src ?\n\n#+end_src"
7813 "<src lang=\"?\">\n\n</src>")
7814 ("e" "#+begin_example\n?\n#+end_example"
7815 "<example>\n?\n</example>")
7816 ("q" "#+begin_quote\n?\n#+end_quote"
7817 "<quote>\n?\n</quote>")
7818 ("v" "#+begin_verse\n?\n#+end_verse"
7819 "<verse>\n?\n/verse>")
7820 ("l" "#+begin_latex\n?\n#+end_latex"
7821 "<literal style=\"latex\">\n?\n</literal>")
7822 ("L" "#+latex: "
7823 "<literal style=\"latex\">?</literal>")
7824 ("h" "#+begin_html\n?\n#+end_html"
7825 "<literal style=\"html\">\n?\n</literal>")
7826 ("H" "#+html: "
7827 "<literal style=\"html\">?</literal>")
7828 ("a" "#+begin_ascii\n?\n#+end_ascii")
7829 ("A" "#+ascii: ")
7830 ("i" "#+include %file ?"
7831 "<include file=%file markup=\"?\">")
7833 "Structure completion elements.
7834 This is a list of abbreviation keys and values. The value gets inserted
7835 it you type @samp{.} followed by the key and then the completion key,
7836 usually `M-TAB'. %file will be replaced by a file name after prompting
7837 for the file uning completion.
7838 There are two templates for each key, the first uses the original Org syntax,
7839 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7840 the default when the /org-mtags.el/ module has been loaded. See also the
7841 variable `org-mtags-prefer-muse-templates'.
7842 This is an experimental feature, it is undecided if it is going to stay in."
7843 :group 'org-completion
7844 :type '(repeat
7845 (string :tag "Key")
7846 (string :tag "Template")
7847 (string :tag "Muse Template")))
7849 (defun org-try-structure-completion ()
7850 "Try to complete a structure template before point.
7851 This looks for strings like \"<e\" on an otherwise empty line and
7852 expands them."
7853 (let ((l (buffer-substring (point-at-bol) (point)))
7855 (when (and (looking-at "[ \t]*$")
7856 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7857 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7858 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7859 (match-beginning 1)) a)
7860 t)))
7862 (defun org-complete-expand-structure-template (start cell)
7863 "Expand a structure template."
7864 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7865 (rpl (nth (if musep 2 1) cell)))
7866 (delete-region start (point))
7867 (when (string-match "\\`#\\+" rpl)
7868 (cond
7869 ((bolp))
7870 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7871 (delete-region (point-at-bol) (point)))
7872 (t (newline))))
7873 (setq start (point))
7874 (if (string-match "%file" rpl)
7875 (setq rpl (replace-match
7876 (concat
7877 "\""
7878 (save-match-data
7879 (abbreviate-file-name (read-file-name "Include file: ")))
7880 "\"")
7881 t t rpl)))
7882 (insert rpl)
7883 (if (re-search-backward "\\?" start t) (delete-char 1))))
7886 (defun org-complete (&optional arg)
7887 "Perform completion on word at point.
7888 At the beginning of a headline, this completes TODO keywords as given in
7889 `org-todo-keywords'.
7890 If the current word is preceded by a backslash, completes the TeX symbols
7891 that are supported for HTML support.
7892 If the current word is preceded by \"#+\", completes special words for
7893 setting file options.
7894 In the line after \"#+STARTUP:, complete valid keywords.\"
7895 At all other locations, this simply calls the value of
7896 `org-completion-fallback-command'."
7897 (interactive "P")
7898 (org-without-partial-completion
7899 (catch 'exit
7900 (let* ((a nil)
7901 (end (point))
7902 (beg1 (save-excursion
7903 (skip-chars-backward (org-re "[:alnum:]_@"))
7904 (point)))
7905 (beg (save-excursion
7906 (skip-chars-backward "a-zA-Z0-9_:$")
7907 (point)))
7908 (confirm (lambda (x) (stringp (car x))))
7909 (searchhead (equal (char-before beg) ?*))
7910 (struct
7911 (when (and (member (char-before beg1) '(?. ?<))
7912 (setq a (assoc (buffer-substring beg1 (point))
7913 org-structure-template-alist)))
7914 (org-complete-expand-structure-template (1- beg1) a)
7915 (throw 'exit t)))
7916 (tag (and (equal (char-before beg1) ?:)
7917 (equal (char-after (point-at-bol)) ?*)))
7918 (prop (and (equal (char-before beg1) ?:)
7919 (not (equal (char-after (point-at-bol)) ?*))))
7920 (texp (equal (char-before beg) ?\\))
7921 (link (equal (char-before beg) ?\[))
7922 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7923 beg)
7924 "#+"))
7925 (startup (string-match "^#\\+STARTUP:.*"
7926 (buffer-substring (point-at-bol) (point))))
7927 (completion-ignore-case opt)
7928 (type nil)
7929 (tbl nil)
7930 (table (cond
7931 (opt
7932 (setq type :opt)
7933 (require 'org-exp)
7934 (append
7935 (mapcar
7936 (lambda (x)
7937 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7938 (cons (match-string 2 x) (match-string 1 x)))
7939 (org-split-string (org-get-current-options) "\n"))
7940 (mapcar 'list org-additional-option-like-keywords)))
7941 (startup
7942 (setq type :startup)
7943 org-startup-options)
7944 (link (append org-link-abbrev-alist-local
7945 org-link-abbrev-alist))
7946 (texp
7947 (setq type :tex)
7948 org-html-entities)
7949 ((string-match "\\`\\*+[ \t]+\\'"
7950 (buffer-substring (point-at-bol) beg))
7951 (setq type :todo)
7952 (mapcar 'list org-todo-keywords-1))
7953 (searchhead
7954 (setq type :searchhead)
7955 (save-excursion
7956 (goto-char (point-min))
7957 (while (re-search-forward org-todo-line-regexp nil t)
7958 (push (list
7959 (org-make-org-heading-search-string
7960 (match-string 3) t))
7961 tbl)))
7962 tbl)
7963 (tag (setq type :tag beg beg1)
7964 (or org-tag-alist (org-get-buffer-tags)))
7965 (prop (setq type :prop beg beg1)
7966 (mapcar 'list (org-buffer-property-keys nil t t)))
7967 (t (progn
7968 (call-interactively org-completion-fallback-command)
7969 (throw 'exit nil)))))
7970 (pattern (buffer-substring-no-properties beg end))
7971 (completion (try-completion pattern table confirm)))
7972 (cond ((eq completion t)
7973 (if (not (assoc (upcase pattern) table))
7974 (message "Already complete")
7975 (if (and (equal type :opt)
7976 (not (member (car (assoc (upcase pattern) table))
7977 org-additional-option-like-keywords)))
7978 (insert (substring (cdr (assoc (upcase pattern) table))
7979 (length pattern)))
7980 (if (memq type '(:tag :prop)) (insert ":")))))
7981 ((null completion)
7982 (message "Can't find completion for \"%s\"" pattern)
7983 (ding))
7984 ((not (string= pattern completion))
7985 (delete-region beg end)
7986 (if (string-match " +$" completion)
7987 (setq completion (replace-match "" t t completion)))
7988 (insert completion)
7989 (if (get-buffer-window "*Completions*")
7990 (delete-window (get-buffer-window "*Completions*")))
7991 (if (assoc completion table)
7992 (if (eq type :todo) (insert " ")
7993 (if (memq type '(:tag :prop)) (insert ":"))))
7994 (if (and (equal type :opt) (assoc completion table))
7995 (message "%s" (substitute-command-keys
7996 "Press \\[org-complete] again to insert example settings"))))
7998 (message "Making completion list...")
7999 (let ((list (sort (all-completions pattern table confirm)
8000 'string<)))
8001 (with-output-to-temp-buffer "*Completions*"
8002 (condition-case nil
8003 ;; Protection needed for XEmacs and emacs 21
8004 (display-completion-list list pattern)
8005 (error (display-completion-list list)))))
8006 (message "Making completion list...%s" "done")))))))
8008 ;;;; TODO, DEADLINE, Comments
8010 (defun org-toggle-comment ()
8011 "Change the COMMENT state of an entry."
8012 (interactive)
8013 (save-excursion
8014 (org-back-to-heading)
8015 (let (case-fold-search)
8016 (if (looking-at (concat outline-regexp
8017 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8018 (replace-match "" t t nil 1)
8019 (if (looking-at outline-regexp)
8020 (progn
8021 (goto-char (match-end 0))
8022 (insert org-comment-string " ")))))))
8024 (defvar org-last-todo-state-is-todo nil
8025 "This is non-nil when the last TODO state change led to a TODO state.
8026 If the last change removed the TODO tag or switched to DONE, then
8027 this is nil.")
8029 (defvar org-setting-tags nil) ; dynamically skiped
8031 (defun org-parse-local-options (string var)
8032 "Parse STRING for startup setting relevant for variable VAR."
8033 (let ((rtn (symbol-value var))
8034 e opts)
8035 (save-match-data
8036 (if (or (not string) (not (string-match "\\S-" string)))
8038 (setq opts (delq nil (mapcar (lambda (x)
8039 (setq e (assoc x org-startup-options))
8040 (if (eq (nth 1 e) var) e nil))
8041 (org-split-string string "[ \t]+"))))
8042 (if (not opts)
8044 (setq rtn nil)
8045 (while (setq e (pop opts))
8046 (if (not (nth 3 e))
8047 (setq rtn (nth 2 e))
8048 (if (not (listp rtn)) (setq rtn nil))
8049 (push (nth 2 e) rtn)))
8050 rtn)))))
8052 (defvar org-blocker-hook nil
8053 "Hook for functions that are allowed to block a state change.
8055 Each function gets as its single argument a property list, see
8056 `org-trigger-hook' for more information about this list.
8058 If any of the functions in this hook returns nil, the state change
8059 is blocked.")
8061 (defvar org-trigger-hook nil
8062 "Hook for functions that are triggered by a state change.
8064 Each function gets as its single argument a property list with at least
8065 the following elements:
8067 (:type type-of-change :position pos-at-entry-start
8068 :from old-state :to new-state)
8070 Depending on the type, more properties may be present.
8072 This mechanism is currently implemented for:
8074 TODO state changes
8075 ------------------
8076 :type todo-state-change
8077 :from previous state (keyword as a string), or nil
8078 :to new state (keyword as a string), or nil")
8080 (defvar org-agenda-headline-snapshot-before-repeat)
8081 (defun org-todo (&optional arg)
8082 "Change the TODO state of an item.
8083 The state of an item is given by a keyword at the start of the heading,
8084 like
8085 *** TODO Write paper
8086 *** DONE Call mom
8088 The different keywords are specified in the variable `org-todo-keywords'.
8089 By default the available states are \"TODO\" and \"DONE\".
8090 So for this example: when the item starts with TODO, it is changed to DONE.
8091 When it starts with DONE, the DONE is removed. And when neither TODO nor
8092 DONE are present, add TODO at the beginning of the heading.
8094 With C-u prefix arg, use completion to determine the new state.
8095 With numeric prefix arg, switch to that state.
8097 For calling through lisp, arg is also interpreted in the following way:
8098 'none -> empty state
8099 \"\"(empty string) -> switch to empty state
8100 'done -> switch to DONE
8101 'nextset -> switch to the next set of keywords
8102 'previousset -> switch to the previous set of keywords
8103 \"WAITING\" -> switch to the specified keyword, but only if it
8104 really is a member of `org-todo-keywords'."
8105 (interactive "P")
8106 (save-excursion
8107 (catch 'exit
8108 (org-back-to-heading)
8109 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8110 (or (looking-at (concat " +" org-todo-regexp " *"))
8111 (looking-at " *"))
8112 (let* ((match-data (match-data))
8113 (startpos (point-at-bol))
8114 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8115 (org-log-done org-log-done)
8116 (org-log-repeat org-log-repeat)
8117 (org-todo-log-states org-todo-log-states)
8118 (this (match-string 1))
8119 (hl-pos (match-beginning 0))
8120 (head (org-get-todo-sequence-head this))
8121 (ass (assoc head org-todo-kwd-alist))
8122 (interpret (nth 1 ass))
8123 (done-word (nth 3 ass))
8124 (final-done-word (nth 4 ass))
8125 (last-state (or this ""))
8126 (completion-ignore-case t)
8127 (member (member this org-todo-keywords-1))
8128 (tail (cdr member))
8129 (state (cond
8130 ((and org-todo-key-trigger
8131 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8132 (and (not arg) org-use-fast-todo-selection
8133 (not (eq org-use-fast-todo-selection 'prefix)))))
8134 ;; Use fast selection
8135 (org-fast-todo-selection))
8136 ((and (equal arg '(4))
8137 (or (not org-use-fast-todo-selection)
8138 (not org-todo-key-trigger)))
8139 ;; Read a state with completion
8140 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8141 org-todo-keywords-1)
8142 nil t))
8143 ((eq arg 'right)
8144 (if this
8145 (if tail (car tail) nil)
8146 (car org-todo-keywords-1)))
8147 ((eq arg 'left)
8148 (if (equal member org-todo-keywords-1)
8150 (if this
8151 (nth (- (length org-todo-keywords-1) (length tail) 2)
8152 org-todo-keywords-1)
8153 (org-last org-todo-keywords-1))))
8154 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8155 (setq arg nil))) ; hack to fall back to cycling
8156 (arg
8157 ;; user or caller requests a specific state
8158 (cond
8159 ((equal arg "") nil)
8160 ((eq arg 'none) nil)
8161 ((eq arg 'done) (or done-word (car org-done-keywords)))
8162 ((eq arg 'nextset)
8163 (or (car (cdr (member head org-todo-heads)))
8164 (car org-todo-heads)))
8165 ((eq arg 'previousset)
8166 (let ((org-todo-heads (reverse org-todo-heads)))
8167 (or (car (cdr (member head org-todo-heads)))
8168 (car org-todo-heads))))
8169 ((car (member arg org-todo-keywords-1)))
8170 ((nth (1- (prefix-numeric-value arg))
8171 org-todo-keywords-1))))
8172 ((null member) (or head (car org-todo-keywords-1)))
8173 ((equal this final-done-word) nil) ;; -> make empty
8174 ((null tail) nil) ;; -> first entry
8175 ((eq interpret 'sequence)
8176 (car tail))
8177 ((memq interpret '(type priority))
8178 (if (eq this-command last-command)
8179 (car tail)
8180 (if (> (length tail) 0)
8181 (or done-word (car org-done-keywords))
8182 nil)))
8183 (t nil)))
8184 (next (if state (concat " " state " ") " "))
8185 (change-plist (list :type 'todo-state-change :from this :to state
8186 :position startpos))
8187 dolog now-done-p)
8188 (when org-blocker-hook
8189 (unless (save-excursion
8190 (save-match-data
8191 (run-hook-with-args-until-failure
8192 'org-blocker-hook change-plist)))
8193 (if (interactive-p)
8194 (error "TODO state change from %s to %s blocked" this state)
8195 ;; fail silently
8196 (message "TODO state change from %s to %s blocked" this state)
8197 (throw 'exit nil))))
8198 (store-match-data match-data)
8199 (replace-match next t t)
8200 (unless (pos-visible-in-window-p hl-pos)
8201 (message "TODO state changed to %s" (org-trim next)))
8202 (unless head
8203 (setq head (org-get-todo-sequence-head state)
8204 ass (assoc head org-todo-kwd-alist)
8205 interpret (nth 1 ass)
8206 done-word (nth 3 ass)
8207 final-done-word (nth 4 ass)))
8208 (when (memq arg '(nextset previousset))
8209 (message "Keyword-Set %d/%d: %s"
8210 (- (length org-todo-sets) -1
8211 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8212 (length org-todo-sets)
8213 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8214 (setq org-last-todo-state-is-todo
8215 (not (member state org-done-keywords)))
8216 (setq now-done-p (and (member state org-done-keywords)
8217 (not (member this org-done-keywords))))
8218 (and logging (org-local-logging logging))
8219 (when (and (or org-todo-log-states org-log-done)
8220 (not (memq arg '(nextset previousset))))
8221 ;; we need to look at recording a time and note
8222 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8223 (nth 2 (assoc this org-todo-log-states))))
8224 (when (and state
8225 (member state org-not-done-keywords)
8226 (not (member this org-not-done-keywords)))
8227 ;; This is now a todo state and was not one before
8228 ;; If there was a CLOSED time stamp, get rid of it.
8229 (org-add-planning-info nil nil 'closed))
8230 (when (and now-done-p org-log-done)
8231 ;; It is now done, and it was not done before
8232 (org-add-planning-info 'closed (org-current-time))
8233 (if (and (not dolog) (eq 'note org-log-done))
8234 (org-add-log-setup 'done state 'findpos 'note)))
8235 (when (and state dolog)
8236 ;; This is a non-nil state, and we need to log it
8237 (org-add-log-setup 'state state 'findpos dolog)))
8238 ;; Fixup tag positioning
8239 (org-todo-trigger-tag-changes state)
8240 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8241 (when org-provide-todo-statistics
8242 (org-update-parent-todo-statistics))
8243 (run-hooks 'org-after-todo-state-change-hook)
8244 (if (and arg (not (member state org-done-keywords)))
8245 (setq head (org-get-todo-sequence-head state)))
8246 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8247 ;; Do we need to trigger a repeat?
8248 (when now-done-p
8249 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8250 ;; This is for the agenda, take a snapshot of the headline.
8251 (save-match-data
8252 (setq org-agenda-headline-snapshot-before-repeat
8253 (org-get-heading))))
8254 (org-auto-repeat-maybe state))
8255 ;; Fixup cursor location if close to the keyword
8256 (if (and (outline-on-heading-p)
8257 (not (bolp))
8258 (save-excursion (beginning-of-line 1)
8259 (looking-at org-todo-line-regexp))
8260 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8261 (progn
8262 (goto-char (or (match-end 2) (match-end 1)))
8263 (just-one-space)))
8264 (when org-trigger-hook
8265 (save-excursion
8266 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8268 (defun org-update-parent-todo-statistics ()
8269 "Update any statistics cookie in the parent of the current headline."
8270 (interactive)
8271 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8272 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8273 (catch 'exit
8274 (save-excursion
8275 (setq level (org-up-heading-safe))
8276 (unless (and level
8277 (re-search-forward box-re (point-at-eol) t))
8278 (throw 'exit nil))
8279 (setq is-percent (match-end 2))
8280 (save-match-data
8281 (unless (outline-next-heading) (throw 'exit nil))
8282 (while (looking-at org-todo-line-regexp)
8283 (setq kwd (match-string 2))
8284 (and kwd (setq cnt-all (1+ cnt-all)))
8285 (and (member kwd org-done-keywords)
8286 (setq cnt-done (1+ cnt-done)))
8287 (condition-case nil
8288 (org-forward-same-level 1)
8289 (error (end-of-line 1)))))
8290 (replace-match
8291 (if is-percent
8292 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8293 (format "[%d/%d]" cnt-done cnt-all)))
8294 (run-hook-with-args 'org-after-todo-statistics-hook
8295 cnt-done (- cnt-all cnt-done))))))
8297 (defvar org-after-todo-statistics-hook nil
8298 "Hook that is called after a TODO statistics cookie has been updated.
8299 Each function is called with two arguments: the number of not-done entries
8300 and the number of done entries.
8302 For example, the following function, when added to this hook, will switch
8303 an entry to DONE when all children are done, and back to TODO when new
8304 entries are set to a TODO status. Note that this hook is only called
8305 when there is a statistics cookie in the headline!
8307 (defun org-summary-todo (n-done n-not-done)
8308 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8309 (let (org-log-done org-log-states) ; turn off logging
8310 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8313 (defun org-todo-trigger-tag-changes (state)
8314 "Apply the changes defined in `org-todo-state-tags-triggers'."
8315 (let ((l org-todo-state-tags-triggers)
8316 changes)
8317 (when (or (not state) (equal state ""))
8318 (setq changes (append changes (cdr (assoc "" l)))))
8319 (when (and (stringp state) (> (length state) 0))
8320 (setq changes (append changes (cdr (assoc state l)))))
8321 (when (member state org-not-done-keywords)
8322 (setq changes (append changes (cdr (assoc 'todo l)))))
8323 (when (member state org-done-keywords)
8324 (setq changes (append changes (cdr (assoc 'done l)))))
8325 (dolist (c changes)
8326 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8328 (defun org-local-logging (value)
8329 "Get logging settings from a property VALUE."
8330 (let* (words w a)
8331 ;; directly set the variables, they are already local.
8332 (setq org-log-done nil
8333 org-log-repeat nil
8334 org-todo-log-states nil)
8335 (setq words (org-split-string value))
8336 (while (setq w (pop words))
8337 (cond
8338 ((setq a (assoc w org-startup-options))
8339 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8340 (set (nth 1 a) (nth 2 a))))
8341 ((setq a (org-extract-log-state-settings w))
8342 (and (member (car a) org-todo-keywords-1)
8343 (push a org-todo-log-states)))))))
8345 (defun org-get-todo-sequence-head (kwd)
8346 "Return the head of the TODO sequence to which KWD belongs.
8347 If KWD is not set, check if there is a text property remembering the
8348 right sequence."
8349 (let (p)
8350 (cond
8351 ((not kwd)
8352 (or (get-text-property (point-at-bol) 'org-todo-head)
8353 (progn
8354 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8355 nil (point-at-eol)))
8356 (get-text-property p 'org-todo-head))))
8357 ((not (member kwd org-todo-keywords-1))
8358 (car org-todo-keywords-1))
8359 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8361 (defun org-fast-todo-selection ()
8362 "Fast TODO keyword selection with single keys.
8363 Returns the new TODO keyword, or nil if no state change should occur."
8364 (let* ((fulltable org-todo-key-alist)
8365 (done-keywords org-done-keywords) ;; needed for the faces.
8366 (maxlen (apply 'max (mapcar
8367 (lambda (x)
8368 (if (stringp (car x)) (string-width (car x)) 0))
8369 fulltable)))
8370 (expert nil)
8371 (fwidth (+ maxlen 3 1 3))
8372 (ncol (/ (- (window-width) 4) fwidth))
8373 tg cnt e c tbl
8374 groups ingroup)
8375 (save-window-excursion
8376 (if expert
8377 (set-buffer (get-buffer-create " *Org todo*"))
8378 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8379 (erase-buffer)
8380 (org-set-local 'org-done-keywords done-keywords)
8381 (setq tbl fulltable cnt 0)
8382 (while (setq e (pop tbl))
8383 (cond
8384 ((equal e '(:startgroup))
8385 (push '() groups) (setq ingroup t)
8386 (when (not (= cnt 0))
8387 (setq cnt 0)
8388 (insert "\n"))
8389 (insert "{ "))
8390 ((equal e '(:endgroup))
8391 (setq ingroup nil cnt 0)
8392 (insert "}\n"))
8394 (setq tg (car e) c (cdr e))
8395 (if ingroup (push tg (car groups)))
8396 (setq tg (org-add-props tg nil 'face
8397 (org-get-todo-face tg)))
8398 (if (and (= cnt 0) (not ingroup)) (insert " "))
8399 (insert "[" c "] " tg (make-string
8400 (- fwidth 4 (length tg)) ?\ ))
8401 (when (= (setq cnt (1+ cnt)) ncol)
8402 (insert "\n")
8403 (if ingroup (insert " "))
8404 (setq cnt 0)))))
8405 (insert "\n")
8406 (goto-char (point-min))
8407 (if (not expert) (org-fit-window-to-buffer))
8408 (message "[a-z..]:Set [SPC]:clear")
8409 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8410 (cond
8411 ((or (= c ?\C-g)
8412 (and (= c ?q) (not (rassoc c fulltable))))
8413 (setq quit-flag t))
8414 ((= c ?\ ) nil)
8415 ((setq e (rassoc c fulltable) tg (car e))
8417 (t (setq quit-flag t))))))
8419 (defun org-entry-is-todo-p ()
8420 (member (org-get-todo-state) org-not-done-keywords))
8422 (defun org-entry-is-done-p ()
8423 (member (org-get-todo-state) org-done-keywords))
8425 (defun org-get-todo-state ()
8426 (save-excursion
8427 (org-back-to-heading t)
8428 (and (looking-at org-todo-line-regexp)
8429 (match-end 2)
8430 (match-string 2))))
8432 (defun org-at-date-range-p (&optional inactive-ok)
8433 "Is the cursor inside a date range?"
8434 (interactive)
8435 (save-excursion
8436 (catch 'exit
8437 (let ((pos (point)))
8438 (skip-chars-backward "^[<\r\n")
8439 (skip-chars-backward "<[")
8440 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8441 (>= (match-end 0) pos)
8442 (throw 'exit t))
8443 (skip-chars-backward "^<[\r\n")
8444 (skip-chars-backward "<[")
8445 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8446 (>= (match-end 0) pos)
8447 (throw 'exit t)))
8448 nil)))
8450 (defun org-get-repeat ()
8451 "Check if there is a deadline/schedule with repeater in this entry."
8452 (save-match-data
8453 (save-excursion
8454 (org-back-to-heading t)
8455 (if (re-search-forward
8456 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8457 (match-string 1)))))
8459 (defvar org-last-changed-timestamp)
8460 (defvar org-last-inserted-timestamp)
8461 (defvar org-log-post-message)
8462 (defvar org-log-note-purpose)
8463 (defvar org-log-note-how)
8464 (defvar org-log-note-extra)
8465 (defun org-auto-repeat-maybe (done-word)
8466 "Check if the current headline contains a repeated deadline/schedule.
8467 If yes, set TODO state back to what it was and change the base date
8468 of repeating deadline/scheduled time stamps to new date.
8469 This function is run automatically after each state change to a DONE state."
8470 ;; last-state is dynamically scoped into this function
8471 (let* ((repeat (org-get-repeat))
8472 (aa (assoc last-state org-todo-kwd-alist))
8473 (interpret (nth 1 aa))
8474 (head (nth 2 aa))
8475 (whata '(("d" . day) ("m" . month) ("y" . year)))
8476 (msg "Entry repeats: ")
8477 (org-log-done nil)
8478 (org-todo-log-states nil)
8479 (nshiftmax 10) (nshift 0)
8480 re type n what ts mb0 time)
8481 (when repeat
8482 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8483 (org-todo (if (eq interpret 'type) last-state head))
8484 (when org-log-repeat
8485 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8486 (memq 'org-add-log-note post-command-hook))
8487 ;; OK, we are already setup for some record
8488 (if (eq org-log-repeat 'note)
8489 ;; make sure we take a note, not only a time stamp
8490 (setq org-log-note-how 'note))
8491 ;; Set up for taking a record
8492 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8493 'findpos org-log-repeat)))
8494 (org-back-to-heading t)
8495 (org-add-planning-info nil nil 'closed)
8496 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8497 org-deadline-time-regexp "\\)\\|\\("
8498 org-ts-regexp "\\)"))
8499 (while (re-search-forward
8500 re (save-excursion (outline-next-heading) (point)) t)
8501 (setq type (if (match-end 1) org-scheduled-string
8502 (if (match-end 3) org-deadline-string "Plain:"))
8503 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8504 mb0 (match-beginning 0))
8505 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8506 (setq n (string-to-number (match-string 2 ts))
8507 what (match-string 3 ts))
8508 (if (equal what "w") (setq n (* n 7) what "d"))
8509 ;; Preparation, see if we need to modify the start date for the change
8510 (when (match-end 1)
8511 (setq time (save-match-data (org-time-string-to-time ts)))
8512 (cond
8513 ((equal (match-string 1 ts) ".")
8514 ;; Shift starting date to today
8515 (org-timestamp-change
8516 (- (time-to-days (current-time)) (time-to-days time))
8517 'day))
8518 ((equal (match-string 1 ts) "+")
8519 (while (or (= nshift 0)
8520 (<= (time-to-days time) (time-to-days (current-time))))
8521 (when (= (incf nshift) nshiftmax)
8522 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8523 (error "Abort")))
8524 (org-timestamp-change n (cdr (assoc what whata)))
8525 (org-at-timestamp-p t)
8526 (setq ts (match-string 1))
8527 (setq time (save-match-data (org-time-string-to-time ts))))
8528 (org-timestamp-change (- n) (cdr (assoc what whata)))
8529 ;; rematch, so that we have everything in place for the real shift
8530 (org-at-timestamp-p t)
8531 (setq ts (match-string 1))
8532 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8533 (org-timestamp-change n (cdr (assoc what whata)))
8534 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8535 (setq org-log-post-message msg)
8536 (message "%s" msg))))
8538 (defun org-show-todo-tree (arg)
8539 "Make a compact tree which shows all headlines marked with TODO.
8540 The tree will show the lines where the regexp matches, and all higher
8541 headlines above the match.
8542 With a \\[universal-argument] prefix, also show the DONE entries.
8543 With a numeric prefix N, construct a sparse tree for the Nth element
8544 of `org-todo-keywords-1'."
8545 (interactive "P")
8546 (let ((case-fold-search nil)
8547 (kwd-re
8548 (cond ((null arg) org-not-done-regexp)
8549 ((equal arg '(4))
8550 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8551 (mapcar 'list org-todo-keywords-1))))
8552 (concat "\\("
8553 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8554 "\\)\\>")))
8555 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8556 (regexp-quote (nth (1- (prefix-numeric-value arg))
8557 org-todo-keywords-1)))
8558 (t (error "Invalid prefix argument: %s" arg)))))
8559 (message "%d TODO entries found"
8560 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8562 (defun org-deadline (&optional remove time)
8563 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8564 With argument REMOVE, remove any deadline from the item.
8565 When TIME is set, it should be an internal time specification, and the
8566 scheduling will use the corresponding date."
8567 (interactive "P")
8568 (if remove
8569 (progn
8570 (org-remove-timestamp-with-keyword org-deadline-string)
8571 (message "Item no longer has a deadline."))
8572 (if (org-get-repeat)
8573 (error "Cannot change deadline on task with repeater, please do that by hand")
8574 (org-add-planning-info 'deadline time 'closed)
8575 (message "Deadline on %s" org-last-inserted-timestamp))))
8577 (defun org-schedule (&optional remove time)
8578 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8579 With argument REMOVE, remove any scheduling date from the item.
8580 When TIME is set, it should be an internal time specification, and the
8581 scheduling will use the corresponding date."
8582 (interactive "P")
8583 (if remove
8584 (progn
8585 (org-remove-timestamp-with-keyword org-scheduled-string)
8586 (message "Item is no longer scheduled."))
8587 (if (org-get-repeat)
8588 (error "Cannot reschedule task with repeater, please do that by hand")
8589 (org-add-planning-info 'scheduled time 'closed)
8590 (message "Scheduled to %s" org-last-inserted-timestamp))))
8592 (defun org-remove-timestamp-with-keyword (keyword)
8593 "Remove all time stamps with KEYWORD in the current entry."
8594 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8595 beg)
8596 (save-excursion
8597 (org-back-to-heading t)
8598 (setq beg (point))
8599 (org-end-of-subtree t t)
8600 (while (re-search-backward re beg t)
8601 (replace-match "")
8602 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8603 (equal (char-before) ?\ ))
8604 (backward-delete-char 1)
8605 (if (string-match "^[ \t]*$" (buffer-substring
8606 (point-at-bol) (point-at-eol)))
8607 (delete-region (point-at-bol)
8608 (min (point-max) (1+ (point-at-eol))))))))))
8610 (defun org-add-planning-info (what &optional time &rest remove)
8611 "Insert new timestamp with keyword in the line directly after the headline.
8612 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8613 If non is given, the user is prompted for a date.
8614 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8615 be removed."
8616 (interactive)
8617 (let (org-time-was-given org-end-time-was-given ts
8618 end default-time default-input)
8620 (when (and (not time) (memq what '(scheduled deadline)))
8621 ;; Try to get a default date/time from existing timestamp
8622 (save-excursion
8623 (org-back-to-heading t)
8624 (setq end (save-excursion (outline-next-heading) (point)))
8625 (when (re-search-forward (if (eq what 'scheduled)
8626 org-scheduled-time-regexp
8627 org-deadline-time-regexp)
8628 end t)
8629 (setq ts (match-string 1)
8630 default-time
8631 (apply 'encode-time (org-parse-time-string ts))
8632 default-input (and ts (org-get-compact-tod ts))))))
8633 (when what
8634 ;; If necessary, get the time from the user
8635 (setq time (or time (org-read-date nil 'to-time nil nil
8636 default-time default-input))))
8638 (when (and org-insert-labeled-timestamps-at-point
8639 (member what '(scheduled deadline)))
8640 (insert
8641 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8642 (org-insert-time-stamp time org-time-was-given
8643 nil nil nil (list org-end-time-was-given))
8644 (setq what nil))
8645 (save-excursion
8646 (save-restriction
8647 (let (col list elt ts buffer-invisibility-spec)
8648 (org-back-to-heading t)
8649 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8650 (goto-char (match-end 1))
8651 (setq col (current-column))
8652 (goto-char (match-end 0))
8653 (if (eobp) (insert "\n") (forward-char 1))
8654 (if (and (not (looking-at outline-regexp))
8655 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8656 "[^\r\n]*"))
8657 (not (equal (match-string 1) org-clock-string)))
8658 (narrow-to-region (match-beginning 0) (match-end 0))
8659 (insert-before-markers "\n")
8660 (backward-char 1)
8661 (narrow-to-region (point) (point))
8662 (and org-adapt-indentation (org-indent-to-column col)))
8663 ;; Check if we have to remove something.
8664 (setq list (cons what remove))
8665 (while list
8666 (setq elt (pop list))
8667 (goto-char (point-min))
8668 (when (or (and (eq elt 'scheduled)
8669 (re-search-forward org-scheduled-time-regexp nil t))
8670 (and (eq elt 'deadline)
8671 (re-search-forward org-deadline-time-regexp nil t))
8672 (and (eq elt 'closed)
8673 (re-search-forward org-closed-time-regexp nil t)))
8674 (replace-match "")
8675 (if (looking-at "--+<[^>]+>") (replace-match ""))
8676 (if (looking-at " +") (replace-match ""))))
8677 (goto-char (point-max))
8678 (when what
8679 (insert
8680 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8681 (cond ((eq what 'scheduled) org-scheduled-string)
8682 ((eq what 'deadline) org-deadline-string)
8683 ((eq what 'closed) org-closed-string))
8684 " ")
8685 (setq ts (org-insert-time-stamp
8686 time
8687 (or org-time-was-given
8688 (and (eq what 'closed) org-log-done-with-time))
8689 (eq what 'closed)
8690 nil nil (list org-end-time-was-given)))
8691 (end-of-line 1))
8692 (goto-char (point-min))
8693 (widen)
8694 (if (and (looking-at "[ \t]+\n")
8695 (equal (char-before) ?\n))
8696 (delete-region (1- (point)) (point-at-eol)))
8697 ts)))))
8699 (defvar org-log-note-marker (make-marker))
8700 (defvar org-log-note-purpose nil)
8701 (defvar org-log-note-state nil)
8702 (defvar org-log-note-how nil)
8703 (defvar org-log-note-extra nil)
8704 (defvar org-log-note-window-configuration nil)
8705 (defvar org-log-note-return-to (make-marker))
8706 (defvar org-log-post-message nil
8707 "Message to be displayed after a log note has been stored.
8708 The auto-repeater uses this.")
8710 (defun org-add-note ()
8711 "Add a note to the current entry.
8712 This is done in the same way as adding a state change note."
8713 (interactive)
8714 (org-add-log-setup 'note nil 'findpos nil))
8716 (defvar org-property-end-re)
8717 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8718 "Set up the post command hook to take a note.
8719 If this is about to TODO state change, the new state is expected in STATE.
8720 When FINDPOS is non-nil, find the correct position for the note in
8721 the current entry. If not, assume that it can be inserted at point.
8722 HOW is an indicator what kind of note should be created.
8723 EXTRA is additional text that will be inserted into the notes buffer."
8724 (save-restriction
8725 (save-excursion
8726 (when findpos
8727 (org-back-to-heading t)
8728 (narrow-to-region (point) (save-excursion
8729 (outline-next-heading) (point)))
8730 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8731 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8732 "[^\r\n]*\\)?"))
8733 (goto-char (match-end 0))
8734 (when (and org-log-state-notes-insert-after-drawers
8735 (save-excursion
8736 (forward-line) (looking-at org-drawer-regexp)))
8737 (progn (forward-line)
8738 (while (looking-at org-drawer-regexp)
8739 (goto-char (match-end 0))
8740 (re-search-forward org-property-end-re (point-max) t)
8741 (forward-line))
8742 (forward-line -1)))
8743 (unless org-log-states-order-reversed
8744 (and (= (char-after) ?\n) (forward-char 1))
8745 (org-skip-over-state-notes)
8746 (skip-chars-backward " \t\n\r")))
8747 (move-marker org-log-note-marker (point))
8748 (setq org-log-note-purpose purpose
8749 org-log-note-state state
8750 org-log-note-how how
8751 org-log-note-extra extra)
8752 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8754 (defun org-skip-over-state-notes ()
8755 "Skip past the list of State notes in an entry."
8756 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8757 (while (looking-at "[ \t]*- State")
8758 (condition-case nil
8759 (org-next-item)
8760 (error (org-end-of-item)))))
8762 (defun org-add-log-note (&optional purpose)
8763 "Pop up a window for taking a note, and add this note later at point."
8764 (remove-hook 'post-command-hook 'org-add-log-note)
8765 (setq org-log-note-window-configuration (current-window-configuration))
8766 (delete-other-windows)
8767 (move-marker org-log-note-return-to (point))
8768 (switch-to-buffer (marker-buffer org-log-note-marker))
8769 (goto-char org-log-note-marker)
8770 (org-switch-to-buffer-other-window "*Org Note*")
8771 (erase-buffer)
8772 (if (memq org-log-note-how '(time state))
8773 (let (current-prefix-arg) (org-store-log-note))
8774 (let ((org-inhibit-startup t)) (org-mode))
8775 (insert (format "# Insert note for %s.
8776 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8777 (cond
8778 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8779 ((eq org-log-note-purpose 'done) "closed todo item")
8780 ((eq org-log-note-purpose 'state)
8781 (format "state change to \"%s\"" org-log-note-state))
8782 ((eq org-log-note-purpose 'note)
8783 "this entry")
8784 (t (error "This should not happen")))))
8785 (if org-log-note-extra (insert org-log-note-extra))
8786 (org-set-local 'org-finish-function 'org-store-log-note)))
8788 (defvar org-note-abort nil) ; dynamically scoped
8789 (defun org-store-log-note ()
8790 "Finish taking a log note, and insert it to where it belongs."
8791 (let ((txt (buffer-string))
8792 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8793 lines ind)
8794 (kill-buffer (current-buffer))
8795 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8796 (setq txt (replace-match "" t t txt)))
8797 (if (string-match "\\s-+\\'" txt)
8798 (setq txt (replace-match "" t t txt)))
8799 (setq lines (org-split-string txt "\n"))
8800 (when (and note (string-match "\\S-" note))
8801 (setq note
8802 (org-replace-escapes
8803 note
8804 (list (cons "%u" (user-login-name))
8805 (cons "%U" user-full-name)
8806 (cons "%t" (format-time-string
8807 (org-time-stamp-format 'long 'inactive)
8808 (current-time)))
8809 (cons "%s" (if org-log-note-state
8810 (concat "\"" org-log-note-state "\"")
8811 "")))))
8812 (if lines (setq note (concat note " \\\\")))
8813 (push note lines))
8814 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8815 (when lines
8816 (save-excursion
8817 (set-buffer (marker-buffer org-log-note-marker))
8818 (save-excursion
8819 (goto-char org-log-note-marker)
8820 (move-marker org-log-note-marker nil)
8821 (end-of-line 1)
8822 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8823 (indent-relative nil)
8824 (insert "- " (pop lines))
8825 (org-indent-line-function)
8826 (beginning-of-line 1)
8827 (looking-at "[ \t]*")
8828 (setq ind (concat (match-string 0) " "))
8829 (end-of-line 1)
8830 (while lines (insert "\n" ind (pop lines)))))))
8831 (set-window-configuration org-log-note-window-configuration)
8832 (with-current-buffer (marker-buffer org-log-note-return-to)
8833 (goto-char org-log-note-return-to))
8834 (move-marker org-log-note-return-to nil)
8835 (and org-log-post-message (message "%s" org-log-post-message)))
8837 (defun org-sparse-tree (&optional arg)
8838 "Create a sparse tree, prompt for the details.
8839 This command can create sparse trees. You first need to select the type
8840 of match used to create the tree:
8842 t Show entries with a specific TODO keyword.
8843 T Show entries selected by a tags match.
8844 p Enter a property name and its value (both with completion on existing
8845 names/values) and show entries with that property.
8846 r Show entries matching a regular expression
8847 d Show deadlines due within `org-deadline-warning-days'."
8848 (interactive "P")
8849 (let (ans kwd value)
8850 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8851 (setq ans (read-char-exclusive))
8852 (cond
8853 ((equal ans ?d)
8854 (call-interactively 'org-check-deadlines))
8855 ((equal ans ?b)
8856 (call-interactively 'org-check-before-date))
8857 ((equal ans ?t)
8858 (org-show-todo-tree '(4)))
8859 ((equal ans ?T)
8860 (call-interactively 'org-tags-sparse-tree))
8861 ((member ans '(?p ?P))
8862 (setq kwd (org-ido-completing-read "Property: "
8863 (mapcar 'list (org-buffer-property-keys))))
8864 (setq value (org-ido-completing-read "Value: "
8865 (mapcar 'list (org-property-values kwd))))
8866 (unless (string-match "\\`{.*}\\'" value)
8867 (setq value (concat "\"" value "\"")))
8868 (org-tags-sparse-tree arg (concat kwd "=" value)))
8869 ((member ans '(?r ?R ?/))
8870 (call-interactively 'org-occur))
8871 (t (error "No such sparse tree command \"%c\"" ans)))))
8873 (defvar org-occur-highlights nil
8874 "List of overlays used for occur matches.")
8875 (make-variable-buffer-local 'org-occur-highlights)
8876 (defvar org-occur-parameters nil
8877 "Parameters of the active org-occur calls.
8878 This is a list, each call to org-occur pushes as cons cell,
8879 containing the regular expression and the callback, onto the list.
8880 The list can contain several entries if `org-occur' has been called
8881 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8882 will only contain one set of parameters. When the highlights are
8883 removed (for example with `C-c C-c', or with the next edit (depending
8884 on `org-remove-highlights-with-change'), this variable is emptied
8885 as well.")
8886 (make-variable-buffer-local 'org-occur-parameters)
8888 (defun org-occur (regexp &optional keep-previous callback)
8889 "Make a compact tree which shows all matches of REGEXP.
8890 The tree will show the lines where the regexp matches, and all higher
8891 headlines above the match. It will also show the heading after the match,
8892 to make sure editing the matching entry is easy.
8893 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8894 call to `org-occur' will be kept, to allow stacking of calls to this
8895 command.
8896 If CALLBACK is non-nil, it is a function which is called to confirm
8897 that the match should indeed be shown."
8898 (interactive "sRegexp: \nP")
8899 (unless keep-previous
8900 (org-remove-occur-highlights nil nil t))
8901 (push (cons regexp callback) org-occur-parameters)
8902 (let ((cnt 0))
8903 (save-excursion
8904 (goto-char (point-min))
8905 (if (or (not keep-previous) ; do not want to keep
8906 (not org-occur-highlights)) ; no previous matches
8907 ;; hide everything
8908 (org-overview))
8909 (while (re-search-forward regexp nil t)
8910 (when (or (not callback)
8911 (save-match-data (funcall callback)))
8912 (setq cnt (1+ cnt))
8913 (when org-highlight-sparse-tree-matches
8914 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8915 (org-show-context 'occur-tree))))
8916 (when org-remove-highlights-with-change
8917 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8918 nil 'local))
8919 (unless org-sparse-tree-open-archived-trees
8920 (org-hide-archived-subtrees (point-min) (point-max)))
8921 (run-hooks 'org-occur-hook)
8922 (if (interactive-p)
8923 (message "%d match(es) for regexp %s" cnt regexp))
8924 cnt))
8926 (defun org-show-context (&optional key)
8927 "Make sure point and context and visible.
8928 How much context is shown depends upon the variables
8929 `org-show-hierarchy-above', `org-show-following-heading'. and
8930 `org-show-siblings'."
8931 (let ((heading-p (org-on-heading-p t))
8932 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8933 (following-p (org-get-alist-option org-show-following-heading key))
8934 (entry-p (org-get-alist-option org-show-entry-below key))
8935 (siblings-p (org-get-alist-option org-show-siblings key)))
8936 (catch 'exit
8937 ;; Show heading or entry text
8938 (if (and heading-p (not entry-p))
8939 (org-flag-heading nil) ; only show the heading
8940 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8941 (org-show-hidden-entry))) ; show entire entry
8942 (when following-p
8943 ;; Show next sibling, or heading below text
8944 (save-excursion
8945 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8946 (org-flag-heading nil))))
8947 (when siblings-p (org-show-siblings))
8948 (when hierarchy-p
8949 ;; show all higher headings, possibly with siblings
8950 (save-excursion
8951 (while (and (condition-case nil
8952 (progn (org-up-heading-all 1) t)
8953 (error nil))
8954 (not (bobp)))
8955 (org-flag-heading nil)
8956 (when siblings-p (org-show-siblings))))))))
8958 (defun org-reveal (&optional siblings)
8959 "Show current entry, hierarchy above it, and the following headline.
8960 This can be used to show a consistent set of context around locations
8961 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8962 not t for the search context.
8964 With optional argument SIBLINGS, on each level of the hierarchy all
8965 siblings are shown. This repairs the tree structure to what it would
8966 look like when opened with hierarchical calls to `org-cycle'."
8967 (interactive "P")
8968 (let ((org-show-hierarchy-above t)
8969 (org-show-following-heading t)
8970 (org-show-siblings (if siblings t org-show-siblings)))
8971 (org-show-context nil)))
8973 (defun org-highlight-new-match (beg end)
8974 "Highlight from BEG to END and mark the highlight is an occur headline."
8975 (let ((ov (org-make-overlay beg end)))
8976 (org-overlay-put ov 'face 'secondary-selection)
8977 (push ov org-occur-highlights)))
8979 (defun org-remove-occur-highlights (&optional beg end noremove)
8980 "Remove the occur highlights from the buffer.
8981 BEG and END are ignored. If NOREMOVE is nil, remove this function
8982 from the `before-change-functions' in the current buffer."
8983 (interactive)
8984 (unless org-inhibit-highlight-removal
8985 (mapc 'org-delete-overlay org-occur-highlights)
8986 (setq org-occur-highlights nil)
8987 (setq org-occur-parameters nil)
8988 (unless noremove
8989 (remove-hook 'before-change-functions
8990 'org-remove-occur-highlights 'local))))
8992 ;;;; Priorities
8994 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8995 "Regular expression matching the priority indicator.")
8997 (defvar org-remove-priority-next-time nil)
8999 (defun org-priority-up ()
9000 "Increase the priority of the current item."
9001 (interactive)
9002 (org-priority 'up))
9004 (defun org-priority-down ()
9005 "Decrease the priority of the current item."
9006 (interactive)
9007 (org-priority 'down))
9009 (defun org-priority (&optional action)
9010 "Change the priority of an item by ARG.
9011 ACTION can be `set', `up', `down', or a character."
9012 (interactive)
9013 (setq action (or action 'set))
9014 (let (current new news have remove)
9015 (save-excursion
9016 (org-back-to-heading)
9017 (if (looking-at org-priority-regexp)
9018 (setq current (string-to-char (match-string 2))
9019 have t)
9020 (setq current org-default-priority))
9021 (cond
9022 ((or (eq action 'set)
9023 (if (featurep 'xemacs) (characterp action) (integerp action)))
9024 (if (not (eq action 'set))
9025 (setq new action)
9026 (message "Priority %c-%c, SPC to remove: "
9027 org-highest-priority org-lowest-priority)
9028 (setq new (read-char-exclusive)))
9029 (if (and (= (upcase org-highest-priority) org-highest-priority)
9030 (= (upcase org-lowest-priority) org-lowest-priority))
9031 (setq new (upcase new)))
9032 (cond ((equal new ?\ ) (setq remove t))
9033 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9034 (error "Priority must be between `%c' and `%c'"
9035 org-highest-priority org-lowest-priority))))
9036 ((eq action 'up)
9037 (if (and (not have) (eq last-command this-command))
9038 (setq new org-lowest-priority)
9039 (setq new (if (and org-priority-start-cycle-with-default (not have))
9040 org-default-priority (1- current)))))
9041 ((eq action 'down)
9042 (if (and (not have) (eq last-command this-command))
9043 (setq new org-highest-priority)
9044 (setq new (if (and org-priority-start-cycle-with-default (not have))
9045 org-default-priority (1+ current)))))
9046 (t (error "Invalid action")))
9047 (if (or (< (upcase new) org-highest-priority)
9048 (> (upcase new) org-lowest-priority))
9049 (setq remove t))
9050 (setq news (format "%c" new))
9051 (if have
9052 (if remove
9053 (replace-match "" t t nil 1)
9054 (replace-match news t t nil 2))
9055 (if remove
9056 (error "No priority cookie found in line")
9057 (looking-at org-todo-line-regexp)
9058 (if (match-end 2)
9059 (progn
9060 (goto-char (match-end 2))
9061 (insert " [#" news "]"))
9062 (goto-char (match-beginning 3))
9063 (insert "[#" news "] ")))))
9064 (org-preserve-lc (org-set-tags nil 'align))
9065 (if remove
9066 (message "Priority removed")
9067 (message "Priority of current item set to %s" news))))
9070 (defun org-get-priority (s)
9071 "Find priority cookie and return priority."
9072 (save-match-data
9073 (if (not (string-match org-priority-regexp s))
9074 (* 1000 (- org-lowest-priority org-default-priority))
9075 (* 1000 (- org-lowest-priority
9076 (string-to-char (match-string 2 s)))))))
9078 ;;;; Tags
9080 (defvar org-agenda-archives-mode)
9081 (defun org-scan-tags (action matcher &optional todo-only)
9082 "Scan headline tags with inheritance and produce output ACTION.
9084 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9085 or `agenda' to produce an entry list for an agenda view. It can also be
9086 a Lisp form or a function that should be called at each matched headline, in
9087 this case the return value is a list of all return values from these calls.
9089 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9090 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9091 only lines with a TODO keyword are included in the output."
9092 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9093 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9094 (org-re
9095 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9096 (props (list 'face 'default
9097 'done-face 'org-done
9098 'undone-face 'default
9099 'mouse-face 'highlight
9100 'org-not-done-regexp org-not-done-regexp
9101 'org-todo-regexp org-todo-regexp
9102 'keymap org-agenda-keymap
9103 'help-echo
9104 (format "mouse-2 or RET jump to org file %s"
9105 (abbreviate-file-name
9106 (or (buffer-file-name (buffer-base-buffer))
9107 (buffer-name (buffer-base-buffer)))))))
9108 (case-fold-search nil)
9109 lspos tags tags-list
9110 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9111 (llast 0) rtn rtn1 level category i txt
9112 todo marker entry priority)
9113 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9114 (setq action (list 'lambda nil action)))
9115 (save-excursion
9116 (goto-char (point-min))
9117 (when (eq action 'sparse-tree)
9118 (org-overview)
9119 (org-remove-occur-highlights))
9120 (while (re-search-forward re nil t)
9121 (catch :skip
9122 (setq todo (if (match-end 1) (match-string 2))
9123 tags (if (match-end 4) (match-string 4)))
9124 (goto-char (setq lspos (1+ (match-beginning 0))))
9125 (setq level (org-reduced-level (funcall outline-level))
9126 category (org-get-category))
9127 (setq i llast llast level)
9128 ;; remove tag lists from same and sublevels
9129 (while (>= i level)
9130 (when (setq entry (assoc i tags-alist))
9131 (setq tags-alist (delete entry tags-alist)))
9132 (setq i (1- i)))
9133 ;; add the next tags
9134 (when tags
9135 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9136 tags-alist
9137 (cons (cons level tags) tags-alist)))
9138 ;; compile tags for current headline
9139 (setq tags-list
9140 (if org-use-tag-inheritance
9141 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9142 tags))
9143 (when org-use-tag-inheritance
9144 (setcdr (car tags-alist)
9145 (mapcar (lambda (x)
9146 (setq x (copy-sequence x))
9147 (org-add-prop-inherited x))
9148 (cdar tags-alist))))
9149 (when (and tags org-use-tag-inheritance
9150 (not (eq t org-use-tag-inheritance)))
9151 ;; selective inheritance, remove uninherited ones
9152 (setcdr (car tags-alist)
9153 (org-remove-uniherited-tags (cdar tags-alist))))
9154 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9155 (let ((case-fold-search t)) (eval matcher))
9157 (not (member org-archive-tag tags-list))
9158 ;; we have an archive tag, should we use this anyway?
9159 (or (not org-agenda-skip-archived-trees)
9160 (and (eq action 'agenda) org-agenda-archives-mode))))
9161 (unless (eq action 'sparse-tree) (org-agenda-skip))
9163 ;; select this headline
9165 (cond
9166 ((eq action 'sparse-tree)
9167 (and org-highlight-sparse-tree-matches
9168 (org-get-heading) (match-end 0)
9169 (org-highlight-new-match
9170 (match-beginning 0) (match-beginning 1)))
9171 (org-show-context 'tags-tree))
9172 ((eq action 'agenda)
9173 (setq txt (org-format-agenda-item
9175 (concat
9176 (if org-tags-match-list-sublevels
9177 (make-string (1- level) ?.) "")
9178 (org-get-heading))
9179 category tags-list)
9180 priority (org-get-priority txt))
9181 (goto-char lspos)
9182 (setq marker (org-agenda-new-marker))
9183 (org-add-props txt props
9184 'org-marker marker 'org-hd-marker marker 'org-category category
9185 'priority priority 'type "tagsmatch")
9186 (push txt rtn))
9187 ((functionp action)
9188 (save-excursion
9189 (setq rtn1 (funcall action))
9190 (push rtn1 rtn))
9191 (goto-char (point-at-eol)))
9192 (t (error "Invalid action")))
9194 ;; if we are to skip sublevels, jump to end of subtree
9195 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9196 (when (and (eq action 'sparse-tree)
9197 (not org-sparse-tree-open-archived-trees))
9198 (org-hide-archived-subtrees (point-min) (point-max)))
9199 (nreverse rtn)))
9201 (defun org-remove-uniherited-tags (tags)
9202 "Remove all tags that are not inherited from the list TAGS."
9203 (cond
9204 ((eq org-use-tag-inheritance t)
9205 (if org-tags-exclude-from-inheritance
9206 (org-delete-all org-tags-exclude-from-inheritance tags)
9207 tags))
9208 ((not org-use-tag-inheritance) nil)
9209 ((stringp org-use-tag-inheritance)
9210 (delq nil (mapcar
9211 (lambda (x)
9212 (if (and (string-match org-use-tag-inheritance x)
9213 (not (member x org-tags-exclude-from-inheritance)))
9214 x nil))
9215 tags)))
9216 ((listp org-use-tag-inheritance)
9217 (delq nil (mapcar
9218 (lambda (x)
9219 (if (member x org-use-tag-inheritance) x nil))
9220 tags)))))
9222 (defvar todo-only) ;; dynamically scoped
9224 (defun org-tags-sparse-tree (&optional todo-only match)
9225 "Create a sparse tree according to tags string MATCH.
9226 MATCH can contain positive and negative selection of tags, like
9227 \"+WORK+URGENT-WITHBOSS\".
9228 If optional argument TODO-ONLY is non-nil, only select lines that are
9229 also TODO lines."
9230 (interactive "P")
9231 (org-prepare-agenda-buffers (list (current-buffer)))
9232 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9234 (defvar org-cached-props nil)
9235 (defun org-cached-entry-get (pom property)
9236 (if (or (eq t org-use-property-inheritance)
9237 (and (stringp org-use-property-inheritance)
9238 (string-match org-use-property-inheritance property))
9239 (and (listp org-use-property-inheritance)
9240 (member property org-use-property-inheritance)))
9241 ;; Caching is not possible, check it directly
9242 (org-entry-get pom property 'inherit)
9243 ;; Get all properties, so that we can do complicated checks easily
9244 (cdr (assoc property (or org-cached-props
9245 (setq org-cached-props
9246 (org-entry-properties pom)))))))
9248 (defun org-global-tags-completion-table (&optional files)
9249 "Return the list of all tags in all agenda buffer/files."
9250 (save-excursion
9251 (org-uniquify
9252 (delq nil
9253 (apply 'append
9254 (mapcar
9255 (lambda (file)
9256 (set-buffer (find-file-noselect file))
9257 (append (org-get-buffer-tags)
9258 (mapcar (lambda (x) (if (stringp (car-safe x))
9259 (list (car-safe x)) nil))
9260 org-tag-alist)))
9261 (if (and files (car files))
9262 files
9263 (org-agenda-files))))))))
9265 (defun org-make-tags-matcher (match)
9266 "Create the TAGS//TODO matcher form for the selection string MATCH."
9267 ;; todo-only is scoped dynamically into this function, and the function
9268 ;; may change it it the matcher asksk for it.
9269 (unless match
9270 ;; Get a new match request, with completion
9271 (let ((org-last-tags-completion-table
9272 (org-global-tags-completion-table)))
9273 (setq match (org-ido-completing-read
9274 "Match: " 'org-tags-completion-function nil nil nil
9275 'org-tags-history))))
9277 ;; Parse the string and create a lisp form
9278 (let ((match0 match)
9279 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9280 minus tag mm
9281 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9282 orterms term orlist re-p str-p level-p level-op time-p
9283 prop-p pn pv po cat-p gv rest)
9284 (if (string-match "/+" match)
9285 ;; match contains also a todo-matching request
9286 (progn
9287 (setq tagsmatch (substring match 0 (match-beginning 0))
9288 todomatch (substring match (match-end 0)))
9289 (if (string-match "^!" todomatch)
9290 (setq todo-only t todomatch (substring todomatch 1)))
9291 (if (string-match "^\\s-*$" todomatch)
9292 (setq todomatch nil)))
9293 ;; only matching tags
9294 (setq tagsmatch match todomatch nil))
9296 ;; Make the tags matcher
9297 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9298 (setq tagsmatcher t)
9299 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9300 (while (setq term (pop orterms))
9301 (while (and (equal (substring term -1) "\\") orterms)
9302 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9303 (while (string-match re term)
9304 (setq rest (substring term (match-end 0))
9305 minus (and (match-end 1)
9306 (equal (match-string 1 term) "-"))
9307 tag (match-string 2 term)
9308 re-p (equal (string-to-char tag) ?{)
9309 level-p (match-end 4)
9310 prop-p (match-end 5)
9311 mm (cond
9312 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9313 (level-p
9314 (setq level-op (org-op-to-function (match-string 3 term)))
9315 `(,level-op level ,(string-to-number
9316 (match-string 4 term))))
9317 (prop-p
9318 (setq pn (match-string 5 term)
9319 po (match-string 6 term)
9320 pv (match-string 7 term)
9321 cat-p (equal pn "CATEGORY")
9322 re-p (equal (string-to-char pv) ?{)
9323 str-p (equal (string-to-char pv) ?\")
9324 time-p (save-match-data
9325 (string-match "^\"[[<].*[]>]\"$" pv))
9326 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9327 (if time-p (setq pv (org-matcher-time pv)))
9328 (setq po (org-op-to-function po (if time-p 'time str-p)))
9329 (cond
9330 ((equal pn "CATEGORY")
9331 (setq gv '(get-text-property (point) 'org-category)))
9332 ((equal pn "TODO")
9333 (setq gv 'todo))
9335 (setq gv `(org-cached-entry-get nil ,pn))))
9336 (if re-p
9337 (if (eq po 'org<>)
9338 `(not (string-match ,pv (or ,gv "")))
9339 `(string-match ,pv (or ,gv "")))
9340 (if str-p
9341 `(,po (or ,gv "") ,pv)
9342 `(,po (string-to-number (or ,gv ""))
9343 ,(string-to-number pv) ))))
9344 (t `(member ,(downcase tag) tags-list)))
9345 mm (if minus (list 'not mm) mm)
9346 term rest)
9347 (push mm tagsmatcher))
9348 (push (if (> (length tagsmatcher) 1)
9349 (cons 'and tagsmatcher)
9350 (car tagsmatcher))
9351 orlist)
9352 (setq tagsmatcher nil))
9353 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9354 (setq tagsmatcher
9355 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9356 ;; Make the todo matcher
9357 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9358 (setq todomatcher t)
9359 (setq orterms (org-split-string todomatch "|") orlist nil)
9360 (while (setq term (pop orterms))
9361 (while (string-match re term)
9362 (setq minus (and (match-end 1)
9363 (equal (match-string 1 term) "-"))
9364 kwd (match-string 2 term)
9365 re-p (equal (string-to-char kwd) ?{)
9366 term (substring term (match-end 0))
9367 mm (if re-p
9368 `(string-match ,(substring kwd 1 -1) todo)
9369 (list 'equal 'todo kwd))
9370 mm (if minus (list 'not mm) mm))
9371 (push mm todomatcher))
9372 (push (if (> (length todomatcher) 1)
9373 (cons 'and todomatcher)
9374 (car todomatcher))
9375 orlist)
9376 (setq todomatcher nil))
9377 (setq todomatcher (if (> (length orlist) 1)
9378 (cons 'or orlist) (car orlist))))
9380 ;; Return the string and lisp forms of the matcher
9381 (setq matcher (if todomatcher
9382 (list 'and tagsmatcher todomatcher)
9383 tagsmatcher))
9384 (cons match0 matcher)))
9386 (defun org-op-to-function (op &optional stringp)
9387 "Turn an operator into the appropriate function."
9388 (setq op
9389 (cond
9390 ((equal op "<" ) '(< string< org-time<))
9391 ((equal op ">" ) '(> org-string> org-time>))
9392 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9393 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9394 ((member op '("=" "==")) '(= string= org-time=))
9395 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9396 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9398 (defun org<> (a b) (not (= a b)))
9399 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9400 (defun org-string>= (a b) (not (string< a b)))
9401 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9402 (defun org-string<> (a b) (not (string= a b)))
9403 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9404 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9405 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9406 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9407 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9408 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9409 (defun org-2ft (s)
9410 "Convert S to a floating point time.
9411 If S is already a number, just return it. If it is a string, parse
9412 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9413 (cond
9414 ((numberp s) s)
9415 ((stringp s)
9416 (condition-case nil
9417 (float-time (apply 'encode-time (org-parse-time-string s)))
9418 (error 0.)))
9419 (t 0.)))
9421 (defun org-time-today ()
9422 "Time in seconds today at 0:00.
9423 Returns the float number of seconds since the beginning of the
9424 epoch to the beginning of today (00:00)."
9425 (float-time (apply 'encode-time
9426 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9428 (defun org-matcher-time (s)
9429 "Interprete a time comparison value."
9430 (save-match-data
9431 (cond
9432 ((string= s "<now>") (float-time))
9433 ((string= s "<today>") (org-time-today))
9434 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9435 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9436 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9437 (+ (org-time-today)
9438 (* (string-to-number (match-string 1 s))
9439 (cdr (assoc (match-string 2 s)
9440 '(("d" . 86400.0) ("w" . 604800.0)
9441 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9442 (t (org-2ft s)))))
9444 (defun org-match-any-p (re list)
9445 "Does re match any element of list?"
9446 (setq list (mapcar (lambda (x) (string-match re x)) list))
9447 (delq nil list))
9449 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9450 (defvar org-tags-overlay (org-make-overlay 1 1))
9451 (org-detach-overlay org-tags-overlay)
9453 (defun org-get-local-tags-at (&optional pos)
9454 "Get a list of tags defined in the current headline."
9455 (org-get-tags-at pos 'local))
9457 (defun org-get-local-tags ()
9458 "Get a list of tags defined in the current headline."
9459 (org-get-tags-at nil 'local))
9461 (defun org-get-tags-at (&optional pos local)
9462 "Get a list of all headline tags applicable at POS.
9463 POS defaults to point. If tags are inherited, the list contains
9464 the targets in the same sequence as the headlines appear, i.e.
9465 the tags of the current headline come last.
9466 When LOCAL is non-nil, only return tags from the current headline,
9467 ignore inherited ones."
9468 (interactive)
9469 (let (tags ltags lastpos parent)
9470 (save-excursion
9471 (save-restriction
9472 (widen)
9473 (goto-char (or pos (point)))
9474 (save-match-data
9475 (catch 'done
9476 (condition-case nil
9477 (progn
9478 (org-back-to-heading t)
9479 (while (not (equal lastpos (point)))
9480 (setq lastpos (point))
9481 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9482 (setq ltags (org-split-string
9483 (org-match-string-no-properties 1) ":"))
9484 (when parent
9485 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9486 (setq tags (append
9487 (if parent
9488 (org-remove-uniherited-tags ltags)
9489 ltags)
9490 tags)))
9491 (or org-use-tag-inheritance (throw 'done t))
9492 (if local (throw 'done t))
9493 (org-up-heading-all 1)
9494 (setq parent t)))
9495 (error nil)))))
9496 (append (org-remove-uniherited-tags org-file-tags) tags))))
9498 (defun org-add-prop-inherited (s)
9499 (add-text-properties 0 (length s) '(inherited t) s)
9502 (defun org-toggle-tag (tag &optional onoff)
9503 "Toggle the tag TAG for the current line.
9504 If ONOFF is `on' or `off', don't toggle but set to this state."
9505 (unless (org-on-heading-p t) (error "Not on headling"))
9506 (let (res current)
9507 (save-excursion
9508 (beginning-of-line)
9509 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9510 (point-at-eol) t)
9511 (progn
9512 (setq current (match-string 1))
9513 (replace-match ""))
9514 (setq current ""))
9515 (setq current (nreverse (org-split-string current ":")))
9516 (cond
9517 ((eq onoff 'on)
9518 (setq res t)
9519 (or (member tag current) (push tag current)))
9520 ((eq onoff 'off)
9521 (or (not (member tag current)) (setq current (delete tag current))))
9522 (t (if (member tag current)
9523 (setq current (delete tag current))
9524 (setq res t)
9525 (push tag current))))
9526 (end-of-line 1)
9527 (if current
9528 (progn
9529 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9530 (org-set-tags nil t))
9531 (delete-horizontal-space))
9532 (run-hooks 'org-after-tags-change-hook))
9533 res))
9535 (defun org-align-tags-here (to-col)
9536 ;; Assumes that this is a headline
9537 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9538 (beginning-of-line 1)
9539 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9540 (< pos (match-beginning 2)))
9541 (progn
9542 (setq tags-l (- (match-end 2) (match-beginning 2)))
9543 (goto-char (match-beginning 1))
9544 (insert " ")
9545 (delete-region (point) (1+ (match-beginning 2)))
9546 (setq ncol (max (1+ (current-column))
9547 (1+ col)
9548 (if (> to-col 0)
9549 to-col
9550 (- (abs to-col) tags-l))))
9551 (setq p (point))
9552 (insert (make-string (- ncol (current-column)) ?\ ))
9553 (setq ncol (current-column))
9554 (when indent-tabs-mode (tabify p (point-at-eol)))
9555 (org-move-to-column (min ncol col) t))
9556 (goto-char pos))))
9558 (defun org-set-tags-command (&optional arg just-align)
9559 "Call the set-tags command for the current entry."
9560 (interactive "P")
9561 (if (org-on-heading-p)
9562 (org-set-tags arg just-align)
9563 (save-excursion
9564 (org-back-to-heading t)
9565 (org-set-tags arg just-align))))
9567 (defun org-set-tags (&optional arg just-align)
9568 "Set the tags for the current headline.
9569 With prefix ARG, realign all tags in headings in the current buffer."
9570 (interactive "P")
9571 (let* ((re (concat "^" outline-regexp))
9572 (current (org-get-tags-string))
9573 (col (current-column))
9574 (org-setting-tags t)
9575 table current-tags inherited-tags ; computed below when needed
9576 tags p0 c0 c1 rpl)
9577 (if arg
9578 (save-excursion
9579 (goto-char (point-min))
9580 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9581 (while (re-search-forward re nil t)
9582 (org-set-tags nil t)
9583 (end-of-line 1)))
9584 (message "All tags realigned to column %d" org-tags-column))
9585 (if just-align
9586 (setq tags current)
9587 ;; Get a new set of tags from the user
9588 (save-excursion
9589 (setq table (or org-tag-alist (org-get-buffer-tags))
9590 org-last-tags-completion-table table
9591 current-tags (org-split-string current ":")
9592 inherited-tags (nreverse
9593 (nthcdr (length current-tags)
9594 (nreverse (org-get-tags-at))))
9595 tags
9596 (if (or (eq t org-use-fast-tag-selection)
9597 (and org-use-fast-tag-selection
9598 (delq nil (mapcar 'cdr table))))
9599 (org-fast-tag-selection
9600 current-tags inherited-tags table
9601 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9602 (let ((org-add-colon-after-tag-completion t))
9603 (org-trim
9604 (org-without-partial-completion
9605 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9606 nil nil current 'org-tags-history)))))))
9607 (while (string-match "[-+&]+" tags)
9608 ;; No boolean logic, just a list
9609 (setq tags (replace-match ":" t t tags))))
9611 (if (string-match "\\`[\t ]*\\'" tags)
9612 (setq tags "")
9613 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9614 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9616 ;; Insert new tags at the correct column
9617 (beginning-of-line 1)
9618 (cond
9619 ((and (equal current "") (equal tags "")))
9620 ((re-search-forward
9621 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9622 (point-at-eol) t)
9623 (if (equal tags "")
9624 (setq rpl "")
9625 (goto-char (match-beginning 0))
9626 (setq c0 (current-column) p0 (point)
9627 c1 (max (1+ c0) (if (> org-tags-column 0)
9628 org-tags-column
9629 (- (- org-tags-column) (length tags))))
9630 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9631 (replace-match rpl t t)
9632 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9633 tags)
9634 (t (error "Tags alignment failed")))
9635 (org-move-to-column col)
9636 (unless just-align
9637 (run-hooks 'org-after-tags-change-hook)))))
9639 (defun org-change-tag-in-region (beg end tag off)
9640 "Add or remove TAG for each entry in the region.
9641 This works in the agenda, and also in an org-mode buffer."
9642 (interactive
9643 (list (region-beginning) (region-end)
9644 (let ((org-last-tags-completion-table
9645 (if (org-mode-p)
9646 (org-get-buffer-tags)
9647 (org-global-tags-completion-table))))
9648 (org-ido-completing-read
9649 "Tag: " 'org-tags-completion-function nil nil nil
9650 'org-tags-history))
9651 (progn
9652 (message "[s]et or [r]emove? ")
9653 (equal (read-char-exclusive) ?r))))
9654 (if (fboundp 'deactivate-mark) (deactivate-mark))
9655 (let ((agendap (equal major-mode 'org-agenda-mode))
9656 l1 l2 m buf pos newhead (cnt 0))
9657 (goto-char end)
9658 (setq l2 (1- (org-current-line)))
9659 (goto-char beg)
9660 (setq l1 (org-current-line))
9661 (loop for l from l1 to l2 do
9662 (goto-line l)
9663 (setq m (get-text-property (point) 'org-hd-marker))
9664 (when (or (and (org-mode-p) (org-on-heading-p))
9665 (and agendap m))
9666 (setq buf (if agendap (marker-buffer m) (current-buffer))
9667 pos (if agendap m (point)))
9668 (with-current-buffer buf
9669 (save-excursion
9670 (save-restriction
9671 (goto-char pos)
9672 (setq cnt (1+ cnt))
9673 (org-toggle-tag tag (if off 'off 'on))
9674 (setq newhead (org-get-heading)))))
9675 (and agendap (org-agenda-change-all-lines newhead m))))
9676 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9678 (defun org-tags-completion-function (string predicate &optional flag)
9679 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9680 (confirm (lambda (x) (stringp (car x)))))
9681 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9682 (setq s1 (match-string 1 string)
9683 s2 (match-string 2 string))
9684 (setq s1 "" s2 string))
9685 (cond
9686 ((eq flag nil)
9687 ;; try completion
9688 (setq rtn (try-completion s2 ctable confirm))
9689 (if (stringp rtn)
9690 (setq rtn
9691 (concat s1 s2 (substring rtn (length s2))
9692 (if (and org-add-colon-after-tag-completion
9693 (assoc rtn ctable))
9694 ":" ""))))
9695 rtn)
9696 ((eq flag t)
9697 ;; all-completions
9698 (all-completions s2 ctable confirm)
9700 ((eq flag 'lambda)
9701 ;; exact match?
9702 (assoc s2 ctable)))
9705 (defun org-fast-tag-insert (kwd tags face &optional end)
9706 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9707 (insert (format "%-12s" (concat kwd ":"))
9708 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9709 (or end "")))
9711 (defun org-fast-tag-show-exit (flag)
9712 (save-excursion
9713 (goto-line 3)
9714 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9715 (replace-match ""))
9716 (when flag
9717 (end-of-line 1)
9718 (org-move-to-column (- (window-width) 19) t)
9719 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9721 (defun org-set-current-tags-overlay (current prefix)
9722 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9723 (if (featurep 'xemacs)
9724 (org-overlay-display org-tags-overlay (concat prefix s)
9725 'secondary-selection)
9726 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9727 (org-overlay-display org-tags-overlay (concat prefix s)))))
9729 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9730 "Fast tag selection with single keys.
9731 CURRENT is the current list of tags in the headline, INHERITED is the
9732 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9733 possibly with grouping information. TODO-TABLE is a similar table with
9734 TODO keywords, should these have keys assigned to them.
9735 If the keys are nil, a-z are automatically assigned.
9736 Returns the new tags string, or nil to not change the current settings."
9737 (let* ((fulltable (append table todo-table))
9738 (maxlen (apply 'max (mapcar
9739 (lambda (x)
9740 (if (stringp (car x)) (string-width (car x)) 0))
9741 fulltable)))
9742 (buf (current-buffer))
9743 (expert (eq org-fast-tag-selection-single-key 'expert))
9744 (buffer-tags nil)
9745 (fwidth (+ maxlen 3 1 3))
9746 (ncol (/ (- (window-width) 4) fwidth))
9747 (i-face 'org-done)
9748 (c-face 'org-todo)
9749 tg cnt e c char c1 c2 ntable tbl rtn
9750 ov-start ov-end ov-prefix
9751 (exit-after-next org-fast-tag-selection-single-key)
9752 (done-keywords org-done-keywords)
9753 groups ingroup)
9754 (save-excursion
9755 (beginning-of-line 1)
9756 (if (looking-at
9757 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9758 (setq ov-start (match-beginning 1)
9759 ov-end (match-end 1)
9760 ov-prefix "")
9761 (setq ov-start (1- (point-at-eol))
9762 ov-end (1+ ov-start))
9763 (skip-chars-forward "^\n\r")
9764 (setq ov-prefix
9765 (concat
9766 (buffer-substring (1- (point)) (point))
9767 (if (> (current-column) org-tags-column)
9769 (make-string (- org-tags-column (current-column)) ?\ ))))))
9770 (org-move-overlay org-tags-overlay ov-start ov-end)
9771 (save-window-excursion
9772 (if expert
9773 (set-buffer (get-buffer-create " *Org tags*"))
9774 (delete-other-windows)
9775 (split-window-vertically)
9776 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9777 (erase-buffer)
9778 (org-set-local 'org-done-keywords done-keywords)
9779 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9780 (org-fast-tag-insert "Current" current c-face "\n\n")
9781 (org-fast-tag-show-exit exit-after-next)
9782 (org-set-current-tags-overlay current ov-prefix)
9783 (setq tbl fulltable char ?a cnt 0)
9784 (while (setq e (pop tbl))
9785 (cond
9786 ((equal e '(:startgroup))
9787 (push '() groups) (setq ingroup t)
9788 (when (not (= cnt 0))
9789 (setq cnt 0)
9790 (insert "\n"))
9791 (insert "{ "))
9792 ((equal e '(:endgroup))
9793 (setq ingroup nil cnt 0)
9794 (insert "}\n"))
9796 (setq tg (car e) c2 nil)
9797 (if (cdr e)
9798 (setq c (cdr e))
9799 ;; automatically assign a character.
9800 (setq c1 (string-to-char
9801 (downcase (substring
9802 tg (if (= (string-to-char tg) ?@) 1 0)))))
9803 (if (or (rassoc c1 ntable) (rassoc c1 table))
9804 (while (or (rassoc char ntable) (rassoc char table))
9805 (setq char (1+ char)))
9806 (setq c2 c1))
9807 (setq c (or c2 char)))
9808 (if ingroup (push tg (car groups)))
9809 (setq tg (org-add-props tg nil 'face
9810 (cond
9811 ((not (assoc tg table))
9812 (org-get-todo-face tg))
9813 ((member tg current) c-face)
9814 ((member tg inherited) i-face)
9815 (t nil))))
9816 (if (and (= cnt 0) (not ingroup)) (insert " "))
9817 (insert "[" c "] " tg (make-string
9818 (- fwidth 4 (length tg)) ?\ ))
9819 (push (cons tg c) ntable)
9820 (when (= (setq cnt (1+ cnt)) ncol)
9821 (insert "\n")
9822 (if ingroup (insert " "))
9823 (setq cnt 0)))))
9824 (setq ntable (nreverse ntable))
9825 (insert "\n")
9826 (goto-char (point-min))
9827 (if (not expert) (org-fit-window-to-buffer))
9828 (setq rtn
9829 (catch 'exit
9830 (while t
9831 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9832 (if groups " [!] no groups" " [!]groups")
9833 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9834 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9835 (cond
9836 ((= c ?\r) (throw 'exit t))
9837 ((= c ?!)
9838 (setq groups (not groups))
9839 (goto-char (point-min))
9840 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9841 ((= c ?\C-c)
9842 (if (not expert)
9843 (org-fast-tag-show-exit
9844 (setq exit-after-next (not exit-after-next)))
9845 (setq expert nil)
9846 (delete-other-windows)
9847 (split-window-vertically)
9848 (org-switch-to-buffer-other-window " *Org tags*")
9849 (org-fit-window-to-buffer)))
9850 ((or (= c ?\C-g)
9851 (and (= c ?q) (not (rassoc c ntable))))
9852 (org-detach-overlay org-tags-overlay)
9853 (setq quit-flag t))
9854 ((= c ?\ )
9855 (setq current nil)
9856 (if exit-after-next (setq exit-after-next 'now)))
9857 ((= c ?\t)
9858 (condition-case nil
9859 (setq tg (org-ido-completing-read
9860 "Tag: "
9861 (or buffer-tags
9862 (with-current-buffer buf
9863 (org-get-buffer-tags)))))
9864 (quit (setq tg "")))
9865 (when (string-match "\\S-" tg)
9866 (add-to-list 'buffer-tags (list tg))
9867 (if (member tg current)
9868 (setq current (delete tg current))
9869 (push tg current)))
9870 (if exit-after-next (setq exit-after-next 'now)))
9871 ((setq e (rassoc c todo-table) tg (car e))
9872 (with-current-buffer buf
9873 (save-excursion (org-todo tg)))
9874 (if exit-after-next (setq exit-after-next 'now)))
9875 ((setq e (rassoc c ntable) tg (car e))
9876 (if (member tg current)
9877 (setq current (delete tg current))
9878 (loop for g in groups do
9879 (if (member tg g)
9880 (mapc (lambda (x)
9881 (setq current (delete x current)))
9882 g)))
9883 (push tg current))
9884 (if exit-after-next (setq exit-after-next 'now))))
9886 ;; Create a sorted list
9887 (setq current
9888 (sort current
9889 (lambda (a b)
9890 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9891 (if (eq exit-after-next 'now) (throw 'exit t))
9892 (goto-char (point-min))
9893 (beginning-of-line 2)
9894 (delete-region (point) (point-at-eol))
9895 (org-fast-tag-insert "Current" current c-face)
9896 (org-set-current-tags-overlay current ov-prefix)
9897 (while (re-search-forward
9898 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9899 (setq tg (match-string 1))
9900 (add-text-properties
9901 (match-beginning 1) (match-end 1)
9902 (list 'face
9903 (cond
9904 ((member tg current) c-face)
9905 ((member tg inherited) i-face)
9906 (t (get-text-property (match-beginning 1) 'face))))))
9907 (goto-char (point-min)))))
9908 (org-detach-overlay org-tags-overlay)
9909 (if rtn
9910 (mapconcat 'identity current ":")
9911 nil))))
9913 (defun org-get-tags-string ()
9914 "Get the TAGS string in the current headline."
9915 (unless (org-on-heading-p t)
9916 (error "Not on a heading"))
9917 (save-excursion
9918 (beginning-of-line 1)
9919 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9920 (org-match-string-no-properties 1)
9921 "")))
9923 (defun org-get-tags ()
9924 "Get the list of tags specified in the current headline."
9925 (org-split-string (org-get-tags-string) ":"))
9927 (defun org-get-buffer-tags ()
9928 "Get a table of all tags used in the buffer, for completion."
9929 (let (tags)
9930 (save-excursion
9931 (goto-char (point-min))
9932 (while (re-search-forward
9933 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9934 (when (equal (char-after (point-at-bol 0)) ?*)
9935 (mapc (lambda (x) (add-to-list 'tags x))
9936 (org-split-string (org-match-string-no-properties 1) ":")))))
9937 (mapcar 'list tags)))
9939 ;;;; The mapping API
9941 ;;;###autoload
9942 (defun org-map-entries (func &optional match scope &rest skip)
9943 "Call FUNC at each headline selected by MATCH in SCOPE.
9945 FUNC is a function or a lisp form. The function will be called without
9946 arguments, with the cursor positioned at the beginning of the headline.
9947 The return values of all calls to the function will be collected and
9948 returned as a list.
9950 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9951 Only headlines that are matched by this query will be considered during
9952 the iteration. When MATCH is nil or t, all headlines will be
9953 visited by the iteration.
9955 SCOPE determines the scope of this command. It can be any of:
9957 nil The current buffer, respecting the restriction if any
9958 tree The subtree started with the entry at point
9959 file The current buffer, without restriction
9960 file-with-archives
9961 The current buffer, and any archives associated with it
9962 agenda All agenda files
9963 agenda-with-archives
9964 All agenda files with any archive files associated with them
9965 \(file1 file2 ...)
9966 If this is a list, all files in the list will be scanned
9968 The remaining args are treated as settings for the skipping facilities of
9969 the scanner. The following items can be given here:
9971 archive skip trees with the archive tag.
9972 comment skip trees with the COMMENT keyword
9973 function or Emacs Lisp form:
9974 will be used as value for `org-agenda-skip-function', so whenever
9975 the the function returns t, FUNC will not be called for that
9976 entry and search will continue from the point where the
9977 function leaves it."
9978 (let* ((org-agenda-archives-mode nil) ; just to make sure
9979 (org-agenda-skip-archived-trees (memq 'archive skip))
9980 (org-agenda-skip-comment-trees (memq 'comment skip))
9981 (org-agenda-skip-function
9982 (car (org-delete-all '(comment archive) skip)))
9983 (org-tags-match-list-sublevels t)
9984 matcher pos file res
9985 org-todo-keywords-for-agenda
9986 org-done-keywords-for-agenda
9987 org-todo-keyword-alist-for-agenda
9988 org-tag-alist-for-agenda)
9990 (cond
9991 ((eq match t) (setq matcher t))
9992 ((eq match nil) (setq matcher t))
9993 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
9995 (when (eq scope 'tree)
9996 (org-back-to-heading t)
9997 (org-narrow-to-subtree)
9998 (setq scope nil))
10000 (if (not scope)
10001 (progn
10002 (org-prepare-agenda-buffers
10003 (list (buffer-file-name (current-buffer))))
10004 (org-scan-tags func matcher))
10005 ;; Get the right scope
10006 (setq pos (point))
10007 (cond
10008 ((and scope (listp scope) (symbolp (car scope)))
10009 (setq scope (eval scope)))
10010 ((eq scope 'agenda)
10011 (setq scope (org-agenda-files t)))
10012 ((eq scope 'agenda-with-archives)
10013 (setq scope (org-agenda-files t))
10014 (setq scope (org-add-archive-files scope)))
10015 ((eq scope 'file)
10016 (setq scope (list (buffer-file-name))))
10017 ((eq scope 'file-with-archives)
10018 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10019 (org-prepare-agenda-buffers scope)
10020 (while (setq file (pop scope))
10021 (with-current-buffer (org-find-base-buffer-visiting file)
10022 (save-excursion
10023 (save-restriction
10024 (widen)
10025 (goto-char (point-min))
10026 (setq res (append res (org-scan-tags func matcher)))))))
10027 res)))
10029 ;;;; Properties
10031 ;;; Setting and retrieving properties
10033 (defconst org-special-properties
10034 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10035 "TIMESTAMP" "TIMESTAMP_IA")
10036 "The special properties valid in Org-mode.
10038 These are properties that are not defined in the property drawer,
10039 but in some other way.")
10041 (defconst org-default-properties
10042 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10043 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10044 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10045 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10046 "Some properties that are used by Org-mode for various purposes.
10047 Being in this list makes sure that they are offered for completion.")
10049 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10050 "Regular expression matching the first line of a property drawer.")
10052 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10053 "Regular expression matching the first line of a property drawer.")
10055 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10056 "Regular expression matching the first line of a property drawer.")
10058 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10059 "Regular expression matching the first line of a property drawer.")
10061 (defconst org-property-drawer-re
10062 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10063 org-property-end-re "\\)\n?")
10064 "Matches an entire property drawer.")
10066 (defconst org-clock-drawer-re
10067 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10068 org-property-end-re "\\)\n?")
10069 "Matches an entire clock drawer.")
10071 (defun org-property-action ()
10072 "Do an action on properties."
10073 (interactive)
10074 (let (c)
10075 (org-at-property-p)
10076 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10077 (setq c (read-char-exclusive))
10078 (cond
10079 ((equal c ?s)
10080 (call-interactively 'org-set-property))
10081 ((equal c ?d)
10082 (call-interactively 'org-delete-property))
10083 ((equal c ?D)
10084 (call-interactively 'org-delete-property-globally))
10085 ((equal c ?c)
10086 (call-interactively 'org-compute-property-at-point))
10087 (t (error "No such property action %c" c)))))
10089 (defun org-at-property-p ()
10090 "Is the cursor in a property line?"
10091 ;; FIXME: Does not check if we are actually in the drawer.
10092 ;; FIXME: also returns true on any drawers.....
10093 ;; This is used by C-c C-c for property action.
10094 (save-excursion
10095 (beginning-of-line 1)
10096 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10098 (defun org-get-property-block (&optional beg end force)
10099 "Return the (beg . end) range of the body of the property drawer.
10100 BEG and END can be beginning and end of subtree, if not given
10101 they will be found.
10102 If the drawer does not exist and FORCE is non-nil, create the drawer."
10103 (catch 'exit
10104 (save-excursion
10105 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10106 (end (or end (progn (outline-next-heading) (point)))))
10107 (goto-char beg)
10108 (if (re-search-forward org-property-start-re end t)
10109 (setq beg (1+ (match-end 0)))
10110 (if force
10111 (save-excursion
10112 (org-insert-property-drawer)
10113 (setq end (progn (outline-next-heading) (point))))
10114 (throw 'exit nil))
10115 (goto-char beg)
10116 (if (re-search-forward org-property-start-re end t)
10117 (setq beg (1+ (match-end 0)))))
10118 (if (re-search-forward org-property-end-re end t)
10119 (setq end (match-beginning 0))
10120 (or force (throw 'exit nil))
10121 (goto-char beg)
10122 (setq end beg)
10123 (org-indent-line-function)
10124 (insert ":END:\n"))
10125 (cons beg end)))))
10127 (defun org-entry-properties (&optional pom which)
10128 "Get all properties of the entry at point-or-marker POM.
10129 This includes the TODO keyword, the tags, time strings for deadline,
10130 scheduled, and clocking, and any additional properties defined in the
10131 entry. The return value is an alist, keys may occur multiple times
10132 if the property key was used several times.
10133 POM may also be nil, in which case the current entry is used.
10134 If WHICH is nil or `all', get all properties. If WHICH is
10135 `special' or `standard', only get that subclass."
10136 (setq which (or which 'all))
10137 (org-with-point-at pom
10138 (let ((clockstr (substring org-clock-string 0 -1))
10139 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10140 beg end range props sum-props key value string clocksum)
10141 (save-excursion
10142 (when (condition-case nil (org-back-to-heading t) (error nil))
10143 (setq beg (point))
10144 (setq sum-props (get-text-property (point) 'org-summaries))
10145 (setq clocksum (get-text-property (point) :org-clock-minutes))
10146 (outline-next-heading)
10147 (setq end (point))
10148 (when (memq which '(all special))
10149 ;; Get the special properties, like TODO and tags
10150 (goto-char beg)
10151 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10152 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10153 (when (looking-at org-priority-regexp)
10154 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10155 (when (and (setq value (org-get-tags-string))
10156 (string-match "\\S-" value))
10157 (push (cons "TAGS" value) props))
10158 (when (setq value (org-get-tags-at))
10159 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10160 props))
10161 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10162 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10163 string (if (equal key clockstr)
10164 (org-no-properties
10165 (org-trim
10166 (buffer-substring
10167 (match-beginning 3) (goto-char (point-at-eol)))))
10168 (substring (org-match-string-no-properties 3) 1 -1)))
10169 (unless key
10170 (if (= (char-after (match-beginning 3)) ?\[)
10171 (setq key "TIMESTAMP_IA")
10172 (setq key "TIMESTAMP")))
10173 (when (or (equal key clockstr) (not (assoc key props)))
10174 (push (cons key string) props)))
10178 (when (memq which '(all standard))
10179 ;; Get the standard properties, like :PORP: ...
10180 (setq range (org-get-property-block beg end))
10181 (when range
10182 (goto-char (car range))
10183 (while (re-search-forward
10184 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10185 (cdr range) t)
10186 (setq key (org-match-string-no-properties 1)
10187 value (org-trim (or (org-match-string-no-properties 2) "")))
10188 (unless (member key excluded)
10189 (push (cons key (or value "")) props)))))
10190 (if clocksum
10191 (push (cons "CLOCKSUM"
10192 (org-columns-number-to-string (/ (float clocksum) 60.)
10193 'add_times))
10194 props))
10195 (unless (assoc "CATEGORY" props)
10196 (setq value (or (org-get-category)
10197 (progn (org-refresh-category-properties)
10198 (org-get-category))))
10199 (push (cons "CATEGORY" value) props))
10200 (append sum-props (nreverse props)))))))
10202 (defun org-entry-get (pom property &optional inherit)
10203 "Get value of PROPERTY for entry at point-or-marker POM.
10204 If INHERIT is non-nil and the entry does not have the property,
10205 then also check higher levels of the hierarchy.
10206 If INHERIT is the symbol `selective', use inheritance only if the setting
10207 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10208 If the property is present but empty, the return value is the empty string.
10209 If the property is not present at all, nil is returned."
10210 (org-with-point-at pom
10211 (if (and inherit (if (eq inherit 'selective)
10212 (org-property-inherit-p property)
10214 (org-entry-get-with-inheritance property)
10215 (if (member property org-special-properties)
10216 ;; We need a special property. Use brute force, get all properties.
10217 (cdr (assoc property (org-entry-properties nil 'special)))
10218 (let ((range (org-get-property-block)))
10219 (if (and range
10220 (goto-char (car range))
10221 (re-search-forward
10222 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10223 (cdr range) t))
10224 ;; Found the property, return it.
10225 (if (match-end 1)
10226 (org-match-string-no-properties 1)
10227 "")))))))
10229 (defun org-property-or-variable-value (var &optional inherit)
10230 "Check if there is a property fixing the value of VAR.
10231 If yes, return this value. If not, return the current value of the variable."
10232 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10233 (if (and prop (stringp prop) (string-match "\\S-" prop))
10234 (read prop)
10235 (symbol-value var))))
10237 (defun org-entry-delete (pom property)
10238 "Delete the property PROPERTY from entry at point-or-marker POM."
10239 (org-with-point-at pom
10240 (if (member property org-special-properties)
10241 nil ; cannot delete these properties.
10242 (let ((range (org-get-property-block)))
10243 (if (and range
10244 (goto-char (car range))
10245 (re-search-forward
10246 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10247 (cdr range) t))
10248 (progn
10249 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10251 nil)))))
10253 ;; Multi-values properties are properties that contain multiple values
10254 ;; These values are assumed to be single words, separated by whitespace.
10255 (defun org-entry-add-to-multivalued-property (pom property value)
10256 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10257 (let* ((old (org-entry-get pom property))
10258 (values (and old (org-split-string old "[ \t]"))))
10259 (setq value (org-entry-protect-space value))
10260 (unless (member value values)
10261 (setq values (cons value values))
10262 (org-entry-put pom property
10263 (mapconcat 'identity values " ")))))
10265 (defun org-entry-remove-from-multivalued-property (pom property value)
10266 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10267 (let* ((old (org-entry-get pom property))
10268 (values (and old (org-split-string old "[ \t]"))))
10269 (setq value (org-entry-protect-space value))
10270 (when (member value values)
10271 (setq values (delete value values))
10272 (org-entry-put pom property
10273 (mapconcat 'identity values " ")))))
10275 (defun org-entry-member-in-multivalued-property (pom property value)
10276 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10277 (let* ((old (org-entry-get pom property))
10278 (values (and old (org-split-string old "[ \t]"))))
10279 (setq value (org-entry-protect-space value))
10280 (member value values)))
10282 (defun org-entry-get-multivalued-property (pom property)
10283 "Return a list of values in a multivalued property."
10284 (let* ((value (org-entry-get pom property))
10285 (values (and value (org-split-string value "[ \t]"))))
10286 (mapcar 'org-entry-restore-space values)))
10288 (defun org-entry-put-multivalued-property (pom property &rest values)
10289 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10290 VALUES should be a list of strings. Spaces will be protected."
10291 (org-entry-put pom property
10292 (mapconcat 'org-entry-protect-space values " "))
10293 (let* ((value (org-entry-get pom property))
10294 (values (and value (org-split-string value "[ \t]"))))
10295 (mapcar 'org-entry-restore-space values)))
10297 (defun org-entry-protect-space (s)
10298 "Protect spaces and newline in string S."
10299 (while (string-match " " s)
10300 (setq s (replace-match "%20" t t s)))
10301 (while (string-match "\n" s)
10302 (setq s (replace-match "%0A" t t s)))
10305 (defun org-entry-restore-space (s)
10306 "Restore spaces and newline in string S."
10307 (while (string-match "%20" s)
10308 (setq s (replace-match " " t t s)))
10309 (while (string-match "%0A" s)
10310 (setq s (replace-match "\n" t t s)))
10313 (defvar org-entry-property-inherited-from (make-marker)
10314 "Marker pointing to the entry from where a proerty was inherited.
10315 Each call to `org-entry-get-with-inheritance' will set this marker to the
10316 location of the entry where the inheriance search matched. If there was
10317 no match, the marker will point nowhere.
10318 Note that also `org-entry-get' calls this function, if the INHERIT flag
10319 is set.")
10321 (defun org-entry-get-with-inheritance (property)
10322 "Get entry property, and search higher levels if not present."
10323 (move-marker org-entry-property-inherited-from nil)
10324 (let (tmp)
10325 (save-excursion
10326 (save-restriction
10327 (widen)
10328 (catch 'ex
10329 (while t
10330 (when (setq tmp (org-entry-get nil property))
10331 (org-back-to-heading t)
10332 (move-marker org-entry-property-inherited-from (point))
10333 (throw 'ex tmp))
10334 (or (org-up-heading-safe) (throw 'ex nil)))))
10335 (or tmp
10336 (cdr (assoc property org-file-properties))
10337 (cdr (assoc property org-global-properties))
10338 (cdr (assoc property org-global-properties-fixed))))))
10340 (defun org-entry-put (pom property value)
10341 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10342 (org-with-point-at pom
10343 (org-back-to-heading t)
10344 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10345 range)
10346 (cond
10347 ((equal property "TODO")
10348 (when (and (stringp value) (string-match "\\S-" value)
10349 (not (member value org-todo-keywords-1)))
10350 (error "\"%s\" is not a valid TODO state" value))
10351 (if (or (not value)
10352 (not (string-match "\\S-" value)))
10353 (setq value 'none))
10354 (org-todo value)
10355 (org-set-tags nil 'align))
10356 ((equal property "PRIORITY")
10357 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10358 (string-to-char value) ?\ ))
10359 (org-set-tags nil 'align))
10360 ((equal property "SCHEDULED")
10361 (if (re-search-forward org-scheduled-time-regexp end t)
10362 (cond
10363 ((eq value 'earlier) (org-timestamp-change -1 'day))
10364 ((eq value 'later) (org-timestamp-change 1 'day))
10365 (t (call-interactively 'org-schedule)))
10366 (call-interactively 'org-schedule)))
10367 ((equal property "DEADLINE")
10368 (if (re-search-forward org-deadline-time-regexp end t)
10369 (cond
10370 ((eq value 'earlier) (org-timestamp-change -1 'day))
10371 ((eq value 'later) (org-timestamp-change 1 'day))
10372 (t (call-interactively 'org-deadline)))
10373 (call-interactively 'org-deadline)))
10374 ((member property org-special-properties)
10375 (error "The %s property can not yet be set with `org-entry-put'"
10376 property))
10377 (t ; a non-special property
10378 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10379 (setq range (org-get-property-block beg end 'force))
10380 (goto-char (car range))
10381 (if (re-search-forward
10382 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10383 (progn
10384 (delete-region (match-beginning 1) (match-end 1))
10385 (goto-char (match-beginning 1)))
10386 (goto-char (cdr range))
10387 (insert "\n")
10388 (backward-char 1)
10389 (org-indent-line-function)
10390 (insert ":" property ":"))
10391 (and value (insert " " value))
10392 (org-indent-line-function)))))))
10394 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10395 "Get all property keys in the current buffer.
10396 With INCLUDE-SPECIALS, also list the special properties that relect things
10397 like tags and TODO state.
10398 With INCLUDE-DEFAULTS, also include properties that has special meaning
10399 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10400 With INCLUDE-COLUMNS, also include property names given in COLUMN
10401 formats in the current buffer."
10402 (let (rtn range cfmt cols s p)
10403 (save-excursion
10404 (save-restriction
10405 (widen)
10406 (goto-char (point-min))
10407 (while (re-search-forward org-property-start-re nil t)
10408 (setq range (org-get-property-block))
10409 (goto-char (car range))
10410 (while (re-search-forward
10411 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10412 (cdr range) t)
10413 (add-to-list 'rtn (org-match-string-no-properties 1)))
10414 (outline-next-heading))))
10416 (when include-specials
10417 (setq rtn (append org-special-properties rtn)))
10419 (when include-defaults
10420 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10422 (when include-columns
10423 (save-excursion
10424 (save-restriction
10425 (widen)
10426 (goto-char (point-min))
10427 (while (re-search-forward
10428 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10429 nil t)
10430 (setq cfmt (match-string 2) s 0)
10431 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10432 cfmt s)
10433 (setq s (match-end 0)
10434 p (match-string 1 cfmt))
10435 (unless (or (equal p "ITEM")
10436 (member p org-special-properties))
10437 (add-to-list 'rtn (match-string 1 cfmt))))))))
10439 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10441 (defun org-property-values (key)
10442 "Return a list of all values of property KEY."
10443 (save-excursion
10444 (save-restriction
10445 (widen)
10446 (goto-char (point-min))
10447 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10448 values)
10449 (while (re-search-forward re nil t)
10450 (add-to-list 'values (org-trim (match-string 1))))
10451 (delete "" values)))))
10453 (defun org-insert-property-drawer ()
10454 "Insert a property drawer into the current entry."
10455 (interactive)
10456 (org-back-to-heading t)
10457 (looking-at outline-regexp)
10458 (let ((indent (- (match-end 0)(match-beginning 0)))
10459 (beg (point))
10460 (re (concat "^[ \t]*" org-keyword-time-regexp))
10461 end hiddenp)
10462 (outline-next-heading)
10463 (setq end (point))
10464 (goto-char beg)
10465 (while (re-search-forward re end t))
10466 (setq hiddenp (org-invisible-p))
10467 (end-of-line 1)
10468 (and (equal (char-after) ?\n) (forward-char 1))
10469 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10470 (beginning-of-line 2))
10471 (org-skip-over-state-notes)
10472 (skip-chars-backward " \t\n\r")
10473 (if (eq (char-before) ?*) (forward-char 1))
10474 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10475 (beginning-of-line 0)
10476 (org-indent-to-column indent)
10477 (beginning-of-line 2)
10478 (org-indent-to-column indent)
10479 (beginning-of-line 0)
10480 (if hiddenp
10481 (save-excursion
10482 (org-back-to-heading t)
10483 (hide-entry))
10484 (org-flag-drawer t))))
10486 (defun org-set-property (property value)
10487 "In the current entry, set PROPERTY to VALUE.
10488 When called interactively, this will prompt for a property name, offering
10489 completion on existing and default properties. And then it will prompt
10490 for a value, offering competion either on allowed values (via an inherited
10491 xxx_ALL property) or on existing values in other instances of this property
10492 in the current file."
10493 (interactive
10494 (let* ((completion-ignore-case t)
10495 (keys (org-buffer-property-keys nil t t))
10496 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10497 (prop (if (member prop0 keys)
10498 prop0
10499 (or (cdr (assoc (downcase prop0)
10500 (mapcar (lambda (x) (cons (downcase x) x))
10501 keys)))
10502 prop0)))
10503 (cur (org-entry-get nil prop))
10504 (allowed (org-property-get-allowed-values nil prop 'table))
10505 (existing (mapcar 'list (org-property-values prop)))
10506 (val (if allowed
10507 (org-completing-read "Value: " allowed nil 'req-match)
10508 (org-completing-read
10509 (concat "Value" (if (and cur (string-match "\\S-" cur))
10510 (concat "[" cur "]") "")
10511 ": ")
10512 existing nil nil "" nil cur))))
10513 (list prop (if (equal val "") cur val))))
10514 (unless (equal (org-entry-get nil property) value)
10515 (org-entry-put nil property value)))
10517 (defun org-delete-property (property)
10518 "In the current entry, delete PROPERTY."
10519 (interactive
10520 (let* ((completion-ignore-case t)
10521 (prop (org-ido-completing-read
10522 "Property: " (org-entry-properties nil 'standard))))
10523 (list prop)))
10524 (message "Property %s %s" property
10525 (if (org-entry-delete nil property)
10526 "deleted"
10527 "was not present in the entry")))
10529 (defun org-delete-property-globally (property)
10530 "Remove PROPERTY globally, from all entries."
10531 (interactive
10532 (let* ((completion-ignore-case t)
10533 (prop (org-ido-completing-read
10534 "Globally remove property: "
10535 (mapcar 'list (org-buffer-property-keys)))))
10536 (list prop)))
10537 (save-excursion
10538 (save-restriction
10539 (widen)
10540 (goto-char (point-min))
10541 (let ((cnt 0))
10542 (while (re-search-forward
10543 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10544 nil t)
10545 (setq cnt (1+ cnt))
10546 (replace-match ""))
10547 (message "Property \"%s\" removed from %d entries" property cnt)))))
10549 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10551 (defun org-compute-property-at-point ()
10552 "Compute the property at point.
10553 This looks for an enclosing column format, extracts the operator and
10554 then applies it to the proerty in the column format's scope."
10555 (interactive)
10556 (unless (org-at-property-p)
10557 (error "Not at a property"))
10558 (let ((prop (org-match-string-no-properties 2)))
10559 (org-columns-get-format-and-top-level)
10560 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10561 (error "No operator defined for property %s" prop))
10562 (org-columns-compute prop)))
10564 (defun org-property-get-allowed-values (pom property &optional table)
10565 "Get allowed values for the property PROPERTY.
10566 When TABLE is non-nil, return an alist that can directly be used for
10567 completion."
10568 (let (vals)
10569 (cond
10570 ((equal property "TODO")
10571 (setq vals (org-with-point-at pom
10572 (append org-todo-keywords-1 '("")))))
10573 ((equal property "PRIORITY")
10574 (let ((n org-lowest-priority))
10575 (while (>= n org-highest-priority)
10576 (push (char-to-string n) vals)
10577 (setq n (1- n)))))
10578 ((member property org-special-properties))
10580 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10582 (when (and vals (string-match "\\S-" vals))
10583 (setq vals (car (read-from-string (concat "(" vals ")"))))
10584 (setq vals (mapcar (lambda (x)
10585 (cond ((stringp x) x)
10586 ((numberp x) (number-to-string x))
10587 ((symbolp x) (symbol-name x))
10588 (t "???")))
10589 vals)))))
10590 (if table (mapcar 'list vals) vals)))
10592 (defun org-property-previous-allowed-value (&optional previous)
10593 "Switch to the next allowed value for this property."
10594 (interactive)
10595 (org-property-next-allowed-value t))
10597 (defun org-property-next-allowed-value (&optional previous)
10598 "Switch to the next allowed value for this property."
10599 (interactive)
10600 (unless (org-at-property-p)
10601 (error "Not at a property"))
10602 (let* ((key (match-string 2))
10603 (value (match-string 3))
10604 (allowed (or (org-property-get-allowed-values (point) key)
10605 (and (member value '("[ ]" "[-]" "[X]"))
10606 '("[ ]" "[X]"))))
10607 nval)
10608 (unless allowed
10609 (error "Allowed values for this property have not been defined"))
10610 (if previous (setq allowed (reverse allowed)))
10611 (if (member value allowed)
10612 (setq nval (car (cdr (member value allowed)))))
10613 (setq nval (or nval (car allowed)))
10614 (if (equal nval value)
10615 (error "Only one allowed value for this property"))
10616 (org-at-property-p)
10617 (replace-match (concat " :" key ": " nval) t t)
10618 (org-indent-line-function)
10619 (beginning-of-line 1)
10620 (skip-chars-forward " \t")))
10622 (defun org-find-entry-with-id (ident)
10623 "Locate the entry that contains the ID property with exact value IDENT.
10624 IDENT can be a string, a symbol or a number, this function will search for
10625 the string representation of it.
10626 Return the position where this entry starts, or nil if there is no such entry."
10627 (interactive "sID: ")
10628 (let ((id (cond
10629 ((stringp ident) ident)
10630 ((symbol-name ident) (symbol-name ident))
10631 ((numberp ident) (number-to-string ident))
10632 (t (error "IDENT %s must be a string, symbol or number" ident))))
10633 (case-fold-search nil))
10634 (save-excursion
10635 (save-restriction
10636 (widen)
10637 (goto-char (point-min))
10638 (when (re-search-forward
10639 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10640 nil t)
10641 (org-back-to-heading)
10642 (point))))))
10644 ;;;; Timestamps
10646 (defvar org-last-changed-timestamp nil)
10647 (defvar org-last-inserted-timestamp nil
10648 "The last time stamp inserted with `org-insert-time-stamp'.")
10649 (defvar org-time-was-given) ; dynamically scoped parameter
10650 (defvar org-end-time-was-given) ; dynamically scoped parameter
10651 (defvar org-ts-what) ; dynamically scoped parameter
10653 (defun org-time-stamp (arg &optional inactive)
10654 "Prompt for a date/time and insert a time stamp.
10655 If the user specifies a time like HH:MM, or if this command is called
10656 with a prefix argument, the time stamp will contain date and time.
10657 Otherwise, only the date will be included. All parts of a date not
10658 specified by the user will be filled in from the current date/time.
10659 So if you press just return without typing anything, the time stamp
10660 will represent the current date/time. If there is already a timestamp
10661 at the cursor, it will be modified."
10662 (interactive "P")
10663 (let* ((ts nil)
10664 (default-time
10665 ;; Default time is either today, or, when entering a range,
10666 ;; the range start.
10667 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10668 (save-excursion
10669 (re-search-backward
10670 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10671 (- (point) 20) t)))
10672 (apply 'encode-time (org-parse-time-string (match-string 1)))
10673 (current-time)))
10674 (default-input (and ts (org-get-compact-tod ts)))
10675 org-time-was-given org-end-time-was-given time)
10676 (cond
10677 ((and (org-at-timestamp-p t)
10678 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10679 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10680 (insert "--")
10681 (setq time (let ((this-command this-command))
10682 (org-read-date arg 'totime nil nil
10683 default-time default-input)))
10684 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10685 ((org-at-timestamp-p t)
10686 (setq time (let ((this-command this-command))
10687 (org-read-date arg 'totime nil nil default-time default-input)))
10688 (when (org-at-timestamp-p t) ; just to get the match data
10689 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10690 (replace-match "")
10691 (setq org-last-changed-timestamp
10692 (org-insert-time-stamp
10693 time (or org-time-was-given arg)
10694 inactive nil nil (list org-end-time-was-given))))
10695 (message "Timestamp updated"))
10697 (setq time (let ((this-command this-command))
10698 (org-read-date arg 'totime nil nil default-time default-input)))
10699 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10700 nil nil (list org-end-time-was-given))))))
10702 ;; FIXME: can we use this for something else, like computing time differences?
10703 (defun org-get-compact-tod (s)
10704 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10705 (let* ((t1 (match-string 1 s))
10706 (h1 (string-to-number (match-string 2 s)))
10707 (m1 (string-to-number (match-string 3 s)))
10708 (t2 (and (match-end 4) (match-string 5 s)))
10709 (h2 (and t2 (string-to-number (match-string 6 s))))
10710 (m2 (and t2 (string-to-number (match-string 7 s))))
10711 dh dm)
10712 (if (not t2)
10714 (setq dh (- h2 h1) dm (- m2 m1))
10715 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10716 (concat t1 "+" (number-to-string dh)
10717 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10719 (defun org-time-stamp-inactive (&optional arg)
10720 "Insert an inactive time stamp.
10721 An inactive time stamp is enclosed in square brackets instead of angle
10722 brackets. It is inactive in the sense that it does not trigger agenda entries,
10723 does not link to the calendar and cannot be changed with the S-cursor keys.
10724 So these are more for recording a certain time/date."
10725 (interactive "P")
10726 (org-time-stamp arg 'inactive))
10728 (defvar org-date-ovl (org-make-overlay 1 1))
10729 (org-overlay-put org-date-ovl 'face 'org-warning)
10730 (org-detach-overlay org-date-ovl)
10732 (defvar org-ans1) ; dynamically scoped parameter
10733 (defvar org-ans2) ; dynamically scoped parameter
10735 (defvar org-plain-time-of-day-regexp) ; defined below
10737 (defvar org-overriding-default-time nil) ; dynamically scoped
10738 (defvar org-read-date-overlay nil)
10739 (defvar org-dcst nil) ; dynamically scoped
10741 (defun org-read-date (&optional with-time to-time from-string prompt
10742 default-time default-input)
10743 "Read a date, possibly a time, and make things smooth for the user.
10744 The prompt will suggest to enter an ISO date, but you can also enter anything
10745 which will at least partially be understood by `parse-time-string'.
10746 Unrecognized parts of the date will default to the current day, month, year,
10747 hour and minute. If this command is called to replace a timestamp at point,
10748 of to enter the second timestamp of a range, the default time is taken from the
10749 existing stamp. For example,
10750 3-2-5 --> 2003-02-05
10751 feb 15 --> currentyear-02-15
10752 sep 12 9 --> 2009-09-12
10753 12:45 --> today 12:45
10754 22 sept 0:34 --> currentyear-09-22 0:34
10755 12 --> currentyear-currentmonth-12
10756 Fri --> nearest Friday (today or later)
10757 etc.
10759 Furthermore you can specify a relative date by giving, as the *first* thing
10760 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10761 change in days weeks, months, years.
10762 With a single plus or minus, the date is relative to today. With a double
10763 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10764 +4d --> four days from today
10765 +4 --> same as above
10766 +2w --> two weeks from today
10767 ++5 --> five days from default date
10769 The function understands only English month and weekday abbreviations,
10770 but this can be configured with the variables `parse-time-months' and
10771 `parse-time-weekdays'.
10773 While prompting, a calendar is popped up - you can also select the
10774 date with the mouse (button 1). The calendar shows a period of three
10775 months. To scroll it to other months, use the keys `>' and `<'.
10776 If you don't like the calendar, turn it off with
10777 \(setq org-read-date-popup-calendar nil)
10779 With optional argument TO-TIME, the date will immediately be converted
10780 to an internal time.
10781 With an optional argument WITH-TIME, the prompt will suggest to also
10782 insert a time. Note that when WITH-TIME is not set, you can still
10783 enter a time, and this function will inform the calling routine about
10784 this change. The calling routine may then choose to change the format
10785 used to insert the time stamp into the buffer to include the time.
10786 With optional argument FROM-STRING, read from this string instead from
10787 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10788 the time/date that is used for everything that is not specified by the
10789 user."
10790 (require 'parse-time)
10791 (let* ((org-time-stamp-rounding-minutes
10792 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10793 (org-dcst org-display-custom-times)
10794 (ct (org-current-time))
10795 (def (or org-overriding-default-time default-time ct))
10796 (defdecode (decode-time def))
10797 (dummy (progn
10798 (when (< (nth 2 defdecode) org-extend-today-until)
10799 (setcar (nthcdr 2 defdecode) -1)
10800 (setcar (nthcdr 1 defdecode) 59)
10801 (setq def (apply 'encode-time defdecode)
10802 defdecode (decode-time def)))))
10803 (calendar-move-hook nil)
10804 (calendar-view-diary-initially-flag nil)
10805 (view-diary-entries-initially nil)
10806 (calendar-view-holidays-initially-flag nil)
10807 (view-calendar-holidays-initially nil)
10808 (timestr (format-time-string
10809 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10810 (prompt (concat (if prompt (concat prompt " ") "")
10811 (format "Date+time [%s]: " timestr)))
10812 ans (org-ans0 "") org-ans1 org-ans2 final)
10814 (cond
10815 (from-string (setq ans from-string))
10816 (org-read-date-popup-calendar
10817 (save-excursion
10818 (save-window-excursion
10819 (calendar)
10820 (calendar-forward-day (- (time-to-days def)
10821 (calendar-absolute-from-gregorian
10822 (calendar-current-date))))
10823 (org-eval-in-calendar nil t)
10824 (let* ((old-map (current-local-map))
10825 (map (copy-keymap calendar-mode-map))
10826 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10827 (org-defkey map (kbd "RET") 'org-calendar-select)
10828 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10829 'org-calendar-select-mouse)
10830 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10831 'org-calendar-select-mouse)
10832 (org-defkey minibuffer-local-map [(meta shift left)]
10833 (lambda () (interactive)
10834 (org-eval-in-calendar '(calendar-backward-month 1))))
10835 (org-defkey minibuffer-local-map [(meta shift right)]
10836 (lambda () (interactive)
10837 (org-eval-in-calendar '(calendar-forward-month 1))))
10838 (org-defkey minibuffer-local-map [(meta shift up)]
10839 (lambda () (interactive)
10840 (org-eval-in-calendar '(calendar-backward-year 1))))
10841 (org-defkey minibuffer-local-map [(meta shift down)]
10842 (lambda () (interactive)
10843 (org-eval-in-calendar '(calendar-forward-year 1))))
10844 (org-defkey minibuffer-local-map [(shift up)]
10845 (lambda () (interactive)
10846 (org-eval-in-calendar '(calendar-backward-week 1))))
10847 (org-defkey minibuffer-local-map [(shift down)]
10848 (lambda () (interactive)
10849 (org-eval-in-calendar '(calendar-forward-week 1))))
10850 (org-defkey minibuffer-local-map [(shift left)]
10851 (lambda () (interactive)
10852 (org-eval-in-calendar '(calendar-backward-day 1))))
10853 (org-defkey minibuffer-local-map [(shift right)]
10854 (lambda () (interactive)
10855 (org-eval-in-calendar '(calendar-forward-day 1))))
10856 (org-defkey minibuffer-local-map ">"
10857 (lambda () (interactive)
10858 (org-eval-in-calendar '(scroll-calendar-left 1))))
10859 (org-defkey minibuffer-local-map "<"
10860 (lambda () (interactive)
10861 (org-eval-in-calendar '(scroll-calendar-right 1))))
10862 (unwind-protect
10863 (progn
10864 (use-local-map map)
10865 (add-hook 'post-command-hook 'org-read-date-display)
10866 (setq org-ans0 (read-string prompt default-input nil nil))
10867 ;; org-ans0: from prompt
10868 ;; org-ans1: from mouse click
10869 ;; org-ans2: from calendar motion
10870 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10871 (remove-hook 'post-command-hook 'org-read-date-display)
10872 (use-local-map old-map)
10873 (when org-read-date-overlay
10874 (org-delete-overlay org-read-date-overlay)
10875 (setq org-read-date-overlay nil)))))))
10877 (t ; Naked prompt only
10878 (unwind-protect
10879 (setq ans (read-string prompt default-input nil timestr))
10880 (when org-read-date-overlay
10881 (org-delete-overlay org-read-date-overlay)
10882 (setq org-read-date-overlay nil)))))
10884 (setq final (org-read-date-analyze ans def defdecode))
10886 (if to-time
10887 (apply 'encode-time final)
10888 (if (and (boundp 'org-time-was-given) org-time-was-given)
10889 (format "%04d-%02d-%02d %02d:%02d"
10890 (nth 5 final) (nth 4 final) (nth 3 final)
10891 (nth 2 final) (nth 1 final))
10892 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10893 (defvar def)
10894 (defvar defdecode)
10895 (defvar with-time)
10896 (defun org-read-date-display ()
10897 "Display the currrent date prompt interpretation in the minibuffer."
10898 (when org-read-date-display-live
10899 (when org-read-date-overlay
10900 (org-delete-overlay org-read-date-overlay))
10901 (let ((p (point)))
10902 (end-of-line 1)
10903 (while (not (equal (buffer-substring
10904 (max (point-min) (- (point) 4)) (point))
10905 " "))
10906 (insert " "))
10907 (goto-char p))
10908 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10909 " " (or org-ans1 org-ans2)))
10910 (org-end-time-was-given nil)
10911 (f (org-read-date-analyze ans def defdecode))
10912 (fmts (if org-dcst
10913 org-time-stamp-custom-formats
10914 org-time-stamp-formats))
10915 (fmt (if (or with-time
10916 (and (boundp 'org-time-was-given) org-time-was-given))
10917 (cdr fmts)
10918 (car fmts)))
10919 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10920 (when (and org-end-time-was-given
10921 (string-match org-plain-time-of-day-regexp txt))
10922 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10923 org-end-time-was-given
10924 (substring txt (match-end 0)))))
10925 (setq org-read-date-overlay
10926 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10927 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10929 (defun org-read-date-analyze (ans def defdecode)
10930 "Analyze the combined answer of the date prompt."
10931 ;; FIXME: cleanup and comment
10932 (let (delta deltan deltaw deltadef year month day
10933 hour minute second wday pm h2 m2 tl wday1
10934 iso-year iso-weekday iso-week iso-year iso-date)
10936 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10937 (setq ans "+0"))
10939 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10940 (setq ans (replace-match "" t t ans)
10941 deltan (car delta)
10942 deltaw (nth 1 delta)
10943 deltadef (nth 2 delta)))
10945 ;; Check if there is an iso week date in there
10946 ;; If yes, sore the info and ostpone interpreting it until the rest
10947 ;; of the parsing is done
10948 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10949 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10950 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10951 iso-week (string-to-number (match-string 2 ans)))
10952 (setq ans (replace-match "" t t ans)))
10954 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10955 (when (string-match
10956 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10957 (setq year (if (match-end 2)
10958 (string-to-number (match-string 2 ans))
10959 (string-to-number (format-time-string "%Y")))
10960 month (string-to-number (match-string 3 ans))
10961 day (string-to-number (match-string 4 ans)))
10962 (if (< year 100) (setq year (+ 2000 year)))
10963 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10964 t nil ans)))
10965 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10966 ;; If there is a time with am/pm, and *no* time without it, we convert
10967 ;; so that matching will be successful.
10968 (loop for i from 1 to 2 do ; twice, for end time as well
10969 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10970 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10971 (setq hour (string-to-number (match-string 1 ans))
10972 minute (if (match-end 3)
10973 (string-to-number (match-string 3 ans))
10975 pm (equal ?p
10976 (string-to-char (downcase (match-string 4 ans)))))
10977 (if (and (= hour 12) (not pm))
10978 (setq hour 0)
10979 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10980 (setq ans (replace-match (format "%02d:%02d" hour minute)
10981 t t ans))))
10983 ;; Check if a time range is given as a duration
10984 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10985 (setq hour (string-to-number (match-string 1 ans))
10986 h2 (+ hour (string-to-number (match-string 3 ans)))
10987 minute (string-to-number (match-string 2 ans))
10988 m2 (+ minute (if (match-end 5) (string-to-number
10989 (match-string 5 ans))0)))
10990 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10991 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10992 t t ans)))
10994 ;; Check if there is a time range
10995 (when (boundp 'org-end-time-was-given)
10996 (setq org-time-was-given nil)
10997 (when (and (string-match org-plain-time-of-day-regexp ans)
10998 (match-end 8))
10999 (setq org-end-time-was-given (match-string 8 ans))
11000 (setq ans (concat (substring ans 0 (match-beginning 7))
11001 (substring ans (match-end 7))))))
11003 (setq tl (parse-time-string ans)
11004 day (or (nth 3 tl) (nth 3 defdecode))
11005 month (or (nth 4 tl)
11006 (if (and org-read-date-prefer-future
11007 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11008 (1+ (nth 4 defdecode))
11009 (nth 4 defdecode)))
11010 year (or (nth 5 tl)
11011 (if (and org-read-date-prefer-future
11012 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11013 (1+ (nth 5 defdecode))
11014 (nth 5 defdecode)))
11015 hour (or (nth 2 tl) (nth 2 defdecode))
11016 minute (or (nth 1 tl) (nth 1 defdecode))
11017 second (or (nth 0 tl) 0)
11018 wday (nth 6 tl))
11020 ;; Special date definitions below
11021 (cond
11022 (iso-week
11023 ;; There was an iso week
11024 (setq year (or iso-year year)
11025 day (or iso-weekday wday 1)
11026 wday nil ; to make sure that the trigger below does not match
11027 iso-date (calendar-gregorian-from-absolute
11028 (calendar-absolute-from-iso
11029 (list iso-week day year))))
11030 ; FIXME: Should we also push ISO weeks into the future?
11031 ; (when (and org-read-date-prefer-future
11032 ; (not iso-year)
11033 ; (< (calendar-absolute-from-gregorian iso-date)
11034 ; (time-to-days (current-time))))
11035 ; (setq year (1+ year)
11036 ; iso-date (calendar-gregorian-from-absolute
11037 ; (calendar-absolute-from-iso
11038 ; (list iso-week day year)))))
11039 (setq month (car iso-date)
11040 year (nth 2 iso-date)
11041 day (nth 1 iso-date)))
11042 (deltan
11043 (unless deltadef
11044 (let ((now (decode-time (current-time))))
11045 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11046 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11047 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11048 ((equal deltaw "m") (setq month (+ month deltan)))
11049 ((equal deltaw "y") (setq year (+ year deltan)))))
11050 ((and wday (not (nth 3 tl)))
11051 ;; Weekday was given, but no day, so pick that day in the week
11052 ;; on or after the derived date.
11053 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11054 (unless (equal wday wday1)
11055 (setq day (+ day (% (- wday wday1 -7) 7))))))
11056 (if (and (boundp 'org-time-was-given)
11057 (nth 2 tl))
11058 (setq org-time-was-given t))
11059 (if (< year 100) (setq year (+ 2000 year)))
11060 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11061 (list second minute hour day month year)))
11063 (defvar parse-time-weekdays)
11065 (defun org-read-date-get-relative (s today default)
11066 "Check string S for special relative date string.
11067 TODAY and DEFAULT are internal times, for today and for a default.
11068 Return shift list (N what def-flag)
11069 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11070 N is the number of WHATs to shift.
11071 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11072 the DEFAULT date rather than TODAY."
11073 (when (and
11074 (string-match
11075 (concat
11076 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11077 "\\([0-9]+\\)?"
11078 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11079 "\\([ \t]\\|$\\)") s)
11080 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11081 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11082 (string-to-char (substring (match-string 1 s) -1))
11083 ?+))
11084 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11085 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11086 (what (if (match-end 3) (match-string 3 s) "d"))
11087 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11088 (date (if rel default today))
11089 (wday (nth 6 (decode-time date)))
11090 delta)
11091 (if wday1
11092 (progn
11093 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11094 (if (= dir ?-) (setq delta (- delta 7)))
11095 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11096 (list delta "d" rel))
11097 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11099 (defun org-eval-in-calendar (form &optional keepdate)
11100 "Eval FORM in the calendar window and return to current window.
11101 Also, store the cursor date in variable org-ans2."
11102 (let ((sw (selected-window)))
11103 (select-window (get-buffer-window "*Calendar*"))
11104 (eval form)
11105 (when (and (not keepdate) (calendar-cursor-to-date))
11106 (let* ((date (calendar-cursor-to-date))
11107 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11108 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11109 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11110 (select-window sw)))
11112 (defun org-calendar-select ()
11113 "Return to `org-read-date' with the date currently selected.
11114 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11115 (interactive)
11116 (when (calendar-cursor-to-date)
11117 (let* ((date (calendar-cursor-to-date))
11118 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11119 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11120 (if (active-minibuffer-window) (exit-minibuffer))))
11122 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11123 "Insert a date stamp for the date given by the internal TIME.
11124 WITH-HM means, use the stamp format that includes the time of the day.
11125 INACTIVE means use square brackets instead of angular ones, so that the
11126 stamp will not contribute to the agenda.
11127 PRE and POST are optional strings to be inserted before and after the
11128 stamp.
11129 The command returns the inserted time stamp."
11130 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11131 stamp)
11132 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11133 (insert-before-markers (or pre ""))
11134 (insert-before-markers (setq stamp (format-time-string fmt time)))
11135 (when (listp extra)
11136 (setq extra (car extra))
11137 (if (and (stringp extra)
11138 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11139 (setq extra (format "-%02d:%02d"
11140 (string-to-number (match-string 1 extra))
11141 (string-to-number (match-string 2 extra))))
11142 (setq extra nil)))
11143 (when extra
11144 (backward-char 1)
11145 (insert-before-markers extra)
11146 (forward-char 1))
11147 (insert-before-markers (or post ""))
11148 (setq org-last-inserted-timestamp stamp)))
11150 (defun org-toggle-time-stamp-overlays ()
11151 "Toggle the use of custom time stamp formats."
11152 (interactive)
11153 (setq org-display-custom-times (not org-display-custom-times))
11154 (unless org-display-custom-times
11155 (let ((p (point-min)) (bmp (buffer-modified-p)))
11156 (while (setq p (next-single-property-change p 'display))
11157 (if (and (get-text-property p 'display)
11158 (eq (get-text-property p 'face) 'org-date))
11159 (remove-text-properties
11160 p (setq p (next-single-property-change p 'display))
11161 '(display t))))
11162 (set-buffer-modified-p bmp)))
11163 (if (featurep 'xemacs)
11164 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11165 (org-restart-font-lock)
11166 (setq org-table-may-need-update t)
11167 (if org-display-custom-times
11168 (message "Time stamps are overlayed with custom format")
11169 (message "Time stamp overlays removed")))
11171 (defun org-display-custom-time (beg end)
11172 "Overlay modified time stamp format over timestamp between BEG and END."
11173 (let* ((ts (buffer-substring beg end))
11174 t1 w1 with-hm tf time str w2 (off 0))
11175 (save-match-data
11176 (setq t1 (org-parse-time-string ts t))
11177 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11178 (setq off (- (match-end 0) (match-beginning 0)))))
11179 (setq end (- end off))
11180 (setq w1 (- end beg)
11181 with-hm (and (nth 1 t1) (nth 2 t1))
11182 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11183 time (org-fix-decoded-time t1)
11184 str (org-add-props
11185 (format-time-string
11186 (substring tf 1 -1) (apply 'encode-time time))
11187 nil 'mouse-face 'highlight)
11188 w2 (length str))
11189 (if (not (= w2 w1))
11190 (add-text-properties (1+ beg) (+ 2 beg)
11191 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11192 (if (featurep 'xemacs)
11193 (progn
11194 (put-text-property beg end 'invisible t)
11195 (put-text-property beg end 'end-glyph (make-glyph str)))
11196 (put-text-property beg end 'display str))))
11198 (defun org-translate-time (string)
11199 "Translate all timestamps in STRING to custom format.
11200 But do this only if the variable `org-display-custom-times' is set."
11201 (when org-display-custom-times
11202 (save-match-data
11203 (let* ((start 0)
11204 (re org-ts-regexp-both)
11205 t1 with-hm inactive tf time str beg end)
11206 (while (setq start (string-match re string start))
11207 (setq beg (match-beginning 0)
11208 end (match-end 0)
11209 t1 (save-match-data
11210 (org-parse-time-string (substring string beg end) t))
11211 with-hm (and (nth 1 t1) (nth 2 t1))
11212 inactive (equal (substring string beg (1+ beg)) "[")
11213 tf (funcall (if with-hm 'cdr 'car)
11214 org-time-stamp-custom-formats)
11215 time (org-fix-decoded-time t1)
11216 str (format-time-string
11217 (concat
11218 (if inactive "[" "<") (substring tf 1 -1)
11219 (if inactive "]" ">"))
11220 (apply 'encode-time time))
11221 string (replace-match str t t string)
11222 start (+ start (length str)))))))
11223 string)
11225 (defun org-fix-decoded-time (time)
11226 "Set 0 instead of nil for the first 6 elements of time.
11227 Don't touch the rest."
11228 (let ((n 0))
11229 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11231 (defun org-days-to-time (timestamp-string)
11232 "Difference between TIMESTAMP-STRING and now in days."
11233 (- (time-to-days (org-time-string-to-time timestamp-string))
11234 (time-to-days (current-time))))
11236 (defun org-deadline-close (timestamp-string &optional ndays)
11237 "Is the time in TIMESTAMP-STRING close to the current date?"
11238 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11239 (and (< (org-days-to-time timestamp-string) ndays)
11240 (not (org-entry-is-done-p))))
11242 (defun org-get-wdays (ts)
11243 "Get the deadline lead time appropriate for timestring TS."
11244 (cond
11245 ((<= org-deadline-warning-days 0)
11246 ;; 0 or negative, enforce this value no matter what
11247 (- org-deadline-warning-days))
11248 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11249 ;; lead time is specified.
11250 (floor (* (string-to-number (match-string 1 ts))
11251 (cdr (assoc (match-string 2 ts)
11252 '(("d" . 1) ("w" . 7)
11253 ("m" . 30.4) ("y" . 365.25)))))))
11254 ;; go for the default.
11255 (t org-deadline-warning-days)))
11257 (defun org-calendar-select-mouse (ev)
11258 "Return to `org-read-date' with the date currently selected.
11259 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11260 (interactive "e")
11261 (mouse-set-point ev)
11262 (when (calendar-cursor-to-date)
11263 (let* ((date (calendar-cursor-to-date))
11264 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11265 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11266 (if (active-minibuffer-window) (exit-minibuffer))))
11268 (defun org-check-deadlines (ndays)
11269 "Check if there are any deadlines due or past due.
11270 A deadline is considered due if it happens within `org-deadline-warning-days'
11271 days from today's date. If the deadline appears in an entry marked DONE,
11272 it is not shown. The prefix arg NDAYS can be used to test that many
11273 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11274 (interactive "P")
11275 (let* ((org-warn-days
11276 (cond
11277 ((equal ndays '(4)) 100000)
11278 (ndays (prefix-numeric-value ndays))
11279 (t (abs org-deadline-warning-days))))
11280 (case-fold-search nil)
11281 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11282 (callback
11283 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11285 (message "%d deadlines past-due or due within %d days"
11286 (org-occur regexp nil callback)
11287 org-warn-days)))
11289 (defun org-check-before-date (date)
11290 "Check if there are deadlines or scheduled entries before DATE."
11291 (interactive (list (org-read-date)))
11292 (let ((case-fold-search nil)
11293 (regexp (concat "\\<\\(" org-deadline-string
11294 "\\|" org-scheduled-string
11295 "\\) *<\\([^>]+\\)>"))
11296 (callback
11297 (lambda () (time-less-p
11298 (org-time-string-to-time (match-string 2))
11299 (org-time-string-to-time date)))))
11300 (message "%d entries before %s"
11301 (org-occur regexp nil callback) date)))
11303 (defun org-evaluate-time-range (&optional to-buffer)
11304 "Evaluate a time range by computing the difference between start and end.
11305 Normally the result is just printed in the echo area, but with prefix arg
11306 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11307 If the time range is actually in a table, the result is inserted into the
11308 next column.
11309 For time difference computation, a year is assumed to be exactly 365
11310 days in order to avoid rounding problems."
11311 (interactive "P")
11313 (org-clock-update-time-maybe)
11314 (save-excursion
11315 (unless (org-at-date-range-p t)
11316 (goto-char (point-at-bol))
11317 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11318 (if (not (org-at-date-range-p t))
11319 (error "Not at a time-stamp range, and none found in current line")))
11320 (let* ((ts1 (match-string 1))
11321 (ts2 (match-string 2))
11322 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11323 (match-end (match-end 0))
11324 (time1 (org-time-string-to-time ts1))
11325 (time2 (org-time-string-to-time ts2))
11326 (t1 (time-to-seconds time1))
11327 (t2 (time-to-seconds time2))
11328 (diff (abs (- t2 t1)))
11329 (negative (< (- t2 t1) 0))
11330 ;; (ys (floor (* 365 24 60 60)))
11331 (ds (* 24 60 60))
11332 (hs (* 60 60))
11333 (fy "%dy %dd %02d:%02d")
11334 (fy1 "%dy %dd")
11335 (fd "%dd %02d:%02d")
11336 (fd1 "%dd")
11337 (fh "%02d:%02d")
11338 y d h m align)
11339 (if havetime
11340 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11342 d (floor (/ diff ds)) diff (mod diff ds)
11343 h (floor (/ diff hs)) diff (mod diff hs)
11344 m (floor (/ diff 60)))
11345 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11347 d (floor (+ (/ diff ds) 0.5))
11348 h 0 m 0))
11349 (if (not to-buffer)
11350 (message "%s" (org-make-tdiff-string y d h m))
11351 (if (org-at-table-p)
11352 (progn
11353 (goto-char match-end)
11354 (setq align t)
11355 (and (looking-at " *|") (goto-char (match-end 0))))
11356 (goto-char match-end))
11357 (if (looking-at
11358 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11359 (replace-match ""))
11360 (if negative (insert " -"))
11361 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11362 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11363 (insert " " (format fh h m))))
11364 (if align (org-table-align))
11365 (message "Time difference inserted")))))
11367 (defun org-make-tdiff-string (y d h m)
11368 (let ((fmt "")
11369 (l nil))
11370 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11371 l (push y l)))
11372 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11373 l (push d l)))
11374 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11375 l (push h l)))
11376 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11377 l (push m l)))
11378 (apply 'format fmt (nreverse l))))
11380 (defun org-time-string-to-time (s)
11381 (apply 'encode-time (org-parse-time-string s)))
11383 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11384 "Convert a time stamp to an absolute day number.
11385 If there is a specifyer for a cyclic time stamp, get the closest date to
11386 DAYNR.
11387 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11388 (cond
11389 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11390 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11391 daynr
11392 (+ daynr 1000)))
11393 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11394 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11395 (time-to-days (current-time))) (match-string 0 s)
11396 prefer show-all))
11397 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11399 (defun org-days-to-iso-week (days)
11400 "Return the iso week number."
11401 (require 'cal-iso)
11402 (car (calendar-iso-from-absolute days)))
11404 (defun org-small-year-to-year (year)
11405 "Convert 2-digit years into 4-digit years.
11406 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11407 The year 2000 cannot be abbreviated. Any year larger than 99
11408 is returned unchanged."
11409 (if (< year 38)
11410 (setq year (+ 2000 year))
11411 (if (< year 100)
11412 (setq year (+ 1900 year))))
11413 year)
11415 (defun org-time-from-absolute (d)
11416 "Return the time corresponding to date D.
11417 D may be an absolute day number, or a calendar-type list (month day year)."
11418 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11419 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11421 (defun org-calendar-holiday ()
11422 "List of holidays, for Diary display in Org-mode."
11423 (require 'holidays)
11424 (let ((hl (funcall
11425 (if (fboundp 'calendar-check-holidays)
11426 'calendar-check-holidays 'check-calendar-holidays) date)))
11427 (if hl (mapconcat 'identity hl "; "))))
11429 (defun org-diary-sexp-entry (sexp entry date)
11430 "Process a SEXP diary ENTRY for DATE."
11431 (require 'diary-lib)
11432 (let ((result (if calendar-debug-sexp
11433 (let ((stack-trace-on-error t))
11434 (eval (car (read-from-string sexp))))
11435 (condition-case nil
11436 (eval (car (read-from-string sexp)))
11437 (error
11438 (beep)
11439 (message "Bad sexp at line %d in %s: %s"
11440 (org-current-line)
11441 (buffer-file-name) sexp)
11442 (sleep-for 2))))))
11443 (cond ((stringp result) result)
11444 ((and (consp result)
11445 (stringp (cdr result))) (cdr result))
11446 (result entry)
11447 (t nil))))
11449 (defun org-diary-to-ical-string (frombuf)
11450 "Get iCalendar entries from diary entries in buffer FROMBUF.
11451 This uses the icalendar.el library."
11452 (let* ((tmpdir (if (featurep 'xemacs)
11453 (temp-directory)
11454 temporary-file-directory))
11455 (tmpfile (make-temp-name
11456 (expand-file-name "orgics" tmpdir)))
11457 buf rtn b e)
11458 (save-excursion
11459 (set-buffer frombuf)
11460 (icalendar-export-region (point-min) (point-max) tmpfile)
11461 (setq buf (find-buffer-visiting tmpfile))
11462 (set-buffer buf)
11463 (goto-char (point-min))
11464 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11465 (setq b (match-beginning 0)))
11466 (goto-char (point-max))
11467 (if (re-search-backward "^END:VEVENT" nil t)
11468 (setq e (match-end 0)))
11469 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11470 (kill-buffer buf)
11471 (delete-file tmpfile)
11472 rtn))
11474 (defun org-closest-date (start current change prefer show-all)
11475 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11476 When PREFER is `past' return a date that is either CURRENT or past.
11477 When PREFER is `future', return a date that is either CURRENT or future.
11478 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11479 ;; Make the proper lists from the dates
11480 (catch 'exit
11481 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11482 dn dw sday cday n1 n2
11483 d m y y1 y2 date1 date2 nmonths nm ny m2)
11485 (setq start (org-date-to-gregorian start)
11486 current (org-date-to-gregorian
11487 (if show-all
11488 current
11489 (time-to-days (current-time))))
11490 sday (calendar-absolute-from-gregorian start)
11491 cday (calendar-absolute-from-gregorian current))
11493 (if (<= cday sday) (throw 'exit sday))
11495 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11496 (setq dn (string-to-number (match-string 1 change))
11497 dw (cdr (assoc (match-string 2 change) a1)))
11498 (error "Invalid change specifyer: %s" change))
11499 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11500 (cond
11501 ((eq dw 'day)
11502 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11503 n2 (+ n1 dn)))
11504 ((eq dw 'year)
11505 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11506 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11507 (setq date1 (list m d y1)
11508 n1 (calendar-absolute-from-gregorian date1)
11509 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11510 n2 (calendar-absolute-from-gregorian date2)))
11511 ((eq dw 'month)
11512 ;; approx number of month between the two dates
11513 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11514 ;; How often does dn fit in there?
11515 (setq d (nth 1 start) m (car start) y (nth 2 start)
11516 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11517 m (+ m nm)
11518 ny (floor (/ m 12))
11519 y (+ y ny)
11520 m (- m (* ny 12)))
11521 (while (> m 12) (setq m (- m 12) y (1+ y)))
11522 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11523 (setq m2 (+ m dn) y2 y)
11524 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11525 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11526 (while (<= n2 cday)
11527 (setq n1 n2 m m2 y y2)
11528 (setq m2 (+ m dn) y2 y)
11529 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11530 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11531 (if show-all
11532 (cond
11533 ((eq prefer 'past) n1)
11534 ((eq prefer 'future) (if (= cday n1) n1 n2))
11535 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11536 (cond
11537 ((eq prefer 'past) n1)
11538 ((eq prefer 'future) (if (= cday n1) n1 n2))
11539 (t (if (= cday n1) n1 n2)))))))
11541 (defun org-date-to-gregorian (date)
11542 "Turn any specification of DATE into a gregorian date for the calendar."
11543 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11544 ((and (listp date) (= (length date) 3)) date)
11545 ((stringp date)
11546 (setq date (org-parse-time-string date))
11547 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11548 ((listp date)
11549 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11551 (defun org-parse-time-string (s &optional nodefault)
11552 "Parse the standard Org-mode time string.
11553 This should be a lot faster than the normal `parse-time-string'.
11554 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11555 hour and minute fields will be nil if not given."
11556 (if (string-match org-ts-regexp0 s)
11557 (list 0
11558 (if (or (match-beginning 8) (not nodefault))
11559 (string-to-number (or (match-string 8 s) "0")))
11560 (if (or (match-beginning 7) (not nodefault))
11561 (string-to-number (or (match-string 7 s) "0")))
11562 (string-to-number (match-string 4 s))
11563 (string-to-number (match-string 3 s))
11564 (string-to-number (match-string 2 s))
11565 nil nil nil)
11566 (make-list 9 0)))
11568 (defun org-timestamp-up (&optional arg)
11569 "Increase the date item at the cursor by one.
11570 If the cursor is on the year, change the year. If it is on the month or
11571 the day, change that.
11572 With prefix ARG, change by that many units."
11573 (interactive "p")
11574 (org-timestamp-change (prefix-numeric-value arg)))
11576 (defun org-timestamp-down (&optional arg)
11577 "Decrease the date item at the cursor by one.
11578 If the cursor is on the year, change the year. If it is on the month or
11579 the day, change that.
11580 With prefix ARG, change by that many units."
11581 (interactive "p")
11582 (org-timestamp-change (- (prefix-numeric-value arg))))
11584 (defun org-timestamp-up-day (&optional arg)
11585 "Increase the date in the time stamp by one day.
11586 With prefix ARG, change that many days."
11587 (interactive "p")
11588 (if (and (not (org-at-timestamp-p t))
11589 (org-on-heading-p))
11590 (org-todo 'up)
11591 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11593 (defun org-timestamp-down-day (&optional arg)
11594 "Decrease the date in the time stamp by one day.
11595 With prefix ARG, change that many days."
11596 (interactive "p")
11597 (if (and (not (org-at-timestamp-p t))
11598 (org-on-heading-p))
11599 (org-todo 'down)
11600 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11602 (defun org-at-timestamp-p (&optional inactive-ok)
11603 "Determine if the cursor is in or at a timestamp."
11604 (interactive)
11605 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11606 (pos (point))
11607 (ans (or (looking-at tsr)
11608 (save-excursion
11609 (skip-chars-backward "^[<\n\r\t")
11610 (if (> (point) (point-min)) (backward-char 1))
11611 (and (looking-at tsr)
11612 (> (- (match-end 0) pos) -1))))))
11613 (and ans
11614 (boundp 'org-ts-what)
11615 (setq org-ts-what
11616 (cond
11617 ((= pos (match-beginning 0)) 'bracket)
11618 ((= pos (1- (match-end 0))) 'bracket)
11619 ((org-pos-in-match-range pos 2) 'year)
11620 ((org-pos-in-match-range pos 3) 'month)
11621 ((org-pos-in-match-range pos 7) 'hour)
11622 ((org-pos-in-match-range pos 8) 'minute)
11623 ((or (org-pos-in-match-range pos 4)
11624 (org-pos-in-match-range pos 5)) 'day)
11625 ((and (> pos (or (match-end 8) (match-end 5)))
11626 (< pos (match-end 0)))
11627 (- pos (or (match-end 8) (match-end 5))))
11628 (t 'day))))
11629 ans))
11631 (defun org-toggle-timestamp-type ()
11632 "Toggle the type (<active> or [inactive]) of a time stamp."
11633 (interactive)
11634 (when (org-at-timestamp-p t)
11635 (let ((beg (match-beginning 0)) (end (match-end 0))
11636 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11637 (save-excursion
11638 (goto-char beg)
11639 (while (re-search-forward "[][<>]" end t)
11640 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11641 t t)))
11642 (message "Timestamp is now %sactive"
11643 (if (equal (char-after beg) ?<) "" "in")))))
11645 (defun org-timestamp-change (n &optional what)
11646 "Change the date in the time stamp at point.
11647 The date will be changed by N times WHAT. WHAT can be `day', `month',
11648 `year', `minute', `second'. If WHAT is not given, the cursor position
11649 in the timestamp determines what will be changed."
11650 (let ((pos (point))
11651 with-hm inactive
11652 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11653 org-ts-what
11654 extra rem
11655 ts time time0)
11656 (if (not (org-at-timestamp-p t))
11657 (error "Not at a timestamp"))
11658 (if (and (not what) (eq org-ts-what 'bracket))
11659 (org-toggle-timestamp-type)
11660 (if (and (not what) (not (eq org-ts-what 'day))
11661 org-display-custom-times
11662 (get-text-property (point) 'display)
11663 (not (get-text-property (1- (point)) 'display)))
11664 (setq org-ts-what 'day))
11665 (setq org-ts-what (or what org-ts-what)
11666 inactive (= (char-after (match-beginning 0)) ?\[)
11667 ts (match-string 0))
11668 (replace-match "")
11669 (if (string-match
11670 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11672 (setq extra (match-string 1 ts)))
11673 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11674 (setq with-hm t))
11675 (setq time0 (org-parse-time-string ts))
11676 (when (and (eq org-ts-what 'minute)
11677 (eq current-prefix-arg nil))
11678 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11679 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11680 (setcar (cdr time0) (+ (nth 1 time0)
11681 (if (> n 0) (- rem) (- dm rem))))))
11682 (setq time
11683 (encode-time (or (car time0) 0)
11684 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11685 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11686 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11687 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11688 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11689 (nthcdr 6 time0)))
11690 (when (integerp org-ts-what)
11691 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11692 (if (eq what 'calendar)
11693 (let ((cal-date (org-get-date-from-calendar)))
11694 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11695 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11696 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11697 (setcar time0 (or (car time0) 0))
11698 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11699 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11700 (setq time (apply 'encode-time time0))))
11701 (setq org-last-changed-timestamp
11702 (org-insert-time-stamp time with-hm inactive nil nil extra))
11703 (org-clock-update-time-maybe)
11704 (goto-char pos)
11705 ;; Try to recenter the calendar window, if any
11706 (if (and org-calendar-follow-timestamp-change
11707 (get-buffer-window "*Calendar*" t)
11708 (memq org-ts-what '(day month year)))
11709 (org-recenter-calendar (time-to-days time))))))
11711 (defun org-modify-ts-extra (s pos n dm)
11712 "Change the different parts of the lead-time and repeat fields in timestamp."
11713 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11714 ng h m new rem)
11715 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11716 (cond
11717 ((or (org-pos-in-match-range pos 2)
11718 (org-pos-in-match-range pos 3))
11719 (setq m (string-to-number (match-string 3 s))
11720 h (string-to-number (match-string 2 s)))
11721 (if (org-pos-in-match-range pos 2)
11722 (setq h (+ h n))
11723 (setq n (* dm (org-no-warnings (signum n))))
11724 (when (not (= 0 (setq rem (% m dm))))
11725 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11726 (setq m (+ m n)))
11727 (if (< m 0) (setq m (+ m 60) h (1- h)))
11728 (if (> m 59) (setq m (- m 60) h (1+ h)))
11729 (setq h (min 24 (max 0 h)))
11730 (setq ng 1 new (format "-%02d:%02d" h m)))
11731 ((org-pos-in-match-range pos 6)
11732 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11733 ((org-pos-in-match-range pos 5)
11734 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11736 ((org-pos-in-match-range pos 9)
11737 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11738 ((org-pos-in-match-range pos 8)
11739 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11741 (when ng
11742 (setq s (concat
11743 (substring s 0 (match-beginning ng))
11745 (substring s (match-end ng))))))
11748 (defun org-recenter-calendar (date)
11749 "If the calendar is visible, recenter it to DATE."
11750 (let* ((win (selected-window))
11751 (cwin (get-buffer-window "*Calendar*" t))
11752 (calendar-move-hook nil))
11753 (when cwin
11754 (select-window cwin)
11755 (calendar-goto-date (if (listp date) date
11756 (calendar-gregorian-from-absolute date)))
11757 (select-window win))))
11759 (defun org-goto-calendar (&optional arg)
11760 "Go to the Emacs calendar at the current date.
11761 If there is a time stamp in the current line, go to that date.
11762 A prefix ARG can be used to force the current date."
11763 (interactive "P")
11764 (let ((tsr org-ts-regexp) diff
11765 (calendar-move-hook nil)
11766 (calendar-view-holidays-initially-flag nil)
11767 (view-calendar-holidays-initially nil)
11768 (calendar-view-diary-initially-flag nil)
11769 (view-diary-entries-initially nil))
11770 (if (or (org-at-timestamp-p)
11771 (save-excursion
11772 (beginning-of-line 1)
11773 (looking-at (concat ".*" tsr))))
11774 (let ((d1 (time-to-days (current-time)))
11775 (d2 (time-to-days
11776 (org-time-string-to-time (match-string 1)))))
11777 (setq diff (- d2 d1))))
11778 (calendar)
11779 (calendar-goto-today)
11780 (if (and diff (not arg)) (calendar-forward-day diff))))
11782 (defun org-get-date-from-calendar ()
11783 "Return a list (month day year) of date at point in calendar."
11784 (with-current-buffer "*Calendar*"
11785 (save-match-data
11786 (calendar-cursor-to-date))))
11788 (defun org-date-from-calendar ()
11789 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11790 If there is already a time stamp at the cursor position, update it."
11791 (interactive)
11792 (if (org-at-timestamp-p t)
11793 (org-timestamp-change 0 'calendar)
11794 (let ((cal-date (org-get-date-from-calendar)))
11795 (org-insert-time-stamp
11796 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11798 (defun org-minutes-to-hh:mm-string (m)
11799 "Compute H:MM from a number of minutes."
11800 (let ((h (/ m 60)))
11801 (setq m (- m (* 60 h)))
11802 (format org-time-clocksum-format h m)))
11804 (defun org-hh:mm-string-to-minutes (s)
11805 "Convert a string H:MM to a number of minutes."
11806 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11807 (+ (* (string-to-number (match-string 1 s)) 60)
11808 (string-to-number (match-string 2 s)))
11811 ;;;; Agenda files
11813 ;;;###autoload
11814 (defun org-iswitchb (&optional arg)
11815 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11816 With a prefix argument, restrict available to files.
11817 With two prefix arguments, restrict available buffers to agenda files.
11819 Due to some yet unresolved reason, the global function
11820 `iswitchb-mode' needs to be active for this function to work."
11821 (interactive "P")
11822 (require 'iswitchb)
11823 (let ((enabled iswitchb-mode) blist)
11824 (or enabled (iswitchb-mode 1))
11825 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11826 ((equal arg '(16)) (org-buffer-list 'agenda))
11827 (t (org-buffer-list))))
11828 (unwind-protect
11829 (let ((iswitchb-make-buflist-hook
11830 (lambda ()
11831 (setq iswitchb-temp-buflist
11832 (mapcar 'buffer-name blist)))))
11833 (switch-to-buffer
11834 (iswitchb-read-buffer
11835 "Switch-to: " nil t))
11836 (or enabled (iswitchb-mode -1))))))
11838 (defun org-buffer-list (&optional predicate exclude-tmp)
11839 "Return a list of Org buffers.
11840 PREDICATE can be `export', `files' or `agenda'.
11842 export restrict the list to Export buffers.
11843 files restrict the list to buffers visiting Org files.
11844 agenda restrict the list to buffers visiting agenda files.
11846 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11847 (let* ((bfn nil)
11848 (agenda-files (and (eq predicate 'agenda)
11849 (mapcar 'file-truename (org-agenda-files t))))
11850 (filter
11851 (cond
11852 ((eq predicate 'files)
11853 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11854 ((eq predicate 'export)
11855 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11856 ((eq predicate 'agenda)
11857 (lambda (b)
11858 (with-current-buffer b
11859 (and (eq major-mode 'org-mode)
11860 (setq bfn (buffer-file-name b))
11861 (member (file-truename bfn) agenda-files)))))
11862 (t (lambda (b) (with-current-buffer b
11863 (or (eq major-mode 'org-mode)
11864 (string-match "\*Org .*Export"
11865 (buffer-name b)))))))))
11866 (delq nil
11867 (mapcar
11868 (lambda(b)
11869 (if (and (funcall filter b)
11870 (or (not exclude-tmp)
11871 (not (string-match "tmp" (buffer-name b)))))
11873 nil))
11874 (buffer-list)))))
11876 (defun org-agenda-files (&optional unrestricted archives)
11877 "Get the list of agenda files.
11878 Optional UNRESTRICTED means return the full list even if a restriction
11879 is currently in place.
11880 When ARCHIVES is t, include all archive files hat are really being
11881 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11882 `org-agenda-archives-mode' is t."
11883 (let ((files
11884 (cond
11885 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11886 ((stringp org-agenda-files) (org-read-agenda-file-list))
11887 ((listp org-agenda-files) org-agenda-files)
11888 (t (error "Invalid value of `org-agenda-files'")))))
11889 (setq files (apply 'append
11890 (mapcar (lambda (f)
11891 (if (file-directory-p f)
11892 (directory-files
11893 f t org-agenda-file-regexp)
11894 (list f)))
11895 files)))
11896 (when org-agenda-skip-unavailable-files
11897 (setq files (delq nil
11898 (mapcar (function
11899 (lambda (file)
11900 (and (file-readable-p file) file)))
11901 files))))
11902 (when (or (eq archives t)
11903 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11904 (setq files (org-add-archive-files files)))
11905 files))
11907 (defun org-edit-agenda-file-list ()
11908 "Edit the list of agenda files.
11909 Depending on setup, this either uses customize to edit the variable
11910 `org-agenda-files', or it visits the file that is holding the list. In the
11911 latter case, the buffer is set up in a way that saving it automatically kills
11912 the buffer and restores the previous window configuration."
11913 (interactive)
11914 (if (stringp org-agenda-files)
11915 (let ((cw (current-window-configuration)))
11916 (find-file org-agenda-files)
11917 (org-set-local 'org-window-configuration cw)
11918 (org-add-hook 'after-save-hook
11919 (lambda ()
11920 (set-window-configuration
11921 (prog1 org-window-configuration
11922 (kill-buffer (current-buffer))))
11923 (org-install-agenda-files-menu)
11924 (message "New agenda file list installed"))
11925 nil 'local)
11926 (message "%s" (substitute-command-keys
11927 "Edit list and finish with \\[save-buffer]")))
11928 (customize-variable 'org-agenda-files)))
11930 (defun org-store-new-agenda-file-list (list)
11931 "Set new value for the agenda file list and save it correcly."
11932 (if (stringp org-agenda-files)
11933 (let ((f org-agenda-files) b)
11934 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11935 (with-temp-file f
11936 (insert (mapconcat 'identity list "\n") "\n")))
11937 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11938 (setq org-agenda-files list)
11939 (customize-save-variable 'org-agenda-files org-agenda-files))))
11941 (defun org-read-agenda-file-list ()
11942 "Read the list of agenda files from a file."
11943 (when (file-directory-p org-agenda-files)
11944 (error "`org-agenda-files' cannot be a single directory"))
11945 (when (stringp org-agenda-files)
11946 (with-temp-buffer
11947 (insert-file-contents org-agenda-files)
11948 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11951 ;;;###autoload
11952 (defun org-cycle-agenda-files ()
11953 "Cycle through the files in `org-agenda-files'.
11954 If the current buffer visits an agenda file, find the next one in the list.
11955 If the current buffer does not, find the first agenda file."
11956 (interactive)
11957 (let* ((fs (org-agenda-files t))
11958 (files (append fs (list (car fs))))
11959 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11960 file)
11961 (unless files (error "No agenda files"))
11962 (catch 'exit
11963 (while (setq file (pop files))
11964 (if (equal (file-truename file) tcf)
11965 (when (car files)
11966 (find-file (car files))
11967 (throw 'exit t))))
11968 (find-file (car fs)))
11969 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11971 (defun org-agenda-file-to-front (&optional to-end)
11972 "Move/add the current file to the top of the agenda file list.
11973 If the file is not present in the list, it is added to the front. If it is
11974 present, it is moved there. With optional argument TO-END, add/move to the
11975 end of the list."
11976 (interactive "P")
11977 (let ((org-agenda-skip-unavailable-files nil)
11978 (file-alist (mapcar (lambda (x)
11979 (cons (file-truename x) x))
11980 (org-agenda-files t)))
11981 (ctf (file-truename buffer-file-name))
11982 x had)
11983 (setq x (assoc ctf file-alist) had x)
11985 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11986 (if to-end
11987 (setq file-alist (append (delq x file-alist) (list x)))
11988 (setq file-alist (cons x (delq x file-alist))))
11989 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11990 (org-install-agenda-files-menu)
11991 (message "File %s to %s of agenda file list"
11992 (if had "moved" "added") (if to-end "end" "front"))))
11994 (defun org-remove-file (&optional file)
11995 "Remove current file from the list of files in variable `org-agenda-files'.
11996 These are the files which are being checked for agenda entries.
11997 Optional argument FILE means, use this file instead of the current."
11998 (interactive)
11999 (let* ((org-agenda-skip-unavailable-files nil)
12000 (file (or file buffer-file-name))
12001 (true-file (file-truename file))
12002 (afile (abbreviate-file-name file))
12003 (files (delq nil (mapcar
12004 (lambda (x)
12005 (if (equal true-file
12006 (file-truename x))
12007 nil x))
12008 (org-agenda-files t)))))
12009 (if (not (= (length files) (length (org-agenda-files t))))
12010 (progn
12011 (org-store-new-agenda-file-list files)
12012 (org-install-agenda-files-menu)
12013 (message "Removed file: %s" afile))
12014 (message "File was not in list: %s (not removed)" afile))))
12016 (defun org-file-menu-entry (file)
12017 (vector file (list 'find-file file) t))
12019 (defun org-check-agenda-file (file)
12020 "Make sure FILE exists. If not, ask user what to do."
12021 (when (not (file-exists-p file))
12022 (message "non-existent file %s. [R]emove from list or [A]bort?"
12023 (abbreviate-file-name file))
12024 (let ((r (downcase (read-char-exclusive))))
12025 (cond
12026 ((equal r ?r)
12027 (org-remove-file file)
12028 (throw 'nextfile t))
12029 (t (error "Abort"))))))
12031 (defun org-get-agenda-file-buffer (file)
12032 "Get a buffer visiting FILE. If the buffer needs to be created, add
12033 it to the list of buffers which might be released later."
12034 (let ((buf (org-find-base-buffer-visiting file)))
12035 (if buf
12036 buf ; just return it
12037 ;; Make a new buffer and remember it
12038 (setq buf (find-file-noselect file))
12039 (if buf (push buf org-agenda-new-buffers))
12040 buf)))
12042 (defun org-release-buffers (blist)
12043 "Release all buffers in list, asking the user for confirmation when needed.
12044 When a buffer is unmodified, it is just killed. When modified, it is saved
12045 \(if the user agrees) and then killed."
12046 (let (buf file)
12047 (while (setq buf (pop blist))
12048 (setq file (buffer-file-name buf))
12049 (when (and (buffer-modified-p buf)
12050 file
12051 (y-or-n-p (format "Save file %s? " file)))
12052 (with-current-buffer buf (save-buffer)))
12053 (kill-buffer buf))))
12055 (defun org-prepare-agenda-buffers (files)
12056 "Create buffers for all agenda files, protect archived trees and comments."
12057 (interactive)
12058 (let ((pa '(:org-archived t))
12059 (pc '(:org-comment t))
12060 (pall '(:org-archived t :org-comment t))
12061 (inhibit-read-only t)
12062 (rea (concat ":" org-archive-tag ":"))
12063 bmp file re)
12064 (save-excursion
12065 (save-restriction
12066 (while (setq file (pop files))
12067 (if (bufferp file)
12068 (set-buffer file)
12069 (org-check-agenda-file file)
12070 (set-buffer (org-get-agenda-file-buffer file)))
12071 (widen)
12072 (setq bmp (buffer-modified-p))
12073 (org-refresh-category-properties)
12074 (setq org-todo-keywords-for-agenda
12075 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12076 (setq org-done-keywords-for-agenda
12077 (append org-done-keywords-for-agenda org-done-keywords))
12078 (setq org-todo-keyword-alist-for-agenda
12079 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12080 (setq org-tag-alist-for-agenda
12081 (append org-tag-alist-for-agenda org-tag-alist))
12083 (save-excursion
12084 (remove-text-properties (point-min) (point-max) pall)
12085 (when org-agenda-skip-archived-trees
12086 (goto-char (point-min))
12087 (while (re-search-forward rea nil t)
12088 (if (org-on-heading-p t)
12089 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12090 (goto-char (point-min))
12091 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12092 (while (re-search-forward re nil t)
12093 (add-text-properties
12094 (match-beginning 0) (org-end-of-subtree t) pc)))
12095 (set-buffer-modified-p bmp))))
12096 (setq org-todo-keyword-alist-for-agenda
12097 (org-uniquify org-todo-keyword-alist-for-agenda)
12098 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12100 ;;;; Embedded LaTeX
12102 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12103 "Keymap for the minor `org-cdlatex-mode'.")
12105 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12106 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12107 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12108 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12109 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12111 (defvar org-cdlatex-texmathp-advice-is-done nil
12112 "Flag remembering if we have applied the advice to texmathp already.")
12114 (define-minor-mode org-cdlatex-mode
12115 "Toggle the minor `org-cdlatex-mode'.
12116 This mode supports entering LaTeX environment and math in LaTeX fragments
12117 in Org-mode.
12118 \\{org-cdlatex-mode-map}"
12119 nil " OCDL" nil
12120 (when org-cdlatex-mode (require 'cdlatex))
12121 (unless org-cdlatex-texmathp-advice-is-done
12122 (setq org-cdlatex-texmathp-advice-is-done t)
12123 (defadvice texmathp (around org-math-always-on activate)
12124 "Always return t in org-mode buffers.
12125 This is because we want to insert math symbols without dollars even outside
12126 the LaTeX math segments. If Orgmode thinks that point is actually inside
12127 en embedded LaTeX fragement, let texmathp do its job.
12128 \\[org-cdlatex-mode-map]"
12129 (interactive)
12130 (let (p)
12131 (cond
12132 ((not (org-mode-p)) ad-do-it)
12133 ((eq this-command 'cdlatex-math-symbol)
12134 (setq ad-return-value t
12135 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12137 (let ((p (org-inside-LaTeX-fragment-p)))
12138 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12139 (setq ad-return-value t
12140 texmathp-why '("Org-mode embedded math" . 0))
12141 (if p ad-do-it)))))))))
12143 (defun turn-on-org-cdlatex ()
12144 "Unconditionally turn on `org-cdlatex-mode'."
12145 (org-cdlatex-mode 1))
12147 (defun org-inside-LaTeX-fragment-p ()
12148 "Test if point is inside a LaTeX fragment.
12149 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12150 sequence appearing also before point.
12151 Even though the matchers for math are configurable, this function assumes
12152 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12153 delimiters are skipped when they have been removed by customization.
12154 The return value is nil, or a cons cell with the delimiter and
12155 and the position of this delimiter.
12157 This function does a reasonably good job, but can locally be fooled by
12158 for example currency specifications. For example it will assume being in
12159 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12160 fragments that are properly closed, but during editing, we have to live
12161 with the uncertainty caused by missing closing delimiters. This function
12162 looks only before point, not after."
12163 (catch 'exit
12164 (let ((pos (point))
12165 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12166 (lim (progn
12167 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12168 (point)))
12169 dd-on str (start 0) m re)
12170 (goto-char pos)
12171 (when dodollar
12172 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12173 re (nth 1 (assoc "$" org-latex-regexps)))
12174 (while (string-match re str start)
12175 (cond
12176 ((= (match-end 0) (length str))
12177 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12178 ((= (match-end 0) (- (length str) 5))
12179 (throw 'exit nil))
12180 (t (setq start (match-end 0))))))
12181 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12182 (goto-char pos)
12183 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12184 (and (match-beginning 2) (throw 'exit nil))
12185 ;; count $$
12186 (while (re-search-backward "\\$\\$" lim t)
12187 (setq dd-on (not dd-on)))
12188 (goto-char pos)
12189 (if dd-on (cons "$$" m))))))
12192 (defun org-try-cdlatex-tab ()
12193 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12194 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12195 - inside a LaTeX fragment, or
12196 - after the first word in a line, where an abbreviation expansion could
12197 insert a LaTeX environment."
12198 (when org-cdlatex-mode
12199 (cond
12200 ((save-excursion
12201 (skip-chars-backward "a-zA-Z0-9*")
12202 (skip-chars-backward " \t")
12203 (bolp))
12204 (cdlatex-tab) t)
12205 ((org-inside-LaTeX-fragment-p)
12206 (cdlatex-tab) t)
12207 (t nil))))
12209 (defun org-cdlatex-underscore-caret (&optional arg)
12210 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12211 Revert to the normal definition outside of these fragments."
12212 (interactive "P")
12213 (if (org-inside-LaTeX-fragment-p)
12214 (call-interactively 'cdlatex-sub-superscript)
12215 (let (org-cdlatex-mode)
12216 (call-interactively (key-binding (vector last-input-event))))))
12218 (defun org-cdlatex-math-modify (&optional arg)
12219 "Execute `cdlatex-math-modify' in LaTeX fragments.
12220 Revert to the normal definition outside of these fragments."
12221 (interactive "P")
12222 (if (org-inside-LaTeX-fragment-p)
12223 (call-interactively 'cdlatex-math-modify)
12224 (let (org-cdlatex-mode)
12225 (call-interactively (key-binding (vector last-input-event))))))
12227 (defvar org-latex-fragment-image-overlays nil
12228 "List of overlays carrying the images of latex fragments.")
12229 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12231 (defun org-remove-latex-fragment-image-overlays ()
12232 "Remove all overlays with LaTeX fragment images in current buffer."
12233 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12234 (setq org-latex-fragment-image-overlays nil))
12236 (defun org-preview-latex-fragment (&optional subtree)
12237 "Preview the LaTeX fragment at point, or all locally or globally.
12238 If the cursor is in a LaTeX fragment, create the image and overlay
12239 it over the source code. If there is no fragment at point, display
12240 all fragments in the current text, from one headline to the next. With
12241 prefix SUBTREE, display all fragments in the current subtree. With a
12242 double prefix `C-u C-u', or when the cursor is before the first headline,
12243 display all fragments in the buffer.
12244 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12245 (interactive "P")
12246 (org-remove-latex-fragment-image-overlays)
12247 (save-excursion
12248 (save-restriction
12249 (let (beg end at msg)
12250 (cond
12251 ((or (equal subtree '(16))
12252 (not (save-excursion
12253 (re-search-backward (concat "^" outline-regexp) nil t))))
12254 (setq beg (point-min) end (point-max)
12255 msg "Creating images for buffer...%s"))
12256 ((equal subtree '(4))
12257 (org-back-to-heading)
12258 (setq beg (point) end (org-end-of-subtree t)
12259 msg "Creating images for subtree...%s"))
12261 (if (setq at (org-inside-LaTeX-fragment-p))
12262 (goto-char (max (point-min) (- (cdr at) 2)))
12263 (org-back-to-heading))
12264 (setq beg (point) end (progn (outline-next-heading) (point))
12265 msg (if at "Creating image...%s"
12266 "Creating images for entry...%s"))))
12267 (message msg "")
12268 (narrow-to-region beg end)
12269 (goto-char beg)
12270 (org-format-latex
12271 (concat "ltxpng/" (file-name-sans-extension
12272 (file-name-nondirectory
12273 buffer-file-name)))
12274 default-directory 'overlays msg at 'forbuffer)
12275 (message msg "done. Use `C-c C-c' to remove images.")))))
12277 (defvar org-latex-regexps
12278 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12279 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12280 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12281 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12282 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12283 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12284 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12285 "Regular expressions for matching embedded LaTeX.")
12287 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12288 "Replace LaTeX fragments with links to an image, and produce images."
12289 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12290 (let* ((prefixnodir (file-name-nondirectory prefix))
12291 (absprefix (expand-file-name prefix dir))
12292 (todir (file-name-directory absprefix))
12293 (opt org-format-latex-options)
12294 (matchers (plist-get opt :matchers))
12295 (re-list org-latex-regexps)
12296 (cnt 0) txt link beg end re e checkdir
12297 m n block linkfile movefile ov)
12298 ;; Check if there are old images files with this prefix, and remove them
12299 (when (file-directory-p todir)
12300 (mapc 'delete-file
12301 (directory-files
12302 todir 'full
12303 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12304 ;; Check the different regular expressions
12305 (while (setq e (pop re-list))
12306 (setq m (car e) re (nth 1 e) n (nth 2 e)
12307 block (if (nth 3 e) "\n\n" ""))
12308 (when (member m matchers)
12309 (goto-char (point-min))
12310 (while (re-search-forward re nil t)
12311 (when (or (not at) (equal (cdr at) (match-beginning n)))
12312 (setq txt (match-string n)
12313 beg (match-beginning n) end (match-end n)
12314 cnt (1+ cnt)
12315 linkfile (format "%s_%04d.png" prefix cnt)
12316 movefile (format "%s_%04d.png" absprefix cnt)
12317 link (concat block "[[file:" linkfile "]]" block))
12318 (if msg (message msg cnt))
12319 (goto-char beg)
12320 (unless checkdir ; make sure the directory exists
12321 (setq checkdir t)
12322 (or (file-directory-p todir) (make-directory todir)))
12323 (org-create-formula-image
12324 txt movefile opt forbuffer)
12325 (if overlays
12326 (progn
12327 (setq ov (org-make-overlay beg end))
12328 (if (featurep 'xemacs)
12329 (progn
12330 (org-overlay-put ov 'invisible t)
12331 (org-overlay-put
12332 ov 'end-glyph
12333 (make-glyph (vector 'png :file movefile))))
12334 (org-overlay-put
12335 ov 'display
12336 (list 'image :type 'png :file movefile :ascent 'center)))
12337 (push ov org-latex-fragment-image-overlays)
12338 (goto-char end))
12339 (delete-region beg end)
12340 (insert link))))))))
12342 ;; This function borrows from Ganesh Swami's latex2png.el
12343 (defun org-create-formula-image (string tofile options buffer)
12344 (let* ((tmpdir (if (featurep 'xemacs)
12345 (temp-directory)
12346 temporary-file-directory))
12347 (texfilebase (make-temp-name
12348 (expand-file-name "orgtex" tmpdir)))
12349 (texfile (concat texfilebase ".tex"))
12350 (dvifile (concat texfilebase ".dvi"))
12351 (pngfile (concat texfilebase ".png"))
12352 (fnh (if (featurep 'xemacs)
12353 (font-height (get-face-font 'default))
12354 (face-attribute 'default :height nil)))
12355 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12356 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12357 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12358 "Black"))
12359 (bg (or (plist-get options (if buffer :background :html-background))
12360 "Transparent")))
12361 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12362 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12363 (with-temp-file texfile
12364 (insert org-format-latex-header
12365 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12366 (let ((dir default-directory))
12367 (condition-case nil
12368 (progn
12369 (cd tmpdir)
12370 (call-process "latex" nil nil nil texfile))
12371 (error nil))
12372 (cd dir))
12373 (if (not (file-exists-p dvifile))
12374 (progn (message "Failed to create dvi file from %s" texfile) nil)
12375 (condition-case nil
12376 (call-process "dvipng" nil nil nil
12377 "-E" "-fg" fg "-bg" bg
12378 "-D" dpi
12379 ;;"-x" scale "-y" scale
12380 "-T" "tight"
12381 "-o" pngfile
12382 dvifile)
12383 (error nil))
12384 (if (not (file-exists-p pngfile))
12385 (progn (message "Failed to create png file from %s" texfile) nil)
12386 ;; Use the requested file name and clean up
12387 (copy-file pngfile tofile 'replace)
12388 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12389 (delete-file (concat texfilebase e)))
12390 pngfile))))
12392 (defun org-dvipng-color (attr)
12393 "Return an rgb color specification for dvipng."
12394 (apply 'format "rgb %s %s %s"
12395 (mapcar 'org-normalize-color
12396 (color-values (face-attribute 'default attr nil)))))
12398 (defun org-normalize-color (value)
12399 "Return string to be used as color value for an RGB component."
12400 (format "%g" (/ value 65535.0)))
12403 ;;;; Key bindings
12405 ;; Make `C-c C-x' a prefix key
12406 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12408 ;; TAB key with modifiers
12409 (org-defkey org-mode-map "\C-i" 'org-cycle)
12410 (org-defkey org-mode-map [(tab)] 'org-cycle)
12411 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12412 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12413 (org-defkey org-mode-map "\M-\t" 'org-complete)
12414 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12415 ;; The following line is necessary under Suse GNU/Linux
12416 (unless (featurep 'xemacs)
12417 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12418 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12419 (define-key org-mode-map [backtab] 'org-shifttab)
12421 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12422 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12423 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12425 ;; Cursor keys with modifiers
12426 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12427 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12428 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12429 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12431 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12432 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12433 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12434 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12436 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12437 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12438 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12439 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12441 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12442 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12444 ;;; Extra keys for tty access.
12445 ;; We only set them when really needed because otherwise the
12446 ;; menus don't show the simple keys
12448 (when (or org-use-extra-keys
12449 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12450 (not window-system))
12451 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12452 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12453 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12454 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12455 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12456 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12457 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12458 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12459 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12460 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12461 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12462 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12463 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12464 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12465 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12466 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12467 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12468 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12469 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12470 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12471 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12472 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12474 ;; All the other keys
12476 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12477 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12478 (if (boundp 'narrow-map)
12479 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12480 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12481 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12482 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12483 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12484 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12485 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12486 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12487 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12488 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12489 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12490 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12491 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12492 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12493 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12494 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12495 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12496 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12497 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12498 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12499 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12500 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12501 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12502 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12503 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12504 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12505 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12506 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12507 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12508 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12509 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12510 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12511 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12512 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12513 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12514 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12515 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12516 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12517 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12518 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12519 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12520 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12521 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12522 (org-defkey org-mode-map "\C-c^" 'org-sort)
12523 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12524 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12525 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12526 (org-defkey org-mode-map "\C-m" 'org-return)
12527 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12528 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12529 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12530 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12531 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12532 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12533 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12534 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12535 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12536 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12537 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12538 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12539 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12540 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12541 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12542 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12544 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12545 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12546 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12547 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12549 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12550 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12551 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12552 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12553 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12554 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12555 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12556 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12557 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12558 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12559 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12560 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12562 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12563 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12564 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12566 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12568 (when (featurep 'xemacs)
12569 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12571 (defvar org-table-auto-blank-field) ; defined in org-table.el
12572 (defun org-self-insert-command (N)
12573 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12574 If the cursor is in a table looking at whitespace, the whitespace is
12575 overwritten, and the table is not marked as requiring realignment."
12576 (interactive "p")
12577 (if (and (org-table-p)
12578 (progn
12579 ;; check if we blank the field, and if that triggers align
12580 (and (featurep 'org-table) org-table-auto-blank-field
12581 (member last-command
12582 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12583 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12584 ;; got extra space, this field does not determine column width
12585 (let (org-table-may-need-update) (org-table-blank-field))
12586 ;; no extra space, this field may determine column width
12587 (org-table-blank-field)))
12589 (eq N 1)
12590 (looking-at "[^|\n]* |"))
12591 (let (org-table-may-need-update)
12592 (goto-char (1- (match-end 0)))
12593 (delete-backward-char 1)
12594 (goto-char (match-beginning 0))
12595 (self-insert-command N))
12596 (setq org-table-may-need-update t)
12597 (self-insert-command N)
12598 (org-fix-tags-on-the-fly)))
12600 (defun org-fix-tags-on-the-fly ()
12601 (when (and (equal (char-after (point-at-bol)) ?*)
12602 (org-on-heading-p))
12603 (org-align-tags-here org-tags-column)))
12605 (defun org-delete-backward-char (N)
12606 "Like `delete-backward-char', insert whitespace at field end in tables.
12607 When deleting backwards, in tables this function will insert whitespace in
12608 front of the next \"|\" separator, to keep the table aligned. The table will
12609 still be marked for re-alignment if the field did fill the entire column,
12610 because, in this case the deletion might narrow the column."
12611 (interactive "p")
12612 (if (and (org-table-p)
12613 (eq N 1)
12614 (string-match "|" (buffer-substring (point-at-bol) (point)))
12615 (looking-at ".*?|"))
12616 (let ((pos (point))
12617 (noalign (looking-at "[^|\n\r]* |"))
12618 (c org-table-may-need-update))
12619 (backward-delete-char N)
12620 (skip-chars-forward "^|")
12621 (insert " ")
12622 (goto-char (1- pos))
12623 ;; noalign: if there were two spaces at the end, this field
12624 ;; does not determine the width of the column.
12625 (if noalign (setq org-table-may-need-update c)))
12626 (backward-delete-char N)
12627 (org-fix-tags-on-the-fly)))
12629 (defun org-delete-char (N)
12630 "Like `delete-char', but insert whitespace at field end in tables.
12631 When deleting characters, in tables this function will insert whitespace in
12632 front of the next \"|\" separator, to keep the table aligned. The table will
12633 still be marked for re-alignment if the field did fill the entire column,
12634 because, in this case the deletion might narrow the column."
12635 (interactive "p")
12636 (if (and (org-table-p)
12637 (not (bolp))
12638 (not (= (char-after) ?|))
12639 (eq N 1))
12640 (if (looking-at ".*?|")
12641 (let ((pos (point))
12642 (noalign (looking-at "[^|\n\r]* |"))
12643 (c org-table-may-need-update))
12644 (replace-match (concat
12645 (substring (match-string 0) 1 -1)
12646 " |"))
12647 (goto-char pos)
12648 ;; noalign: if there were two spaces at the end, this field
12649 ;; does not determine the width of the column.
12650 (if noalign (setq org-table-may-need-update c)))
12651 (delete-char N))
12652 (delete-char N)
12653 (org-fix-tags-on-the-fly)))
12655 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12656 (put 'org-self-insert-command 'delete-selection t)
12657 (put 'orgtbl-self-insert-command 'delete-selection t)
12658 (put 'org-delete-char 'delete-selection 'supersede)
12659 (put 'org-delete-backward-char 'delete-selection 'supersede)
12661 ;; Make `flyspell-mode' delay after some commands
12662 (put 'org-self-insert-command 'flyspell-delayed t)
12663 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12664 (put 'org-delete-char 'flyspell-delayed t)
12665 (put 'org-delete-backward-char 'flyspell-delayed t)
12667 ;; Make pabbrev-mode expand after org-mode commands
12668 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12669 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12671 ;; How to do this: Measure non-white length of current string
12672 ;; If equal to column width, we should realign.
12674 (defun org-remap (map &rest commands)
12675 "In MAP, remap the functions given in COMMANDS.
12676 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12677 (let (new old)
12678 (while commands
12679 (setq old (pop commands) new (pop commands))
12680 (if (fboundp 'command-remapping)
12681 (org-defkey map (vector 'remap old) new)
12682 (substitute-key-definition old new map global-map)))))
12684 (when (eq org-enable-table-editor 'optimized)
12685 ;; If the user wants maximum table support, we need to hijack
12686 ;; some standard editing functions
12687 (org-remap org-mode-map
12688 'self-insert-command 'org-self-insert-command
12689 'delete-char 'org-delete-char
12690 'delete-backward-char 'org-delete-backward-char)
12691 (org-defkey org-mode-map "|" 'org-force-self-insert))
12693 (defun org-shiftcursor-error ()
12694 "Throw an error because Shift-Cursor command was applied in wrong context."
12695 (error "This command is active in special context like tables, headlines or timestamps"))
12697 (defun org-shifttab (&optional arg)
12698 "Global visibility cycling or move to previous table field.
12699 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12700 on context.
12701 See the individual commands for more information."
12702 (interactive "P")
12703 (cond
12704 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12705 ((integerp arg)
12706 (message "Content view to level: %d" arg)
12707 (org-content (prefix-numeric-value arg))
12708 (setq org-cycle-global-status 'overview))
12709 (t (call-interactively 'org-global-cycle))))
12711 (defun org-shiftmetaleft ()
12712 "Promote subtree or delete table column.
12713 Calls `org-promote-subtree', `org-outdent-item',
12714 or `org-table-delete-column', depending on context.
12715 See the individual commands for more information."
12716 (interactive)
12717 (cond
12718 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12719 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12720 ((org-at-item-p) (call-interactively 'org-outdent-item))
12721 (t (org-shiftcursor-error))))
12723 (defun org-shiftmetaright ()
12724 "Demote subtree or insert table column.
12725 Calls `org-demote-subtree', `org-indent-item',
12726 or `org-table-insert-column', depending on context.
12727 See the individual commands for more information."
12728 (interactive)
12729 (cond
12730 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12731 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12732 ((org-at-item-p) (call-interactively 'org-indent-item))
12733 (t (org-shiftcursor-error))))
12735 (defun org-shiftmetaup (&optional arg)
12736 "Move subtree up or kill table row.
12737 Calls `org-move-subtree-up' or `org-table-kill-row' or
12738 `org-move-item-up' depending on context. See the individual commands
12739 for more information."
12740 (interactive "P")
12741 (cond
12742 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12743 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12744 ((org-at-item-p) (call-interactively 'org-move-item-up))
12745 (t (org-shiftcursor-error))))
12746 (defun org-shiftmetadown (&optional arg)
12747 "Move subtree down or insert table row.
12748 Calls `org-move-subtree-down' or `org-table-insert-row' or
12749 `org-move-item-down', depending on context. See the individual
12750 commands for more information."
12751 (interactive "P")
12752 (cond
12753 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12754 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12755 ((org-at-item-p) (call-interactively 'org-move-item-down))
12756 (t (org-shiftcursor-error))))
12758 (defun org-metaleft (&optional arg)
12759 "Promote heading or move table column to left.
12760 Calls `org-do-promote' or `org-table-move-column', depending on context.
12761 With no specific context, calls the Emacs default `backward-word'.
12762 See the individual commands for more information."
12763 (interactive "P")
12764 (cond
12765 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12766 ((or (org-on-heading-p) (org-region-active-p))
12767 (call-interactively 'org-do-promote))
12768 ((org-at-item-p) (call-interactively 'org-outdent-item))
12769 (t (call-interactively 'backward-word))))
12771 (defun org-metaright (&optional arg)
12772 "Demote subtree or move table column to right.
12773 Calls `org-do-demote' or `org-table-move-column', depending on context.
12774 With no specific context, calls the Emacs default `forward-word'.
12775 See the individual commands for more information."
12776 (interactive "P")
12777 (cond
12778 ((org-at-table-p) (call-interactively 'org-table-move-column))
12779 ((or (org-on-heading-p) (org-region-active-p))
12780 (call-interactively 'org-do-demote))
12781 ((org-at-item-p) (call-interactively 'org-indent-item))
12782 (t (call-interactively 'forward-word))))
12784 (defun org-metaup (&optional arg)
12785 "Move subtree up or move table row up.
12786 Calls `org-move-subtree-up' or `org-table-move-row' or
12787 `org-move-item-up', depending on context. See the individual commands
12788 for more information."
12789 (interactive "P")
12790 (cond
12791 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12792 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12793 ((org-at-item-p) (call-interactively 'org-move-item-up))
12794 (t (transpose-lines 1) (beginning-of-line -1))))
12796 (defun org-metadown (&optional arg)
12797 "Move subtree down or move table row down.
12798 Calls `org-move-subtree-down' or `org-table-move-row' or
12799 `org-move-item-down', depending on context. See the individual
12800 commands for more information."
12801 (interactive "P")
12802 (cond
12803 ((org-at-table-p) (call-interactively 'org-table-move-row))
12804 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12805 ((org-at-item-p) (call-interactively 'org-move-item-down))
12806 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12808 (defun org-shiftup (&optional arg)
12809 "Increase item in timestamp or increase priority of current headline.
12810 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12811 depending on context. See the individual commands for more information."
12812 (interactive "P")
12813 (cond
12814 ((org-at-timestamp-p t)
12815 (call-interactively (if org-edit-timestamp-down-means-later
12816 'org-timestamp-down 'org-timestamp-up)))
12817 ((org-on-heading-p) (call-interactively 'org-priority-up))
12818 ((org-at-item-p) (call-interactively 'org-previous-item))
12819 ((org-clocktable-try-shift 'up arg))
12820 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12822 (defun org-shiftdown (&optional arg)
12823 "Decrease item in timestamp or decrease priority of current headline.
12824 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12825 depending on context. See the individual commands for more information."
12826 (interactive "P")
12827 (cond
12828 ((org-at-timestamp-p t)
12829 (call-interactively (if org-edit-timestamp-down-means-later
12830 'org-timestamp-up 'org-timestamp-down)))
12831 ((org-on-heading-p) (call-interactively 'org-priority-down))
12832 ((org-clocktable-try-shift 'down arg))
12833 (t (call-interactively 'org-next-item))))
12835 (defun org-shiftright (&optional arg)
12836 "Cycle the thing at point or in the current line, depending on context.
12837 Depending on context, this does one of the following:
12839 - switch a timestamp at point one day into the future
12840 - on a headline, switch to the next TODO keyword.
12841 - on an item, switch entire list to the next bullet type
12842 - on a property line, switch to the next allowed value
12843 - on a clocktable definition line, move time block into the future"
12844 (interactive "P")
12845 (cond
12846 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12847 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12848 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12849 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12850 ((org-clocktable-try-shift 'right arg))
12851 (t (org-shiftcursor-error))))
12853 (defun org-shiftleft (&optional arg)
12854 "Cycle the thing at point or in the current line, depending on context.
12855 Depending on context, this does one of the following:
12857 - switch a timestamp at point one day into the past
12858 - on a headline, switch to the previous TODO keyword.
12859 - on an item, switch entire list to the previous bullet type
12860 - on a property line, switch to the previous allowed value
12861 - on a clocktable definition line, move time block into the past"
12862 (interactive "P")
12863 (cond
12864 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12865 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12866 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12867 ((org-at-property-p)
12868 (call-interactively 'org-property-previous-allowed-value))
12869 ((org-clocktable-try-shift 'left arg))
12870 (t (org-shiftcursor-error))))
12872 (defun org-shiftcontrolright ()
12873 "Switch to next TODO set."
12874 (interactive)
12875 (cond
12876 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12877 (t (org-shiftcursor-error))))
12879 (defun org-shiftcontrolleft ()
12880 "Switch to previous TODO set."
12881 (interactive)
12882 (cond
12883 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12884 (t (org-shiftcursor-error))))
12886 (defun org-ctrl-c-ret ()
12887 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12888 (interactive)
12889 (cond
12890 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12891 (t (call-interactively 'org-insert-heading))))
12893 (defun org-copy-special ()
12894 "Copy region in table or copy current subtree.
12895 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12896 See the individual commands for more information."
12897 (interactive)
12898 (call-interactively
12899 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12901 (defun org-cut-special ()
12902 "Cut region in table or cut current subtree.
12903 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12904 See the individual commands for more information."
12905 (interactive)
12906 (call-interactively
12907 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12909 (defun org-paste-special (arg)
12910 "Paste rectangular region into table, or past subtree relative to level.
12911 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12912 See the individual commands for more information."
12913 (interactive "P")
12914 (if (org-at-table-p)
12915 (org-table-paste-rectangle)
12916 (org-paste-subtree arg)))
12918 (defun org-edit-special ()
12919 "Call a special editor for the stuff at point.
12920 When at a table, call the formula editor with `org-table-edit-formulas'.
12921 When at the first line of an src example, call `org-edit-src-code'.
12922 When in an #+include line, visit the include file. Otherwise call
12923 `ffap' to visit the file at point."
12924 (interactive)
12925 (cond
12926 ((org-at-table-p)
12927 (call-interactively 'org-table-edit-formulas))
12928 ((save-excursion
12929 (beginning-of-line 1)
12930 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12931 (find-file (org-trim (match-string 1))))
12932 ((org-edit-src-code))
12933 ((org-edit-fixed-width-region))
12934 (t (call-interactively 'ffap))))
12936 (defun org-ctrl-c-ctrl-c (&optional arg)
12937 "Set tags in headline, or update according to changed information at point.
12939 This command does many different things, depending on context:
12941 - If the cursor is in a headline, prompt for tags and insert them
12942 into the current line, aligned to `org-tags-column'. When called
12943 with prefix arg, realign all tags in the current buffer.
12945 - If the cursor is in one of the special #+KEYWORD lines, this
12946 triggers scanning the buffer for these lines and updating the
12947 information.
12949 - If the cursor is inside a table, realign the table. This command
12950 works even if the automatic table editor has been turned off.
12952 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12953 the entire table.
12955 - If the cursor is a the beginning of a dynamic block, update it.
12957 - If the cursor is inside a table created by the table.el package,
12958 activate that table.
12960 - If the current buffer is a remember buffer, close note and file
12961 it. A prefix argument of 1 files to the default location
12962 without further interaction. A prefix argument of 2 files to
12963 the currently clocking task.
12965 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12966 links in this buffer.
12968 - If the cursor is on a numbered item in a plain list, renumber the
12969 ordered list.
12971 - If the cursor is on a checkbox, toggle it."
12972 (interactive "P")
12973 (let ((org-enable-table-editor t))
12974 (cond
12975 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12976 org-occur-highlights
12977 org-latex-fragment-image-overlays)
12978 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12979 (org-remove-occur-highlights)
12980 (org-remove-latex-fragment-image-overlays)
12981 (message "Temporary highlights/overlays removed from current buffer"))
12982 ((and (local-variable-p 'org-finish-function (current-buffer))
12983 (fboundp org-finish-function))
12984 (funcall org-finish-function))
12985 ((org-at-property-p)
12986 (call-interactively 'org-property-action))
12987 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12988 ((org-on-heading-p) (call-interactively 'org-set-tags))
12989 ((org-at-table.el-p)
12990 (require 'table)
12991 (beginning-of-line 1)
12992 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12993 (call-interactively 'table-recognize-table))
12994 ((org-at-table-p)
12995 (org-table-maybe-eval-formula)
12996 (if arg
12997 (call-interactively 'org-table-recalculate)
12998 (org-table-maybe-recalculate-line))
12999 (call-interactively 'org-table-align))
13000 ((org-at-item-checkbox-p)
13001 (call-interactively 'org-toggle-checkbox))
13002 ((org-at-item-p)
13003 (call-interactively 'org-maybe-renumber-ordered-list))
13004 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13005 ;; Dynamic block
13006 (beginning-of-line 1)
13007 (save-excursion (org-update-dblock)))
13008 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13009 (cond
13010 ((equal (match-string 1) "TBLFM")
13011 ;; Recalculate the table before this line
13012 (save-excursion
13013 (beginning-of-line 1)
13014 (skip-chars-backward " \r\n\t")
13015 (if (org-at-table-p)
13016 (org-call-with-arg 'org-table-recalculate t))))
13018 ; (org-set-regexps-and-options)
13019 ; (org-restart-font-lock)
13020 (let ((org-inhibit-startup t)) (org-mode-restart))
13021 (message "Local setup has been refreshed"))))
13022 (t (error "C-c C-c can do nothing useful at this location.")))))
13024 (defun org-mode-restart ()
13025 "Restart Org-mode, to scan again for special lines.
13026 Also updates the keyword regular expressions."
13027 (interactive)
13028 (org-mode)
13029 (message "Org-mode restarted"))
13031 (defun org-kill-note-or-show-branches ()
13032 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13033 (interactive)
13034 (if (not org-finish-function)
13035 (call-interactively 'show-branches)
13036 (let ((org-note-abort t))
13037 (funcall org-finish-function))))
13039 (defun org-return (&optional indent)
13040 "Goto next table row or insert a newline.
13041 Calls `org-table-next-row' or `newline', depending on context.
13042 See the individual commands for more information."
13043 (interactive)
13044 (cond
13045 ((bobp) (if indent (newline-and-indent) (newline)))
13046 ((and (org-at-heading-p)
13047 (looking-at
13048 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13049 (org-show-entry)
13050 (end-of-line 1)
13051 (newline))
13052 ((org-at-table-p)
13053 (org-table-justify-field-maybe)
13054 (call-interactively 'org-table-next-row))
13055 (t (if indent (newline-and-indent) (newline)))))
13057 (defun org-return-indent ()
13058 "Goto next table row or insert a newline and indent.
13059 Calls `org-table-next-row' or `newline-and-indent', depending on
13060 context. See the individual commands for more information."
13061 (interactive)
13062 (org-return t))
13064 (defun org-ctrl-c-star ()
13065 "Compute table, or change heading status of lines.
13066 Calls `org-table-recalculate' or `org-toggle-region-headings',
13067 depending on context. This will also turn a plain list item or a normal
13068 line into a subheading."
13069 (interactive)
13070 (cond
13071 ((org-at-table-p)
13072 (call-interactively 'org-table-recalculate))
13073 ((org-region-active-p)
13074 ;; Convert all lines in region to list items
13075 (call-interactively 'org-toggle-region-headings))
13076 ((org-on-heading-p)
13077 (org-toggle-region-headings (point-at-bol)
13078 (min (1+ (point-at-eol)) (point-max))))
13079 ((org-at-item-p)
13080 ;; Convert to heading
13081 (let ((level (save-match-data
13082 (save-excursion
13083 (condition-case nil
13084 (progn
13085 (org-back-to-heading t)
13086 (funcall outline-level))
13087 (error 0))))))
13088 (replace-match
13089 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13090 (t (org-toggle-region-headings (point-at-bol)
13091 (min (1+ (point-at-eol)) (point-max))))))
13093 (defun org-ctrl-c-minus ()
13094 "Insert separator line in table or modify bullet status of line.
13095 Also turns a plain line or a region of lines into list items.
13096 Calls `org-table-insert-hline', `org-toggle-region-items', or
13097 `org-cycle-list-bullet', depending on context."
13098 (interactive)
13099 (cond
13100 ((org-at-table-p)
13101 (call-interactively 'org-table-insert-hline))
13102 ((org-on-heading-p)
13103 ;; Convert to item
13104 (save-excursion
13105 (beginning-of-line 1)
13106 (if (looking-at "\\*+ ")
13107 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13108 ((org-region-active-p)
13109 ;; Convert all lines in region to list items
13110 (call-interactively 'org-toggle-region-items))
13111 ((org-in-item-p)
13112 (call-interactively 'org-cycle-list-bullet))
13113 (t (org-toggle-region-items (point-at-bol)
13114 (min (1+ (point-at-eol)) (point-max))))))
13116 (defun org-toggle-region-items (beg end)
13117 "Convert all lines in region to list items.
13118 If the first line is already an item, convert all list items in the region
13119 to normal lines."
13120 (interactive "r")
13121 (let (l2 l)
13122 (save-excursion
13123 (goto-char end)
13124 (setq l2 (org-current-line))
13125 (goto-char beg)
13126 (beginning-of-line 1)
13127 (setq l (1- (org-current-line)))
13128 (if (org-at-item-p)
13129 ;; We already have items, de-itemize
13130 (while (< (setq l (1+ l)) l2)
13131 (when (org-at-item-p)
13132 (goto-char (match-beginning 2))
13133 (delete-region (match-beginning 2) (match-end 2))
13134 (and (looking-at "[ \t]+") (replace-match "")))
13135 (beginning-of-line 2))
13136 (while (< (setq l (1+ l)) l2)
13137 (unless (org-at-item-p)
13138 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13139 (replace-match "\\1- \\2")))
13140 (beginning-of-line 2))))))
13142 (defun org-toggle-region-headings (beg end)
13143 "Convert all lines in region to list items.
13144 If the first line is already an item, convert all list items in the region
13145 to normal lines."
13146 (interactive "r")
13147 (let (l2 l)
13148 (save-excursion
13149 (goto-char end)
13150 (setq l2 (org-current-line))
13151 (goto-char beg)
13152 (beginning-of-line 1)
13153 (setq l (1- (org-current-line)))
13154 (if (org-on-heading-p)
13155 ;; We already have headlines, de-star them
13156 (while (< (setq l (1+ l)) l2)
13157 (when (org-on-heading-p t)
13158 (and (looking-at outline-regexp) (replace-match "")))
13159 (beginning-of-line 2))
13160 (let* ((stars (save-excursion
13161 (re-search-backward org-complex-heading-regexp nil t)
13162 (or (match-string 1) "*")))
13163 (add-stars (if org-odd-levels-only "**" "*"))
13164 (rpl (concat stars add-stars " \\2")))
13165 (while (< (setq l (1+ l)) l2)
13166 (unless (org-on-heading-p)
13167 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13168 (replace-match rpl)))
13169 (beginning-of-line 2)))))))
13171 (defun org-meta-return (&optional arg)
13172 "Insert a new heading or wrap a region in a table.
13173 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13174 See the individual commands for more information."
13175 (interactive "P")
13176 (cond
13177 ((org-at-table-p)
13178 (call-interactively 'org-table-wrap-region))
13179 (t (call-interactively 'org-insert-heading))))
13181 ;;; Menu entries
13183 ;; Define the Org-mode menus
13184 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13185 '("Tbl"
13186 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13187 ["Next Field" org-cycle (org-at-table-p)]
13188 ["Previous Field" org-shifttab (org-at-table-p)]
13189 ["Next Row" org-return (org-at-table-p)]
13190 "--"
13191 ["Blank Field" org-table-blank-field (org-at-table-p)]
13192 ["Edit Field" org-table-edit-field (org-at-table-p)]
13193 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13194 "--"
13195 ("Column"
13196 ["Move Column Left" org-metaleft (org-at-table-p)]
13197 ["Move Column Right" org-metaright (org-at-table-p)]
13198 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13199 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13200 ("Row"
13201 ["Move Row Up" org-metaup (org-at-table-p)]
13202 ["Move Row Down" org-metadown (org-at-table-p)]
13203 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13204 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13205 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13206 "--"
13207 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13208 ("Rectangle"
13209 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13210 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13211 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13212 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13213 "--"
13214 ("Calculate"
13215 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13216 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13217 ["Edit Formulas" org-edit-special (org-at-table-p)]
13218 "--"
13219 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13220 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13221 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13222 "--"
13223 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13224 "--"
13225 ["Sum Column/Rectangle" org-table-sum
13226 (or (org-at-table-p) (org-region-active-p))]
13227 ["Which Column?" org-table-current-column (org-at-table-p)])
13228 ["Debug Formulas"
13229 org-table-toggle-formula-debugger
13230 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13231 ["Show Col/Row Numbers"
13232 org-table-toggle-coordinate-overlays
13233 :style toggle
13234 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13235 "--"
13236 ["Create" org-table-create (and (not (org-at-table-p))
13237 org-enable-table-editor)]
13238 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13239 ["Import from File" org-table-import (not (org-at-table-p))]
13240 ["Export to File" org-table-export (org-at-table-p)]
13241 "--"
13242 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13244 (easy-menu-define org-org-menu org-mode-map "Org menu"
13245 '("Org"
13246 ("Show/Hide"
13247 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13248 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13249 ["Sparse Tree..." org-sparse-tree t]
13250 ["Reveal Context" org-reveal t]
13251 ["Show All" show-all t]
13252 "--"
13253 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13254 "--"
13255 ["New Heading" org-insert-heading t]
13256 ("Navigate Headings"
13257 ["Up" outline-up-heading t]
13258 ["Next" outline-next-visible-heading t]
13259 ["Previous" outline-previous-visible-heading t]
13260 ["Next Same Level" outline-forward-same-level t]
13261 ["Previous Same Level" outline-backward-same-level t]
13262 "--"
13263 ["Jump" org-goto t])
13264 ("Edit Structure"
13265 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13266 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13267 "--"
13268 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13269 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13270 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13271 "--"
13272 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13273 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13274 ["Demote Heading" org-metaright (not (org-at-table-p))]
13275 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13276 "--"
13277 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13278 "--"
13279 ["Convert to odd levels" org-convert-to-odd-levels t]
13280 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13281 ("Editing"
13282 ["Emphasis..." org-emphasize t]
13283 ["Edit Source Example" org-edit-special t])
13284 ("Archive"
13285 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13286 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13287 ; :active t :keys "C-u C-c C-x C-a"]
13288 ["Sparse trees open ARCHIVE trees"
13289 (setq org-sparse-tree-open-archived-trees
13290 (not org-sparse-tree-open-archived-trees))
13291 :style toggle :selected org-sparse-tree-open-archived-trees]
13292 ["Cycling opens ARCHIVE trees"
13293 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13294 :style toggle :selected org-cycle-open-archived-trees]
13295 "--"
13296 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13297 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13298 ; ["Check and Move Children" (org-archive-subtree '(4))
13299 ; :active t :keys "C-u C-c C-x C-s"]
13301 "--"
13302 ("TODO Lists"
13303 ["TODO/DONE/-" org-todo t]
13304 ("Select keyword"
13305 ["Next keyword" org-shiftright (org-on-heading-p)]
13306 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13307 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13308 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13309 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13310 ["Show TODO Tree" org-show-todo-tree t]
13311 ["Global TODO list" org-todo-list t]
13312 "--"
13313 ["Set Priority" org-priority t]
13314 ["Priority Up" org-shiftup t]
13315 ["Priority Down" org-shiftdown t])
13316 ("TAGS and Properties"
13317 ["Set Tags" 'org-set-tags-command t]
13318 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13319 "--"
13320 ["Set property" 'org-set-property t]
13321 ["Column view of properties" org-columns t]
13322 ["Insert Column View DBlock" org-insert-columns-dblock t])
13323 ("Dates and Scheduling"
13324 ["Timestamp" org-time-stamp t]
13325 ["Timestamp (inactive)" org-time-stamp-inactive t]
13326 ("Change Date"
13327 ["1 Day Later" org-shiftright t]
13328 ["1 Day Earlier" org-shiftleft t]
13329 ["1 ... Later" org-shiftup t]
13330 ["1 ... Earlier" org-shiftdown t])
13331 ["Compute Time Range" org-evaluate-time-range t]
13332 ["Schedule Item" org-schedule t]
13333 ["Deadline" org-deadline t]
13334 "--"
13335 ["Custom time format" org-toggle-time-stamp-overlays
13336 :style radio :selected org-display-custom-times]
13337 "--"
13338 ["Goto Calendar" org-goto-calendar t]
13339 ["Date from Calendar" org-date-from-calendar t]
13340 "--"
13341 ["Start/restart timer" org-timer-start t]
13342 ["Insert timer string" org-timer t]
13343 ["Insert timer item" org-timer-item t])
13344 ("Logging work"
13345 ["Clock in" org-clock-in t]
13346 ["Clock out" org-clock-out t]
13347 ["Clock cancel" org-clock-cancel t]
13348 ["Goto running clock" org-clock-goto t]
13349 ["Display times" org-clock-display t]
13350 ["Create clock table" org-clock-report t]
13351 "--"
13352 ["Record DONE time"
13353 (progn (setq org-log-done (not org-log-done))
13354 (message "Switching to %s will %s record a timestamp"
13355 (car org-done-keywords)
13356 (if org-log-done "automatically" "not")))
13357 :style toggle :selected org-log-done])
13358 "--"
13359 ["Agenda Command..." org-agenda t]
13360 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13361 ("File List for Agenda")
13362 ("Special views current file"
13363 ["TODO Tree" org-show-todo-tree t]
13364 ["Check Deadlines" org-check-deadlines t]
13365 ["Timeline" org-timeline t]
13366 ["Tags Tree" org-tags-sparse-tree t])
13367 "--"
13368 ("Hyperlinks"
13369 ["Store Link (Global)" org-store-link t]
13370 ["Insert Link" org-insert-link t]
13371 ["Follow Link" org-open-at-point t]
13372 "--"
13373 ["Next link" org-next-link t]
13374 ["Previous link" org-previous-link t]
13375 "--"
13376 ["Descriptive Links"
13377 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13378 :style radio
13379 :selected (member '(org-link) buffer-invisibility-spec)]
13380 ["Literal Links"
13381 (progn
13382 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13383 :style radio
13384 :selected (not (member '(org-link) buffer-invisibility-spec))])
13385 "--"
13386 ["Export/Publish..." org-export t]
13387 ("LaTeX"
13388 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13389 :selected org-cdlatex-mode]
13390 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13391 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13392 ["Modify math symbol" org-cdlatex-math-modify
13393 (org-inside-LaTeX-fragment-p)]
13394 ["Export LaTeX fragments as images"
13395 (if (featurep 'org-exp)
13396 (setq org-export-with-LaTeX-fragments
13397 (not org-export-with-LaTeX-fragments))
13398 (require 'org-exp))
13399 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13400 org-export-with-LaTeX-fragments)])
13401 "--"
13402 ("Documentation"
13403 ["Show Version" org-version t]
13404 ["Info Documentation" org-info t])
13405 ("Customize"
13406 ["Browse Org Group" org-customize t]
13407 "--"
13408 ["Expand This Menu" org-create-customize-menu
13409 (fboundp 'customize-menu-create)])
13410 "--"
13411 ["Refresh setup" org-mode-restart t]
13414 (defun org-info (&optional node)
13415 "Read documentation for Org-mode in the info system.
13416 With optional NODE, go directly to that node."
13417 (interactive)
13418 (info (format "(org)%s" (or node ""))))
13420 (defun org-install-agenda-files-menu ()
13421 (let ((bl (buffer-list)))
13422 (save-excursion
13423 (while bl
13424 (set-buffer (pop bl))
13425 (if (org-mode-p) (setq bl nil)))
13426 (when (org-mode-p)
13427 (easy-menu-change
13428 '("Org") "File List for Agenda"
13429 (append
13430 (list
13431 ["Edit File List" (org-edit-agenda-file-list) t]
13432 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13433 ["Remove Current File from List" org-remove-file t]
13434 ["Cycle through agenda files" org-cycle-agenda-files t]
13435 ["Occur in all agenda files" org-occur-in-agenda-files t]
13436 "--")
13437 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13439 ;;;; Documentation
13441 ;;;###autoload
13442 (defun org-require-autoloaded-modules ()
13443 (interactive)
13444 (mapc 'require
13445 '(org-agenda org-archive org-clock org-colview
13446 org-exp org-id org-export-latex org-publish
13447 org-remember org-table)))
13449 ;;;###autoload
13450 (defun org-customize ()
13451 "Call the customize function with org as argument."
13452 (interactive)
13453 (org-load-modules-maybe)
13454 (org-require-autoloaded-modules)
13455 (customize-browse 'org))
13457 (defun org-create-customize-menu ()
13458 "Create a full customization menu for Org-mode, insert it into the menu."
13459 (interactive)
13460 (org-load-modules-maybe)
13461 (org-require-autoloaded-modules)
13462 (if (fboundp 'customize-menu-create)
13463 (progn
13464 (easy-menu-change
13465 '("Org") "Customize"
13466 `(["Browse Org group" org-customize t]
13467 "--"
13468 ,(customize-menu-create 'org)
13469 ["Set" Custom-set t]
13470 ["Save" Custom-save t]
13471 ["Reset to Current" Custom-reset-current t]
13472 ["Reset to Saved" Custom-reset-saved t]
13473 ["Reset to Standard Settings" Custom-reset-standard t]))
13474 (message "\"Org\"-menu now contains full customization menu"))
13475 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13477 ;;;; Miscellaneous stuff
13479 ;;; Generally useful functions
13481 (defun org-find-text-property-in-string (prop s)
13482 "Return the first non-nil value of property PROP in string S."
13483 (or (get-text-property 0 prop s)
13484 (get-text-property (or (next-single-property-change 0 prop s) 0)
13485 prop s)))
13487 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13488 "Display the given MESSAGE as a warning."
13489 (if (fboundp 'display-warning)
13490 (display-warning 'org message
13491 (if (featurep 'xemacs)
13492 'warning
13493 :warning))
13494 (let ((buf (get-buffer-create "*Org warnings*")))
13495 (with-current-buffer buf
13496 (goto-char (point-max))
13497 (insert "Warning (Org): " message)
13498 (unless (bolp)
13499 (newline)))
13500 (display-buffer buf)
13501 (sit-for 0))))
13503 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13504 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13505 (if (and marker (marker-buffer marker)
13506 (buffer-live-p (marker-buffer marker)))
13507 (progn
13508 (switch-to-buffer (marker-buffer marker))
13509 (if (or (> marker (point-max)) (< marker (point-min)))
13510 (widen))
13511 (goto-char marker))
13512 (if bookmark
13513 (bookmark-jump bookmark)
13514 (error "Cannot find location"))))
13516 (defun org-quote-csv-field (s)
13517 "Quote field for inclusion in CSV material."
13518 (if (string-match "[\",]" s)
13519 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13522 (defun org-plist-delete (plist property)
13523 "Delete PROPERTY from PLIST.
13524 This is in contrast to merely setting it to 0."
13525 (let (p)
13526 (while plist
13527 (if (not (eq property (car plist)))
13528 (setq p (plist-put p (car plist) (nth 1 plist))))
13529 (setq plist (cddr plist)))
13532 (defun org-force-self-insert (N)
13533 "Needed to enforce self-insert under remapping."
13534 (interactive "p")
13535 (self-insert-command N))
13537 (defun org-string-width (s)
13538 "Compute width of string, ignoring invisible characters.
13539 This ignores character with invisibility property `org-link', and also
13540 characters with property `org-cwidth', because these will become invisible
13541 upon the next fontification round."
13542 (let (b l)
13543 (when (or (eq t buffer-invisibility-spec)
13544 (assq 'org-link buffer-invisibility-spec))
13545 (while (setq b (text-property-any 0 (length s)
13546 'invisible 'org-link s))
13547 (setq s (concat (substring s 0 b)
13548 (substring s (or (next-single-property-change
13549 b 'invisible s) (length s)))))))
13550 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13551 (setq s (concat (substring s 0 b)
13552 (substring s (or (next-single-property-change
13553 b 'org-cwidth s) (length s))))))
13554 (setq l (string-width s) b -1)
13555 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13556 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13559 (defun org-get-indentation (&optional line)
13560 "Get the indentation of the current line, interpreting tabs.
13561 When LINE is given, assume it represents a line and compute its indentation."
13562 (if line
13563 (if (string-match "^ *" (org-remove-tabs line))
13564 (match-end 0))
13565 (save-excursion
13566 (beginning-of-line 1)
13567 (skip-chars-forward " \t")
13568 (current-column))))
13570 (defun org-remove-tabs (s &optional width)
13571 "Replace tabulators in S with spaces.
13572 Assumes that s is a single line, starting in column 0."
13573 (setq width (or width tab-width))
13574 (while (string-match "\t" s)
13575 (setq s (replace-match
13576 (make-string
13577 (- (* width (/ (+ (match-beginning 0) width) width))
13578 (match-beginning 0)) ?\ )
13579 t t s)))
13582 (defun org-fix-indentation (line ind)
13583 "Fix indentation in LINE.
13584 IND is a cons cell with target and minimum indentation.
13585 If the current indenation in LINE is smaller than the minimum,
13586 leave it alone. If it is larger than ind, set it to the target."
13587 (let* ((l (org-remove-tabs line))
13588 (i (org-get-indentation l))
13589 (i1 (car ind)) (i2 (cdr ind)))
13590 (if (>= i i2) (setq l (substring line i2)))
13591 (if (> i1 0)
13592 (concat (make-string i1 ?\ ) l)
13593 l)))
13595 (defun org-base-buffer (buffer)
13596 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13597 (if (not buffer)
13598 buffer
13599 (or (buffer-base-buffer buffer)
13600 buffer)))
13602 (defun org-trim (s)
13603 "Remove whitespace at beginning and end of string."
13604 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13605 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13608 (defun org-wrap (string &optional width lines)
13609 "Wrap string to either a number of lines, or a width in characters.
13610 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13611 that costs. If there is a word longer than WIDTH, the text is actually
13612 wrapped to the length of that word.
13613 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13614 many lines, whatever width that takes.
13615 The return value is a list of lines, without newlines at the end."
13616 (let* ((words (org-split-string string "[ \t\n]+"))
13617 (maxword (apply 'max (mapcar 'org-string-width words)))
13618 w ll)
13619 (cond (width
13620 (org-do-wrap words (max maxword width)))
13621 (lines
13622 (setq w maxword)
13623 (setq ll (org-do-wrap words maxword))
13624 (if (<= (length ll) lines)
13626 (setq ll words)
13627 (while (> (length ll) lines)
13628 (setq w (1+ w))
13629 (setq ll (org-do-wrap words w)))
13630 ll))
13631 (t (error "Cannot wrap this")))))
13633 (defun org-do-wrap (words width)
13634 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13635 (let (lines line)
13636 (while words
13637 (setq line (pop words))
13638 (while (and words (< (+ (length line) (length (car words))) width))
13639 (setq line (concat line " " (pop words))))
13640 (setq lines (push line lines)))
13641 (nreverse lines)))
13643 (defun org-split-string (string &optional separators)
13644 "Splits STRING into substrings at SEPARATORS.
13645 No empty strings are returned if there are matches at the beginning
13646 and end of string."
13647 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13648 (start 0)
13649 notfirst
13650 (list nil))
13651 (while (and (string-match rexp string
13652 (if (and notfirst
13653 (= start (match-beginning 0))
13654 (< start (length string)))
13655 (1+ start) start))
13656 (< (match-beginning 0) (length string)))
13657 (setq notfirst t)
13658 (or (eq (match-beginning 0) 0)
13659 (and (eq (match-beginning 0) (match-end 0))
13660 (eq (match-beginning 0) start))
13661 (setq list
13662 (cons (substring string start (match-beginning 0))
13663 list)))
13664 (setq start (match-end 0)))
13665 (or (eq start (length string))
13666 (setq list
13667 (cons (substring string start)
13668 list)))
13669 (nreverse list)))
13671 (defun org-context ()
13672 "Return a list of contexts of the current cursor position.
13673 If several contexts apply, all are returned.
13674 Each context entry is a list with a symbol naming the context, and
13675 two positions indicating start and end of the context. Possible
13676 contexts are:
13678 :headline anywhere in a headline
13679 :headline-stars on the leading stars in a headline
13680 :todo-keyword on a TODO keyword (including DONE) in a headline
13681 :tags on the TAGS in a headline
13682 :priority on the priority cookie in a headline
13683 :item on the first line of a plain list item
13684 :item-bullet on the bullet/number of a plain list item
13685 :checkbox on the checkbox in a plain list item
13686 :table in an org-mode table
13687 :table-special on a special filed in a table
13688 :table-table in a table.el table
13689 :link on a hyperlink
13690 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13691 :target on a <<target>>
13692 :radio-target on a <<<radio-target>>>
13693 :latex-fragment on a LaTeX fragment
13694 :latex-preview on a LaTeX fragment with overlayed preview image
13696 This function expects the position to be visible because it uses font-lock
13697 faces as a help to recognize the following contexts: :table-special, :link,
13698 and :keyword."
13699 (let* ((f (get-text-property (point) 'face))
13700 (faces (if (listp f) f (list f)))
13701 (p (point)) clist o)
13702 ;; First the large context
13703 (cond
13704 ((org-on-heading-p t)
13705 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13706 (when (progn
13707 (beginning-of-line 1)
13708 (looking-at org-todo-line-tags-regexp))
13709 (push (org-point-in-group p 1 :headline-stars) clist)
13710 (push (org-point-in-group p 2 :todo-keyword) clist)
13711 (push (org-point-in-group p 4 :tags) clist))
13712 (goto-char p)
13713 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13714 (if (looking-at "\\[#[A-Z0-9]\\]")
13715 (push (org-point-in-group p 0 :priority) clist)))
13717 ((org-at-item-p)
13718 (push (org-point-in-group p 2 :item-bullet) clist)
13719 (push (list :item (point-at-bol)
13720 (save-excursion (org-end-of-item) (point)))
13721 clist)
13722 (and (org-at-item-checkbox-p)
13723 (push (org-point-in-group p 0 :checkbox) clist)))
13725 ((org-at-table-p)
13726 (push (list :table (org-table-begin) (org-table-end)) clist)
13727 (if (memq 'org-formula faces)
13728 (push (list :table-special
13729 (previous-single-property-change p 'face)
13730 (next-single-property-change p 'face)) clist)))
13731 ((org-at-table-p 'any)
13732 (push (list :table-table) clist)))
13733 (goto-char p)
13735 ;; Now the small context
13736 (cond
13737 ((org-at-timestamp-p)
13738 (push (org-point-in-group p 0 :timestamp) clist))
13739 ((memq 'org-link faces)
13740 (push (list :link
13741 (previous-single-property-change p 'face)
13742 (next-single-property-change p 'face)) clist))
13743 ((memq 'org-special-keyword faces)
13744 (push (list :keyword
13745 (previous-single-property-change p 'face)
13746 (next-single-property-change p 'face)) clist))
13747 ((org-on-target-p)
13748 (push (org-point-in-group p 0 :target) clist)
13749 (goto-char (1- (match-beginning 0)))
13750 (if (looking-at org-radio-target-regexp)
13751 (push (org-point-in-group p 0 :radio-target) clist))
13752 (goto-char p))
13753 ((setq o (car (delq nil
13754 (mapcar
13755 (lambda (x)
13756 (if (memq x org-latex-fragment-image-overlays) x))
13757 (org-overlays-at (point))))))
13758 (push (list :latex-fragment
13759 (org-overlay-start o) (org-overlay-end o)) clist)
13760 (push (list :latex-preview
13761 (org-overlay-start o) (org-overlay-end o)) clist))
13762 ((org-inside-LaTeX-fragment-p)
13763 ;; FIXME: positions wrong.
13764 (push (list :latex-fragment (point) (point)) clist)))
13766 (setq clist (nreverse (delq nil clist)))
13767 clist))
13769 ;; FIXME: Compare with at-regexp-p Do we need both?
13770 (defun org-in-regexp (re &optional nlines visually)
13771 "Check if point is inside a match of regexp.
13772 Normally only the current line is checked, but you can include NLINES extra
13773 lines both before and after point into the search.
13774 If VISUALLY is set, require that the cursor is not after the match but
13775 really on, so that the block visually is on the match."
13776 (catch 'exit
13777 (let ((pos (point))
13778 (eol (point-at-eol (+ 1 (or nlines 0))))
13779 (inc (if visually 1 0)))
13780 (save-excursion
13781 (beginning-of-line (- 1 (or nlines 0)))
13782 (while (re-search-forward re eol t)
13783 (if (and (<= (match-beginning 0) pos)
13784 (>= (+ inc (match-end 0)) pos))
13785 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13787 (defun org-at-regexp-p (regexp)
13788 "Is point inside a match of REGEXP in the current line?"
13789 (catch 'exit
13790 (save-excursion
13791 (let ((pos (point)) (end (point-at-eol)))
13792 (beginning-of-line 1)
13793 (while (re-search-forward regexp end t)
13794 (if (and (<= (match-beginning 0) pos)
13795 (>= (match-end 0) pos))
13796 (throw 'exit t)))
13797 nil))))
13799 (defun org-occur-in-agenda-files (regexp &optional nlines)
13800 "Call `multi-occur' with buffers for all agenda files."
13801 (interactive "sOrg-files matching: \np")
13802 (let* ((files (org-agenda-files))
13803 (tnames (mapcar 'file-truename files))
13804 (extra org-agenda-text-search-extra-files)
13806 (when (eq (car extra) 'agenda-archives)
13807 (setq extra (cdr extra))
13808 (setq files (org-add-archive-files files)))
13809 (while (setq f (pop extra))
13810 (unless (member (file-truename f) tnames)
13811 (add-to-list 'files f 'append)
13812 (add-to-list 'tnames (file-truename f) 'append)))
13813 (multi-occur
13814 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13815 regexp)))
13817 (if (boundp 'occur-mode-find-occurrence-hook)
13818 ;; Emacs 23
13819 (add-hook 'occur-mode-find-occurrence-hook
13820 (lambda ()
13821 (when (org-mode-p)
13822 (org-reveal))))
13823 ;; Emacs 22
13824 (defadvice occur-mode-goto-occurrence
13825 (after org-occur-reveal activate)
13826 (and (org-mode-p) (org-reveal)))
13827 (defadvice occur-mode-goto-occurrence-other-window
13828 (after org-occur-reveal activate)
13829 (and (org-mode-p) (org-reveal)))
13830 (defadvice occur-mode-display-occurrence
13831 (after org-occur-reveal activate)
13832 (when (org-mode-p)
13833 (let ((pos (occur-mode-find-occurrence)))
13834 (with-current-buffer (marker-buffer pos)
13835 (save-excursion
13836 (goto-char pos)
13837 (org-reveal)))))))
13839 (defun org-uniquify (list)
13840 "Remove duplicate elements from LIST."
13841 (let (res)
13842 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13843 res))
13845 (defun org-delete-all (elts list)
13846 "Remove all elements in ELTS from LIST."
13847 (while elts
13848 (setq list (delete (pop elts) list)))
13849 list)
13851 (defun org-back-over-empty-lines ()
13852 "Move backwards over witespace, to the beginning of the first empty line.
13853 Returns the number of empty lines passed."
13854 (let ((pos (point)))
13855 (skip-chars-backward " \t\n\r")
13856 (beginning-of-line 2)
13857 (goto-char (min (point) pos))
13858 (count-lines (point) pos)))
13860 (defun org-skip-whitespace ()
13861 (skip-chars-forward " \t\n\r"))
13863 (defun org-point-in-group (point group &optional context)
13864 "Check if POINT is in match-group GROUP.
13865 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13866 match. If the match group does ot exist or point is not inside it,
13867 return nil."
13868 (and (match-beginning group)
13869 (>= point (match-beginning group))
13870 (<= point (match-end group))
13871 (if context
13872 (list context (match-beginning group) (match-end group))
13873 t)))
13875 (defun org-switch-to-buffer-other-window (&rest args)
13876 "Switch to buffer in a second window on the current frame.
13877 In particular, do not allow pop-up frames."
13878 (let (pop-up-frames special-display-buffer-names special-display-regexps
13879 special-display-function)
13880 (apply 'switch-to-buffer-other-window args)))
13882 (defun org-combine-plists (&rest plists)
13883 "Create a single property list from all plists in PLISTS.
13884 The process starts by copying the first list, and then setting properties
13885 from the other lists. Settings in the last list are the most significant
13886 ones and overrule settings in the other lists."
13887 (let ((rtn (copy-sequence (pop plists)))
13888 p v ls)
13889 (while plists
13890 (setq ls (pop plists))
13891 (while ls
13892 (setq p (pop ls) v (pop ls))
13893 (setq rtn (plist-put rtn p v))))
13894 rtn))
13896 (defun org-move-line-down (arg)
13897 "Move the current line down. With prefix argument, move it past ARG lines."
13898 (interactive "p")
13899 (let ((col (current-column))
13900 beg end pos)
13901 (beginning-of-line 1) (setq beg (point))
13902 (beginning-of-line 2) (setq end (point))
13903 (beginning-of-line (+ 1 arg))
13904 (setq pos (move-marker (make-marker) (point)))
13905 (insert (delete-and-extract-region beg end))
13906 (goto-char pos)
13907 (org-move-to-column col)))
13909 (defun org-move-line-up (arg)
13910 "Move the current line up. With prefix argument, move it past ARG lines."
13911 (interactive "p")
13912 (let ((col (current-column))
13913 beg end pos)
13914 (beginning-of-line 1) (setq beg (point))
13915 (beginning-of-line 2) (setq end (point))
13916 (beginning-of-line (- arg))
13917 (setq pos (move-marker (make-marker) (point)))
13918 (insert (delete-and-extract-region beg end))
13919 (goto-char pos)
13920 (org-move-to-column col)))
13922 (defun org-replace-escapes (string table)
13923 "Replace %-escapes in STRING with values in TABLE.
13924 TABLE is an association list with keys like \"%a\" and string values.
13925 The sequences in STRING may contain normal field width and padding information,
13926 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13927 so values can contain further %-escapes if they are define later in TABLE."
13928 (let ((case-fold-search nil)
13929 e re rpl)
13930 (while (setq e (pop table))
13931 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13932 (while (string-match re string)
13933 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13934 (cdr e)))
13935 (setq string (replace-match rpl t t string))))
13936 string))
13939 (defun org-sublist (list start end)
13940 "Return a section of LIST, from START to END.
13941 Counting starts at 1."
13942 (let (rtn (c start))
13943 (setq list (nthcdr (1- start) list))
13944 (while (and list (<= c end))
13945 (push (pop list) rtn)
13946 (setq c (1+ c)))
13947 (nreverse rtn)))
13949 (defun org-find-base-buffer-visiting (file)
13950 "Like `find-buffer-visiting' but alway return the base buffer and
13951 not an indirect buffer."
13952 (let ((buf (find-buffer-visiting file)))
13953 (if buf
13954 (or (buffer-base-buffer buf) buf)
13955 nil)))
13957 (defun org-image-file-name-regexp ()
13958 "Return regexp matching the file names of images."
13959 (if (fboundp 'image-file-name-regexp)
13960 (image-file-name-regexp)
13961 (let ((image-file-name-extensions
13962 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13963 "xbm" "xpm" "pbm" "pgm" "ppm")))
13964 (concat "\\."
13965 (regexp-opt (nconc (mapcar 'upcase
13966 image-file-name-extensions)
13967 image-file-name-extensions)
13969 "\\'"))))
13971 (defun org-file-image-p (file)
13972 "Return non-nil if FILE is an image."
13973 (save-match-data
13974 (string-match (org-image-file-name-regexp) file)))
13976 (defun org-get-cursor-date ()
13977 "Return the date at cursor in as a time.
13978 This works in the calendar and in the agenda, anywhere else it just
13979 returns the current time."
13980 (let (date day defd)
13981 (cond
13982 ((eq major-mode 'calendar-mode)
13983 (setq date (calendar-cursor-to-date)
13984 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13985 ((eq major-mode 'org-agenda-mode)
13986 (setq day (get-text-property (point) 'day))
13987 (if day
13988 (setq date (calendar-gregorian-from-absolute day)
13989 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13990 (nth 2 date))))))
13991 (or defd (current-time))))
13993 (defvar org-agenda-action-marker (make-marker)
13994 "Marker pointing to the entry for the next agenda action.")
13996 (defun org-mark-entry-for-agenda-action ()
13997 "Mark the current entry as target of an agenda action.
13998 Agenda actions are actions executed from the agenda with the key `k',
13999 which make use of the date at the cursor."
14000 (interactive)
14001 (move-marker org-agenda-action-marker
14002 (save-excursion (org-back-to-heading t) (point))
14003 (current-buffer))
14004 (message
14005 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14007 ;;; Paragraph filling stuff.
14008 ;; We want this to be just right, so use the full arsenal.
14010 (defun org-indent-line-function ()
14011 "Indent line like previous, but further if previous was headline or item."
14012 (interactive)
14013 (let* ((pos (point))
14014 (itemp (org-at-item-p))
14015 column bpos bcol tpos tcol bullet btype bullet-type)
14016 ;; Find the previous relevant line
14017 (beginning-of-line 1)
14018 (cond
14019 ((looking-at "#") (setq column 0))
14020 ((looking-at "\\*+ ") (setq column 0))
14022 (beginning-of-line 0)
14023 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14024 (beginning-of-line 0))
14025 (cond
14026 ((looking-at "\\*+[ \t]+")
14027 (if (not org-adapt-indentation)
14028 (setq column 0)
14029 (goto-char (match-end 0))
14030 (setq column (current-column))))
14031 ((org-in-item-p)
14032 (org-beginning-of-item)
14033 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14034 (setq bpos (match-beginning 1) tpos (match-end 0)
14035 bcol (progn (goto-char bpos) (current-column))
14036 tcol (progn (goto-char tpos) (current-column))
14037 bullet (match-string 1)
14038 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14039 (if (> tcol (+ bcol org-description-max-indent))
14040 (setq tcol (+ bcol 5)))
14041 (if (not itemp)
14042 (setq column tcol)
14043 (goto-char pos)
14044 (beginning-of-line 1)
14045 (if (looking-at "\\S-")
14046 (progn
14047 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14048 (setq bullet (match-string 1)
14049 btype (if (string-match "[0-9]" bullet) "n" bullet))
14050 (setq column (if (equal btype bullet-type) bcol tcol)))
14051 (setq column (org-get-indentation)))))
14052 (t (setq column (org-get-indentation))))))
14053 (goto-char pos)
14054 (if (<= (current-column) (current-indentation))
14055 (org-indent-line-to column)
14056 (save-excursion (org-indent-line-to column)))
14057 (setq column (current-column))
14058 (beginning-of-line 1)
14059 (if (looking-at
14060 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14061 (replace-match (concat "\\1" (format org-property-format
14062 (match-string 2) (match-string 3)))
14063 t nil))
14064 (org-move-to-column column)))
14066 (defun org-set-autofill-regexps ()
14067 (interactive)
14068 ;; In the paragraph separator we include headlines, because filling
14069 ;; text in a line directly attached to a headline would otherwise
14070 ;; fill the headline as well.
14071 (org-set-local 'comment-start-skip "^#+[ \t]*")
14072 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14073 ;; The paragraph starter includes hand-formatted lists.
14074 (org-set-local 'paragraph-start
14075 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14076 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14077 ;; But only if the user has not turned off tables or fixed-width regions
14078 (org-set-local
14079 'auto-fill-inhibit-regexp
14080 (concat "\\*+ \\|#\\+"
14081 "\\|[ \t]*" org-keyword-time-regexp
14082 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14083 (concat
14084 "\\|[ \t]*["
14085 (if org-enable-table-editor "|" "")
14086 (if org-enable-fixed-width-editor ":" "")
14087 "]"))))
14088 ;; We use our own fill-paragraph function, to make sure that tables
14089 ;; and fixed-width regions are not wrapped. That function will pass
14090 ;; through to `fill-paragraph' when appropriate.
14091 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14092 ; Adaptive filling: To get full control, first make sure that
14093 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14094 (org-set-local 'adaptive-fill-regexp "\000")
14095 (org-set-local 'adaptive-fill-function
14096 'org-adaptive-fill-function)
14097 (org-set-local
14098 'align-mode-rules-list
14099 '((org-in-buffer-settings
14100 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14101 (modes . '(org-mode))))))
14103 (defun org-fill-paragraph (&optional justify)
14104 "Re-align a table, pass through to fill-paragraph if no table."
14105 (let ((table-p (org-at-table-p))
14106 (table.el-p (org-at-table.el-p)))
14107 (cond ((and (equal (char-after (point-at-bol)) ?*)
14108 (save-excursion (goto-char (point-at-bol))
14109 (looking-at outline-regexp)))
14110 t) ; skip headlines
14111 (table.el-p t) ; skip table.el tables
14112 (table-p (org-table-align) t) ; align org-mode tables
14113 (t nil)))) ; call paragraph-fill
14115 ;; For reference, this is the default value of adaptive-fill-regexp
14116 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14118 (defun org-adaptive-fill-function ()
14119 "Return a fill prefix for org-mode files.
14120 In particular, this makes sure hanging paragraphs for hand-formatted lists
14121 work correctly."
14122 (cond ((looking-at "#[ \t]+")
14123 (match-string 0))
14124 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14125 (save-excursion
14126 (if (> (match-end 1) (+ (match-beginning 1)
14127 org-description-max-indent))
14128 (goto-char (+ (match-beginning 1) 5))
14129 (goto-char (match-end 0)))
14130 (make-string (current-column) ?\ )))
14131 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14132 (save-excursion
14133 (goto-char (match-end 0))
14134 (make-string (current-column) ?\ )))
14135 (t nil)))
14137 ;;; Other stuff.
14139 (defun org-toggle-fixed-width-section (arg)
14140 "Toggle the fixed-width export.
14141 If there is no active region, the QUOTE keyword at the current headline is
14142 inserted or removed. When present, it causes the text between this headline
14143 and the next to be exported as fixed-width text, and unmodified.
14144 If there is an active region, this command adds or removes a colon as the
14145 first character of this line. If the first character of a line is a colon,
14146 this line is also exported in fixed-width font."
14147 (interactive "P")
14148 (let* ((cc 0)
14149 (regionp (org-region-active-p))
14150 (beg (if regionp (region-beginning) (point)))
14151 (end (if regionp (region-end)))
14152 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14153 (case-fold-search nil)
14154 (re "[ \t]*\\(:\\)")
14155 off)
14156 (if regionp
14157 (save-excursion
14158 (goto-char beg)
14159 (setq cc (current-column))
14160 (beginning-of-line 1)
14161 (setq off (looking-at re))
14162 (while (> nlines 0)
14163 (setq nlines (1- nlines))
14164 (beginning-of-line 1)
14165 (cond
14166 (arg
14167 (org-move-to-column cc t)
14168 (insert ":\n")
14169 (forward-line -1))
14170 ((and off (looking-at re))
14171 (replace-match "" t t nil 1))
14172 ((not off) (org-move-to-column cc t) (insert ":")))
14173 (forward-line 1)))
14174 (save-excursion
14175 (org-back-to-heading)
14176 (if (looking-at (concat outline-regexp
14177 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14178 (replace-match "" t t nil 1)
14179 (if (looking-at outline-regexp)
14180 (progn
14181 (goto-char (match-end 0))
14182 (insert org-quote-string " "))))))))
14184 ;;;; Functions extending outline functionality
14186 (defun org-beginning-of-line (&optional arg)
14187 "Go to the beginning of the current line. If that is invisible, continue
14188 to a visible line beginning. This makes the function of C-a more intuitive.
14189 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14190 first attempt, and only move to after the tags when the cursor is already
14191 beyond the end of the headline."
14192 (interactive "P")
14193 (let ((pos (point)) refpos)
14194 (beginning-of-line 1)
14195 (if (bobp)
14197 (backward-char 1)
14198 (if (org-invisible-p)
14199 (while (and (not (bobp)) (org-invisible-p))
14200 (backward-char 1)
14201 (beginning-of-line 1))
14202 (forward-char 1)))
14203 (when org-special-ctrl-a/e
14204 (cond
14205 ((and (looking-at org-complex-heading-regexp)
14206 (= (char-after (match-end 1)) ?\ ))
14207 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14208 (point-at-eol)))
14209 (goto-char
14210 (if (eq org-special-ctrl-a/e t)
14211 (cond ((> pos refpos) refpos)
14212 ((= pos (point)) refpos)
14213 (t (point)))
14214 (cond ((> pos (point)) (point))
14215 ((not (eq last-command this-command)) (point))
14216 (t refpos)))))
14217 ((org-at-item-p)
14218 (goto-char
14219 (if (eq org-special-ctrl-a/e t)
14220 (cond ((> pos (match-end 4)) (match-end 4))
14221 ((= pos (point)) (match-end 4))
14222 (t (point)))
14223 (cond ((> pos (point)) (point))
14224 ((not (eq last-command this-command)) (point))
14225 (t (match-end 4))))))))
14226 (org-no-warnings
14227 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14229 (defun org-end-of-line (&optional arg)
14230 "Go to the end of the line.
14231 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14232 first attempt, and only move to after the tags when the cursor is already
14233 beyond the end of the headline."
14234 (interactive "P")
14235 (if (or (not org-special-ctrl-a/e)
14236 (not (org-on-heading-p)))
14237 (end-of-line arg)
14238 (let ((pos (point)))
14239 (beginning-of-line 1)
14240 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14241 (if (eq org-special-ctrl-a/e t)
14242 (if (or (< pos (match-beginning 1))
14243 (= pos (match-end 0)))
14244 (goto-char (match-beginning 1))
14245 (goto-char (match-end 0)))
14246 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14247 (goto-char (match-end 0))
14248 (goto-char (match-beginning 1))))
14249 (end-of-line arg))))
14250 (org-no-warnings
14251 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14254 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14255 (define-key org-mode-map "\C-e" 'org-end-of-line)
14257 (defun org-kill-line (&optional arg)
14258 "Kill line, to tags or end of line."
14259 (interactive "P")
14260 (cond
14261 ((or (not org-special-ctrl-k)
14262 (bolp)
14263 (not (org-on-heading-p)))
14264 (call-interactively 'kill-line))
14265 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14266 (kill-region (point) (match-beginning 1))
14267 (org-set-tags nil t))
14268 (t (kill-region (point) (point-at-eol)))))
14270 (define-key org-mode-map "\C-k" 'org-kill-line)
14272 (defun org-yank (&optional arg)
14273 "Yank. If the kill is a subtree, treat it specially.
14274 This command will look at the current kill and check if is a single
14275 subtree, or a series of subtrees[1]. If it passes the test, and if the
14276 cursor is at the beginning of a line or after the stars of a currently
14277 empty headline, then the yank is handeled specially. How exactly depends
14278 on the value of the following variables, both set by default.
14280 org-yank-folded-subtrees
14281 When set, the subree(s) will be folded after insertion, but only
14282 if doing so would now swallow text after the yanked text.
14284 org-yank-adjusted-subtrees
14285 When set, the subtree will be promoted or demoted in order to
14286 fit into the local outline tree structure, which means that the level
14287 will be adjusted so that it becomes the smaller one of the two
14288 *visible* surrounding headings.
14290 Any prefix to this command will cause `yank' to be called directly with
14291 no special treatment. In particular, a simple `C-u' prefix will just
14292 plainly yank the text as it is.
14294 \[1] Basically, the test checks if the first non-white line is a heading
14295 and if there are no other headings with fewer stars."
14296 (interactive "P")
14297 (setq this-command 'yank)
14298 (if arg
14299 (call-interactively 'yank)
14300 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14301 (and (org-kill-is-subtree-p)
14302 (or (bolp)
14303 (and (looking-at "[ \t]*$")
14304 (string-match
14305 "\\`\\*+\\'"
14306 (buffer-substring (point-at-bol) (point)))))))
14307 swallowp)
14308 (cond
14309 ((and subtreep org-yank-folded-subtrees)
14310 (let ((beg (point))
14311 end)
14312 (if (and subtreep org-yank-adjusted-subtrees)
14313 (org-paste-subtree nil nil 'for-yank)
14314 (call-interactively 'yank))
14315 (setq end (point))
14316 (goto-char beg)
14317 (when (and (bolp) subtreep
14318 (not (setq swallowp
14319 (org-yank-folding-would-swallow-text beg end))))
14320 (or (looking-at outline-regexp)
14321 (re-search-forward (concat "^" outline-regexp) end t))
14322 (while (and (< (point) end) (looking-at outline-regexp))
14323 (hide-subtree)
14324 (org-cycle-show-empty-lines 'folded)
14325 (condition-case nil
14326 (outline-forward-same-level 1)
14327 (error (goto-char end)))))
14328 (when swallowp
14329 (message
14330 "Yanked text not folded because that would swallow text"))
14331 (goto-char end)
14332 (skip-chars-forward " \t\n\r")
14333 (beginning-of-line 1)
14334 (push-mark beg 'nomsg)))
14335 ((and subtreep org-yank-adjusted-subtrees)
14336 (let ((beg (point-at-bol)))
14337 (org-paste-subtree nil nil 'for-yank)
14338 (push-mark beg 'nomsg)))
14340 (call-interactively 'yank))))))
14342 (defun org-yank-folding-would-swallow-text (beg end)
14343 "Would hide-subtree at BEG swallow any text after END?"
14344 (let (level)
14345 (save-excursion
14346 (goto-char beg)
14347 (when (or (looking-at outline-regexp)
14348 (re-search-forward (concat "^" outline-regexp) end t))
14349 (setq level (org-outline-level)))
14350 (goto-char end)
14351 (skip-chars-forward " \t\r\n\v\f")
14352 (if (or (eobp)
14353 (and (bolp) (looking-at org-outline-regexp)
14354 (<= (org-outline-level) level)))
14355 nil ; Nothing would be swallowed
14356 t)))) ; something would swallow
14358 (define-key org-mode-map "\C-y" 'org-yank)
14360 (defun org-invisible-p ()
14361 "Check if point is at a character currently not visible."
14362 ;; Early versions of noutline don't have `outline-invisible-p'.
14363 (if (fboundp 'outline-invisible-p)
14364 (outline-invisible-p)
14365 (get-char-property (point) 'invisible)))
14367 (defun org-invisible-p2 ()
14368 "Check if point is at a character currently not visible."
14369 (save-excursion
14370 (if (and (eolp) (not (bobp))) (backward-char 1))
14371 ;; Early versions of noutline don't have `outline-invisible-p'.
14372 (if (fboundp 'outline-invisible-p)
14373 (outline-invisible-p)
14374 (get-char-property (point) 'invisible))))
14376 (defun org-back-to-heading (&optional invisible-ok)
14377 "Call `outline-back-to-heading', but provide a better error message."
14378 (condition-case nil
14379 (outline-back-to-heading invisible-ok)
14380 (error (error "Before first headline at position %d in buffer %s"
14381 (point) (current-buffer)))))
14383 (defun org-before-first-heading-p ()
14384 "Before first heading?"
14385 (save-excursion
14386 (null (re-search-backward "^\\*+ " nil t))))
14388 (defalias 'org-on-heading-p 'outline-on-heading-p)
14389 (defalias 'org-at-heading-p 'outline-on-heading-p)
14390 (defun org-at-heading-or-item-p ()
14391 (or (org-on-heading-p) (org-at-item-p)))
14393 (defun org-on-target-p ()
14394 (or (org-in-regexp org-radio-target-regexp)
14395 (org-in-regexp org-target-regexp)))
14397 (defun org-up-heading-all (arg)
14398 "Move to the heading line of which the present line is a subheading.
14399 This function considers both visible and invisible heading lines.
14400 With argument, move up ARG levels."
14401 (if (fboundp 'outline-up-heading-all)
14402 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14403 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14405 (defun org-up-heading-safe ()
14406 "Move to the heading line of which the present line is a subheading.
14407 This version will not throw an error. It will return the level of the
14408 headline found, or nil if no higher level is found."
14409 (let ((pos (point)) start-level level
14410 (re (concat "^" outline-regexp)))
14411 (catch 'exit
14412 (org-back-to-heading t)
14413 (setq start-level (funcall outline-level))
14414 (if (equal start-level 1) (throw 'exit nil))
14415 (while (re-search-backward re nil t)
14416 (setq level (funcall outline-level))
14417 (if (< level start-level) (throw 'exit level)))
14418 nil)))
14420 (defun org-first-sibling-p ()
14421 "Is this heading the first child of its parents?"
14422 (interactive)
14423 (let ((re (concat "^" outline-regexp))
14424 level l)
14425 (unless (org-at-heading-p t)
14426 (error "Not at a heading"))
14427 (setq level (funcall outline-level))
14428 (save-excursion
14429 (if (not (re-search-backward re nil t))
14431 (setq l (funcall outline-level))
14432 (< l level)))))
14434 (defun org-goto-sibling (&optional previous)
14435 "Goto the next sibling, even if it is invisible.
14436 When PREVIOUS is set, go to the previous sibling instead. Returns t
14437 when a sibling was found. When none is found, return nil and don't
14438 move point."
14439 (let ((fun (if previous 're-search-backward 're-search-forward))
14440 (pos (point))
14441 (re (concat "^" outline-regexp))
14442 level l)
14443 (when (condition-case nil (org-back-to-heading t) (error nil))
14444 (setq level (funcall outline-level))
14445 (catch 'exit
14446 (or previous (forward-char 1))
14447 (while (funcall fun re nil t)
14448 (setq l (funcall outline-level))
14449 (when (< l level) (goto-char pos) (throw 'exit nil))
14450 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14451 (goto-char pos)
14452 nil))))
14454 (defun org-show-siblings ()
14455 "Show all siblings of the current headline."
14456 (save-excursion
14457 (while (org-goto-sibling) (org-flag-heading nil)))
14458 (save-excursion
14459 (while (org-goto-sibling 'previous)
14460 (org-flag-heading nil))))
14462 (defun org-show-hidden-entry ()
14463 "Show an entry where even the heading is hidden."
14464 (save-excursion
14465 (org-show-entry)))
14467 (defun org-flag-heading (flag &optional entry)
14468 "Flag the current heading. FLAG non-nil means make invisible.
14469 When ENTRY is non-nil, show the entire entry."
14470 (save-excursion
14471 (org-back-to-heading t)
14472 ;; Check if we should show the entire entry
14473 (if entry
14474 (progn
14475 (org-show-entry)
14476 (save-excursion
14477 (and (outline-next-heading)
14478 (org-flag-heading nil))))
14479 (outline-flag-region (max (point-min) (1- (point)))
14480 (save-excursion (outline-end-of-heading) (point))
14481 flag))))
14483 (defun org-forward-same-level (arg)
14484 "Move forward to the ARG'th subheading at same level as this one.
14485 Stop at the first and last subheadings of a superior heading.
14486 This is like outline-forward-same-level, but invisible headings are ok."
14487 (interactive "p")
14488 (org-back-to-heading t)
14489 (while (> arg 0)
14490 (let ((point-to-move-to (save-excursion
14491 (org-get-next-sibling))))
14492 (if point-to-move-to
14493 (progn
14494 (goto-char point-to-move-to)
14495 (setq arg (1- arg)))
14496 (progn
14497 (setq arg 0)
14498 (error "No following same-level heading"))))))
14500 (defun org-get-next-sibling ()
14501 "Move to next heading of the same level, and return point.
14502 If there is no such heading, return nil.
14503 This is like outline-next-sibling, but invisible headings are ok."
14504 (let ((level (funcall outline-level)))
14505 (outline-next-heading)
14506 (while (and (not (eobp)) (> (funcall outline-level) level))
14507 (outline-next-heading))
14508 (if (or (eobp) (< (funcall outline-level) level))
14510 (point))))
14512 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14513 ;; This is an exact copy of the original function, but it uses
14514 ;; `org-back-to-heading', to make it work also in invisible
14515 ;; trees. And is uses an invisible-OK argument.
14516 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14517 (org-back-to-heading invisible-OK)
14518 (let ((first t)
14519 (level (funcall outline-level)))
14520 (while (and (not (eobp))
14521 (or first (> (funcall outline-level) level)))
14522 (setq first nil)
14523 (outline-next-heading))
14524 (unless to-heading
14525 (if (memq (preceding-char) '(?\n ?\^M))
14526 (progn
14527 ;; Go to end of line before heading
14528 (forward-char -1)
14529 (if (memq (preceding-char) '(?\n ?\^M))
14530 ;; leave blank line before heading
14531 (forward-char -1))))))
14532 (point))
14534 (defun org-show-subtree ()
14535 "Show everything after this heading at deeper levels."
14536 (outline-flag-region
14537 (point)
14538 (save-excursion
14539 (outline-end-of-subtree) (outline-next-heading) (point))
14540 nil))
14542 (defun org-show-entry ()
14543 "Show the body directly following this heading.
14544 Show the heading too, if it is currently invisible."
14545 (interactive)
14546 (save-excursion
14547 (condition-case nil
14548 (progn
14549 (org-back-to-heading t)
14550 (outline-flag-region
14551 (max (point-min) (1- (point)))
14552 (save-excursion
14553 (re-search-forward
14554 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14555 (or (match-beginning 1) (point-max)))
14556 nil))
14557 (error nil))))
14559 (defun org-make-options-regexp (kwds)
14560 "Make a regular expression for keyword lines."
14561 (concat
14563 "#?[ \t]*\\+\\("
14564 (mapconcat 'regexp-quote kwds "\\|")
14565 "\\):[ \t]*"
14566 "\\(.+\\)"))
14568 ;; Make isearch reveal the necessary context
14569 (defun org-isearch-end ()
14570 "Reveal context after isearch exits."
14571 (when isearch-success ; only if search was successful
14572 (if (featurep 'xemacs)
14573 ;; Under XEmacs, the hook is run in the correct place,
14574 ;; we directly show the context.
14575 (org-show-context 'isearch)
14576 ;; In Emacs the hook runs *before* restoring the overlays.
14577 ;; So we have to use a one-time post-command-hook to do this.
14578 ;; (Emacs 22 has a special variable, see function `org-mode')
14579 (unless (and (boundp 'isearch-mode-end-hook-quit)
14580 isearch-mode-end-hook-quit)
14581 ;; Only when the isearch was not quitted.
14582 (org-add-hook 'post-command-hook 'org-isearch-post-command
14583 'append 'local)))))
14585 (defun org-isearch-post-command ()
14586 "Remove self from hook, and show context."
14587 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14588 (org-show-context 'isearch))
14591 ;;;; Integration with and fixes for other packages
14593 ;;; Imenu support
14595 (defvar org-imenu-markers nil
14596 "All markers currently used by Imenu.")
14597 (make-variable-buffer-local 'org-imenu-markers)
14599 (defun org-imenu-new-marker (&optional pos)
14600 "Return a new marker for use by Imenu, and remember the marker."
14601 (let ((m (make-marker)))
14602 (move-marker m (or pos (point)))
14603 (push m org-imenu-markers)
14606 (defun org-imenu-get-tree ()
14607 "Produce the index for Imenu."
14608 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14609 (setq org-imenu-markers nil)
14610 (let* ((n org-imenu-depth)
14611 (re (concat "^" outline-regexp))
14612 (subs (make-vector (1+ n) nil))
14613 (last-level 0)
14614 m tree level head)
14615 (save-excursion
14616 (save-restriction
14617 (widen)
14618 (goto-char (point-max))
14619 (while (re-search-backward re nil t)
14620 (setq level (org-reduced-level (funcall outline-level)))
14621 (when (<= level n)
14622 (looking-at org-complex-heading-regexp)
14623 (setq head (org-link-display-format
14624 (org-match-string-no-properties 4))
14625 m (org-imenu-new-marker))
14626 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14627 (if (>= level last-level)
14628 (push (cons head m) (aref subs level))
14629 (push (cons head (aref subs (1+ level))) (aref subs level))
14630 (loop for i from (1+ level) to n do (aset subs i nil)))
14631 (setq last-level level)))))
14632 (aref subs 1)))
14634 (eval-after-load "imenu"
14635 '(progn
14636 (add-hook 'imenu-after-jump-hook
14637 (lambda ()
14638 (if (eq major-mode 'org-mode)
14639 (org-show-context 'org-goto))))))
14641 (defun org-link-display-format (link)
14642 "Replace a link with either the description, or the link target
14643 if no description is present"
14644 (save-match-data
14645 (if (string-match org-bracket-link-analytic-regexp link)
14646 (replace-match (or (match-string 5 link)
14647 (concat (match-string 1 link)
14648 (match-string 3 link)))
14649 nil nil link)
14650 link)))
14652 ;; Speedbar support
14654 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14655 "Overlay marking the agenda restriction line in speedbar.")
14656 (org-overlay-put org-speedbar-restriction-lock-overlay
14657 'face 'org-agenda-restriction-lock)
14658 (org-overlay-put org-speedbar-restriction-lock-overlay
14659 'help-echo "Agendas are currently limited to this item.")
14660 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14662 (defun org-speedbar-set-agenda-restriction ()
14663 "Restrict future agenda commands to the location at point in speedbar.
14664 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14665 (interactive)
14666 (require 'org-agenda)
14667 (let (p m tp np dir txt w)
14668 (cond
14669 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14670 'org-imenu t))
14671 (setq m (get-text-property p 'org-imenu-marker))
14672 (save-excursion
14673 (save-restriction
14674 (set-buffer (marker-buffer m))
14675 (goto-char m)
14676 (org-agenda-set-restriction-lock 'subtree))))
14677 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14678 'speedbar-function 'speedbar-find-file))
14679 (setq tp (previous-single-property-change
14680 (1+ p) 'speedbar-function)
14681 np (next-single-property-change
14682 tp 'speedbar-function)
14683 dir (speedbar-line-directory)
14684 txt (buffer-substring-no-properties (or tp (point-min))
14685 (or np (point-max))))
14686 (save-excursion
14687 (save-restriction
14688 (set-buffer (find-file-noselect
14689 (let ((default-directory dir))
14690 (expand-file-name txt))))
14691 (unless (org-mode-p)
14692 (error "Cannot restrict to non-Org-mode file"))
14693 (org-agenda-set-restriction-lock 'file))))
14694 (t (error "Don't know how to restrict Org-mode's agenda")))
14695 (org-move-overlay org-speedbar-restriction-lock-overlay
14696 (point-at-bol) (point-at-eol))
14697 (setq current-prefix-arg nil)
14698 (org-agenda-maybe-redo)))
14700 (eval-after-load "speedbar"
14701 '(progn
14702 (speedbar-add-supported-extension ".org")
14703 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14704 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14705 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14706 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14707 (add-hook 'speedbar-visiting-tag-hook
14708 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14711 ;;; Fixes and Hacks for problems with other packages
14713 ;; Make flyspell not check words in links, to not mess up our keymap
14714 (defun org-mode-flyspell-verify ()
14715 "Don't let flyspell put overlays at active buttons."
14716 (not (get-text-property (point) 'keymap)))
14718 ;; Make `bookmark-jump' show the jump location if it was hidden.
14719 (eval-after-load "bookmark"
14720 '(if (boundp 'bookmark-after-jump-hook)
14721 ;; We can use the hook
14722 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14723 ;; Hook not available, use advice
14724 (defadvice bookmark-jump (after org-make-visible activate)
14725 "Make the position visible."
14726 (org-bookmark-jump-unhide))))
14728 ;; Make sure saveplace show the location if it was hidden
14729 (eval-after-load "saveplace"
14730 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14731 "Make the position visible."
14732 (org-bookmark-jump-unhide)))
14734 (defun org-bookmark-jump-unhide ()
14735 "Unhide the current position, to show the bookmark location."
14736 (and (org-mode-p)
14737 (or (org-invisible-p)
14738 (save-excursion (goto-char (max (point-min) (1- (point))))
14739 (org-invisible-p)))
14740 (org-show-context 'bookmark-jump)))
14742 ;; Make session.el ignore our circular variable
14743 (eval-after-load "session"
14744 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14746 ;;;; Experimental code
14748 (defun org-closed-in-range ()
14749 "Sparse tree of items closed in a certain time range.
14750 Still experimental, may disappear in the future."
14751 (interactive)
14752 ;; Get the time interval from the user.
14753 (let* ((time1 (time-to-seconds
14754 (org-read-date nil 'to-time nil "Starting date: ")))
14755 (time2 (time-to-seconds
14756 (org-read-date nil 'to-time nil "End date:")))
14757 ;; callback function
14758 (callback (lambda ()
14759 (let ((time
14760 (time-to-seconds
14761 (apply 'encode-time
14762 (org-parse-time-string
14763 (match-string 1))))))
14764 ;; check if time in interval
14765 (and (>= time time1) (<= time time2))))))
14766 ;; make tree, check each match with the callback
14767 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14770 ;;;; Finish up
14772 (provide 'org)
14774 (run-hooks 'org-load-hook)
14776 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14778 ;;; org.el ends here