Store link: Capture description for ID links.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blobaeda46b98352e483760d76f178b967b20e5c32b3
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.15trans
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.15trans"
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 Remember 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 standard 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][description]]. 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 brackets 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 %-escapes 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. Usually \"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 matched 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 modified 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 'integer)
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 matched 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 inside 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 setting 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 values are:
1309 outline The interface shows an outline of the relevant file
1310 and the correct heading is found by moving through
1311 the outline or by searching with incremental search.
1312 outline-path-completion Headlines in the current buffer are offered via
1313 completion. This is the interface also used by
1314 the refile command."
1315 :group 'org-refile
1316 :type '(choice
1317 (const :tag "Outline" outline)
1318 (const :tag "Outline-path-completion" outline-path-completion)))
1320 (defcustom org-goto-max-level 5
1321 "Maximum level to be considered when running org-goto with refile interface."
1322 :group 'org-refile
1323 :type 'number)
1325 (defcustom org-reverse-note-order nil
1326 "Non-nil means, store new notes at the beginning of a file or entry.
1327 When nil, new notes will be filed to the end of a file or entry.
1328 This can also be a list with cons cells of regular expressions that
1329 are matched against file names, and values."
1330 :group 'org-remember
1331 :group 'org-refile
1332 :type '(choice
1333 (const :tag "Reverse always" t)
1334 (const :tag "Reverse never" nil)
1335 (repeat :tag "By file name regexp"
1336 (cons regexp boolean))))
1338 (defcustom org-refile-targets nil
1339 "Targets for refiling entries with \\[org-refile].
1340 This is list of cons cells. Each cell contains:
1341 - a specification of the files to be considered, either a list of files,
1342 or a symbol whose function or variable value will be used to retrieve
1343 a file name or a list of file names. If you use `org-agenda-files' for
1344 that, all agenda files will be scanned for targets. Nil means, consider
1345 headings in the current buffer.
1346 - A specification of how to select find candidate refile targets. This
1347 may be any of
1348 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1349 This tag has to be present in all target headlines, inheritance will
1350 not be considered.
1351 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1352 todo keyword.
1353 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1354 headlines that are refiling targets.
1355 - a cons cell (:level . N). Any headline of level N is considered a target.
1356 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1358 When this variable is nil, all top-level headlines in the current buffer
1359 are used, equivalent to the value `((nil . (:level . 1))'."
1360 :group 'org-refile
1361 :type '(repeat
1362 (cons
1363 (choice :value org-agenda-files
1364 (const :tag "All agenda files" org-agenda-files)
1365 (const :tag "Current buffer" nil)
1366 (function) (variable) (file))
1367 (choice :tag "Identify target headline by"
1368 (cons :tag "Specific tag" (const :value :tag) (string))
1369 (cons :tag "TODO keyword" (const :value :todo) (string))
1370 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1371 (cons :tag "Level number" (const :value :level) (integer))
1372 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1374 (defcustom org-refile-use-outline-path nil
1375 "Non-nil means, provide refile targets as paths.
1376 So a level 3 headline will be available as level1/level2/level3.
1377 When the value is `file', also include the file name (without directory)
1378 into the path. When `full-file-path', include the full file path."
1379 :group 'org-refile
1380 :type '(choice
1381 (const :tag "Not" nil)
1382 (const :tag "Yes" t)
1383 (const :tag "Start with file name" file)
1384 (const :tag "Start with full file path" full-file-path)))
1386 (defcustom org-outline-path-complete-in-steps t
1387 "Non-nil means, complete the outline path in hierarchical steps.
1388 When Org-mode uses the refile interface to select an outline path
1389 \(see variable `org-refile-use-outline-path'), the completion of
1390 the path can be done is a single go, or if can be done in steps down
1391 the headline hierarchy. Going in steps is probably the best if you
1392 do not use a special completion package like `ido' or `icicles'.
1393 However, when using these packages, going in one step can be very
1394 fast, while still showing the whole path to the entry."
1395 :group 'org-refile
1396 :type 'boolean)
1398 (defgroup org-todo nil
1399 "Options concerning TODO items in Org-mode."
1400 :tag "Org TODO"
1401 :group 'org)
1403 (defgroup org-progress nil
1404 "Options concerning Progress logging in Org-mode."
1405 :tag "Org Progress"
1406 :group 'org-time)
1408 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1409 "List of TODO entry keyword sequences and their interpretation.
1410 \\<org-mode-map>This is a list of sequences.
1412 Each sequence starts with a symbol, either `sequence' or `type',
1413 indicating if the keywords should be interpreted as a sequence of
1414 action steps, or as different types of TODO items. The first
1415 keywords are states requiring action - these states will select a headline
1416 for inclusion into the global TODO list Org-mode produces. If one of
1417 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1418 signify that no further action is necessary. If \"|\" is not found,
1419 the last keyword is treated as the only DONE state of the sequence.
1421 The command \\[org-todo] cycles an entry through these states, and one
1422 additional state where no keyword is present. For details about this
1423 cycling, see the manual.
1425 TODO keywords and interpretation can also be set on a per-file basis with
1426 the special #+SEQ_TODO and #+TYP_TODO lines.
1428 Each keyword can optionally specify a character for fast state selection
1429 \(in combination with the variable `org-use-fast-todo-selection')
1430 and specifiers for state change logging, using the same syntax
1431 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1432 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1433 indicates to record a time stamp each time this state is selected.
1435 Each keyword may also specify if a timestamp or a note should be
1436 recorded when entering or leaving the state, by adding additional
1437 characters in the parenthesis after the keyword. This looks like this:
1438 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1439 record only the time of the state change. With X and Y being either
1440 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1441 Y when leaving the state if and only if the *target* state does not
1442 define X. You may omit any of the fast-selection key or X or /Y,
1443 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1445 For backward compatibility, this variable may also be just a list
1446 of keywords - in this case the interpretation (sequence or type) will be
1447 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1448 :group 'org-todo
1449 :group 'org-keywords
1450 :type '(choice
1451 (repeat :tag "Old syntax, just keywords"
1452 (string :tag "Keyword"))
1453 (repeat :tag "New syntax"
1454 (cons
1455 (choice
1456 :tag "Interpretation"
1457 (const :tag "Sequence (cycling hits every state)" sequence)
1458 (const :tag "Type (cycling directly to DONE)" type))
1459 (repeat
1460 (string :tag "Keyword"))))))
1462 (defvar org-todo-keywords-1 nil
1463 "All TODO and DONE keywords active in a buffer.")
1464 (make-variable-buffer-local 'org-todo-keywords-1)
1465 (defvar org-todo-keywords-for-agenda nil)
1466 (defvar org-done-keywords-for-agenda nil)
1467 (defvar org-todo-keyword-alist-for-agenda nil)
1468 (defvar org-tag-alist-for-agenda nil)
1469 (defvar org-agenda-contributing-files nil)
1470 (defvar org-not-done-keywords nil)
1471 (make-variable-buffer-local 'org-not-done-keywords)
1472 (defvar org-done-keywords nil)
1473 (make-variable-buffer-local 'org-done-keywords)
1474 (defvar org-todo-heads nil)
1475 (make-variable-buffer-local 'org-todo-heads)
1476 (defvar org-todo-sets nil)
1477 (make-variable-buffer-local 'org-todo-sets)
1478 (defvar org-todo-log-states nil)
1479 (make-variable-buffer-local 'org-todo-log-states)
1480 (defvar org-todo-kwd-alist nil)
1481 (make-variable-buffer-local 'org-todo-kwd-alist)
1482 (defvar org-todo-key-alist nil)
1483 (make-variable-buffer-local 'org-todo-key-alist)
1484 (defvar org-todo-key-trigger nil)
1485 (make-variable-buffer-local 'org-todo-key-trigger)
1487 (defcustom org-todo-interpretation 'sequence
1488 "Controls how TODO keywords are interpreted.
1489 This variable is in principle obsolete and is only used for
1490 backward compatibility, if the interpretation of todo keywords is
1491 not given already in `org-todo-keywords'. See that variable for
1492 more information."
1493 :group 'org-todo
1494 :group 'org-keywords
1495 :type '(choice (const sequence)
1496 (const type)))
1498 (defcustom org-use-fast-todo-selection 'prefix
1499 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1500 This variable describes if and under what circumstances the cycling
1501 mechanism for TODO keywords will be replaced by a single-key, direct
1502 selection scheme.
1504 When nil, fast selection is never used.
1506 When the symbol `prefix', it will be used when `org-todo' is called with
1507 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1508 in an agenda buffer.
1510 When t, fast selection is used by default. In this case, the prefix
1511 argument forces cycling instead.
1513 In all cases, the special interface is only used if access keys have actually
1514 been assigned by the user, i.e. if keywords in the configuration are followed
1515 by a letter in parenthesis, like TODO(t)."
1516 :group 'org-todo
1517 :type '(choice
1518 (const :tag "Never" nil)
1519 (const :tag "By default" t)
1520 (const :tag "Only with C-u C-c C-t" prefix)))
1522 (defcustom org-provide-todo-statistics t
1523 "Non-nil means, update todo statistics after insert and toggle.
1524 When this is set, todo statistics is updated in the parent of the current
1525 entry each time a todo state is changed."
1526 :group 'org-todo
1527 :type 'boolean)
1529 (defcustom org-after-todo-state-change-hook nil
1530 "Hook which is run after the state of a TODO item was changed.
1531 The new state (a string with a TODO keyword, or nil) is available in the
1532 Lisp variable `state'."
1533 :group 'org-todo
1534 :type 'hook)
1536 (defcustom org-todo-state-tags-triggers nil
1537 "Tag changes that should be triggered by TODO state changes.
1538 This is a list. Each entry is
1540 (state-change (tag . flag) .......)
1542 State-change can be a string with a state, and empty string to indicate the
1543 state that has no TODO keyword, or it can be one of the symbols `todo'
1544 or `done', meaning any not-done or done state, respectively."
1545 :group 'org-todo
1546 :group 'org-tags
1547 :type '(repeat
1548 (cons (choice :tag "When changing to"
1549 (const :tag "Not-done state" todo)
1550 (const :tag "Done state" done)
1551 (string :tag "State"))
1552 (repeat
1553 (cons :tag "Tag action"
1554 (string :tag "Tag")
1555 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1557 (defcustom org-log-done nil
1558 "Information to record when a task moves to the DONE state.
1560 Possible values are:
1562 nil Don't add anything, just change the keyword
1563 time Add a time stamp to the task
1564 note Prompt a closing note and add it with template `org-log-note-headings'
1566 This option can also be set with on a per-file-basis with
1568 #+STARTUP: nologdone
1569 #+STARTUP: logdone
1570 #+STARTUP: lognotedone
1572 You can have local logging settings for a subtree by setting the LOGGING
1573 property to one or more of these keywords."
1574 :group 'org-todo
1575 :group 'org-progress
1576 :type '(choice
1577 (const :tag "No logging" nil)
1578 (const :tag "Record CLOSED timestamp" time)
1579 (const :tag "Record CLOSED timestamp with closing note." note)))
1581 ;; Normalize old uses of org-log-done.
1582 (cond
1583 ((eq org-log-done t) (setq org-log-done 'time))
1584 ((and (listp org-log-done) (memq 'done org-log-done))
1585 (setq org-log-done 'note)))
1587 (defcustom org-log-note-clock-out nil
1588 "Non-nil means, record a note when clocking out of an item.
1589 This can also be configured on a per-file basis by adding one of
1590 the following lines anywhere in the buffer:
1592 #+STARTUP: lognoteclock-out
1593 #+STARTUP: nolognoteclock-out"
1594 :group 'org-todo
1595 :group 'org-progress
1596 :type 'boolean)
1598 (defcustom org-log-done-with-time t
1599 "Non-nil means, the CLOSED time stamp will contain date and time.
1600 When nil, only the date will be recorded."
1601 :group 'org-progress
1602 :type 'boolean)
1604 (defcustom org-log-note-headings
1605 '((done . "CLOSING NOTE %t")
1606 (state . "State %-12s %t")
1607 (note . "Note taken on %t")
1608 (clock-out . ""))
1609 "Headings for notes added to entries.
1610 The value is an alist, with the car being a symbol indicating the note
1611 context, and the cdr is the heading to be used. The heading may also be the
1612 empty string.
1613 %t in the heading will be replaced by a time stamp.
1614 %s will be replaced by the new TODO state, in double quotes.
1615 %u will be replaced by the user name.
1616 %U will be replaced by the full user name."
1617 :group 'org-todo
1618 :group 'org-progress
1619 :type '(list :greedy t
1620 (cons (const :tag "Heading when closing an item" done) string)
1621 (cons (const :tag
1622 "Heading when changing todo state (todo sequence only)"
1623 state) string)
1624 (cons (const :tag "Heading when just taking a note" note) string)
1625 (cons (const :tag "Heading when clocking out" clock-out) string)))
1627 (unless (assq 'note org-log-note-headings)
1628 (push '(note . "%t") org-log-note-headings))
1630 (defcustom org-log-state-notes-insert-after-drawers nil
1631 "Non-nil means, insert state change notes after any drawers in entry.
1632 Only the drawers that *immediately* follow the headline and the
1633 deadline/scheduled line are skipped.
1634 When nil, insert notes right after the heading and perhaps the line
1635 with deadline/scheduling if present."
1636 :group 'org-todo
1637 :group 'org-progress
1638 :type 'boolean)
1640 (defcustom org-log-states-order-reversed t
1641 "Non-nil means, the latest state change note will be directly after heading.
1642 When nil, the notes will be orderer according to time."
1643 :group 'org-todo
1644 :group 'org-progress
1645 :type 'boolean)
1647 (defcustom org-log-repeat 'time
1648 "Non-nil means, record moving through the DONE state when triggering repeat.
1649 An auto-repeating tasks is immediately switched back to TODO when marked
1650 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1651 the TODO keyword definition, or recording a closing note by setting
1652 `org-log-done', there will be no record of the task moving through DONE.
1653 This variable forces taking a note anyway. Possible values are:
1655 nil Don't force a record
1656 time Record a time stamp
1657 note Record a note
1659 This option can also be set with on a per-file-basis with
1661 #+STARTUP: logrepeat
1662 #+STARTUP: lognoterepeat
1663 #+STARTUP: nologrepeat
1665 You can have local logging settings for a subtree by setting the LOGGING
1666 property to one or more of these keywords."
1667 :group 'org-todo
1668 :group 'org-progress
1669 :type '(choice
1670 (const :tag "Don't force a record" nil)
1671 (const :tag "Force recording the DONE state" time)
1672 (const :tag "Force recording a note with the DONE state" note)))
1675 (defgroup org-priorities nil
1676 "Priorities in Org-mode."
1677 :tag "Org Priorities"
1678 :group 'org-todo)
1680 (defcustom org-highest-priority ?A
1681 "The highest priority of TODO items. A character like ?A, ?B etc.
1682 Must have a smaller ASCII number than `org-lowest-priority'."
1683 :group 'org-priorities
1684 :type 'character)
1686 (defcustom org-lowest-priority ?C
1687 "The lowest priority of TODO items. A character like ?A, ?B etc.
1688 Must have a larger ASCII number than `org-highest-priority'."
1689 :group 'org-priorities
1690 :type 'character)
1692 (defcustom org-default-priority ?B
1693 "The default priority of TODO items.
1694 This is the priority an item get if no explicit priority is given."
1695 :group 'org-priorities
1696 :type 'character)
1698 (defcustom org-priority-start-cycle-with-default t
1699 "Non-nil means, start with default priority when starting to cycle.
1700 When this is nil, the first step in the cycle will be (depending on the
1701 command used) one higher or lower that the default priority."
1702 :group 'org-priorities
1703 :type 'boolean)
1705 (defgroup org-time nil
1706 "Options concerning time stamps and deadlines in Org-mode."
1707 :tag "Org Time"
1708 :group 'org)
1710 (defcustom org-insert-labeled-timestamps-at-point nil
1711 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1712 When nil, these labeled time stamps are forces into the second line of an
1713 entry, just after the headline. When scheduling from the global TODO list,
1714 the time stamp will always be forced into the second line."
1715 :group 'org-time
1716 :type 'boolean)
1718 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1719 "Formats for `format-time-string' which are used for time stamps.
1720 It is not recommended to change this constant.")
1722 (defcustom org-time-stamp-rounding-minutes '(0 5)
1723 "Number of minutes to round time stamps to.
1724 These are two values, the first applies when first creating a time stamp.
1725 The second applies when changing it with the commands `S-up' and `S-down'.
1726 When changing the time stamp, this means that it will change in steps
1727 of N minutes, as given by the second value.
1729 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1730 numbers should be factors of 60, so for example 5, 10, 15.
1732 When this is larger than 1, you can still force an exact time-stamp by using
1733 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1734 and by using a prefix arg to `S-up/down' to specify the exact number
1735 of minutes to shift."
1736 :group 'org-time
1737 :get '(lambda (var) ; Make sure all entries have 5 elements
1738 (if (integerp (default-value var))
1739 (list (default-value var) 5)
1740 (default-value var)))
1741 :type '(list
1742 (integer :tag "when inserting times")
1743 (integer :tag "when modifying times")))
1745 ;; Normalize old customizations of this variable.
1746 (when (integerp org-time-stamp-rounding-minutes)
1747 (setq org-time-stamp-rounding-minutes
1748 (list org-time-stamp-rounding-minutes
1749 org-time-stamp-rounding-minutes)))
1751 (defcustom org-display-custom-times nil
1752 "Non-nil means, overlay custom formats over all time stamps.
1753 The formats are defined through the variable `org-time-stamp-custom-formats'.
1754 To turn this on on a per-file basis, insert anywhere in the file:
1755 #+STARTUP: customtime"
1756 :group 'org-time
1757 :set 'set-default
1758 :type 'sexp)
1759 (make-variable-buffer-local 'org-display-custom-times)
1761 (defcustom org-time-stamp-custom-formats
1762 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1763 "Custom formats for time stamps. See `format-time-string' for the syntax.
1764 These are overlayed over the default ISO format if the variable
1765 `org-display-custom-times' is set. Time like %H:%M should be at the
1766 end of the second format."
1767 :group 'org-time
1768 :type 'sexp)
1770 (defun org-time-stamp-format (&optional long inactive)
1771 "Get the right format for a time string."
1772 (let ((f (if long (cdr org-time-stamp-formats)
1773 (car org-time-stamp-formats))))
1774 (if inactive
1775 (concat "[" (substring f 1 -1) "]")
1776 f)))
1778 (defcustom org-time-clocksum-format "%d:%02d"
1779 "The format string used when creating CLOCKSUM lines, or when
1780 org-mode generates a time duration."
1781 :group 'org-time
1782 :type 'string)
1784 (defcustom org-deadline-warning-days 14
1785 "No. of days before expiration during which a deadline becomes active.
1786 This variable governs the display in sparse trees and in the agenda.
1787 When 0 or negative, it means use this number (the absolute value of it)
1788 even if a deadline has a different individual lead time specified."
1789 :group 'org-time
1790 :group 'org-agenda-daily/weekly
1791 :type 'number)
1793 (defcustom org-read-date-prefer-future t
1794 "Non-nil means, assume future for incomplete date input from user.
1795 This affects the following situations:
1796 1. The user gives a day, but no month.
1797 For example, if today is the 15th, and you enter \"3\", Org-mode will
1798 read this as the third of *next* month. However, if you enter \"17\",
1799 it will be considered as *this* month.
1800 2. The user gives a month but not a year.
1801 For example, if it is april and you enter \"feb 2\", this will be read
1802 as feb 2, *next* year. \"May 5\", however, will be this year.
1804 Currently this does not work for ISO week specifications.
1806 When this option is nil, the current month and year will always be used
1807 as defaults."
1808 :group 'org-time
1809 :type 'boolean)
1811 (defcustom org-read-date-display-live t
1812 "Non-nil means, display current interpretation of date prompt live.
1813 This display will be in an overlay, in the minibuffer."
1814 :group 'org-time
1815 :type 'boolean)
1817 (defcustom org-read-date-popup-calendar t
1818 "Non-nil means, pop up a calendar when prompting for a date.
1819 In the calendar, the date can be selected with mouse-1. However, the
1820 minibuffer will also be active, and you can simply enter the date as well.
1821 When nil, only the minibuffer will be available."
1822 :group 'org-time
1823 :type 'boolean)
1824 (if (fboundp 'defvaralias)
1825 (defvaralias 'org-popup-calendar-for-date-prompt
1826 'org-read-date-popup-calendar))
1828 (defcustom org-extend-today-until 0
1829 "The hour when your day really ends. Must be an integer.
1830 This has influence for the following applications:
1831 - When switching the agenda to \"today\". It it is still earlier than
1832 the time given here, the day recognized as TODAY is actually yesterday.
1833 - When a date is read from the user and it is still before the time given
1834 here, the current date and time will be assumed to be yesterday, 23:59.
1835 Also, timestamps inserted in remember templates follow this rule.
1837 IMPORTANT: This is a feature whose implementation is and likely will
1838 remain incomplete. Really, it is only here because past midnight seems to
1839 be the favorite working time of John Wiegley :-)"
1840 :group 'org-time
1841 :type 'number)
1843 (defcustom org-edit-timestamp-down-means-later nil
1844 "Non-nil means, S-down will increase the time in a time stamp.
1845 When nil, S-up will increase."
1846 :group 'org-time
1847 :type 'boolean)
1849 (defcustom org-calendar-follow-timestamp-change t
1850 "Non-nil means, make the calendar window follow timestamp changes.
1851 When a timestamp is modified and the calendar window is visible, it will be
1852 moved to the new date."
1853 :group 'org-time
1854 :type 'boolean)
1856 (defgroup org-tags nil
1857 "Options concerning tags in Org-mode."
1858 :tag "Org Tags"
1859 :group 'org)
1861 (defcustom org-tag-alist nil
1862 "List of tags allowed in Org-mode files.
1863 When this list is nil, Org-mode will base TAG input on what is already in the
1864 buffer.
1865 The value of this variable is an alist, the car of each entry must be a
1866 keyword as a string, the cdr may be a character that is used to select
1867 that tag through the fast-tag-selection interface.
1868 See the manual for details."
1869 :group 'org-tags
1870 :type '(repeat
1871 (choice
1872 (cons (string :tag "Tag name")
1873 (character :tag "Access char"))
1874 (const :tag "Start radio group" (:startgroup))
1875 (const :tag "End radio group" (:endgroup)))))
1877 (defvar org-file-tags nil
1878 "List of tags that can be inherited by all entries in the file.
1879 The tags will be inherited if the variable `org-use-tag-inheritance'
1880 says they should be.
1881 This variable is populated from #+TAG lines.")
1883 (defcustom org-use-fast-tag-selection 'auto
1884 "Non-nil means, use fast tag selection scheme.
1885 This is a special interface to select and deselect tags with single keys.
1886 When nil, fast selection is never used.
1887 When the symbol `auto', fast selection is used if and only if selection
1888 characters for tags have been configured, either through the variable
1889 `org-tag-alist' or through a #+TAGS line in the buffer.
1890 When t, fast selection is always used and selection keys are assigned
1891 automatically if necessary."
1892 :group 'org-tags
1893 :type '(choice
1894 (const :tag "Always" t)
1895 (const :tag "Never" nil)
1896 (const :tag "When selection characters are configured" 'auto)))
1898 (defcustom org-fast-tag-selection-single-key nil
1899 "Non-nil means, fast tag selection exits after first change.
1900 When nil, you have to press RET to exit it.
1901 During fast tag selection, you can toggle this flag with `C-c'.
1902 This variable can also have the value `expert'. In this case, the window
1903 displaying the tags menu is not even shown, until you press C-c again."
1904 :group 'org-tags
1905 :type '(choice
1906 (const :tag "No" nil)
1907 (const :tag "Yes" t)
1908 (const :tag "Expert" expert)))
1910 (defvar org-fast-tag-selection-include-todo nil
1911 "Non-nil means, fast tags selection interface will also offer TODO states.
1912 This is an undocumented feature, you should not rely on it.")
1914 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1915 "The column to which tags should be indented in a headline.
1916 If this number is positive, it specifies the column. If it is negative,
1917 it means that the tags should be flushright to that column. For example,
1918 -80 works well for a normal 80 character screen."
1919 :group 'org-tags
1920 :type 'integer)
1922 (defcustom org-auto-align-tags t
1923 "Non-nil means, realign tags after pro/demotion of TODO state change.
1924 These operations change the length of a headline and therefore shift
1925 the tags around. With this options turned on, after each such operation
1926 the tags are again aligned to `org-tags-column'."
1927 :group 'org-tags
1928 :type 'boolean)
1930 (defcustom org-use-tag-inheritance t
1931 "Non-nil means, tags in levels apply also for sublevels.
1932 When nil, only the tags directly given in a specific line apply there.
1933 This may also be a list of tags that should be inherited, or a regexp that
1934 matches tags that should be inherited. Additional control is possible
1935 with the variable `org-tags-exclude-from-inheritance' which gives an
1936 explicit list of tags to be excluded from inheritance., even if the value of
1937 `org-use-tag-inheritance' would select it for inheritance.
1939 If this option is t, a match early-on in a tree can lead to a large
1940 number of matches in the subtree when constructing the agenda or creating
1941 a sparse tree. If you only want to see the first match in a tree during
1942 a search, check out the variable `org-tags-match-list-sublevels'."
1943 :group 'org-tags
1944 :type '(choice
1945 (const :tag "Not" nil)
1946 (const :tag "Always" t)
1947 (repeat :tag "Specific tags" (string :tag "Tag"))
1948 (regexp :tag "Tags matched by regexp")))
1950 (defcustom org-tags-exclude-from-inheritance nil
1951 "List of tags that should never be inherited.
1952 This is a way to exclude a few tags from inheritance. For way to do
1953 the opposite, to actively allow inheritance for selected tags,
1954 see the variable `org-use-tag-inheritance'."
1955 :group 'org-tags
1956 :type '(repeat (string :tag "Tag")))
1958 (defun org-tag-inherit-p (tag)
1959 "Check if TAG is one that should be inherited."
1960 (cond
1961 ((member tag org-tags-exclude-from-inheritance) nil)
1962 ((eq org-use-tag-inheritance t) t)
1963 ((not org-use-tag-inheritance) nil)
1964 ((stringp org-use-tag-inheritance)
1965 (string-match org-use-tag-inheritance tag))
1966 ((listp org-use-tag-inheritance)
1967 (member tag org-use-tag-inheritance))
1968 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1970 (defcustom org-tags-match-list-sublevels t
1971 "Non-nil means list also sublevels of headlines matching tag search.
1972 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1973 the sublevels of a headline matching a tag search often also match
1974 the same search. Listing all of them can create very long lists.
1975 Setting this variable to nil causes subtrees of a match to be skipped.
1976 This option is off by default, because inheritance in on. If you turn
1977 inheritance off, you very likely want to turn this option on.
1979 As a special case, if the tag search is restricted to TODO items, the
1980 value of this variable is ignored and sublevels are always checked, to
1981 make sure all corresponding TODO items find their way into the list.
1983 This variable is semi-obsolete and probably should always be true. It
1984 is better to limit inheritance to certain tags using the variables
1985 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
1986 :group 'org-tags
1987 :type 'boolean)
1989 (defvar org-tags-history nil
1990 "History of minibuffer reads for tags.")
1991 (defvar org-last-tags-completion-table nil
1992 "The last used completion table for tags.")
1993 (defvar org-after-tags-change-hook nil
1994 "Hook that is run after the tags in a line have changed.")
1996 (defgroup org-properties nil
1997 "Options concerning properties in Org-mode."
1998 :tag "Org Properties"
1999 :group 'org)
2001 (defcustom org-property-format "%-10s %s"
2002 "How property key/value pairs should be formatted by `indent-line'.
2003 When `indent-line' hits a property definition, it will format the line
2004 according to this format, mainly to make sure that the values are
2005 lined-up with respect to each other."
2006 :group 'org-properties
2007 :type 'string)
2009 (defcustom org-use-property-inheritance nil
2010 "Non-nil means, properties apply also for sublevels.
2012 This setting is chiefly used during property searches. Turning it on can
2013 cause significant overhead when doing a search, which is why it is not
2014 on by default.
2016 When nil, only the properties directly given in the current entry count.
2017 When t, every property is inherited. The value may also be a list of
2018 properties that should have inheritance, or a regular expression matching
2019 properties that should be inherited.
2021 However, note that some special properties use inheritance under special
2022 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2023 and the properties ending in \"_ALL\" when they are used as descriptor
2024 for valid values of a property.
2026 Note for programmers:
2027 When querying an entry with `org-entry-get', you can control if inheritance
2028 should be used. By default, `org-entry-get' looks only at the local
2029 properties. You can request inheritance by setting the inherit argument
2030 to t (to force inheritance) or to `selective' (to respect the setting
2031 in this variable)."
2032 :group 'org-properties
2033 :type '(choice
2034 (const :tag "Not" nil)
2035 (const :tag "Always" t)
2036 (repeat :tag "Specific properties" (string :tag "Property"))
2037 (regexp :tag "Properties matched by regexp")))
2039 (defun org-property-inherit-p (property)
2040 "Check if PROPERTY is one that should be inherited."
2041 (cond
2042 ((eq org-use-property-inheritance t) t)
2043 ((not org-use-property-inheritance) nil)
2044 ((stringp org-use-property-inheritance)
2045 (string-match org-use-property-inheritance property))
2046 ((listp org-use-property-inheritance)
2047 (member property org-use-property-inheritance))
2048 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2050 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2051 "The default column format, if no other format has been defined.
2052 This variable can be set on the per-file basis by inserting a line
2054 #+COLUMNS: %25ITEM ....."
2055 :group 'org-properties
2056 :type 'string)
2058 (defcustom org-columns-ellipses ".."
2059 "The ellipses to be used when a field in column view is truncated.
2060 When this is the empty string, as many characters as possible are shown,
2061 but then there will be no visual indication that the field has been truncated.
2062 When this is a string of length N, the last N characters of a truncated
2063 field are replaced by this string. If the column is narrower than the
2064 ellipses string, only part of the ellipses string will be shown."
2065 :group 'org-properties
2066 :type 'string)
2068 (defcustom org-columns-modify-value-for-display-function nil
2069 "Function that modifies values for display in column view.
2070 For example, it can be used to cut out a certain part from a time stamp.
2071 The function must take 2 arguments:
2073 column-title The title of the column (*not* the property name)
2074 value The value that should be modified.
2076 The function should return the value that should be displayed,
2077 or nil if the normal value should be used."
2078 :group 'org-properties
2079 :type 'function)
2081 (defcustom org-effort-property "Effort"
2082 "The property that is being used to keep track of effort estimates.
2083 Effort estimates given in this property need to have the format H:MM."
2084 :group 'org-properties
2085 :group 'org-progress
2086 :type '(string :tag "Property"))
2088 (defconst org-global-properties-fixed
2089 '(("VISIBILITY_ALL" . "folded children content all"))
2090 "List of property/value pairs that can be inherited by any entry.
2091 These are fixed values, for the preset properties.")
2094 (defcustom org-global-properties nil
2095 "List of property/value pairs that can be inherited by any entry.
2096 You can set buffer-local values for the same purpose in the variable
2097 `org-file-properties' this by adding lines like
2099 #+PROPERTY: NAME VALUE"
2100 :group 'org-properties
2101 :type '(repeat
2102 (cons (string :tag "Property")
2103 (string :tag "Value"))))
2105 (defvar org-file-properties nil
2106 "List of property/value pairs that can be inherited by any entry.
2107 Valid for the current buffer.
2108 This variable is populated from #+PROPERTY lines.")
2109 (make-variable-buffer-local 'org-file-properties)
2111 (defgroup org-agenda nil
2112 "Options concerning agenda views in Org-mode."
2113 :tag "Org Agenda"
2114 :group 'org)
2116 (defvar org-category nil
2117 "Variable used by org files to set a category for agenda display.
2118 Such files should use a file variable to set it, for example
2120 # -*- mode: org; org-category: \"ELisp\"
2122 or contain a special line
2124 #+CATEGORY: ELisp
2126 If the file does not specify a category, then file's base name
2127 is used instead.")
2128 (make-variable-buffer-local 'org-category)
2129 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2131 (defcustom org-agenda-files nil
2132 "The files to be used for agenda display.
2133 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2134 \\[org-remove-file]. You can also use customize to edit the list.
2136 If an entry is a directory, all files in that directory that are matched by
2137 `org-agenda-file-regexp' will be part of the file list.
2139 If the value of the variable is not a list but a single file name, then
2140 the list of agenda files is actually stored and maintained in that file, one
2141 agenda file per line."
2142 :group 'org-agenda
2143 :type '(choice
2144 (repeat :tag "List of files and directories" file)
2145 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2147 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2148 "Regular expression to match files for `org-agenda-files'.
2149 If any element in the list in that variable contains a directory instead
2150 of a normal file, all files in that directory that are matched by this
2151 regular expression will be included."
2152 :group 'org-agenda
2153 :type 'regexp)
2155 (defcustom org-agenda-text-search-extra-files nil
2156 "List of extra files to be searched by text search commands.
2157 These files will be search in addition to the agenda files by the
2158 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2159 Note that these files will only be searched for text search commands,
2160 not for the other agenda views like todo lists, tag searches or the weekly
2161 agenda. This variable is intended to list notes and possibly archive files
2162 that should also be searched by these two commands.
2163 In fact, if the first element in the list is the symbol `agenda-archives',
2164 than all archive files of all agenda files will be added to the search
2165 scope."
2166 :group 'org-agenda
2167 :type '(set :greedy t
2168 (const :tag "Agenda Archives" agenda-archives)
2169 (repeat :inline t (file))))
2171 (if (fboundp 'defvaralias)
2172 (defvaralias 'org-agenda-multi-occur-extra-files
2173 'org-agenda-text-search-extra-files))
2175 (defcustom org-agenda-skip-unavailable-files nil
2176 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2177 A nil value means to remove them, after a query, from the list."
2178 :group 'org-agenda
2179 :type 'boolean)
2181 (defcustom org-calendar-to-agenda-key [?c]
2182 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2183 The command `org-calendar-goto-agenda' will be bound to this key. The
2184 default is the character `c' because then `c' can be used to switch back and
2185 forth between agenda and calendar."
2186 :group 'org-agenda
2187 :type 'sexp)
2189 (defcustom org-calendar-agenda-action-key [?k]
2190 "The key to be installed in `calendar-mode-map' for agenda-action.
2191 The command `org-agenda-action' will be bound to this key. The
2192 default is the character `k' because we use the same key in the agenda."
2193 :group 'org-agenda
2194 :type 'sexp)
2196 (eval-after-load "calendar"
2197 '(progn
2198 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2199 'org-calendar-goto-agenda)
2200 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2201 'org-agenda-action)))
2203 (defgroup org-latex nil
2204 "Options for embedding LaTeX code into Org-mode."
2205 :tag "Org LaTeX"
2206 :group 'org)
2208 (defcustom org-format-latex-options
2209 '(:foreground default :background default :scale 1.0
2210 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2211 :matchers ("begin" "$" "$$" "\\(" "\\["))
2212 "Options for creating images from LaTeX fragments.
2213 This is a property list with the following properties:
2214 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2215 `default' means use the foreground of the default face.
2216 :background the background color, or \"Transparent\".
2217 `default' means use the background of the default face.
2218 :scale a scaling factor for the size of the images.
2219 :html-foreground, :html-background, :html-scale
2220 the same numbers for HTML export.
2221 :matchers a list indicating which matchers should be used to
2222 find LaTeX fragments. Valid members of this list are:
2223 \"begin\" find environments
2224 \"$\" find math expressions surrounded by $...$
2225 \"$$\" find math expressions surrounded by $$....$$
2226 \"\\(\" find math expressions surrounded by \\(...\\)
2227 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2228 :group 'org-latex
2229 :type 'plist)
2231 (defcustom org-format-latex-header "\\documentclass{article}
2232 \\usepackage{fullpage} % do not remove
2233 \\usepackage{amssymb}
2234 \\usepackage[usenames]{color}
2235 \\usepackage{amsmath}
2236 \\usepackage{latexsym}
2237 \\usepackage[mathscr]{eucal}
2238 \\pagestyle{empty} % do not remove"
2239 "The document header used for processing LaTeX fragments."
2240 :group 'org-latex
2241 :type 'string)
2244 (defgroup org-font-lock nil
2245 "Font-lock settings for highlighting in Org-mode."
2246 :tag "Org Font Lock"
2247 :group 'org)
2249 (defcustom org-level-color-stars-only nil
2250 "Non-nil means fontify only the stars in each headline.
2251 When nil, the entire headline is fontified.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified."
2254 :group 'org-font-lock
2255 :type 'boolean)
2257 (defcustom org-hide-leading-stars nil
2258 "Non-nil means, hide the first N-1 stars in a headline.
2259 This works by using the face `org-hide' for these stars. This
2260 face is white for a light background, and black for a dark
2261 background. You may have to customize the face `org-hide' to
2262 make this work.
2263 Changing it requires restart of `font-lock-mode' to become effective
2264 also in regions already fontified.
2265 You may also set this on a per-file basis by adding one of the following
2266 lines to the buffer:
2268 #+STARTUP: hidestars
2269 #+STARTUP: showstars"
2270 :group 'org-font-lock
2271 :type 'boolean)
2273 (defcustom org-fontify-done-headline nil
2274 "Non-nil means, change the face of a headline if it is marked DONE.
2275 Normally, only the TODO/DONE keyword indicates the state of a headline.
2276 When this is non-nil, the headline after the keyword is set to the
2277 `org-headline-done' as an additional indication."
2278 :group 'org-font-lock
2279 :type 'boolean)
2281 (defcustom org-fontify-emphasized-text t
2282 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2283 Changing this variable requires a restart of Emacs to take effect."
2284 :group 'org-font-lock
2285 :type 'boolean)
2287 (defcustom org-highlight-latex-fragments-and-specials nil
2288 "Non-nil means, fontify what is treated specially by the exporters."
2289 :group 'org-font-lock
2290 :type 'boolean)
2292 (defcustom org-hide-emphasis-markers nil
2293 "Non-nil mean font-lock should hide the emphasis marker characters."
2294 :group 'org-font-lock
2295 :type 'boolean)
2297 (defvar org-emph-re nil
2298 "Regular expression for matching emphasis.")
2299 (defvar org-verbatim-re nil
2300 "Regular expression for matching verbatim text.")
2301 (defvar org-emphasis-regexp-components) ; defined just below
2302 (defvar org-emphasis-alist) ; defined just below
2303 (defun org-set-emph-re (var val)
2304 "Set variable and compute the emphasis regular expression."
2305 (set var val)
2306 (when (and (boundp 'org-emphasis-alist)
2307 (boundp 'org-emphasis-regexp-components)
2308 org-emphasis-alist org-emphasis-regexp-components)
2309 (let* ((e org-emphasis-regexp-components)
2310 (pre (car e))
2311 (post (nth 1 e))
2312 (border (nth 2 e))
2313 (body (nth 3 e))
2314 (nl (nth 4 e))
2315 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2316 (body1 (concat body "*?"))
2317 (markers (mapconcat 'car org-emphasis-alist ""))
2318 (vmarkers (mapconcat
2319 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2320 org-emphasis-alist "")))
2321 ;; make sure special characters appear at the right position in the class
2322 (if (string-match "\\^" markers)
2323 (setq markers (concat (replace-match "" t t markers) "^")))
2324 (if (string-match "-" markers)
2325 (setq markers (concat (replace-match "" t t markers) "-")))
2326 (if (string-match "\\^" vmarkers)
2327 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2328 (if (string-match "-" vmarkers)
2329 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2330 (if (> nl 0)
2331 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2332 (int-to-string nl) "\\}")))
2333 ;; Make the regexp
2334 (setq org-emph-re
2335 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2336 "\\("
2337 "\\([" markers "]\\)"
2338 "\\("
2339 "[^" border "]\\|"
2340 "[^" border (if (and nil stacked) markers) "]"
2341 body1
2342 "[^" border (if (and nil stacked) markers) "]"
2343 "\\)"
2344 "\\3\\)"
2345 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2346 (setq org-verbatim-re
2347 (concat "\\([" pre "]\\|^\\)"
2348 "\\("
2349 "\\([" vmarkers "]\\)"
2350 "\\("
2351 "[^" border "]\\|"
2352 "[^" border "]"
2353 body1
2354 "[^" border "]"
2355 "\\)"
2356 "\\3\\)"
2357 "\\([" post "]\\|$\\)")))))
2359 (defcustom org-emphasis-regexp-components
2360 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2361 "Components used to build the regular expression for emphasis.
2362 This is a list with 6 entries. Terminology: In an emphasis string
2363 like \" *strong word* \", we call the initial space PREMATCH, the final
2364 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2365 and \"trong wor\" is the body. The different components in this variable
2366 specify what is allowed/forbidden in each part:
2368 pre Chars allowed as prematch. Beginning of line will be allowed too.
2369 post Chars allowed as postmatch. End of line will be allowed too.
2370 border The chars *forbidden* as border characters.
2371 body-regexp A regexp like \".\" to match a body character. Don't use
2372 non-shy groups here, and don't allow newline here.
2373 newline The maximum number of newlines allowed in an emphasis exp.
2375 Use customize to modify this, or restart Emacs after changing it."
2376 :group 'org-font-lock
2377 :set 'org-set-emph-re
2378 :type '(list
2379 (sexp :tag "Allowed chars in pre ")
2380 (sexp :tag "Allowed chars in post ")
2381 (sexp :tag "Forbidden chars in border ")
2382 (sexp :tag "Regexp for body ")
2383 (integer :tag "number of newlines allowed")
2384 (option (boolean :tag "Please ignore this button"))))
2386 (defcustom org-emphasis-alist
2387 `(("*" bold "<b>" "</b>")
2388 ("/" italic "<i>" "</i>")
2389 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2390 ("=" org-code "<code>" "</code>" verbatim)
2391 ("~" org-verbatim "<code>" "</code>" verbatim)
2392 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2393 "<del>" "</del>")
2395 "Special syntax for emphasized text.
2396 Text starting and ending with a special character will be emphasized, for
2397 example *bold*, _underlined_ and /italic/. This variable sets the marker
2398 characters, the face to be used by font-lock for highlighting in Org-mode
2399 Emacs buffers, and the HTML tags to be used for this.
2400 Use customize to modify this, or restart Emacs after changing it."
2401 :group 'org-font-lock
2402 :set 'org-set-emph-re
2403 :type '(repeat
2404 (list
2405 (string :tag "Marker character")
2406 (choice
2407 (face :tag "Font-lock-face")
2408 (plist :tag "Face property list"))
2409 (string :tag "HTML start tag")
2410 (string :tag "HTML end tag")
2411 (option (const verbatim)))))
2413 ;;; Miscellaneous options
2415 (defgroup org-completion nil
2416 "Completion in Org-mode."
2417 :tag "Org Completion"
2418 :group 'org)
2420 (defcustom org-completion-use-ido nil
2421 "Non-nil means, use ido completion wherever possible."
2422 :group 'org-completion
2423 :type 'boolean)
2425 (defcustom org-completion-fallback-command 'hippie-expand
2426 "The expansion command called by \\[org-complete] in normal context.
2427 Normal means, no org-mode-specific context."
2428 :group 'org-completion
2429 :type 'function)
2431 ;;; Functions and variables from ther packages
2432 ;; Declared here to avoid compiler warnings
2434 ;; XEmacs only
2435 (defvar outline-mode-menu-heading)
2436 (defvar outline-mode-menu-show)
2437 (defvar outline-mode-menu-hide)
2438 (defvar zmacs-regions) ; XEmacs regions
2440 ;; Emacs only
2441 (defvar mark-active)
2443 ;; Various packages
2444 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2445 (declare-function calendar-forward-day "cal-move" (arg))
2446 (declare-function calendar-goto-date "cal-move" (date))
2447 (declare-function calendar-goto-today "cal-move" ())
2448 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2449 (defvar calc-embedded-close-formula)
2450 (defvar calc-embedded-open-formula)
2451 (declare-function cdlatex-tab "ext:cdlatex" ())
2452 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2453 (defvar font-lock-unfontify-region-function)
2454 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2455 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2456 (defvar iswitchb-temp-buflist)
2457 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2458 (declare-function org-agenda-skip "org-agenda" ())
2459 (declare-function org-format-agenda-item "org-agenda"
2460 (extra txt &optional category tags dotime noprefix remove-re))
2461 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2462 (declare-function org-agenda-change-all-lines "org-agenda"
2463 (newhead hdmarker &optional fixface just-this))
2464 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2465 (declare-function org-agenda-maybe-redo "org-agenda" ())
2466 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2467 (beg end))
2468 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2469 (declare-function parse-time-string "parse-time" (string))
2470 (declare-function remember "remember" (&optional initial))
2471 (declare-function remember-buffer-desc "remember" ())
2472 (declare-function remember-finalize "remember" ())
2473 (defvar remember-save-after-remembering)
2474 (defvar remember-data-file)
2475 (defvar remember-register)
2476 (defvar remember-buffer)
2477 (defvar remember-handler-functions)
2478 (defvar remember-annotation-functions)
2479 (defvar texmathp-why)
2480 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2481 (declare-function table--at-cell-p "table" (position &optional object at-column))
2483 (defvar w3m-current-url)
2484 (defvar w3m-current-title)
2486 (defvar org-latex-regexps)
2488 ;;; Autoload and prepare some org modules
2490 ;; Some table stuff that needs to be defined here, because it is used
2491 ;; by the functions setting up org-mode or checking for table context.
2493 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2494 "Detects an org-type or table-type table.")
2495 (defconst org-table-line-regexp "^[ \t]*|"
2496 "Detects an org-type table line.")
2497 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2498 "Detects an org-type table line.")
2499 (defconst org-table-hline-regexp "^[ \t]*|-"
2500 "Detects an org-type table hline.")
2501 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2502 "Detects a table-type table hline.")
2503 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2504 "Searching from within a table (any type) this finds the first line
2505 outside the table.")
2507 ;; Autoload the functions in org-table.el that are needed by functions here.
2509 (eval-and-compile
2510 (org-autoload "org-table"
2511 '(org-table-align org-table-begin org-table-blank-field
2512 org-table-convert org-table-convert-region org-table-copy-down
2513 org-table-copy-region org-table-create
2514 org-table-create-or-convert-from-region
2515 org-table-create-with-table.el org-table-current-dline
2516 org-table-cut-region org-table-delete-column org-table-edit-field
2517 org-table-edit-formulas org-table-end org-table-eval-formula
2518 org-table-export org-table-field-info
2519 org-table-get-stored-formulas org-table-goto-column
2520 org-table-hline-and-move org-table-import org-table-insert-column
2521 org-table-insert-hline org-table-insert-row org-table-iterate
2522 org-table-justify-field-maybe org-table-kill-row
2523 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2524 org-table-move-column org-table-move-column-left
2525 org-table-move-column-right org-table-move-row
2526 org-table-move-row-down org-table-move-row-up
2527 org-table-next-field org-table-next-row org-table-paste-rectangle
2528 org-table-previous-field org-table-recalculate
2529 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2530 org-table-toggle-coordinate-overlays
2531 org-table-toggle-formula-debugger org-table-wrap-region
2532 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2534 (defun org-at-table-p (&optional table-type)
2535 "Return t if the cursor is inside an org-type table.
2536 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2537 (if org-enable-table-editor
2538 (save-excursion
2539 (beginning-of-line 1)
2540 (looking-at (if table-type org-table-any-line-regexp
2541 org-table-line-regexp)))
2542 nil))
2543 (defsubst org-table-p () (org-at-table-p))
2545 (defun org-at-table.el-p ()
2546 "Return t if and only if we are at a table.el table."
2547 (and (org-at-table-p 'any)
2548 (save-excursion
2549 (goto-char (org-table-begin 'any))
2550 (looking-at org-table1-hline-regexp))))
2551 (defun org-table-recognize-table.el ()
2552 "If there is a table.el table nearby, recognize it and move into it."
2553 (if org-table-tab-recognizes-table.el
2554 (if (org-at-table.el-p)
2555 (progn
2556 (beginning-of-line 1)
2557 (if (looking-at org-table-dataline-regexp)
2559 (if (looking-at org-table1-hline-regexp)
2560 (progn
2561 (beginning-of-line 2)
2562 (if (looking-at org-table-any-border-regexp)
2563 (beginning-of-line -1)))))
2564 (if (re-search-forward "|" (org-table-end t) t)
2565 (progn
2566 (require 'table)
2567 (if (table--at-cell-p (point))
2569 (message "recognizing table.el table...")
2570 (table-recognize-table)
2571 (message "recognizing table.el table...done")))
2572 (error "This should not happen..."))
2574 nil)
2575 nil))
2577 (defun org-at-table-hline-p ()
2578 "Return t if the cursor is inside a hline in a table."
2579 (if org-enable-table-editor
2580 (save-excursion
2581 (beginning-of-line 1)
2582 (looking-at org-table-hline-regexp))
2583 nil))
2585 (defvar org-table-clean-did-remove-column nil)
2587 (defun org-table-map-tables (function)
2588 "Apply FUNCTION to the start of all tables in the buffer."
2589 (save-excursion
2590 (save-restriction
2591 (widen)
2592 (goto-char (point-min))
2593 (while (re-search-forward org-table-any-line-regexp nil t)
2594 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2595 (beginning-of-line 1)
2596 (if (looking-at org-table-line-regexp)
2597 (save-excursion (funcall function)))
2598 (re-search-forward org-table-any-border-regexp nil 1))))
2599 (message "Mapping tables: done"))
2601 ;; Declare and autoload functions from org-exp.el
2603 (declare-function org-default-export-plist "org-exp")
2604 (declare-function org-infile-export-plist "org-exp")
2605 (declare-function org-get-current-options "org-exp")
2606 (eval-and-compile
2607 (org-autoload "org-exp"
2608 '(org-export org-export-as-ascii org-export-visible
2609 org-insert-export-options-template org-export-as-html-and-open
2610 org-export-as-html-batch org-export-as-html-to-buffer
2611 org-replace-region-by-html org-export-region-as-html
2612 org-export-as-html org-export-icalendar-this-file
2613 org-export-icalendar-all-agenda-files
2614 org-table-clean-before-export
2615 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2617 ;; Declare and autoload functions from org-agenda.el
2619 (eval-and-compile
2620 (org-autoload "org-agenda"
2621 '(org-agenda org-agenda-list org-search-view
2622 org-todo-list org-tags-view org-agenda-list-stuck-projects
2623 org-diary org-agenda-to-appt)))
2625 ;; Autoload org-remember
2627 (eval-and-compile
2628 (org-autoload "org-remember"
2629 '(org-remember-insinuate org-remember-annotation
2630 org-remember-apply-template org-remember org-remember-handler)))
2632 ;; Autoload org-clock.el
2635 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2636 (beg end))
2637 (declare-function org-update-mode-line "org-clock" ())
2638 (defvar org-clock-start-time)
2639 (defvar org-clock-marker (make-marker)
2640 "Marker recording the last clock-in.")
2642 (eval-and-compile
2643 (org-autoload
2644 "org-clock"
2645 '(org-clock-in org-clock-out org-clock-cancel
2646 org-clock-goto org-clock-sum org-clock-display
2647 org-remove-clock-overlays org-clock-report
2648 org-clocktable-shift org-dblock-write:clocktable
2649 org-get-clocktable)))
2651 (defun org-clock-update-time-maybe ()
2652 "If this is a CLOCK line, update it and return t.
2653 Otherwise, return nil."
2654 (interactive)
2655 (save-excursion
2656 (beginning-of-line 1)
2657 (skip-chars-forward " \t")
2658 (when (looking-at org-clock-string)
2659 (let ((re (concat "[ \t]*" org-clock-string
2660 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2661 "\\([ \t]*=>.*\\)?\\)?"))
2662 ts te h m s neg)
2663 (cond
2664 ((not (looking-at re))
2665 nil)
2666 ((not (match-end 2))
2667 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2668 (> org-clock-marker (point))
2669 (<= org-clock-marker (point-at-eol)))
2670 ;; The clock is running here
2671 (setq org-clock-start-time
2672 (apply 'encode-time
2673 (org-parse-time-string (match-string 1))))
2674 (org-update-mode-line)))
2676 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2677 (end-of-line 1)
2678 (setq ts (match-string 1)
2679 te (match-string 3))
2680 (setq s (- (time-to-seconds
2681 (apply 'encode-time (org-parse-time-string te)))
2682 (time-to-seconds
2683 (apply 'encode-time (org-parse-time-string ts))))
2684 neg (< s 0)
2685 s (abs s)
2686 h (floor (/ s 3600))
2687 s (- s (* 3600 h))
2688 m (floor (/ s 60))
2689 s (- s (* 60 s)))
2690 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2691 t))))))
2693 (defun org-check-running-clock ()
2694 "Check if the current buffer contains the running clock.
2695 If yes, offer to stop it and to save the buffer with the changes."
2696 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2697 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2698 (buffer-name))))
2699 (org-clock-out)
2700 (when (y-or-n-p "Save changed buffer?")
2701 (save-buffer))))
2703 (defun org-clocktable-try-shift (dir n)
2704 "Check if this line starts a clock table, if yes, shift the time block."
2705 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2706 (org-clocktable-shift dir n)))
2708 ;; Autoload org-timer.el
2710 ;(declare-function org-timer "org-timer")
2712 (eval-and-compile
2713 (org-autoload
2714 "org-timer"
2715 '(org-timer-start org-timer org-timer-item
2716 org-timer-change-times-in-region)))
2719 ;; Autoload archiving code
2720 ;; The stuff that is needed for cycling and tags has to be defined here.
2722 (defgroup org-archive nil
2723 "Options concerning archiving in Org-mode."
2724 :tag "Org Archive"
2725 :group 'org-structure)
2727 (defcustom org-archive-location "%s_archive::"
2728 "The location where subtrees should be archived.
2730 The value of this variable is a string, consisting of two parts,
2731 separated by a double-colon. The first part is a filename and
2732 the second part is a headline.
2734 When the filename is omitted, archiving happens in the same file.
2735 %s in the filename will be replaced by the current file
2736 name (without the directory part). Archiving to a different file
2737 is useful to keep archived entries from contributing to the
2738 Org-mode Agenda.
2740 The archived entries will be filed as subtrees of the specified
2741 headline. When the headline is omitted, the subtrees are simply
2742 filed away at the end of the file, as top-level entries.
2744 Here are a few examples:
2745 \"%s_archive::\"
2746 If the current file is Projects.org, archive in file
2747 Projects.org_archive, as top-level trees. This is the default.
2749 \"::* Archived Tasks\"
2750 Archive in the current file, under the top-level headline
2751 \"* Archived Tasks\".
2753 \"~/org/archive.org::\"
2754 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2756 \"basement::** Finished Tasks\"
2757 Archive in file ./basement (relative path), as level 3 trees
2758 below the level 2 heading \"** Finished Tasks\".
2760 You may set this option on a per-file basis by adding to the buffer a
2761 line like
2763 #+ARCHIVE: basement::** Finished Tasks
2765 You may also define it locally for a subtree by setting an ARCHIVE property
2766 in the entry. If such a property is found in an entry, or anywhere up
2767 the hierarchy, it will be used."
2768 :group 'org-archive
2769 :type 'string)
2771 (defcustom org-archive-tag "ARCHIVE"
2772 "The tag that marks a subtree as archived.
2773 An archived subtree does not open during visibility cycling, and does
2774 not contribute to the agenda listings.
2775 After changing this, font-lock must be restarted in the relevant buffers to
2776 get the proper fontification."
2777 :group 'org-archive
2778 :group 'org-keywords
2779 :type 'string)
2781 (defcustom org-agenda-skip-archived-trees t
2782 "Non-nil means, the agenda will skip any items located in archived trees.
2783 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2784 variable is no longer recommended, you should leave it at the value t.
2785 Instead, use the key `v' to cycle the archives-mode in the agenda."
2786 :group 'org-archive
2787 :group 'org-agenda-skip
2788 :type 'boolean)
2790 (defcustom org-cycle-open-archived-trees nil
2791 "Non-nil means, `org-cycle' will open archived trees.
2792 An archived tree is a tree marked with the tag ARCHIVE.
2793 When nil, archived trees will stay folded. You can still open them with
2794 normal outline commands like `show-all', but not with the cycling commands."
2795 :group 'org-archive
2796 :group 'org-cycle
2797 :type 'boolean)
2799 (defcustom org-sparse-tree-open-archived-trees nil
2800 "Non-nil means sparse tree construction shows matches in archived trees.
2801 When nil, matches in these trees are highlighted, but the trees are kept in
2802 collapsed state."
2803 :group 'org-archive
2804 :group 'org-sparse-trees
2805 :type 'boolean)
2807 (defun org-cycle-hide-archived-subtrees (state)
2808 "Re-hide all archived subtrees after a visibility state change."
2809 (when (and (not org-cycle-open-archived-trees)
2810 (not (memq state '(overview folded))))
2811 (save-excursion
2812 (let* ((globalp (memq state '(contents all)))
2813 (beg (if globalp (point-min) (point)))
2814 (end (if globalp (point-max) (org-end-of-subtree t))))
2815 (org-hide-archived-subtrees beg end)
2816 (goto-char beg)
2817 (if (looking-at (concat ".*:" org-archive-tag ":"))
2818 (message "%s" (substitute-command-keys
2819 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2821 (defun org-force-cycle-archived ()
2822 "Cycle subtree even if it is archived."
2823 (interactive)
2824 (setq this-command 'org-cycle)
2825 (let ((org-cycle-open-archived-trees t))
2826 (call-interactively 'org-cycle)))
2828 (defun org-hide-archived-subtrees (beg end)
2829 "Re-hide all archived subtrees after a visibility state change."
2830 (save-excursion
2831 (let* ((re (concat ":" org-archive-tag ":")))
2832 (goto-char beg)
2833 (while (re-search-forward re end t)
2834 (and (org-on-heading-p) (hide-subtree))
2835 (org-end-of-subtree t)))))
2837 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2839 (eval-and-compile
2840 (org-autoload "org-archive"
2841 '(org-add-archive-files org-archive-subtree
2842 org-archive-to-archive-sibling org-toggle-archive-tag)))
2844 ;; Autoload Column View Code
2846 (declare-function org-columns-number-to-string "org-colview")
2847 (declare-function org-columns-get-format-and-top-level "org-colview")
2848 (declare-function org-columns-compute "org-colview")
2850 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2851 '(org-columns-number-to-string org-columns-get-format-and-top-level
2852 org-columns-compute org-agenda-columns org-columns-remove-overlays
2853 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2855 ;; Autoload ID code
2857 (declare-function org-id-store-link "org-id")
2858 (org-autoload "org-id"
2859 '(org-id-get-create org-id-new org-id-copy org-id-get
2860 org-id-get-with-outline-path-completion
2861 org-id-get-with-outline-drilling
2862 org-id-goto org-id-find org-id-store-link))
2864 ;;; Variables for pre-computed regular expressions, all buffer local
2866 (defvar org-drawer-regexp nil
2867 "Matches first line of a hidden block.")
2868 (make-variable-buffer-local 'org-drawer-regexp)
2869 (defvar org-todo-regexp nil
2870 "Matches any of the TODO state keywords.")
2871 (make-variable-buffer-local 'org-todo-regexp)
2872 (defvar org-not-done-regexp nil
2873 "Matches any of the TODO state keywords except the last one.")
2874 (make-variable-buffer-local 'org-not-done-regexp)
2875 (defvar org-todo-line-regexp nil
2876 "Matches a headline and puts TODO state into group 2 if present.")
2877 (make-variable-buffer-local 'org-todo-line-regexp)
2878 (defvar org-complex-heading-regexp nil
2879 "Matches a headline and puts everything into groups:
2880 group 1: the stars
2881 group 2: The todo keyword, maybe
2882 group 3: Priority cookie
2883 group 4: True headline
2884 group 5: Tags")
2885 (make-variable-buffer-local 'org-complex-heading-regexp)
2886 (defvar org-todo-line-tags-regexp nil
2887 "Matches a headline and puts TODO state into group 2 if present.
2888 Also put tags into group 4 if tags are present.")
2889 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2890 (defvar org-nl-done-regexp nil
2891 "Matches newline followed by a headline with the DONE keyword.")
2892 (make-variable-buffer-local 'org-nl-done-regexp)
2893 (defvar org-looking-at-done-regexp nil
2894 "Matches the DONE keyword a point.")
2895 (make-variable-buffer-local 'org-looking-at-done-regexp)
2896 (defvar org-ds-keyword-length 12
2897 "Maximum length of the Deadline and SCHEDULED keywords.")
2898 (make-variable-buffer-local 'org-ds-keyword-length)
2899 (defvar org-deadline-regexp nil
2900 "Matches the DEADLINE keyword.")
2901 (make-variable-buffer-local 'org-deadline-regexp)
2902 (defvar org-deadline-time-regexp nil
2903 "Matches the DEADLINE keyword together with a time stamp.")
2904 (make-variable-buffer-local 'org-deadline-time-regexp)
2905 (defvar org-deadline-line-regexp nil
2906 "Matches the DEADLINE keyword and the rest of the line.")
2907 (make-variable-buffer-local 'org-deadline-line-regexp)
2908 (defvar org-scheduled-regexp nil
2909 "Matches the SCHEDULED keyword.")
2910 (make-variable-buffer-local 'org-scheduled-regexp)
2911 (defvar org-scheduled-time-regexp nil
2912 "Matches the SCHEDULED keyword together with a time stamp.")
2913 (make-variable-buffer-local 'org-scheduled-time-regexp)
2914 (defvar org-closed-time-regexp nil
2915 "Matches the CLOSED keyword together with a time stamp.")
2916 (make-variable-buffer-local 'org-closed-time-regexp)
2918 (defvar org-keyword-time-regexp nil
2919 "Matches any of the 4 keywords, together with the time stamp.")
2920 (make-variable-buffer-local 'org-keyword-time-regexp)
2921 (defvar org-keyword-time-not-clock-regexp nil
2922 "Matches any of the 3 keywords, together with the time stamp.")
2923 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2924 (defvar org-maybe-keyword-time-regexp nil
2925 "Matches a timestamp, possibly preceeded by a keyword.")
2926 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2927 (defvar org-planning-or-clock-line-re nil
2928 "Matches a line with planning or clock info.")
2929 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2931 (defconst org-plain-time-of-day-regexp
2932 (concat
2933 "\\(\\<[012]?[0-9]"
2934 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2935 "\\(--?"
2936 "\\(\\<[012]?[0-9]"
2937 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2938 "\\)?")
2939 "Regular expression to match a plain time or time range.
2940 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2941 groups carry important information:
2942 0 the full match
2943 1 the first time, range or not
2944 8 the second time, if it is a range.")
2946 (defconst org-plain-time-extension-regexp
2947 (concat
2948 "\\(\\<[012]?[0-9]"
2949 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2950 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2951 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2952 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2953 groups carry important information:
2954 0 the full match
2955 7 hours of duration
2956 9 minutes of duration")
2958 (defconst org-stamp-time-of-day-regexp
2959 (concat
2960 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2961 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2962 "\\(--?"
2963 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2964 "Regular expression to match a timestamp time or time range.
2965 After a match, the following groups carry important information:
2966 0 the full match
2967 1 date plus weekday, for backreferencing to make sure both times on same day
2968 2 the first time, range or not
2969 4 the second time, if it is a range.")
2971 (defconst org-startup-options
2972 '(("fold" org-startup-folded t)
2973 ("overview" org-startup-folded t)
2974 ("nofold" org-startup-folded nil)
2975 ("showall" org-startup-folded nil)
2976 ("content" org-startup-folded content)
2977 ("hidestars" org-hide-leading-stars t)
2978 ("showstars" org-hide-leading-stars nil)
2979 ("odd" org-odd-levels-only t)
2980 ("oddeven" org-odd-levels-only nil)
2981 ("align" org-startup-align-all-tables t)
2982 ("noalign" org-startup-align-all-tables nil)
2983 ("customtime" org-display-custom-times t)
2984 ("logdone" org-log-done time)
2985 ("lognotedone" org-log-done note)
2986 ("nologdone" org-log-done nil)
2987 ("lognoteclock-out" org-log-note-clock-out t)
2988 ("nolognoteclock-out" org-log-note-clock-out nil)
2989 ("logrepeat" org-log-repeat state)
2990 ("lognoterepeat" org-log-repeat note)
2991 ("nologrepeat" org-log-repeat nil)
2992 ("constcgs" constants-unit-system cgs)
2993 ("constSI" constants-unit-system SI))
2994 "Variable associated with STARTUP options for org-mode.
2995 Each element is a list of three items: The startup options as written
2996 in the #+STARTUP line, the corresponding variable, and the value to
2997 set this variable to if the option is found. An optional forth element PUSH
2998 means to push this value onto the list in the variable.")
3000 (defun org-set-regexps-and-options ()
3001 "Precompute regular expressions for current buffer."
3002 (when (org-mode-p)
3003 (org-set-local 'org-todo-kwd-alist nil)
3004 (org-set-local 'org-todo-key-alist nil)
3005 (org-set-local 'org-todo-key-trigger nil)
3006 (org-set-local 'org-todo-keywords-1 nil)
3007 (org-set-local 'org-done-keywords nil)
3008 (org-set-local 'org-todo-heads nil)
3009 (org-set-local 'org-todo-sets nil)
3010 (org-set-local 'org-todo-log-states nil)
3011 (org-set-local 'org-file-properties nil)
3012 (org-set-local 'org-file-tags nil)
3013 (let ((re (org-make-options-regexp
3014 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3015 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3016 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3017 (splitre "[ \t]+")
3018 kwds kws0 kwsa key log value cat arch tags const links hw dws
3019 tail sep kws1 prio props ftags drawers
3020 ext-setup-or-nil setup-contents (start 0))
3021 (save-excursion
3022 (save-restriction
3023 (widen)
3024 (goto-char (point-min))
3025 (while (or (and ext-setup-or-nil
3026 (string-match re ext-setup-or-nil start)
3027 (setq start (match-end 0)))
3028 (and (setq ext-setup-or-nil nil start 0)
3029 (re-search-forward re nil t)))
3030 (setq key (upcase (match-string 1 ext-setup-or-nil))
3031 value (org-match-string-no-properties 2 ext-setup-or-nil))
3032 (cond
3033 ((equal key "CATEGORY")
3034 (if (string-match "[ \t]+$" value)
3035 (setq value (replace-match "" t t value)))
3036 (setq cat value))
3037 ((member key '("SEQ_TODO" "TODO"))
3038 (push (cons 'sequence (org-split-string value splitre)) kwds))
3039 ((equal key "TYP_TODO")
3040 (push (cons 'type (org-split-string value splitre)) kwds))
3041 ((equal key "TAGS")
3042 (setq tags (append tags (org-split-string value splitre))))
3043 ((equal key "COLUMNS")
3044 (org-set-local 'org-columns-default-format value))
3045 ((equal key "LINK")
3046 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3047 (push (cons (match-string 1 value)
3048 (org-trim (match-string 2 value)))
3049 links)))
3050 ((equal key "PRIORITIES")
3051 (setq prio (org-split-string value " +")))
3052 ((equal key "PROPERTY")
3053 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3054 (push (cons (match-string 1 value) (match-string 2 value))
3055 props)))
3056 ((equal key "FILETAGS")
3057 (when (string-match "\\S-" value)
3058 (setq ftags
3059 (append
3060 ftags
3061 (apply 'append
3062 (mapcar (lambda (x) (org-split-string x ":"))
3063 (org-split-string value)))))))
3064 ((equal key "DRAWERS")
3065 (setq drawers (org-split-string value splitre)))
3066 ((equal key "CONSTANTS")
3067 (setq const (append const (org-split-string value splitre))))
3068 ((equal key "STARTUP")
3069 (let ((opts (org-split-string value splitre))
3070 l var val)
3071 (while (setq l (pop opts))
3072 (when (setq l (assoc l org-startup-options))
3073 (setq var (nth 1 l) val (nth 2 l))
3074 (if (not (nth 3 l))
3075 (set (make-local-variable var) val)
3076 (if (not (listp (symbol-value var)))
3077 (set (make-local-variable var) nil))
3078 (set (make-local-variable var) (symbol-value var))
3079 (add-to-list var val))))))
3080 ((equal key "ARCHIVE")
3081 (string-match " *$" value)
3082 (setq arch (replace-match "" t t value))
3083 (remove-text-properties 0 (length arch)
3084 '(face t fontified t) arch))
3085 ((equal key "SETUPFILE")
3086 (setq setup-contents (org-file-contents
3087 (expand-file-name
3088 (org-remove-double-quotes value))
3089 'noerror))
3090 (if (not ext-setup-or-nil)
3091 (setq ext-setup-or-nil setup-contents start 0)
3092 (setq ext-setup-or-nil
3093 (concat (substring ext-setup-or-nil 0 start)
3094 "\n" setup-contents "\n"
3095 (substring ext-setup-or-nil start)))))
3096 ))))
3097 (when cat
3098 (org-set-local 'org-category (intern cat))
3099 (push (cons "CATEGORY" cat) props))
3100 (when prio
3101 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3102 (setq prio (mapcar 'string-to-char prio))
3103 (org-set-local 'org-highest-priority (nth 0 prio))
3104 (org-set-local 'org-lowest-priority (nth 1 prio))
3105 (org-set-local 'org-default-priority (nth 2 prio)))
3106 (and props (org-set-local 'org-file-properties (nreverse props)))
3107 (and ftags (org-set-local 'org-file-tags ftags))
3108 (and drawers (org-set-local 'org-drawers drawers))
3109 (and arch (org-set-local 'org-archive-location arch))
3110 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3111 ;; Process the TODO keywords
3112 (unless kwds
3113 ;; Use the global values as if they had been given locally.
3114 (setq kwds (default-value 'org-todo-keywords))
3115 (if (stringp (car kwds))
3116 (setq kwds (list (cons org-todo-interpretation
3117 (default-value 'org-todo-keywords)))))
3118 (setq kwds (reverse kwds)))
3119 (setq kwds (nreverse kwds))
3120 (let (inter kws kw)
3121 (while (setq kws (pop kwds))
3122 (setq inter (pop kws) sep (member "|" kws)
3123 kws0 (delete "|" (copy-sequence kws))
3124 kwsa nil
3125 kws1 (mapcar
3126 (lambda (x)
3127 ;; 1 2
3128 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3129 (progn
3130 (setq kw (match-string 1 x)
3131 key (and (match-end 2) (match-string 2 x))
3132 log (org-extract-log-state-settings x))
3133 (push (cons kw (and key (string-to-char key))) kwsa)
3134 (and log (push log org-todo-log-states))
3136 (error "Invalid TODO keyword %s" x)))
3137 kws0)
3138 kwsa (if kwsa (append '((:startgroup))
3139 (nreverse kwsa)
3140 '((:endgroup))))
3141 hw (car kws1)
3142 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3143 tail (list inter hw (car dws) (org-last dws)))
3144 (add-to-list 'org-todo-heads hw 'append)
3145 (push kws1 org-todo-sets)
3146 (setq org-done-keywords (append org-done-keywords dws nil))
3147 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3148 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3149 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3150 (setq org-todo-sets (nreverse org-todo-sets)
3151 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3152 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3153 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3154 ;; Process the constants
3155 (when const
3156 (let (e cst)
3157 (while (setq e (pop const))
3158 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3159 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3160 (setq org-table-formula-constants-local cst)))
3162 ;; Process the tags.
3163 (when tags
3164 (let (e tgs)
3165 (while (setq e (pop tags))
3166 (cond
3167 ((equal e "{") (push '(:startgroup) tgs))
3168 ((equal e "}") (push '(:endgroup) tgs))
3169 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3170 (push (cons (match-string 1 e)
3171 (string-to-char (match-string 2 e)))
3172 tgs))
3173 (t (push (list e) tgs))))
3174 (org-set-local 'org-tag-alist nil)
3175 (while (setq e (pop tgs))
3176 (or (and (stringp (car e))
3177 (assoc (car e) org-tag-alist))
3178 (push e org-tag-alist)))))
3180 ;; Compute the regular expressions and other local variables
3181 (if (not org-done-keywords)
3182 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3183 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3184 (length org-scheduled-string)
3185 (length org-clock-string)
3186 (length org-closed-string)))
3187 org-drawer-regexp
3188 (concat "^[ \t]*:\\("
3189 (mapconcat 'regexp-quote org-drawers "\\|")
3190 "\\):[ \t]*$")
3191 org-not-done-keywords
3192 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3193 org-todo-regexp
3194 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3195 "\\|") "\\)\\>")
3196 org-not-done-regexp
3197 (concat "\\<\\("
3198 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3199 "\\)\\>")
3200 org-todo-line-regexp
3201 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3202 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3203 "\\)\\>\\)?[ \t]*\\(.*\\)")
3204 org-complex-heading-regexp
3205 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3206 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3207 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3208 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3209 org-nl-done-regexp
3210 (concat "\n\\*+[ \t]+"
3211 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3212 "\\)" "\\>")
3213 org-todo-line-tags-regexp
3214 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3215 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3216 (org-re
3217 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3218 org-looking-at-done-regexp
3219 (concat "^" "\\(?:"
3220 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3221 "\\>")
3222 org-deadline-regexp (concat "\\<" org-deadline-string)
3223 org-deadline-time-regexp
3224 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3225 org-deadline-line-regexp
3226 (concat "\\<\\(" org-deadline-string "\\).*")
3227 org-scheduled-regexp
3228 (concat "\\<" org-scheduled-string)
3229 org-scheduled-time-regexp
3230 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3231 org-closed-time-regexp
3232 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3233 org-keyword-time-regexp
3234 (concat "\\<\\(" org-scheduled-string
3235 "\\|" org-deadline-string
3236 "\\|" org-closed-string
3237 "\\|" org-clock-string "\\)"
3238 " *[[<]\\([^]>]+\\)[]>]")
3239 org-keyword-time-not-clock-regexp
3240 (concat "\\<\\(" org-scheduled-string
3241 "\\|" org-deadline-string
3242 "\\|" org-closed-string
3243 "\\)"
3244 " *[[<]\\([^]>]+\\)[]>]")
3245 org-maybe-keyword-time-regexp
3246 (concat "\\(\\<\\(" org-scheduled-string
3247 "\\|" org-deadline-string
3248 "\\|" org-closed-string
3249 "\\|" org-clock-string "\\)\\)?"
3250 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3251 org-planning-or-clock-line-re
3252 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3253 "\\|" org-deadline-string
3254 "\\|" org-closed-string "\\|" org-clock-string
3255 "\\)\\>\\)")
3257 (org-compute-latex-and-specials-regexp)
3258 (org-set-font-lock-defaults))))
3260 (defun org-file-contents (file &optional noerror)
3261 "Return the contents of FILE, as a string."
3262 (if (or (not file)
3263 (not (file-readable-p file)))
3264 (if noerror
3265 (progn
3266 (message "Cannot read file %s" file)
3267 (ding) (sit-for 2)
3269 (error "Cannot read file %s" file))
3270 (with-temp-buffer
3271 (insert-file-contents file)
3272 (buffer-string))))
3274 (defun org-extract-log-state-settings (x)
3275 "Extract the log state setting from a TODO keyword string.
3276 This will extract info from a string like \"WAIT(w@/!)\"."
3277 (let (kw key log1 log2)
3278 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3279 (setq kw (match-string 1 x)
3280 key (and (match-end 2) (match-string 2 x))
3281 log1 (and (match-end 3) (match-string 3 x))
3282 log2 (and (match-end 4) (match-string 4 x)))
3283 (and (or log1 log2)
3284 (list kw
3285 (and log1 (if (equal log1 "!") 'time 'note))
3286 (and log2 (if (equal log2 "!") 'time 'note)))))))
3288 (defun org-remove-keyword-keys (list)
3289 "Remove a pair of parenthesis at the end of each string in LIST."
3290 (mapcar (lambda (x)
3291 (if (string-match "(.*)$" x)
3292 (substring x 0 (match-beginning 0))
3294 list))
3296 ;; FIXME: this could be done much better, using second characters etc.
3297 (defun org-assign-fast-keys (alist)
3298 "Assign fast keys to a keyword-key alist.
3299 Respect keys that are already there."
3300 (let (new e k c c1 c2 (char ?a))
3301 (while (setq e (pop alist))
3302 (cond
3303 ((equal e '(:startgroup)) (push e new))
3304 ((equal e '(:endgroup)) (push e new))
3306 (setq k (car e) c2 nil)
3307 (if (cdr e)
3308 (setq c (cdr e))
3309 ;; automatically assign a character.
3310 (setq c1 (string-to-char
3311 (downcase (substring
3312 k (if (= (string-to-char k) ?@) 1 0)))))
3313 (if (or (rassoc c1 new) (rassoc c1 alist))
3314 (while (or (rassoc char new) (rassoc char alist))
3315 (setq char (1+ char)))
3316 (setq c2 c1))
3317 (setq c (or c2 char)))
3318 (push (cons k c) new))))
3319 (nreverse new)))
3321 ;;; Some variables used in various places
3323 (defvar org-window-configuration nil
3324 "Used in various places to store a window configuration.")
3325 (defvar org-finish-function nil
3326 "Function to be called when `C-c C-c' is used.
3327 This is for getting out of special buffers like remember.")
3330 ;; FIXME: Occasionally check by commenting these, to make sure
3331 ;; no other functions uses these, forgetting to let-bind them.
3332 (defvar entry)
3333 (defvar state)
3334 (defvar last-state)
3335 (defvar date)
3336 (defvar description)
3338 ;; Defined somewhere in this file, but used before definition.
3339 (defvar org-html-entities)
3340 (defvar org-struct-menu)
3341 (defvar org-org-menu)
3342 (defvar org-tbl-menu)
3343 (defvar org-agenda-keymap)
3345 ;;;; Define the Org-mode
3347 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3348 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3351 ;; We use a before-change function to check if a table might need
3352 ;; an update.
3353 (defvar org-table-may-need-update t
3354 "Indicates that a table might need an update.
3355 This variable is set by `org-before-change-function'.
3356 `org-table-align' sets it back to nil.")
3357 (defun org-before-change-function (beg end)
3358 "Every change indicates that a table might need an update."
3359 (setq org-table-may-need-update t))
3360 (defvar org-mode-map)
3361 (defvar org-mode-hook nil)
3362 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3363 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3364 (defvar org-table-buffer-is-an nil)
3365 (defconst org-outline-regexp "\\*+ ")
3367 ;;;###autoload
3368 (define-derived-mode org-mode outline-mode "Org"
3369 "Outline-based notes management and organizer, alias
3370 \"Carsten's outline-mode for keeping track of everything.\"
3372 Org-mode develops organizational tasks around a NOTES file which
3373 contains information about projects as plain text. Org-mode is
3374 implemented on top of outline-mode, which is ideal to keep the content
3375 of large files well structured. It supports ToDo items, deadlines and
3376 time stamps, which magically appear in the diary listing of the Emacs
3377 calendar. Tables are easily created with a built-in table editor.
3378 Plain text URL-like links connect to websites, emails (VM), Usenet
3379 messages (Gnus), BBDB entries, and any files related to the project.
3380 For printing and sharing of notes, an Org-mode file (or a part of it)
3381 can be exported as a structured ASCII or HTML file.
3383 The following commands are available:
3385 \\{org-mode-map}"
3387 ;; Get rid of Outline menus, they are not needed
3388 ;; Need to do this here because define-derived-mode sets up
3389 ;; the keymap so late. Still, it is a waste to call this each time
3390 ;; we switch another buffer into org-mode.
3391 (if (featurep 'xemacs)
3392 (when (boundp 'outline-mode-menu-heading)
3393 ;; Assume this is Greg's port, it used easymenu
3394 (easy-menu-remove outline-mode-menu-heading)
3395 (easy-menu-remove outline-mode-menu-show)
3396 (easy-menu-remove outline-mode-menu-hide))
3397 (define-key org-mode-map [menu-bar headings] 'undefined)
3398 (define-key org-mode-map [menu-bar hide] 'undefined)
3399 (define-key org-mode-map [menu-bar show] 'undefined))
3401 (org-load-modules-maybe)
3402 (easy-menu-add org-org-menu)
3403 (easy-menu-add org-tbl-menu)
3404 (org-install-agenda-files-menu)
3405 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3406 (org-add-to-invisibility-spec '(org-cwidth))
3407 (when (featurep 'xemacs)
3408 (org-set-local 'line-move-ignore-invisible t))
3409 (org-set-local 'outline-regexp org-outline-regexp)
3410 (org-set-local 'outline-level 'org-outline-level)
3411 (when (and org-ellipsis
3412 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3413 (fboundp 'make-glyph-code))
3414 (unless org-display-table
3415 (setq org-display-table (make-display-table)))
3416 (set-display-table-slot
3417 org-display-table 4
3418 (vconcat (mapcar
3419 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3420 org-ellipsis)))
3421 (if (stringp org-ellipsis) org-ellipsis "..."))))
3422 (setq buffer-display-table org-display-table))
3423 (org-set-regexps-and-options)
3424 ;; Calc embedded
3425 (org-set-local 'calc-embedded-open-mode "# ")
3426 (modify-syntax-entry ?# "<")
3427 (modify-syntax-entry ?@ "w")
3428 (if org-startup-truncated (setq truncate-lines t))
3429 (org-set-local 'font-lock-unfontify-region-function
3430 'org-unfontify-region)
3431 ;; Activate before-change-function
3432 (org-set-local 'org-table-may-need-update t)
3433 (org-add-hook 'before-change-functions 'org-before-change-function nil
3434 'local)
3435 ;; Check for running clock before killing a buffer
3436 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3437 ;; Paragraphs and auto-filling
3438 (org-set-autofill-regexps)
3439 (setq indent-line-function 'org-indent-line-function)
3440 (org-update-radio-target-regexp)
3442 ;; Comment characters
3443 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3444 (org-set-local 'comment-padding " ")
3446 ;; Align options lines
3447 (org-set-local
3448 'align-mode-rules-list
3449 '((org-in-buffer-settings
3450 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3451 (modes . '(org-mode)))))
3453 ;; Imenu
3454 (org-set-local 'imenu-create-index-function
3455 'org-imenu-get-tree)
3457 ;; Make isearch reveal context
3458 (if (or (featurep 'xemacs)
3459 (not (boundp 'outline-isearch-open-invisible-function)))
3460 ;; Emacs 21 and XEmacs make use of the hook
3461 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3462 ;; Emacs 22 deals with this through a special variable
3463 (org-set-local 'outline-isearch-open-invisible-function
3464 (lambda (&rest ignore) (org-show-context 'isearch))))
3466 ;; If empty file that did not turn on org-mode automatically, make it to.
3467 (if (and org-insert-mode-line-in-empty-file
3468 (interactive-p)
3469 (= (point-min) (point-max)))
3470 (insert "# -*- mode: org -*-\n\n"))
3472 (unless org-inhibit-startup
3473 (when org-startup-align-all-tables
3474 (let ((bmp (buffer-modified-p)))
3475 (org-table-map-tables 'org-table-align)
3476 (set-buffer-modified-p bmp)))
3477 (org-set-startup-visibility)))
3479 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3481 (defun org-current-time ()
3482 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3483 (if (> (car org-time-stamp-rounding-minutes) 1)
3484 (let ((r (car org-time-stamp-rounding-minutes))
3485 (time (decode-time)))
3486 (apply 'encode-time
3487 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3488 (nthcdr 2 time))))
3489 (current-time)))
3491 ;;;; Font-Lock stuff, including the activators
3493 (defvar org-mouse-map (make-sparse-keymap))
3494 (org-defkey org-mouse-map
3495 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3496 (org-defkey org-mouse-map
3497 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3498 (when org-mouse-1-follows-link
3499 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3500 (when org-tab-follows-link
3501 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3502 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3503 (when org-return-follows-link
3504 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3505 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3507 (require 'font-lock)
3509 (defconst org-non-link-chars "]\t\n\r<>")
3510 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3511 "shell" "elisp"))
3512 (defvar org-link-types-re nil
3513 "Matches a link that has a url-like prefix like \"http:\"")
3514 (defvar org-link-re-with-space nil
3515 "Matches a link with spaces, optional angular brackets around it.")
3516 (defvar org-link-re-with-space2 nil
3517 "Matches a link with spaces, optional angular brackets around it.")
3518 (defvar org-link-re-with-space3 nil
3519 "Matches a link with spaces, only for internal part in bracket links.")
3520 (defvar org-angle-link-re nil
3521 "Matches link with angular brackets, spaces are allowed.")
3522 (defvar org-plain-link-re nil
3523 "Matches plain link, without spaces.")
3524 (defvar org-bracket-link-regexp nil
3525 "Matches a link in double brackets.")
3526 (defvar org-bracket-link-analytic-regexp nil
3527 "Regular expression used to analyze links.
3528 Here is what the match groups contain after a match:
3529 1: http:
3530 2: http
3531 3: path
3532 4: [desc]
3533 5: desc")
3534 (defvar org-any-link-re nil
3535 "Regular expression matching any link.")
3537 (defun org-make-link-regexps ()
3538 "Update the link regular expressions.
3539 This should be called after the variable `org-link-types' has changed."
3540 (setq org-link-types-re
3541 (concat
3542 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3543 org-link-re-with-space
3544 (concat
3545 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3546 "\\([^" org-non-link-chars " ]"
3547 "[^" org-non-link-chars "]*"
3548 "[^" org-non-link-chars " ]\\)>?")
3549 org-link-re-with-space2
3550 (concat
3551 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3552 "\\([^" org-non-link-chars " ]"
3553 "[^\t\n\r]*"
3554 "[^" org-non-link-chars " ]\\)>?")
3555 org-link-re-with-space3
3556 (concat
3557 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3558 "\\([^" org-non-link-chars " ]"
3559 "[^\t\n\r]*\\)")
3560 org-angle-link-re
3561 (concat
3562 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3563 "\\([^" org-non-link-chars " ]"
3564 "[^" org-non-link-chars "]*"
3565 "\\)>")
3566 org-plain-link-re
3567 (concat
3568 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3569 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3570 org-bracket-link-regexp
3571 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3572 org-bracket-link-analytic-regexp
3573 (concat
3574 "\\[\\["
3575 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3576 "\\([^]]+\\)"
3577 "\\]"
3578 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3579 "\\]")
3580 org-any-link-re
3581 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3582 org-angle-link-re "\\)\\|\\("
3583 org-plain-link-re "\\)")))
3585 (org-make-link-regexps)
3587 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3588 "Regular expression for fast time stamp matching.")
3589 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3590 "Regular expression for fast time stamp matching.")
3591 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3592 "Regular expression matching time strings for analysis.
3593 This one does not require the space after the date, so it can be used
3594 on a string that terminates immediately after the date.")
3595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3596 "Regular expression matching time strings for analysis.")
3597 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3598 "Regular expression matching time stamps, with groups.")
3599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3600 "Regular expression matching time stamps (also [..]), with groups.")
3601 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3602 "Regular expression matching a time stamp range.")
3603 (defconst org-tr-regexp-both
3604 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3605 "Regular expression matching a time stamp range.")
3606 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3607 org-ts-regexp "\\)?")
3608 "Regular expression matching a time stamp or time stamp range.")
3609 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3610 org-ts-regexp-both "\\)?")
3611 "Regular expression matching a time stamp or time stamp range.
3612 The time stamps may be either active or inactive.")
3614 (defvar org-emph-face nil)
3616 (defun org-do-emphasis-faces (limit)
3617 "Run through the buffer and add overlays to links."
3618 (let (rtn)
3619 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3620 (if (not (= (char-after (match-beginning 3))
3621 (char-after (match-beginning 4))))
3622 (progn
3623 (setq rtn t)
3624 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3625 'face
3626 (nth 1 (assoc (match-string 3)
3627 org-emphasis-alist)))
3628 (add-text-properties (match-beginning 2) (match-end 2)
3629 '(font-lock-multiline t))
3630 (when org-hide-emphasis-markers
3631 (add-text-properties (match-end 4) (match-beginning 5)
3632 '(invisible org-link))
3633 (add-text-properties (match-beginning 3) (match-end 3)
3634 '(invisible org-link)))))
3635 (backward-char 1))
3636 rtn))
3638 (defun org-emphasize (&optional char)
3639 "Insert or change an emphasis, i.e. a font like bold or italic.
3640 If there is an active region, change that region to a new emphasis.
3641 If there is no region, just insert the marker characters and position
3642 the cursor between them.
3643 CHAR should be either the marker character, or the first character of the
3644 HTML tag associated with that emphasis. If CHAR is a space, the means
3645 to remove the emphasis of the selected region.
3646 If char is not given (for example in an interactive call) it
3647 will be prompted for."
3648 (interactive)
3649 (let ((eal org-emphasis-alist) e det
3650 (erc org-emphasis-regexp-components)
3651 (prompt "")
3652 (string "") beg end move tag c s)
3653 (if (org-region-active-p)
3654 (setq beg (region-beginning) end (region-end)
3655 string (buffer-substring beg end))
3656 (setq move t))
3658 (while (setq e (pop eal))
3659 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3660 c (aref tag 0))
3661 (push (cons c (string-to-char (car e))) det)
3662 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3663 (substring tag 1)))))
3664 (setq det (nreverse det))
3665 (unless char
3666 (message "%s" (concat "Emphasis marker or tag:" prompt))
3667 (setq char (read-char-exclusive)))
3668 (setq char (or (cdr (assoc char det)) char))
3669 (if (equal char ?\ )
3670 (setq s "" move nil)
3671 (unless (assoc (char-to-string char) org-emphasis-alist)
3672 (error "No such emphasis marker: \"%c\"" char))
3673 (setq s (char-to-string char)))
3674 (while (and (> (length string) 1)
3675 (equal (substring string 0 1) (substring string -1))
3676 (assoc (substring string 0 1) org-emphasis-alist))
3677 (setq string (substring string 1 -1)))
3678 (setq string (concat s string s))
3679 (if beg (delete-region beg end))
3680 (unless (or (bolp)
3681 (string-match (concat "[" (nth 0 erc) "\n]")
3682 (char-to-string (char-before (point)))))
3683 (insert " "))
3684 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3685 (char-to-string (char-after (point))))
3686 (insert " ") (backward-char 1))
3687 (insert string)
3688 (and move (backward-char 1))))
3690 (defconst org-nonsticky-props
3691 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3694 (defun org-activate-plain-links (limit)
3695 "Run through the buffer and add overlays to links."
3696 (catch 'exit
3697 (let (f)
3698 (while (re-search-forward org-plain-link-re limit t)
3699 (setq f (get-text-property (match-beginning 0) 'face))
3700 (if (or (eq f 'org-tag)
3701 (and (listp f) (memq 'org-tag f)))
3703 (add-text-properties (match-beginning 0) (match-end 0)
3704 (list 'mouse-face 'highlight
3705 'rear-nonsticky org-nonsticky-props
3706 'keymap org-mouse-map
3708 (throw 'exit t))))))
3710 (defun org-activate-code (limit)
3711 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3712 (progn
3713 (remove-text-properties (match-beginning 0) (match-end 0)
3714 '(display t invisible t intangible t))
3715 t)))
3717 (defun org-activate-angle-links (limit)
3718 "Run through the buffer and add overlays to links."
3719 (if (re-search-forward org-angle-link-re limit t)
3720 (progn
3721 (add-text-properties (match-beginning 0) (match-end 0)
3722 (list 'mouse-face 'highlight
3723 'rear-nonsticky org-nonsticky-props
3724 'keymap org-mouse-map
3726 t)))
3728 (defun org-activate-bracket-links (limit)
3729 "Run through the buffer and add overlays to bracketed links."
3730 (if (re-search-forward org-bracket-link-regexp limit t)
3731 (let* ((help (concat "LINK: "
3732 (org-match-string-no-properties 1)))
3733 ;; FIXME: above we should remove the escapes.
3734 ;; but that requires another match, protecting match data,
3735 ;; a lot of overhead for font-lock.
3736 (ip (org-maybe-intangible
3737 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3738 'keymap org-mouse-map 'mouse-face 'highlight
3739 'font-lock-multiline t 'help-echo help)))
3740 (vp (list 'rear-nonsticky org-nonsticky-props
3741 'keymap org-mouse-map 'mouse-face 'highlight
3742 ' font-lock-multiline t 'help-echo help)))
3743 ;; We need to remove the invisible property here. Table narrowing
3744 ;; may have made some of this invisible.
3745 (remove-text-properties (match-beginning 0) (match-end 0)
3746 '(invisible nil))
3747 (if (match-end 3)
3748 (progn
3749 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3750 (add-text-properties (match-beginning 3) (match-end 3) vp)
3751 (add-text-properties (match-end 3) (match-end 0) ip))
3752 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3753 (add-text-properties (match-beginning 1) (match-end 1) vp)
3754 (add-text-properties (match-end 1) (match-end 0) ip))
3755 t)))
3757 (defun org-activate-dates (limit)
3758 "Run through the buffer and add overlays to dates."
3759 (if (re-search-forward org-tsr-regexp-both limit t)
3760 (progn
3761 (add-text-properties (match-beginning 0) (match-end 0)
3762 (list 'mouse-face 'highlight
3763 'rear-nonsticky org-nonsticky-props
3764 'keymap org-mouse-map))
3765 (when org-display-custom-times
3766 (if (match-end 3)
3767 (org-display-custom-time (match-beginning 3) (match-end 3)))
3768 (org-display-custom-time (match-beginning 1) (match-end 1)))
3769 t)))
3771 (defvar org-target-link-regexp nil
3772 "Regular expression matching radio targets in plain text.")
3773 (make-variable-buffer-local 'org-target-link-regexp)
3774 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3775 "Regular expression matching a link target.")
3776 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3777 "Regular expression matching a radio target.")
3778 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3779 "Regular expression matching any target.")
3781 (defun org-activate-target-links (limit)
3782 "Run through the buffer and add overlays to target matches."
3783 (when org-target-link-regexp
3784 (let ((case-fold-search t))
3785 (if (re-search-forward org-target-link-regexp limit t)
3786 (progn
3787 (add-text-properties (match-beginning 0) (match-end 0)
3788 (list 'mouse-face 'highlight
3789 'rear-nonsticky org-nonsticky-props
3790 'keymap org-mouse-map
3791 'help-echo "Radio target link"
3792 'org-linked-text t))
3793 t)))))
3795 (defun org-update-radio-target-regexp ()
3796 "Find all radio targets in this file and update the regular expression."
3797 (interactive)
3798 (when (memq 'radio org-activate-links)
3799 (setq org-target-link-regexp
3800 (org-make-target-link-regexp (org-all-targets 'radio)))
3801 (org-restart-font-lock)))
3803 (defun org-hide-wide-columns (limit)
3804 (let (s e)
3805 (setq s (text-property-any (point) (or limit (point-max))
3806 'org-cwidth t))
3807 (when s
3808 (setq e (next-single-property-change s 'org-cwidth))
3809 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3810 (goto-char e)
3811 t)))
3813 (defvar org-latex-and-specials-regexp nil
3814 "Regular expression for highlighting export special stuff.")
3815 (defvar org-match-substring-regexp)
3816 (defvar org-match-substring-with-braces-regexp)
3817 (defvar org-export-html-special-string-regexps)
3819 (defun org-compute-latex-and-specials-regexp ()
3820 "Compute regular expression for stuff treated specially by exporters."
3821 (if (not org-highlight-latex-fragments-and-specials)
3822 (org-set-local 'org-latex-and-specials-regexp nil)
3823 (require 'org-exp)
3824 (let*
3825 ((matchers (plist-get org-format-latex-options :matchers))
3826 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3827 org-latex-regexps)))
3828 (options (org-combine-plists (org-default-export-plist)
3829 (org-infile-export-plist)))
3830 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3831 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3832 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3833 (org-export-html-expand (plist-get options :expand-quoted-html))
3834 (org-export-with-special-strings (plist-get options :special-strings))
3835 (re-sub
3836 (cond
3837 ((equal org-export-with-sub-superscripts '{})
3838 (list org-match-substring-with-braces-regexp))
3839 (org-export-with-sub-superscripts
3840 (list org-match-substring-regexp))
3841 (t nil)))
3842 (re-latex
3843 (if org-export-with-LaTeX-fragments
3844 (mapcar (lambda (x) (nth 1 x)) latexs)))
3845 (re-macros
3846 (if org-export-with-TeX-macros
3847 (list (concat "\\\\"
3848 (regexp-opt
3849 (append (mapcar 'car org-html-entities)
3850 (if (boundp 'org-latex-entities)
3851 org-latex-entities nil))
3852 'words))) ; FIXME
3854 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3855 (re-special (if org-export-with-special-strings
3856 (mapcar (lambda (x) (car x))
3857 org-export-html-special-string-regexps)))
3858 (re-rest
3859 (delq nil
3860 (list
3861 (if org-export-html-expand "@<[^>\n]+>")
3862 ))))
3863 (org-set-local
3864 'org-latex-and-specials-regexp
3865 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3866 re-rest) "\\|")))))
3868 (defun org-do-latex-and-special-faces (limit)
3869 "Run through the buffer and add overlays to links."
3870 (when org-latex-and-specials-regexp
3871 (let (rtn d)
3872 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3873 limit t))
3874 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3875 'face))
3876 '(org-code org-verbatim underline)))
3877 (progn
3878 (setq rtn t
3879 d (cond ((member (char-after (1+ (match-beginning 0)))
3880 '(?_ ?^)) 1)
3881 (t 0)))
3882 (font-lock-prepend-text-property
3883 (+ d (match-beginning 0)) (match-end 0)
3884 'face 'org-latex-and-export-specials)
3885 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3886 '(font-lock-multiline t)))))
3887 rtn)))
3889 (defun org-restart-font-lock ()
3890 "Restart font-lock-mode, to force refontification."
3891 (when (and (boundp 'font-lock-mode) font-lock-mode)
3892 (font-lock-mode -1)
3893 (font-lock-mode 1)))
3895 (defun org-all-targets (&optional radio)
3896 "Return a list of all targets in this file.
3897 With optional argument RADIO, only find radio targets."
3898 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3899 rtn)
3900 (save-excursion
3901 (goto-char (point-min))
3902 (while (re-search-forward re nil t)
3903 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3904 rtn)))
3906 (defun org-make-target-link-regexp (targets)
3907 "Make regular expression matching all strings in TARGETS.
3908 The regular expression finds the targets also if there is a line break
3909 between words."
3910 (and targets
3911 (concat
3912 "\\<\\("
3913 (mapconcat
3914 (lambda (x)
3915 (while (string-match " +" x)
3916 (setq x (replace-match "\\s-+" t t x)))
3918 targets
3919 "\\|")
3920 "\\)\\>")))
3922 (defun org-activate-tags (limit)
3923 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3924 (progn
3925 (add-text-properties (match-beginning 1) (match-end 1)
3926 (list 'mouse-face 'highlight
3927 'rear-nonsticky org-nonsticky-props
3928 'keymap org-mouse-map))
3929 t)))
3931 (defun org-outline-level ()
3932 (save-excursion
3933 (looking-at outline-regexp)
3934 (if (match-beginning 1)
3935 (+ (org-get-string-indentation (match-string 1)) 1000)
3936 (1- (- (match-end 0) (match-beginning 0))))))
3938 (defvar org-font-lock-keywords nil)
3940 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3941 "Regular expression matching a property line.")
3943 (defvar org-font-lock-hook nil
3944 "Functions to be called for special font lock stuff.")
3946 (defun org-font-lock-hook (limit)
3947 (run-hook-with-args 'org-font-lock-hook limit))
3949 (defun org-set-font-lock-defaults ()
3950 (let* ((em org-fontify-emphasized-text)
3951 (lk org-activate-links)
3952 (org-font-lock-extra-keywords
3953 (list
3954 ;; Call the hook
3955 '(org-font-lock-hook)
3956 ;; Headlines
3957 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3958 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3959 ;; Table lines
3960 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3961 (1 'org-table t))
3962 ;; Table internals
3963 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3964 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3965 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3966 ;; Drawers
3967 (list org-drawer-regexp '(0 'org-special-keyword t))
3968 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3969 ;; Properties
3970 (list org-property-re
3971 '(1 'org-special-keyword t)
3972 '(3 'org-property-value t))
3973 (if org-format-transports-properties-p
3974 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3975 ;; Links
3976 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3977 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3978 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3979 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3980 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3981 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3982 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3983 '(org-hide-wide-columns (0 nil append))
3984 ;; TODO lines
3985 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3986 '(1 (org-get-todo-face 1) t))
3987 ;; DONE
3988 (if org-fontify-done-headline
3989 (list (concat "^[*]+ +\\<\\("
3990 (mapconcat 'regexp-quote org-done-keywords "\\|")
3991 "\\)\\(.*\\)")
3992 '(2 'org-headline-done t))
3993 nil)
3994 ;; Priorities
3995 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3996 ;; Tags
3997 '(org-font-lock-add-tag-faces)
3998 ;; Special keywords
3999 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4000 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4001 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4002 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4003 ;; Emphasis
4004 (if em
4005 (if (featurep 'xemacs)
4006 '(org-do-emphasis-faces (0 nil append))
4007 '(org-do-emphasis-faces)))
4008 ;; Checkboxes
4009 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4010 2 'bold prepend)
4011 (if org-provide-checkbox-statistics
4012 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4013 (0 (org-get-checkbox-statistics-face) t)))
4014 ;; Description list items
4015 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4016 2 'bold prepend)
4017 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4018 '(1 'org-archived prepend))
4019 ;; Specials
4020 '(org-do-latex-and-special-faces)
4021 ;; Code
4022 '(org-activate-code (1 'org-code t))
4023 ;; COMMENT
4024 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4025 "\\|" org-quote-string "\\)\\>")
4026 '(1 'org-special-keyword t))
4027 '("^#.*" (0 'font-lock-comment-face t))
4029 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4030 ;; Now set the full font-lock-keywords
4031 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4032 (org-set-local 'font-lock-defaults
4033 '(org-font-lock-keywords t nil nil backward-paragraph))
4034 (kill-local-variable 'font-lock-keywords) nil))
4036 (defvar org-m nil)
4037 (defvar org-l nil)
4038 (defvar org-f nil)
4039 (defun org-get-level-face (n)
4040 "Get the right face for match N in font-lock matching of headlines."
4041 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4042 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4043 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4044 (cond
4045 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4046 ((eq n 2) org-f)
4047 (t (if org-level-color-stars-only nil org-f))))
4049 (defun org-get-todo-face (kwd)
4050 "Get the right face for a TODO keyword KWD.
4051 If KWD is a number, get the corresponding match group."
4052 (if (numberp kwd) (setq kwd (match-string kwd)))
4053 (or (cdr (assoc kwd org-todo-keyword-faces))
4054 (and (member kwd org-done-keywords) 'org-done)
4055 'org-todo))
4057 (defun org-font-lock-add-tag-faces (limit)
4058 "Add the special tag faces."
4059 (when (and org-tag-faces org-tags-special-faces-re)
4060 (while (re-search-forward org-tags-special-faces-re limit t)
4061 (add-text-properties (match-beginning 1) (match-end 1)
4062 (list 'face (org-get-tag-face 1)
4063 'font-lock-fontified t))
4064 (backward-char 1))))
4066 (defun org-get-tag-face (kwd)
4067 "Get the right face for a TODO keyword KWD.
4068 If KWD is a number, get the corresponding match group."
4069 (if (numberp kwd) (setq kwd (match-string kwd)))
4070 (or (cdr (assoc kwd org-tag-faces))
4071 'org-tag))
4073 (defun org-unfontify-region (beg end &optional maybe_loudly)
4074 "Remove fontification and activation overlays from links."
4075 (font-lock-default-unfontify-region beg end)
4076 (let* ((buffer-undo-list t)
4077 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4078 (inhibit-modification-hooks t)
4079 deactivate-mark buffer-file-name buffer-file-truename)
4080 (remove-text-properties beg end
4081 '(mouse-face t keymap t org-linked-text t
4082 invisible t intangible t))))
4084 ;;;; Visibility cycling, including org-goto and indirect buffer
4086 ;;; Cycling
4088 (defvar org-cycle-global-status nil)
4089 (make-variable-buffer-local 'org-cycle-global-status)
4090 (defvar org-cycle-subtree-status nil)
4091 (make-variable-buffer-local 'org-cycle-subtree-status)
4093 ;;;###autoload
4094 (defun org-cycle (&optional arg)
4095 "Visibility cycling for Org-mode.
4097 - When this function is called with a prefix argument, rotate the entire
4098 buffer through 3 states (global cycling)
4099 1. OVERVIEW: Show only top-level headlines.
4100 2. CONTENTS: Show all headlines of all levels, but no body text.
4101 3. SHOW ALL: Show everything.
4102 When called with two C-u C-u prefixes, switch to the startup visibility,
4103 determined by the variable `org-startup-folded', and by any VISIBILITY
4104 properties in the buffer.
4105 When called with three C-u C-u C-u prefixed, show the entire buffer,
4106 including drawers.
4108 - When point is at the beginning of a headline, rotate the subtree started
4109 by this line through 3 different states (local cycling)
4110 1. FOLDED: Only the main headline is shown.
4111 2. CHILDREN: The main headline and the direct children are shown.
4112 From this state, you can move to one of the children
4113 and zoom in further.
4114 3. SUBTREE: Show the entire subtree, including body text.
4116 - When there is a numeric prefix, go up to a heading with level ARG, do
4117 a `show-subtree' and return to the previous cursor position. If ARG
4118 is negative, go up that many levels.
4120 - When point is not at the beginning of a headline, execute the global
4121 binding for TAB, which is re-indenting the line. See the option
4122 `org-cycle-emulate-tab' for details.
4124 - Special case: if point is at the beginning of the buffer and there is
4125 no headline in line 1, this function will act as if called with prefix arg.
4126 But only if also the variable `org-cycle-global-at-bob' is t."
4127 (interactive "P")
4128 (org-load-modules-maybe)
4129 (let* ((outline-regexp
4130 (if (and (org-mode-p) org-cycle-include-plain-lists)
4131 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4132 outline-regexp))
4133 (bob-special (and org-cycle-global-at-bob (bobp)
4134 (not (looking-at outline-regexp))))
4135 (org-cycle-hook
4136 (if bob-special
4137 (delq 'org-optimize-window-after-visibility-change
4138 (copy-sequence org-cycle-hook))
4139 org-cycle-hook))
4140 (pos (point)))
4142 (if (or bob-special (equal arg '(4)))
4143 ;; special case: use global cycling
4144 (setq arg t))
4146 (cond
4148 ((equal arg '(16))
4149 (org-set-startup-visibility)
4150 (message "Startup visibility, plus VISIBILITY properties"))
4152 ((equal arg '(64))
4153 (show-all)
4154 (message "Entire buffer visible, including drawers"))
4156 ((org-at-table-p 'any)
4157 ;; Enter the table or move to the next field in the table
4158 (or (org-table-recognize-table.el)
4159 (progn
4160 (if arg (org-table-edit-field t)
4161 (org-table-justify-field-maybe)
4162 (call-interactively 'org-table-next-field)))))
4164 ((eq arg t) ;; Global cycling
4166 (cond
4167 ((and (eq last-command this-command)
4168 (eq org-cycle-global-status 'overview))
4169 ;; We just created the overview - now do table of contents
4170 ;; This can be slow in very large buffers, so indicate action
4171 (message "CONTENTS...")
4172 (org-content)
4173 (message "CONTENTS...done")
4174 (setq org-cycle-global-status 'contents)
4175 (run-hook-with-args 'org-cycle-hook 'contents))
4177 ((and (eq last-command this-command)
4178 (eq org-cycle-global-status 'contents))
4179 ;; We just showed the table of contents - now show everything
4180 (show-all)
4181 (message "SHOW ALL")
4182 (setq org-cycle-global-status 'all)
4183 (run-hook-with-args 'org-cycle-hook 'all))
4186 ;; Default action: go to overview
4187 (org-overview)
4188 (message "OVERVIEW")
4189 (setq org-cycle-global-status 'overview)
4190 (run-hook-with-args 'org-cycle-hook 'overview))))
4192 ((and org-drawers org-drawer-regexp
4193 (save-excursion
4194 (beginning-of-line 1)
4195 (looking-at org-drawer-regexp)))
4196 ;; Toggle block visibility
4197 (org-flag-drawer
4198 (not (get-char-property (match-end 0) 'invisible))))
4200 ((integerp arg)
4201 ;; Show-subtree, ARG levels up from here.
4202 (save-excursion
4203 (org-back-to-heading)
4204 (outline-up-heading (if (< arg 0) (- arg)
4205 (- (funcall outline-level) arg)))
4206 (org-show-subtree)))
4208 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4209 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4210 ;; At a heading: rotate between three different views
4211 (org-back-to-heading)
4212 (let ((goal-column 0) eoh eol eos)
4213 ;; First, some boundaries
4214 (save-excursion
4215 (org-back-to-heading)
4216 (save-excursion
4217 (beginning-of-line 2)
4218 (while (and (not (eobp)) ;; this is like `next-line'
4219 (get-char-property (1- (point)) 'invisible))
4220 (beginning-of-line 2)) (setq eol (point)))
4221 (outline-end-of-heading) (setq eoh (point))
4222 (org-end-of-subtree t)
4223 (unless (eobp)
4224 (skip-chars-forward " \t\n")
4225 (beginning-of-line 1) ; in case this is an item
4227 (setq eos (1- (point))))
4228 ;; Find out what to do next and set `this-command'
4229 (cond
4230 ((= eos eoh)
4231 ;; Nothing is hidden behind this heading
4232 (message "EMPTY ENTRY")
4233 (setq org-cycle-subtree-status nil)
4234 (save-excursion
4235 (goto-char eos)
4236 (outline-next-heading)
4237 (if (org-invisible-p) (org-flag-heading nil))))
4238 ((or (>= eol eos)
4239 (not (string-match "\\S-" (buffer-substring eol eos))))
4240 ;; Entire subtree is hidden in one line: open it
4241 (org-show-entry)
4242 (show-children)
4243 (message "CHILDREN")
4244 (save-excursion
4245 (goto-char eos)
4246 (outline-next-heading)
4247 (if (org-invisible-p) (org-flag-heading nil)))
4248 (setq org-cycle-subtree-status 'children)
4249 (run-hook-with-args 'org-cycle-hook 'children))
4250 ((and (eq last-command this-command)
4251 (eq org-cycle-subtree-status 'children))
4252 ;; We just showed the children, now show everything.
4253 (org-show-subtree)
4254 (message "SUBTREE")
4255 (setq org-cycle-subtree-status 'subtree)
4256 (run-hook-with-args 'org-cycle-hook 'subtree))
4258 ;; Default action: hide the subtree.
4259 (hide-subtree)
4260 (message "FOLDED")
4261 (setq org-cycle-subtree-status 'folded)
4262 (run-hook-with-args 'org-cycle-hook 'folded)))))
4264 ;; TAB emulation and template completion
4265 (buffer-read-only (org-back-to-heading))
4267 ((org-try-structure-completion))
4269 ((org-try-cdlatex-tab))
4271 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4272 (or (not (bolp))
4273 (not (looking-at outline-regexp))))
4274 (call-interactively (global-key-binding "\t")))
4276 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4277 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4278 (or (and (eq org-cycle-emulate-tab 'white)
4279 (= (match-end 0) (point-at-eol)))
4280 (and (eq org-cycle-emulate-tab 'whitestart)
4281 (>= (match-end 0) pos))))
4283 (eq org-cycle-emulate-tab t))
4284 (call-interactively (global-key-binding "\t")))
4286 (t (save-excursion
4287 (org-back-to-heading)
4288 (org-cycle))))))
4290 ;;;###autoload
4291 (defun org-global-cycle (&optional arg)
4292 "Cycle the global visibility. For details see `org-cycle'.
4293 With C-u prefix arg, switch to startup visibility.
4294 With a numeric prefix, show all headlines up to that level."
4295 (interactive "P")
4296 (let ((org-cycle-include-plain-lists
4297 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4298 (cond
4299 ((integerp arg)
4300 (show-all)
4301 (hide-sublevels arg)
4302 (setq org-cycle-global-status 'contents))
4303 ((equal arg '(4))
4304 (org-set-startup-visibility)
4305 (message "Startup visibility, plus VISIBILITY properties."))
4307 (org-cycle '(4))))))
4309 (defun org-set-startup-visibility ()
4310 "Set the visibility required by startup options and properties."
4311 (cond
4312 ((eq org-startup-folded t)
4313 (org-cycle '(4)))
4314 ((eq org-startup-folded 'content)
4315 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4316 (org-cycle '(4)) (org-cycle '(4)))))
4317 (org-set-visibility-according-to-property 'no-cleanup)
4318 (org-cycle-hide-archived-subtrees 'all)
4319 (org-cycle-hide-drawers 'all)
4320 (org-cycle-show-empty-lines 'all))
4322 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4323 "Switch subtree visibilities according to :VISIBILITY: property."
4324 (interactive)
4325 (let (state)
4326 (save-excursion
4327 (goto-char (point-min))
4328 (while (re-search-forward
4329 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4330 nil t)
4331 (setq state (match-string 1))
4332 (save-excursion
4333 (org-back-to-heading t)
4334 (hide-subtree)
4335 (org-reveal)
4336 (cond
4337 ((equal state '("fold" "folded"))
4338 (hide-subtree))
4339 ((equal state "children")
4340 (org-show-hidden-entry)
4341 (show-children))
4342 ((equal state "content")
4343 (save-excursion
4344 (save-restriction
4345 (org-narrow-to-subtree)
4346 (org-content))))
4347 ((member state '("all" "showall"))
4348 (show-subtree)))))
4349 (unless no-cleanup
4350 (org-cycle-hide-archived-subtrees 'all)
4351 (org-cycle-hide-drawers 'all)
4352 (org-cycle-show-empty-lines 'all)))))
4354 (defun org-overview ()
4355 "Switch to overview mode, showing only top-level headlines.
4356 Really, this shows all headlines with level equal or greater than the level
4357 of the first headline in the buffer. This is important, because if the
4358 first headline is not level one, then (hide-sublevels 1) gives confusing
4359 results."
4360 (interactive)
4361 (let ((level (save-excursion
4362 (goto-char (point-min))
4363 (if (re-search-forward (concat "^" outline-regexp) nil t)
4364 (progn
4365 (goto-char (match-beginning 0))
4366 (funcall outline-level))))))
4367 (and level (hide-sublevels level))))
4369 (defun org-content (&optional arg)
4370 "Show all headlines in the buffer, like a table of contents.
4371 With numerical argument N, show content up to level N."
4372 (interactive "P")
4373 (save-excursion
4374 ;; Visit all headings and show their offspring
4375 (and (integerp arg) (org-overview))
4376 (goto-char (point-max))
4377 (catch 'exit
4378 (while (and (progn (condition-case nil
4379 (outline-previous-visible-heading 1)
4380 (error (goto-char (point-min))))
4382 (looking-at outline-regexp))
4383 (if (integerp arg)
4384 (show-children (1- arg))
4385 (show-branches))
4386 (if (bobp) (throw 'exit nil))))))
4389 (defun org-optimize-window-after-visibility-change (state)
4390 "Adjust the window after a change in outline visibility.
4391 This function is the default value of the hook `org-cycle-hook'."
4392 (when (get-buffer-window (current-buffer))
4393 (cond
4394 ; ((eq state 'overview) (org-first-headline-recenter 1))
4395 ; ((eq state 'overview) (org-beginning-of-line))
4396 ((eq state 'content) nil)
4397 ((eq state 'all) nil)
4398 ((eq state 'folded) nil)
4399 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4400 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4402 (defun org-compact-display-after-subtree-move ()
4403 (let (beg end)
4404 (save-excursion
4405 (if (org-up-heading-safe)
4406 (progn
4407 (hide-subtree)
4408 (show-entry)
4409 (show-children)
4410 (org-cycle-show-empty-lines 'children)
4411 (org-cycle-hide-drawers 'children))
4412 (org-overview)))))
4414 (defun org-cycle-show-empty-lines (state)
4415 "Show empty lines above all visible headlines.
4416 The region to be covered depends on STATE when called through
4417 `org-cycle-hook'. Lisp program can use t for STATE to get the
4418 entire buffer covered. Note that an empty line is only shown if there
4419 are at least `org-cycle-separator-lines' empty lines before the headline."
4420 (when (> org-cycle-separator-lines 0)
4421 (save-excursion
4422 (let* ((n org-cycle-separator-lines)
4423 (re (cond
4424 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4425 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4426 (t (let ((ns (number-to-string (- n 2))))
4427 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4428 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4429 beg end)
4430 (cond
4431 ((memq state '(overview contents t))
4432 (setq beg (point-min) end (point-max)))
4433 ((memq state '(children folded))
4434 (setq beg (point) end (progn (org-end-of-subtree t t)
4435 (beginning-of-line 2)
4436 (point)))))
4437 (when beg
4438 (goto-char beg)
4439 (while (re-search-forward re end t)
4440 (if (not (get-char-property (match-end 1) 'invisible))
4441 (outline-flag-region
4442 (match-beginning 1) (match-end 1) nil)))))))
4443 ;; Never hide empty lines at the end of the file.
4444 (save-excursion
4445 (goto-char (point-max))
4446 (outline-previous-heading)
4447 (outline-end-of-heading)
4448 (if (and (looking-at "[ \t\n]+")
4449 (= (match-end 0) (point-max)))
4450 (outline-flag-region (point) (match-end 0) nil))))
4452 (defun org-show-empty-lines-in-parent ()
4453 "Move to the parent and re-show empty lines before visible headlines."
4454 (save-excursion
4455 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4456 (org-cycle-show-empty-lines context))))
4458 (defun org-cycle-hide-drawers (state)
4459 "Re-hide all drawers after a visibility state change."
4460 (when (and (org-mode-p)
4461 (not (memq state '(overview folded))))
4462 (save-excursion
4463 (let* ((globalp (memq state '(contents all)))
4464 (beg (if globalp (point-min) (point)))
4465 (end (if globalp (point-max) (org-end-of-subtree t))))
4466 (goto-char beg)
4467 (while (re-search-forward org-drawer-regexp end t)
4468 (org-flag-drawer t))))))
4470 (defun org-flag-drawer (flag)
4471 (save-excursion
4472 (beginning-of-line 1)
4473 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4474 (let ((b (match-end 0))
4475 (outline-regexp org-outline-regexp))
4476 (if (re-search-forward
4477 "^[ \t]*:END:"
4478 (save-excursion (outline-next-heading) (point)) t)
4479 (outline-flag-region b (point-at-eol) flag)
4480 (error ":END: line missing"))))))
4482 (defun org-subtree-end-visible-p ()
4483 "Is the end of the current subtree visible?"
4484 (pos-visible-in-window-p
4485 (save-excursion (org-end-of-subtree t) (point))))
4487 (defun org-first-headline-recenter (&optional N)
4488 "Move cursor to the first headline and recenter the headline.
4489 Optional argument N means, put the headline into the Nth line of the window."
4490 (goto-char (point-min))
4491 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4492 (beginning-of-line)
4493 (recenter (prefix-numeric-value N))))
4495 ;;; Org-goto
4497 (defvar org-goto-window-configuration nil)
4498 (defvar org-goto-marker nil)
4499 (defvar org-goto-map
4500 (let ((map (make-sparse-keymap)))
4501 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4502 (while (setq cmd (pop cmds))
4503 (substitute-key-definition cmd cmd map global-map)))
4504 (suppress-keymap map)
4505 (org-defkey map "\C-m" 'org-goto-ret)
4506 (org-defkey map [(return)] 'org-goto-ret)
4507 (org-defkey map [(left)] 'org-goto-left)
4508 (org-defkey map [(right)] 'org-goto-right)
4509 (org-defkey map [(control ?g)] 'org-goto-quit)
4510 (org-defkey map "\C-i" 'org-cycle)
4511 (org-defkey map [(tab)] 'org-cycle)
4512 (org-defkey map [(down)] 'outline-next-visible-heading)
4513 (org-defkey map [(up)] 'outline-previous-visible-heading)
4514 (if org-goto-auto-isearch
4515 (if (fboundp 'define-key-after)
4516 (define-key-after map [t] 'org-goto-local-auto-isearch)
4517 nil)
4518 (org-defkey map "q" 'org-goto-quit)
4519 (org-defkey map "n" 'outline-next-visible-heading)
4520 (org-defkey map "p" 'outline-previous-visible-heading)
4521 (org-defkey map "f" 'outline-forward-same-level)
4522 (org-defkey map "b" 'outline-backward-same-level)
4523 (org-defkey map "u" 'outline-up-heading))
4524 (org-defkey map "/" 'org-occur)
4525 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4526 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4527 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4528 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4529 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4530 map))
4532 (defconst org-goto-help
4533 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4534 RET=jump to location [Q]uit and return to previous location
4535 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4537 (defvar org-goto-start-pos) ; dynamically scoped parameter
4539 ;; FIXME: Docstring doe not mention both interfaces
4540 (defun org-goto (&optional alternative-interface)
4541 "Look up a different location in the current file, keeping current visibility.
4543 When you want look-up or go to a different location in a document, the
4544 fastest way is often to fold the entire buffer and then dive into the tree.
4545 This method has the disadvantage, that the previous location will be folded,
4546 which may not be what you want.
4548 This command works around this by showing a copy of the current buffer
4549 in an indirect buffer, in overview mode. You can dive into the tree in
4550 that copy, use org-occur and incremental search to find a location.
4551 When pressing RET or `Q', the command returns to the original buffer in
4552 which the visibility is still unchanged. After RET is will also jump to
4553 the location selected in the indirect buffer and expose the
4554 the headline hierarchy above."
4555 (interactive "P")
4556 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4557 (org-refile-use-outline-path t)
4558 (interface
4559 (if (not alternative-interface)
4560 org-goto-interface
4561 (if (eq org-goto-interface 'outline)
4562 'outline-path-completion
4563 'outline)))
4564 (org-goto-start-pos (point))
4565 (selected-point
4566 (if (eq interface 'outline)
4567 (car (org-get-location (current-buffer) org-goto-help))
4568 (nth 3 (org-refile-get-location "Goto: ")))))
4569 (if selected-point
4570 (progn
4571 (org-mark-ring-push org-goto-start-pos)
4572 (goto-char selected-point)
4573 (if (or (org-invisible-p) (org-invisible-p2))
4574 (org-show-context 'org-goto)))
4575 (message "Quit"))))
4577 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4578 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4579 (defvar org-goto-local-auto-isearch-map) ; defined below
4581 (defun org-get-location (buf help)
4582 "Let the user select a location in the Org-mode buffer BUF.
4583 This function uses a recursive edit. It returns the selected position
4584 or nil."
4585 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4586 (isearch-hide-immediately nil)
4587 (isearch-search-fun-function
4588 (lambda () 'org-goto-local-search-headings))
4589 (org-goto-selected-point org-goto-exit-command))
4590 (save-excursion
4591 (save-window-excursion
4592 (delete-other-windows)
4593 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4594 (switch-to-buffer
4595 (condition-case nil
4596 (make-indirect-buffer (current-buffer) "*org-goto*")
4597 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4598 (with-output-to-temp-buffer "*Help*"
4599 (princ help))
4600 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4601 (setq buffer-read-only nil)
4602 (let ((org-startup-truncated t)
4603 (org-startup-folded nil)
4604 (org-startup-align-all-tables nil))
4605 (org-mode)
4606 (org-overview))
4607 (setq buffer-read-only t)
4608 (if (and (boundp 'org-goto-start-pos)
4609 (integer-or-marker-p org-goto-start-pos))
4610 (let ((org-show-hierarchy-above t)
4611 (org-show-siblings t)
4612 (org-show-following-heading t))
4613 (goto-char org-goto-start-pos)
4614 (and (org-invisible-p) (org-show-context)))
4615 (goto-char (point-min)))
4616 (org-beginning-of-line)
4617 (message "Select location and press RET")
4618 (use-local-map org-goto-map)
4619 (recursive-edit)
4621 (kill-buffer "*org-goto*")
4622 (cons org-goto-selected-point org-goto-exit-command)))
4624 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4625 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4626 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4627 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4629 (defun org-goto-local-search-headings (string bound noerror)
4630 "Search and make sure that any matches are in headlines."
4631 (catch 'return
4632 (while (if isearch-forward
4633 (search-forward string bound noerror)
4634 (search-backward string bound noerror))
4635 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4636 (and (member :headline context)
4637 (not (member :tags context))))
4638 (throw 'return (point))))))
4640 (defun org-goto-local-auto-isearch ()
4641 "Start isearch."
4642 (interactive)
4643 (goto-char (point-min))
4644 (let ((keys (this-command-keys)))
4645 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4646 (isearch-mode t)
4647 (isearch-process-search-char (string-to-char keys)))))
4649 (defun org-goto-ret (&optional arg)
4650 "Finish `org-goto' by going to the new location."
4651 (interactive "P")
4652 (setq org-goto-selected-point (point)
4653 org-goto-exit-command 'return)
4654 (throw 'exit nil))
4656 (defun org-goto-left ()
4657 "Finish `org-goto' by going to the new location."
4658 (interactive)
4659 (if (org-on-heading-p)
4660 (progn
4661 (beginning-of-line 1)
4662 (setq org-goto-selected-point (point)
4663 org-goto-exit-command 'left)
4664 (throw 'exit nil))
4665 (error "Not on a heading")))
4667 (defun org-goto-right ()
4668 "Finish `org-goto' by going to the new location."
4669 (interactive)
4670 (if (org-on-heading-p)
4671 (progn
4672 (setq org-goto-selected-point (point)
4673 org-goto-exit-command 'right)
4674 (throw 'exit nil))
4675 (error "Not on a heading")))
4677 (defun org-goto-quit ()
4678 "Finish `org-goto' without cursor motion."
4679 (interactive)
4680 (setq org-goto-selected-point nil)
4681 (setq org-goto-exit-command 'quit)
4682 (throw 'exit nil))
4684 ;;; Indirect buffer display of subtrees
4686 (defvar org-indirect-dedicated-frame nil
4687 "This is the frame being used for indirect tree display.")
4688 (defvar org-last-indirect-buffer nil)
4690 (defun org-tree-to-indirect-buffer (&optional arg)
4691 "Create indirect buffer and narrow it to current subtree.
4692 With numerical prefix ARG, go up to this level and then take that tree.
4693 If ARG is negative, go up that many levels.
4694 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4695 indirect buffer previously made with this command, to avoid proliferation of
4696 indirect buffers. However, when you call the command with a `C-u' prefix, or
4697 when `org-indirect-buffer-display' is `new-frame', the last buffer
4698 is kept so that you can work with several indirect buffers at the same time.
4699 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4700 requests that a new frame be made for the new buffer, so that the dedicated
4701 frame is not changed."
4702 (interactive "P")
4703 (let ((cbuf (current-buffer))
4704 (cwin (selected-window))
4705 (pos (point))
4706 beg end level heading ibuf)
4707 (save-excursion
4708 (org-back-to-heading t)
4709 (when (numberp arg)
4710 (setq level (org-outline-level))
4711 (if (< arg 0) (setq arg (+ level arg)))
4712 (while (> (setq level (org-outline-level)) arg)
4713 (outline-up-heading 1 t)))
4714 (setq beg (point)
4715 heading (org-get-heading))
4716 (org-end-of-subtree t) (setq end (point)))
4717 (if (and (buffer-live-p org-last-indirect-buffer)
4718 (not (eq org-indirect-buffer-display 'new-frame))
4719 (not arg))
4720 (kill-buffer org-last-indirect-buffer))
4721 (setq ibuf (org-get-indirect-buffer cbuf)
4722 org-last-indirect-buffer ibuf)
4723 (cond
4724 ((or (eq org-indirect-buffer-display 'new-frame)
4725 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4726 (select-frame (make-frame))
4727 (delete-other-windows)
4728 (switch-to-buffer ibuf)
4729 (org-set-frame-title heading))
4730 ((eq org-indirect-buffer-display 'dedicated-frame)
4731 (raise-frame
4732 (select-frame (or (and org-indirect-dedicated-frame
4733 (frame-live-p org-indirect-dedicated-frame)
4734 org-indirect-dedicated-frame)
4735 (setq org-indirect-dedicated-frame (make-frame)))))
4736 (delete-other-windows)
4737 (switch-to-buffer ibuf)
4738 (org-set-frame-title (concat "Indirect: " heading)))
4739 ((eq org-indirect-buffer-display 'current-window)
4740 (switch-to-buffer ibuf))
4741 ((eq org-indirect-buffer-display 'other-window)
4742 (pop-to-buffer ibuf))
4743 (t (error "Invalid value.")))
4744 (if (featurep 'xemacs)
4745 (save-excursion (org-mode) (turn-on-font-lock)))
4746 (narrow-to-region beg end)
4747 (show-all)
4748 (goto-char pos)
4749 (and (window-live-p cwin) (select-window cwin))))
4751 (defun org-get-indirect-buffer (&optional buffer)
4752 (setq buffer (or buffer (current-buffer)))
4753 (let ((n 1) (base (buffer-name buffer)) bname)
4754 (while (buffer-live-p
4755 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4756 (setq n (1+ n)))
4757 (condition-case nil
4758 (make-indirect-buffer buffer bname 'clone)
4759 (error (make-indirect-buffer buffer bname)))))
4761 (defun org-set-frame-title (title)
4762 "Set the title of the current frame to the string TITLE."
4763 ;; FIXME: how to name a single frame in XEmacs???
4764 (unless (featurep 'xemacs)
4765 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4767 ;;;; Structure editing
4769 ;;; Inserting headlines
4771 (defun org-insert-heading (&optional force-heading)
4772 "Insert a new heading or item with same depth at point.
4773 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4774 If point is at the beginning of a headline, insert a sibling before the
4775 current headline. If point is not at the beginning, do not split the line,
4776 but create the new headline after the current line."
4777 (interactive "P")
4778 (if (= (buffer-size) 0)
4779 (insert "\n* ")
4780 (when (or force-heading (not (org-insert-item)))
4781 (let* ((head (save-excursion
4782 (condition-case nil
4783 (progn
4784 (org-back-to-heading)
4785 (match-string 0))
4786 (error "*"))))
4787 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4788 pos hide-previous previous-pos)
4789 (cond
4790 ((and (org-on-heading-p) (bolp)
4791 (or (bobp)
4792 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4793 ;; insert before the current line
4794 (open-line (if blank 2 1)))
4795 ((and (bolp)
4796 (or (bobp)
4797 (save-excursion
4798 (backward-char 1) (not (org-invisible-p)))))
4799 ;; insert right here
4800 nil)
4802 ;; somewhere in the line
4803 (save-excursion
4804 (setq previous-pos (point-at-bol))
4805 (end-of-line)
4806 (setq hide-previous (org-invisible-p)))
4807 (and org-insert-heading-respect-content (org-show-subtree))
4808 (let ((split
4809 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4810 (save-excursion
4811 (let ((p (point)))
4812 (goto-char (point-at-bol))
4813 (and (looking-at org-complex-heading-regexp)
4814 (> p (match-beginning 4)))))))
4815 tags pos)
4816 (cond
4817 (org-insert-heading-respect-content
4818 (org-end-of-subtree nil t)
4819 (or (bolp) (newline))
4820 (open-line 1))
4821 ((org-on-heading-p)
4822 (when hide-previous
4823 (show-children)
4824 (org-show-entry))
4825 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4826 (setq tags (and (match-end 2) (match-string 2)))
4827 (and (match-end 1)
4828 (delete-region (match-beginning 1) (match-end 1)))
4829 (setq pos (point-at-bol))
4830 (or split (end-of-line 1))
4831 (delete-horizontal-space)
4832 (newline (if blank 2 1))
4833 (when tags
4834 (save-excursion
4835 (goto-char pos)
4836 (end-of-line 1)
4837 (insert " " tags)
4838 (org-set-tags nil 'align))))
4840 (or split (end-of-line 1))
4841 (newline (if blank 2 1)))))))
4842 (insert head) (just-one-space)
4843 (setq pos (point))
4844 (end-of-line 1)
4845 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4846 (when (and org-insert-heading-respect-content hide-previous)
4847 (save-excursion
4848 (goto-char previous-pos)
4849 (hide-subtree)))
4850 (run-hooks 'org-insert-heading-hook)))))
4852 (defun org-get-heading (&optional no-tags)
4853 "Return the heading of the current entry, without the stars."
4854 (save-excursion
4855 (org-back-to-heading t)
4856 (if (looking-at
4857 (if no-tags
4858 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4859 "\\*+[ \t]+\\([^\r\n]*\\)"))
4860 (match-string 1) "")))
4862 (defun org-insert-heading-after-current ()
4863 "Insert a new heading with same level as current, after current subtree."
4864 (interactive)
4865 (org-back-to-heading)
4866 (org-insert-heading)
4867 (org-move-subtree-down)
4868 (end-of-line 1))
4870 (defun org-insert-heading-respect-content ()
4871 (interactive)
4872 (let ((org-insert-heading-respect-content t))
4873 (org-insert-heading t)))
4875 (defun org-insert-todo-heading-respect-content (&optional force-state)
4876 (interactive "P")
4877 (let ((org-insert-heading-respect-content t))
4878 (org-insert-todo-heading force-state t)))
4880 (defun org-insert-todo-heading (arg &optional force-heading)
4881 "Insert a new heading with the same level and TODO state as current heading.
4882 If the heading has no TODO state, or if the state is DONE, use the first
4883 state (TODO by default). Also with prefix arg, force first state."
4884 (interactive "P")
4885 (when (or force-heading (not (org-insert-item 'checkbox)))
4886 (org-insert-heading force-heading)
4887 (save-excursion
4888 (org-back-to-heading)
4889 (outline-previous-heading)
4890 (looking-at org-todo-line-regexp))
4891 (if (or arg
4892 (not (match-beginning 2))
4893 (member (match-string 2) org-done-keywords))
4894 (insert (car org-todo-keywords-1) " ")
4895 (insert (match-string 2) " "))
4896 (when org-provide-todo-statistics
4897 (org-update-parent-todo-statistics))))
4899 (defun org-insert-subheading (arg)
4900 "Insert a new subheading and demote it.
4901 Works for outline headings and for plain lists alike."
4902 (interactive "P")
4903 (org-insert-heading arg)
4904 (cond
4905 ((org-on-heading-p) (org-do-demote))
4906 ((org-at-item-p) (org-indent-item 1))))
4908 (defun org-insert-todo-subheading (arg)
4909 "Insert a new subheading with TODO keyword or checkbox and demote it.
4910 Works for outline headings and for plain lists alike."
4911 (interactive "P")
4912 (org-insert-todo-heading arg)
4913 (cond
4914 ((org-on-heading-p) (org-do-demote))
4915 ((org-at-item-p) (org-indent-item 1))))
4917 ;;; Promotion and Demotion
4919 (defun org-promote-subtree ()
4920 "Promote the entire subtree.
4921 See also `org-promote'."
4922 (interactive)
4923 (save-excursion
4924 (org-map-tree 'org-promote))
4925 (org-fix-position-after-promote))
4927 (defun org-demote-subtree ()
4928 "Demote the entire subtree. See `org-demote'.
4929 See also `org-promote'."
4930 (interactive)
4931 (save-excursion
4932 (org-map-tree 'org-demote))
4933 (org-fix-position-after-promote))
4936 (defun org-do-promote ()
4937 "Promote the current heading higher up the tree.
4938 If the region is active in `transient-mark-mode', promote all headings
4939 in the region."
4940 (interactive)
4941 (save-excursion
4942 (if (org-region-active-p)
4943 (org-map-region 'org-promote (region-beginning) (region-end))
4944 (org-promote)))
4945 (org-fix-position-after-promote))
4947 (defun org-do-demote ()
4948 "Demote the current heading lower down the tree.
4949 If the region is active in `transient-mark-mode', demote all headings
4950 in the region."
4951 (interactive)
4952 (save-excursion
4953 (if (org-region-active-p)
4954 (org-map-region 'org-demote (region-beginning) (region-end))
4955 (org-demote)))
4956 (org-fix-position-after-promote))
4958 (defun org-fix-position-after-promote ()
4959 "Make sure that after pro/demotion cursor position is right."
4960 (let ((pos (point)))
4961 (when (save-excursion
4962 (beginning-of-line 1)
4963 (looking-at org-todo-line-regexp)
4964 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4965 (cond ((eobp) (insert " "))
4966 ((eolp) (insert " "))
4967 ((equal (char-after) ?\ ) (forward-char 1))))))
4969 (defun org-reduced-level (l)
4970 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4972 (defun org-get-valid-level (level &optional change)
4973 "Rectify a level change under the influence of `org-odd-levels-only'
4974 LEVEL is a current level, CHANGE is by how much the level should be
4975 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4976 even level numbers will become the next higher odd number."
4977 (if org-odd-levels-only
4978 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4979 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4980 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4981 (max 1 (+ level change))))
4983 (if (boundp 'define-obsolete-function-alias)
4984 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4985 (define-obsolete-function-alias 'org-get-legal-level
4986 'org-get-valid-level)
4987 (define-obsolete-function-alias 'org-get-legal-level
4988 'org-get-valid-level "23.1")))
4990 (defun org-promote ()
4991 "Promote the current heading higher up the tree.
4992 If the region is active in `transient-mark-mode', promote all headings
4993 in the region."
4994 (org-back-to-heading t)
4995 (let* ((level (save-match-data (funcall outline-level)))
4996 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4997 (diff (abs (- level (length up-head) -1))))
4998 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4999 (replace-match up-head nil t)
5000 ;; Fixup tag positioning
5001 (and org-auto-align-tags (org-set-tags nil t))
5002 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5004 (defun org-demote ()
5005 "Demote the current heading lower down the tree.
5006 If the region is active in `transient-mark-mode', demote all headings
5007 in the region."
5008 (org-back-to-heading t)
5009 (let* ((level (save-match-data (funcall outline-level)))
5010 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5011 (diff (abs (- level (length down-head) -1))))
5012 (replace-match down-head nil t)
5013 ;; Fixup tag positioning
5014 (and org-auto-align-tags (org-set-tags nil t))
5015 (if org-adapt-indentation (org-fixup-indentation diff))))
5017 (defun org-map-tree (fun)
5018 "Call FUN for every heading underneath the current one."
5019 (org-back-to-heading)
5020 (let ((level (funcall outline-level)))
5021 (save-excursion
5022 (funcall fun)
5023 (while (and (progn
5024 (outline-next-heading)
5025 (> (funcall outline-level) level))
5026 (not (eobp)))
5027 (funcall fun)))))
5029 (defun org-map-region (fun beg end)
5030 "Call FUN for every heading between BEG and END."
5031 (let ((org-ignore-region t))
5032 (save-excursion
5033 (setq end (copy-marker end))
5034 (goto-char beg)
5035 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5036 (< (point) end))
5037 (funcall fun))
5038 (while (and (progn
5039 (outline-next-heading)
5040 (< (point) end))
5041 (not (eobp)))
5042 (funcall fun)))))
5044 (defun org-fixup-indentation (diff)
5045 "Change the indentation in the current entry by DIFF
5046 However, if any line in the current entry has no indentation, or if it
5047 would end up with no indentation after the change, nothing at all is done."
5048 (save-excursion
5049 (let ((end (save-excursion (outline-next-heading)
5050 (point-marker)))
5051 (prohibit (if (> diff 0)
5052 "^\\S-"
5053 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5054 col)
5055 (unless (save-excursion (end-of-line 1)
5056 (re-search-forward prohibit end t))
5057 (while (and (< (point) end)
5058 (re-search-forward "^[ \t]+" end t))
5059 (goto-char (match-end 0))
5060 (setq col (current-column))
5061 (if (< diff 0) (replace-match ""))
5062 (org-indent-to-column (+ diff col))))
5063 (move-marker end nil))))
5065 (defun org-convert-to-odd-levels ()
5066 "Convert an org-mode file with all levels allowed to one with odd levels.
5067 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5068 level 5 etc."
5069 (interactive)
5070 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5071 (let ((org-odd-levels-only nil) n)
5072 (save-excursion
5073 (goto-char (point-min))
5074 (while (re-search-forward "^\\*\\*+ " nil t)
5075 (setq n (- (length (match-string 0)) 2))
5076 (while (>= (setq n (1- n)) 0)
5077 (org-demote))
5078 (end-of-line 1))))))
5081 (defun org-convert-to-oddeven-levels ()
5082 "Convert an org-mode file with only odd levels to one with odd and even levels.
5083 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5084 section with an even level, conversion would destroy the structure of the file. An error
5085 is signaled in this case."
5086 (interactive)
5087 (goto-char (point-min))
5088 ;; First check if there are no even levels
5089 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5090 (org-show-context t)
5091 (error "Not all levels are odd in this file. Conversion not possible."))
5092 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5093 (let ((org-odd-levels-only nil) n)
5094 (save-excursion
5095 (goto-char (point-min))
5096 (while (re-search-forward "^\\*\\*+ " nil t)
5097 (setq n (/ (1- (length (match-string 0))) 2))
5098 (while (>= (setq n (1- n)) 0)
5099 (org-promote))
5100 (end-of-line 1))))))
5102 (defun org-tr-level (n)
5103 "Make N odd if required."
5104 (if org-odd-levels-only (1+ (/ n 2)) n))
5106 ;;; Vertical tree motion, cutting and pasting of subtrees
5108 (defun org-move-subtree-up (&optional arg)
5109 "Move the current subtree up past ARG headlines of the same level."
5110 (interactive "p")
5111 (org-move-subtree-down (- (prefix-numeric-value arg))))
5113 (defun org-move-subtree-down (&optional arg)
5114 "Move the current subtree down past ARG headlines of the same level."
5115 (interactive "p")
5116 (setq arg (prefix-numeric-value arg))
5117 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5118 'outline-get-last-sibling))
5119 (ins-point (make-marker))
5120 (cnt (abs arg))
5121 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5122 ;; Select the tree
5123 (org-back-to-heading)
5124 (setq beg0 (point))
5125 (save-excursion
5126 (setq ne-beg (org-back-over-empty-lines))
5127 (setq beg (point)))
5128 (save-match-data
5129 (save-excursion (outline-end-of-heading)
5130 (setq folded (org-invisible-p)))
5131 (outline-end-of-subtree))
5132 (outline-next-heading)
5133 (setq ne-end (org-back-over-empty-lines))
5134 (setq end (point))
5135 (goto-char beg0)
5136 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5137 ;; include less whitespace
5138 (save-excursion
5139 (goto-char beg)
5140 (forward-line (- ne-beg ne-end))
5141 (setq beg (point))))
5142 ;; Find insertion point, with error handling
5143 (while (> cnt 0)
5144 (or (and (funcall movfunc) (looking-at outline-regexp))
5145 (progn (goto-char beg0)
5146 (error "Cannot move past superior level or buffer limit")))
5147 (setq cnt (1- cnt)))
5148 (if (> arg 0)
5149 ;; Moving forward - still need to move over subtree
5150 (progn (org-end-of-subtree t t)
5151 (save-excursion
5152 (org-back-over-empty-lines)
5153 (or (bolp) (newline)))))
5154 (setq ne-ins (org-back-over-empty-lines))
5155 (move-marker ins-point (point))
5156 (setq txt (buffer-substring beg end))
5157 (org-save-markers-in-region beg end)
5158 (delete-region beg end)
5159 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5160 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5161 (let ((bbb (point)))
5162 (insert-before-markers txt)
5163 (org-reinstall-markers-in-region bbb)
5164 (move-marker ins-point bbb))
5165 (or (bolp) (insert "\n"))
5166 (setq ins-end (point))
5167 (goto-char ins-point)
5168 (org-skip-whitespace)
5169 (when (and (< arg 0)
5170 (org-first-sibling-p)
5171 (> ne-ins ne-beg))
5172 ;; Move whitespace back to beginning
5173 (save-excursion
5174 (goto-char ins-end)
5175 (let ((kill-whole-line t))
5176 (kill-line (- ne-ins ne-beg)) (point)))
5177 (insert (make-string (- ne-ins ne-beg) ?\n)))
5178 (move-marker ins-point nil)
5179 (org-compact-display-after-subtree-move)
5180 (org-show-empty-lines-in-parent)
5181 (unless folded
5182 (org-show-entry)
5183 (show-children)
5184 (org-cycle-hide-drawers 'children))))
5186 (defvar org-subtree-clip ""
5187 "Clipboard for cut and paste of subtrees.
5188 This is actually only a copy of the kill, because we use the normal kill
5189 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5191 (defvar org-subtree-clip-folded nil
5192 "Was the last copied subtree folded?
5193 This is used to fold the tree back after pasting.")
5195 (defun org-cut-subtree (&optional n)
5196 "Cut the current subtree into the clipboard.
5197 With prefix arg N, cut this many sequential subtrees.
5198 This is a short-hand for marking the subtree and then cutting it."
5199 (interactive "p")
5200 (org-copy-subtree n 'cut))
5202 (defun org-copy-subtree (&optional n cut force-store-markers)
5203 "Cut the current subtree into the clipboard.
5204 With prefix arg N, cut this many sequential subtrees.
5205 This is a short-hand for marking the subtree and then copying it.
5206 If CUT is non-nil, actually cut the subtree.
5207 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5208 of some markers in the region, even if CUT is non-nil. This is
5209 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5210 (interactive "p")
5211 (let (beg end folded (beg0 (point)))
5212 (if (interactive-p)
5213 (org-back-to-heading nil) ; take what looks like a subtree
5214 (org-back-to-heading t)) ; take what is really there
5215 (org-back-over-empty-lines)
5216 (setq beg (point))
5217 (skip-chars-forward " \t\r\n")
5218 (save-match-data
5219 (save-excursion (outline-end-of-heading)
5220 (setq folded (org-invisible-p)))
5221 (condition-case nil
5222 (outline-forward-same-level (1- n))
5223 (error nil))
5224 (org-end-of-subtree t t))
5225 (org-back-over-empty-lines)
5226 (setq end (point))
5227 (goto-char beg0)
5228 (when (> end beg)
5229 (setq org-subtree-clip-folded folded)
5230 (when (or cut force-store-markers)
5231 (org-save-markers-in-region beg end))
5232 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5233 (setq org-subtree-clip (current-kill 0))
5234 (message "%s: Subtree(s) with %d characters"
5235 (if cut "Cut" "Copied")
5236 (length org-subtree-clip)))))
5238 (defun org-paste-subtree (&optional level tree for-yank)
5239 "Paste the clipboard as a subtree, with modification of headline level.
5240 The entire subtree is promoted or demoted in order to match a new headline
5241 level.
5243 If the cursor is at the beginning of a headline, the same level as
5244 that headline is used to paste the tree
5246 If not, the new level is derived from the *visible* headings
5247 before and after the insertion point, and taken to be the inferior headline
5248 level of the two. So if the previous visible heading is level 3 and the
5249 next is level 4 (or vice versa), level 4 will be used for insertion.
5250 This makes sure that the subtree remains an independent subtree and does
5251 not swallow low level entries.
5253 You can also force a different level, either by using a numeric prefix
5254 argument, or by inserting the heading marker by hand. For example, if the
5255 cursor is after \"*****\", then the tree will be shifted to level 5.
5257 If optional TREE is given, use this text instead of the kill ring.
5259 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5260 move back over whitespace before inserting, and move point to the end of
5261 the inserted text when done."
5262 (interactive "P")
5263 (unless (org-kill-is-subtree-p tree)
5264 (error "%s"
5265 (substitute-command-keys
5266 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5267 (let* ((visp (not (org-invisible-p)))
5268 (txt (or tree (and kill-ring (current-kill 0))))
5269 (^re (concat "^\\(" outline-regexp "\\)"))
5270 (re (concat "\\(" outline-regexp "\\)"))
5271 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5273 (old-level (if (string-match ^re txt)
5274 (- (match-end 0) (match-beginning 0) 1)
5275 -1))
5276 (force-level (cond (level (prefix-numeric-value level))
5277 ((and (looking-at "[ \t]*$")
5278 (string-match
5279 ^re_ (buffer-substring
5280 (point-at-bol) (point))))
5281 (- (match-end 1) (match-beginning 1)))
5282 ((and (bolp)
5283 (looking-at org-outline-regexp))
5284 (- (match-end 0) (point) 1))
5285 (t nil)))
5286 (previous-level (save-excursion
5287 (condition-case nil
5288 (progn
5289 (outline-previous-visible-heading 1)
5290 (if (looking-at re)
5291 (- (match-end 0) (match-beginning 0) 1)
5293 (error 1))))
5294 (next-level (save-excursion
5295 (condition-case nil
5296 (progn
5297 (or (looking-at outline-regexp)
5298 (outline-next-visible-heading 1))
5299 (if (looking-at re)
5300 (- (match-end 0) (match-beginning 0) 1)
5302 (error 1))))
5303 (new-level (or force-level (max previous-level next-level)))
5304 (shift (if (or (= old-level -1)
5305 (= new-level -1)
5306 (= old-level new-level))
5308 (- new-level old-level)))
5309 (delta (if (> shift 0) -1 1))
5310 (func (if (> shift 0) 'org-demote 'org-promote))
5311 (org-odd-levels-only nil)
5312 beg end newend)
5313 ;; Remove the forced level indicator
5314 (if force-level
5315 (delete-region (point-at-bol) (point)))
5316 ;; Paste
5317 (beginning-of-line 1)
5318 (unless for-yank (org-back-over-empty-lines))
5319 (setq beg (point))
5320 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5321 (insert-before-markers txt)
5322 (unless (string-match "\n\\'" txt) (insert "\n"))
5323 (setq newend (point))
5324 (org-reinstall-markers-in-region beg)
5325 (setq end (point))
5326 (goto-char beg)
5327 (skip-chars-forward " \t\n\r")
5328 (setq beg (point))
5329 (if (and (org-invisible-p) visp)
5330 (save-excursion (outline-show-heading)))
5331 ;; Shift if necessary
5332 (unless (= shift 0)
5333 (save-restriction
5334 (narrow-to-region beg end)
5335 (while (not (= shift 0))
5336 (org-map-region func (point-min) (point-max))
5337 (setq shift (+ delta shift)))
5338 (goto-char (point-min))
5339 (setq newend (point-max))))
5340 (when (or (interactive-p) for-yank)
5341 (message "Clipboard pasted as level %d subtree" new-level))
5342 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5343 kill-ring
5344 (eq org-subtree-clip (current-kill 0))
5345 org-subtree-clip-folded)
5346 ;; The tree was folded before it was killed/copied
5347 (hide-subtree))
5348 (and for-yank (goto-char newend))))
5350 (defun org-kill-is-subtree-p (&optional txt)
5351 "Check if the current kill is an outline subtree, or a set of trees.
5352 Returns nil if kill does not start with a headline, or if the first
5353 headline level is not the largest headline level in the tree.
5354 So this will actually accept several entries of equal levels as well,
5355 which is OK for `org-paste-subtree'.
5356 If optional TXT is given, check this string instead of the current kill."
5357 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5358 (start-level (and kill
5359 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5360 org-outline-regexp "\\)")
5361 kill)
5362 (- (match-end 2) (match-beginning 2) 1)))
5363 (re (concat "^" org-outline-regexp))
5364 (start (1+ (or (match-beginning 2) -1))))
5365 (if (not start-level)
5366 (progn
5367 nil) ;; does not even start with a heading
5368 (catch 'exit
5369 (while (setq start (string-match re kill (1+ start)))
5370 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5371 (throw 'exit nil)))
5372 t))))
5374 (defvar org-markers-to-move nil
5375 "Markers that should be moved with a cut-and-paste operation.
5376 Those markers are stored together with their positions relative to
5377 the start of the region.")
5379 (defun org-save-markers-in-region (beg end)
5380 "Check markers in region.
5381 If these markers are between BEG and END, record their position relative
5382 to BEG, so that after moving the block of text, we can put the markers back
5383 into place.
5384 This function gets called just before an entry or tree gets cut from the
5385 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5386 called immediately, to move the markers with the entries."
5387 (setq org-markers-to-move nil)
5388 (when (featurep 'org-clock)
5389 (org-clock-save-markers-for-cut-and-paste beg end))
5390 (when (featurep 'org-agenda)
5391 (org-agenda-save-markers-for-cut-and-paste beg end)))
5393 (defun org-check-and-save-marker (marker beg end)
5394 "Check if MARKER is between BEG and END.
5395 If yes, remember the marker and the distance to BEG."
5396 (when (and (marker-buffer marker)
5397 (equal (marker-buffer marker) (current-buffer)))
5398 (if (and (>= marker beg) (< marker end))
5399 (push (cons marker (- marker beg)) org-markers-to-move))))
5401 (defun org-reinstall-markers-in-region (beg)
5402 "Move all remembered markers to their position relative to BEG."
5403 (mapc (lambda (x)
5404 (move-marker (car x) (+ beg (cdr x))))
5405 org-markers-to-move)
5406 (setq org-markers-to-move nil))
5408 (defun org-narrow-to-subtree ()
5409 "Narrow buffer to the current subtree."
5410 (interactive)
5411 (save-excursion
5412 (save-match-data
5413 (narrow-to-region
5414 (progn (org-back-to-heading) (point))
5415 (progn (org-end-of-subtree t) (point))))))
5418 ;;; Outline Sorting
5420 (defun org-sort (with-case)
5421 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5422 Optional argument WITH-CASE means sort case-sensitively."
5423 (interactive "P")
5424 (if (org-at-table-p)
5425 (org-call-with-arg 'org-table-sort-lines with-case)
5426 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5428 (defun org-sort-remove-invisible (s)
5429 (remove-text-properties 0 (length s) org-rm-props s)
5430 (while (string-match org-bracket-link-regexp s)
5431 (setq s (replace-match (if (match-end 2)
5432 (match-string 3 s)
5433 (match-string 1 s)) t t s)))
5436 (defvar org-priority-regexp) ; defined later in the file
5438 (defun org-sort-entries-or-items
5439 (&optional with-case sorting-type getkey-func compare-func property)
5440 "Sort entries on a certain level of an outline tree.
5441 If there is an active region, the entries in the region are sorted.
5442 Else, if the cursor is before the first entry, sort the top-level items.
5443 Else, the children of the entry at point are sorted.
5445 Sorting can be alphabetically, numerically, and by date/time as given by
5446 the first time stamp in the entry. The command prompts for the sorting
5447 type unless it has been given to the function through the SORTING-TYPE
5448 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5449 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5450 called with point at the beginning of the record. It must return either
5451 a string or a number that should serve as the sorting key for that record.
5453 Comparing entries ignores case by default. However, with an optional argument
5454 WITH-CASE, the sorting considers case as well."
5455 (interactive "P")
5456 (let ((case-func (if with-case 'identity 'downcase))
5457 start beg end stars re re2
5458 txt what tmp plain-list-p)
5459 ;; Find beginning and end of region to sort
5460 (cond
5461 ((org-region-active-p)
5462 ;; we will sort the region
5463 (setq end (region-end)
5464 what "region")
5465 (goto-char (region-beginning))
5466 (if (not (org-on-heading-p)) (outline-next-heading))
5467 (setq start (point)))
5468 ((org-at-item-p)
5469 ;; we will sort this plain list
5470 (org-beginning-of-item-list) (setq start (point))
5471 (org-end-of-item-list) (setq end (point))
5472 (goto-char start)
5473 (setq plain-list-p t
5474 what "plain list"))
5475 ((or (org-on-heading-p)
5476 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5477 ;; we will sort the children of the current headline
5478 (org-back-to-heading)
5479 (setq start (point)
5480 end (progn (org-end-of-subtree t t)
5481 (org-back-over-empty-lines)
5482 (point))
5483 what "children")
5484 (goto-char start)
5485 (show-subtree)
5486 (outline-next-heading))
5488 ;; we will sort the top-level entries in this file
5489 (goto-char (point-min))
5490 (or (org-on-heading-p) (outline-next-heading))
5491 (setq start (point) end (point-max) what "top-level")
5492 (goto-char start)
5493 (show-all)))
5495 (setq beg (point))
5496 (if (>= beg end) (error "Nothing to sort"))
5498 (unless plain-list-p
5499 (looking-at "\\(\\*+\\)")
5500 (setq stars (match-string 1)
5501 re (concat "^" (regexp-quote stars) " +")
5502 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5503 txt (buffer-substring beg end))
5504 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5505 (if (and (not (equal stars "*")) (string-match re2 txt))
5506 (error "Region to sort contains a level above the first entry")))
5508 (unless sorting-type
5509 (message
5510 (if plain-list-p
5511 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5512 "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:")
5513 what)
5514 (setq sorting-type (read-char-exclusive))
5516 (and (= (downcase sorting-type) ?f)
5517 (setq getkey-func
5518 (org-ido-completing-read "Sort using function: "
5519 obarray 'fboundp t nil nil))
5520 (setq getkey-func (intern getkey-func)))
5522 (and (= (downcase sorting-type) ?r)
5523 (setq property
5524 (org-ido-completing-read "Property: "
5525 (mapcar 'list (org-buffer-property-keys t))
5526 nil t))))
5528 (message "Sorting entries...")
5530 (save-restriction
5531 (narrow-to-region start end)
5533 (let ((dcst (downcase sorting-type))
5534 (now (current-time)))
5535 (sort-subr
5536 (/= dcst sorting-type)
5537 ;; This function moves to the beginning character of the "record" to
5538 ;; be sorted.
5539 (if plain-list-p
5540 (lambda nil
5541 (if (org-at-item-p) t (goto-char (point-max))))
5542 (lambda nil
5543 (if (re-search-forward re nil t)
5544 (goto-char (match-beginning 0))
5545 (goto-char (point-max)))))
5546 ;; This function moves to the last character of the "record" being
5547 ;; sorted.
5548 (if plain-list-p
5549 'org-end-of-item
5550 (lambda nil
5551 (save-match-data
5552 (condition-case nil
5553 (outline-forward-same-level 1)
5554 (error
5555 (goto-char (point-max)))))))
5557 ;; This function returns the value that gets sorted against.
5558 (if plain-list-p
5559 (lambda nil
5560 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5561 (cond
5562 ((= dcst ?n)
5563 (string-to-number (buffer-substring (match-end 0)
5564 (point-at-eol))))
5565 ((= dcst ?a)
5566 (buffer-substring (match-end 0) (point-at-eol)))
5567 ((= dcst ?t)
5568 (if (re-search-forward org-ts-regexp
5569 (point-at-eol) t)
5570 (org-time-string-to-time (match-string 0))
5571 now))
5572 ((= dcst ?f)
5573 (if getkey-func
5574 (progn
5575 (setq tmp (funcall getkey-func))
5576 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5577 tmp)
5578 (error "Invalid key function `%s'" getkey-func)))
5579 (t (error "Invalid sorting type `%c'" sorting-type)))))
5580 (lambda nil
5581 (cond
5582 ((= dcst ?n)
5583 (if (looking-at org-complex-heading-regexp)
5584 (string-to-number (match-string 4))
5585 nil))
5586 ((= dcst ?a)
5587 (if (looking-at org-complex-heading-regexp)
5588 (funcall case-func (match-string 4))
5589 nil))
5590 ((= dcst ?t)
5591 (if (re-search-forward org-ts-regexp
5592 (save-excursion
5593 (forward-line 2)
5594 (point)) t)
5595 (org-time-string-to-time (match-string 0))
5596 now))
5597 ((= dcst ?p)
5598 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5599 (string-to-char (match-string 2))
5600 org-default-priority))
5601 ((= dcst ?r)
5602 (or (org-entry-get nil property) ""))
5603 ((= dcst ?o)
5604 (if (looking-at org-complex-heading-regexp)
5605 (- 9999 (length (member (match-string 2)
5606 org-todo-keywords-1)))))
5607 ((= dcst ?f)
5608 (if getkey-func
5609 (progn
5610 (setq tmp (funcall getkey-func))
5611 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5612 tmp)
5613 (error "Invalid key function `%s'" getkey-func)))
5614 (t (error "Invalid sorting type `%c'" sorting-type)))))
5616 (cond
5617 ((= dcst ?a) 'string<)
5618 ((= dcst ?t) 'time-less-p)
5619 ((= dcst ?f) compare-func)
5620 (t nil)))))
5621 (message "Sorting entries...done")))
5623 (defun org-do-sort (table what &optional with-case sorting-type)
5624 "Sort TABLE of WHAT according to SORTING-TYPE.
5625 The user will be prompted for the SORTING-TYPE if the call to this
5626 function does not specify it. WHAT is only for the prompt, to indicate
5627 what is being sorted. The sorting key will be extracted from
5628 the car of the elements of the table.
5629 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5630 (unless sorting-type
5631 (message
5632 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5633 what)
5634 (setq sorting-type (read-char-exclusive)))
5635 (let ((dcst (downcase sorting-type))
5636 extractfun comparefun)
5637 ;; Define the appropriate functions
5638 (cond
5639 ((= dcst ?n)
5640 (setq extractfun 'string-to-number
5641 comparefun (if (= dcst sorting-type) '< '>)))
5642 ((= dcst ?a)
5643 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5644 (lambda(x) (downcase (org-sort-remove-invisible x))))
5645 comparefun (if (= dcst sorting-type)
5646 'string<
5647 (lambda (a b) (and (not (string< a b))
5648 (not (string= a b)))))))
5649 ((= dcst ?t)
5650 (setq extractfun
5651 (lambda (x)
5652 (if (string-match org-ts-regexp x)
5653 (time-to-seconds
5654 (org-time-string-to-time (match-string 0 x)))
5656 comparefun (if (= dcst sorting-type) '< '>)))
5657 (t (error "Invalid sorting type `%c'" sorting-type)))
5659 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5660 table)
5661 (lambda (a b) (funcall comparefun (car a) (car b))))))
5663 ;;; Editing source examples
5665 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5666 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5667 (defvar org-edit-src-force-single-line nil)
5668 (defvar org-edit-src-from-org-mode nil)
5669 (defvar org-edit-src-picture nil)
5671 (define-minor-mode org-exit-edit-mode
5672 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5674 (defun org-edit-src-code ()
5675 "Edit the source code example at point.
5676 An indirect buffer is created, and that buffer is then narrowed to the
5677 example at point and switched to the correct language mode. When done,
5678 exit by killing the buffer with \\[org-edit-src-exit]."
5679 (interactive)
5680 (let ((line (org-current-line))
5681 (case-fold-search t)
5682 (msg (substitute-command-keys
5683 "Edit, then exit with C-c ' (C-c and single quote)"))
5684 (info (org-edit-src-find-region-and-lang))
5685 (org-mode-p (eq major-mode 'org-mode))
5686 beg end lang lang-f single)
5687 (if (not info)
5689 (setq beg (nth 0 info)
5690 end (nth 1 info)
5691 lang (nth 2 info)
5692 single (nth 3 info)
5693 lang-f (intern (concat lang "-mode")))
5694 (unless (functionp lang-f)
5695 (error "No such language mode: %s" lang-f))
5696 (goto-line line)
5697 (if (get-buffer "*Org Edit Src Example*")
5698 (kill-buffer "*Org Edit Src Example*"))
5699 (switch-to-buffer (make-indirect-buffer (current-buffer)
5700 "*Org Edit Src Example*"))
5701 (narrow-to-region beg end)
5702 (remove-text-properties beg end '(display nil invisible nil
5703 intangible nil))
5704 (let ((org-inhibit-startup t))
5705 (funcall lang-f))
5706 (set (make-local-variable 'org-edit-src-force-single-line) single)
5707 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5708 (when org-mode-p
5709 (goto-char (point-min))
5710 (while (re-search-forward "^," nil t)
5711 (replace-match "")))
5712 (goto-line line)
5713 (org-exit-edit-mode)
5714 (org-set-local 'header-line-format msg)
5715 (message "%s" msg)
5716 t)))
5718 (defun org-edit-fixed-width-region ()
5719 "Edit the fixed-width ascii drawing at point.
5720 This must be a region where each line starts with a colon followed by
5721 a space character.
5722 An indirect buffer is created, and that buffer is then narrowed to the
5723 example at point and switched to artist-mode. When done,
5724 exit by killing the buffer with \\[org-edit-src-exit]."
5725 (interactive)
5726 (let ((line (org-current-line))
5727 (case-fold-search t)
5728 (msg (substitute-command-keys
5729 "Edit, then exit with C-c ' (C-c and single quote)"))
5730 (org-mode-p (eq major-mode 'org-mode))
5731 beg end lang lang-f)
5732 (beginning-of-line 1)
5733 (if (looking-at "[ \t]*[^:\n \t]")
5735 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5736 (setq beg (point) end beg)
5737 (save-excursion
5738 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5739 (setq beg (point-at-bol 2))
5740 (setq beg (point))))
5741 (save-excursion
5742 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5743 (setq end (1- (match-beginning 0)))
5744 (setq end (point))))
5745 (goto-line line))
5746 (if (get-buffer "*Org Edit Picture*")
5747 (kill-buffer "*Org Edit Picture*"))
5748 (switch-to-buffer (make-indirect-buffer (current-buffer)
5749 "*Org Edit Picture*"))
5750 (narrow-to-region beg end)
5751 (remove-text-properties beg end '(display nil invisible nil
5752 intangible nil))
5753 (when (fboundp 'font-lock-unfontify-region)
5754 (font-lock-unfontify-region (point-min) (point-max)))
5755 (cond
5756 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5757 (fundamental-mode)
5758 (artist-mode 1))
5759 (t (funcall org-edit-fixed-width-region-mode)))
5760 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5761 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5762 (set (make-local-variable 'org-edit-src-picture) t)
5763 (goto-char (point-min))
5764 (while (re-search-forward "^[ \t]*: ?" nil t)
5765 (replace-match ""))
5766 (goto-line line)
5767 (org-exit-edit-mode)
5768 (org-set-local 'header-line-format msg)
5769 (message "%s" msg)
5770 t)))
5773 (defun org-edit-src-find-region-and-lang ()
5774 "Find the region and language for a local edit.
5775 Return a list with beginning and end of the region, a string representing
5776 the language, a switch telling of the content should be in a single line."
5777 (let ((re-list
5778 (append
5779 org-edit-src-region-extra
5781 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5782 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5783 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5784 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5785 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5786 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5787 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5788 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5789 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5790 ("^#\\+html:" "\n" "html" single-line)
5791 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5792 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5793 ("^#\\+latex:" "\n" "latex" single-line)
5794 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5795 ("^#\\+ascii:" "\n" "ascii" single-line)
5797 (pos (point))
5798 re re1 re2 single beg end lang)
5799 (catch 'exit
5800 (while (setq entry (pop re-list))
5801 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5802 single (nth 3 entry))
5803 (save-excursion
5804 (if (or (looking-at re1)
5805 (re-search-backward re1 nil t))
5806 (progn
5807 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5808 (if (and (re-search-forward re2 nil t)
5809 (>= (match-end 0) pos))
5810 (throw 'exit (list beg (match-beginning 0) lang single))))
5811 (if (or (looking-at re2)
5812 (re-search-forward re2 nil t))
5813 (progn
5814 (setq end (match-beginning 0))
5815 (if (and (re-search-backward re1 nil t)
5816 (<= (match-beginning 0) pos))
5817 (throw 'exit
5818 (list (match-end 0) end
5819 (org-edit-src-get-lang lang) single)))))))))))
5821 (defun org-edit-src-get-lang (lang)
5822 "Extract the src language."
5823 (let ((m (match-string 0)))
5824 (cond
5825 ((stringp lang) lang)
5826 ((integerp lang) (match-string lang))
5827 ((and (eq lang 'lang)
5828 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5829 (match-string 1 m))
5830 ((and (eq lang 'style)
5831 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5832 (match-string 1 m))
5833 (t "fundamental"))))
5835 (defun org-edit-src-exit ()
5836 "Exit special edit and protect problematic lines."
5837 (interactive)
5838 (unless (buffer-base-buffer (current-buffer))
5839 (error "This is not an indirect buffer, something is wrong..."))
5840 (unless (> (point-min) 1)
5841 (error "This buffer is not narrowed, something is wrong..."))
5842 (goto-char (point-min))
5843 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5844 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5845 (when (org-bound-and-true-p org-edit-src-force-single-line)
5846 (goto-char (point-min))
5847 (while (re-search-forward "\n" nil t)
5848 (replace-match " "))
5849 (goto-char (point-min))
5850 (if (looking-at "\\s-*") (replace-match " "))
5851 (if (re-search-forward "\\s-+\\'" nil t)
5852 (replace-match "")))
5853 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5854 (goto-char (point-min))
5855 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5856 (replace-match ",\\1"))
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 (when (org-bound-and-true-p org-edit-src-picture)
5861 (untabify (point-min) (point-max))
5862 (goto-char (point-min))
5863 (while (re-search-forward "^" nil t)
5864 (replace-match ": "))
5865 (when font-lock-mode
5866 (font-lock-unfontify-region (point-min) (point-max)))
5867 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5868 (kill-buffer (current-buffer))
5869 (and (org-mode-p) (org-restart-font-lock)))
5872 ;;; The orgstruct minor mode
5874 ;; Define a minor mode which can be used in other modes in order to
5875 ;; integrate the org-mode structure editing commands.
5877 ;; This is really a hack, because the org-mode structure commands use
5878 ;; keys which normally belong to the major mode. Here is how it
5879 ;; works: The minor mode defines all the keys necessary to operate the
5880 ;; structure commands, but wraps the commands into a function which
5881 ;; tests if the cursor is currently at a headline or a plain list
5882 ;; item. If that is the case, the structure command is used,
5883 ;; temporarily setting many Org-mode variables like regular
5884 ;; expressions for filling etc. However, when any of those keys is
5885 ;; used at a different location, function uses `key-binding' to look
5886 ;; up if the key has an associated command in another currently active
5887 ;; keymap (minor modes, major mode, global), and executes that
5888 ;; command. There might be problems if any of the keys is otherwise
5889 ;; used as a prefix key.
5891 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5892 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5893 ;; addresses this by checking explicitly for both bindings.
5895 (defvar orgstruct-mode-map (make-sparse-keymap)
5896 "Keymap for the minor `orgstruct-mode'.")
5898 (defvar org-local-vars nil
5899 "List of local variables, for use by `orgstruct-mode'")
5901 ;;;###autoload
5902 (define-minor-mode orgstruct-mode
5903 "Toggle the minor more `orgstruct-mode'.
5904 This mode is for using Org-mode structure commands in other modes.
5905 The following key behave as if Org-mode was active, if the cursor
5906 is on a headline, or on a plain list item (both in the definition
5907 of Org-mode).
5909 M-up Move entry/item up
5910 M-down Move entry/item down
5911 M-left Promote
5912 M-right Demote
5913 M-S-up Move entry/item up
5914 M-S-down Move entry/item down
5915 M-S-left Promote subtree
5916 M-S-right Demote subtree
5917 M-q Fill paragraph and items like in Org-mode
5918 C-c ^ Sort entries
5919 C-c - Cycle list bullet
5920 TAB Cycle item visibility
5921 M-RET Insert new heading/item
5922 S-M-RET Insert new TODO heading / Checkbox item
5923 C-c C-c Set tags / toggle checkbox"
5924 nil " OrgStruct" nil
5925 (org-load-modules-maybe)
5926 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5928 ;;;###autoload
5929 (defun turn-on-orgstruct ()
5930 "Unconditionally turn on `orgstruct-mode'."
5931 (orgstruct-mode 1))
5933 ;;;###autoload
5934 (defun turn-on-orgstruct++ ()
5935 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5936 In addition to setting orgstruct-mode, this also exports all indentation and
5937 autofilling variables from org-mode into the buffer. Note that turning
5938 off orgstruct-mode will *not* remove these additional settings."
5939 (orgstruct-mode 1)
5940 (let (var val)
5941 (mapc
5942 (lambda (x)
5943 (when (string-match
5944 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5945 (symbol-name (car x)))
5946 (setq var (car x) val (nth 1 x))
5947 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5948 org-local-vars)))
5950 (defun orgstruct-error ()
5951 "Error when there is no default binding for a structure key."
5952 (interactive)
5953 (error "This key has no function outside structure elements"))
5955 (defun orgstruct-setup ()
5956 "Setup orgstruct keymaps."
5957 (let ((nfunc 0)
5958 (bindings
5959 (list
5960 '([(meta up)] org-metaup)
5961 '([(meta down)] org-metadown)
5962 '([(meta left)] org-metaleft)
5963 '([(meta right)] org-metaright)
5964 '([(meta shift up)] org-shiftmetaup)
5965 '([(meta shift down)] org-shiftmetadown)
5966 '([(meta shift left)] org-shiftmetaleft)
5967 '([(meta shift right)] org-shiftmetaright)
5968 '([(shift up)] org-shiftup)
5969 '([(shift down)] org-shiftdown)
5970 '([(shift left)] org-shiftleft)
5971 '([(shift right)] org-shiftright)
5972 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5973 '("\M-q" fill-paragraph)
5974 '("\C-c^" org-sort)
5975 '("\C-c-" org-cycle-list-bullet)))
5976 elt key fun cmd)
5977 (while (setq elt (pop bindings))
5978 (setq nfunc (1+ nfunc))
5979 (setq key (org-key (car elt))
5980 fun (nth 1 elt)
5981 cmd (orgstruct-make-binding fun nfunc key))
5982 (org-defkey orgstruct-mode-map key cmd))
5984 ;; Special treatment needed for TAB and RET
5985 (org-defkey orgstruct-mode-map [(tab)]
5986 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5987 (org-defkey orgstruct-mode-map "\C-i"
5988 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5990 (org-defkey orgstruct-mode-map "\M-\C-m"
5991 (orgstruct-make-binding 'org-insert-heading 105
5992 "\M-\C-m" [(meta return)]))
5993 (org-defkey orgstruct-mode-map [(meta return)]
5994 (orgstruct-make-binding 'org-insert-heading 106
5995 [(meta return)] "\M-\C-m"))
5997 (org-defkey orgstruct-mode-map [(shift meta return)]
5998 (orgstruct-make-binding 'org-insert-todo-heading 107
5999 [(meta return)] "\M-\C-m"))
6001 (unless org-local-vars
6002 (setq org-local-vars (org-get-local-variables)))
6006 (defun orgstruct-make-binding (fun n &rest keys)
6007 "Create a function for binding in the structure minor mode.
6008 FUN is the command to call inside a table. N is used to create a unique
6009 command name. KEYS are keys that should be checked in for a command
6010 to execute outside of tables."
6011 (eval
6012 (list 'defun
6013 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6014 '(arg)
6015 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6016 "Outside of structure, run the binding of `"
6017 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6018 "'.")
6019 '(interactive "p")
6020 (list 'if
6021 '(org-context-p 'headline 'item)
6022 (list 'org-run-like-in-org-mode (list 'quote fun))
6023 (list 'let '(orgstruct-mode)
6024 (list 'call-interactively
6025 (append '(or)
6026 (mapcar (lambda (k)
6027 (list 'key-binding k))
6028 keys)
6029 '('orgstruct-error))))))))
6031 (defun org-context-p (&rest contexts)
6032 "Check if local context is any of CONTEXTS.
6033 Possible values in the list of contexts are `table', `headline', and `item'."
6034 (let ((pos (point)))
6035 (goto-char (point-at-bol))
6036 (prog1 (or (and (memq 'table contexts)
6037 (looking-at "[ \t]*|"))
6038 (and (memq 'headline contexts)
6039 ;;????????? (looking-at "\\*+"))
6040 (looking-at outline-regexp))
6041 (and (memq 'item contexts)
6042 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6043 (goto-char pos))))
6045 (defun org-get-local-variables ()
6046 "Return a list of all local variables in an org-mode buffer."
6047 (let (varlist)
6048 (with-current-buffer (get-buffer-create "*Org tmp*")
6049 (erase-buffer)
6050 (org-mode)
6051 (setq varlist (buffer-local-variables)))
6052 (kill-buffer "*Org tmp*")
6053 (delq nil
6054 (mapcar
6055 (lambda (x)
6056 (setq x
6057 (if (symbolp x)
6058 (list x)
6059 (list (car x) (list 'quote (cdr x)))))
6060 (if (string-match
6061 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6062 (symbol-name (car x)))
6063 x nil))
6064 varlist))))
6066 ;;;###autoload
6067 (defun org-run-like-in-org-mode (cmd)
6068 (org-load-modules-maybe)
6069 (unless org-local-vars
6070 (setq org-local-vars (org-get-local-variables)))
6071 (eval (list 'let org-local-vars
6072 (list 'call-interactively (list 'quote cmd)))))
6074 ;;;; Archiving
6076 (defun org-get-category (&optional pos)
6077 "Get the category applying to position POS."
6078 (get-text-property (or pos (point)) 'org-category))
6080 (defun org-refresh-category-properties ()
6081 "Refresh category text properties in the buffer."
6082 (let ((def-cat (cond
6083 ((null org-category)
6084 (if buffer-file-name
6085 (file-name-sans-extension
6086 (file-name-nondirectory buffer-file-name))
6087 "???"))
6088 ((symbolp org-category) (symbol-name org-category))
6089 (t org-category)))
6090 beg end cat pos optionp)
6091 (org-unmodified
6092 (save-excursion
6093 (save-restriction
6094 (widen)
6095 (goto-char (point-min))
6096 (put-text-property (point) (point-max) 'org-category def-cat)
6097 (while (re-search-forward
6098 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6099 (setq pos (match-end 0)
6100 optionp (equal (char-after (match-beginning 0)) ?#)
6101 cat (org-trim (match-string 2)))
6102 (if optionp
6103 (setq beg (point-at-bol) end (point-max))
6104 (org-back-to-heading t)
6105 (setq beg (point) end (org-end-of-subtree t t)))
6106 (put-text-property beg end 'org-category cat)
6107 (goto-char pos)))))))
6110 ;;;; Link Stuff
6112 ;;; Link abbreviations
6114 (defun org-link-expand-abbrev (link)
6115 "Apply replacements as defined in `org-link-abbrev-alist."
6116 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6117 (let* ((key (match-string 1 link))
6118 (as (or (assoc key org-link-abbrev-alist-local)
6119 (assoc key org-link-abbrev-alist)))
6120 (tag (and (match-end 2) (match-string 3 link)))
6121 rpl)
6122 (if (not as)
6123 link
6124 (setq rpl (cdr as))
6125 (cond
6126 ((symbolp rpl) (funcall rpl tag))
6127 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6128 ((string-match "%h" rpl)
6129 (replace-match (url-hexify-string (or tag "")) t t rpl))
6130 (t (concat rpl tag)))))
6131 link))
6133 ;;; Storing and inserting links
6135 (defvar org-insert-link-history nil
6136 "Minibuffer history for links inserted with `org-insert-link'.")
6138 (defvar org-stored-links nil
6139 "Contains the links stored with `org-store-link'.")
6141 (defvar org-store-link-plist nil
6142 "Plist with info about the most recently link created with `org-store-link'.")
6144 (defvar org-link-protocols nil
6145 "Link protocols added to Org-mode using `org-add-link-type'.")
6147 (defvar org-store-link-functions nil
6148 "List of functions that are called to create and store a link.
6149 Each function will be called in turn until one returns a non-nil
6150 value. Each function should check if it is responsible for creating
6151 this link (for example by looking at the major mode).
6152 If not, it must exit and return nil.
6153 If yes, it should return a non-nil value after a calling
6154 `org-store-link-props' with a list of properties and values.
6155 Special properties are:
6157 :type The link prefix. like \"http\". This must be given.
6158 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6159 This is obligatory as well.
6160 :description Optional default description for the second pair
6161 of brackets in an Org-mode link. The user can still change
6162 this when inserting this link into an Org-mode buffer.
6164 In addition to these, any additional properties can be specified
6165 and then used in remember templates.")
6167 (defun org-add-link-type (type &optional follow export)
6168 "Add TYPE to the list of `org-link-types'.
6169 Re-compute all regular expressions depending on `org-link-types'
6171 FOLLOW and EXPORT are two functions.
6173 FOLLOW should take the link path as the single argument and do whatever
6174 is necessary to follow the link, for example find a file or display
6175 a mail message.
6177 EXPORT should format the link path for export to one of the export formats.
6178 It should be a function accepting three arguments:
6180 path the path of the link, the text after the prefix (like \"http:\")
6181 desc the description of the link, if any, nil if there was no description
6182 format the export format, a symbol like `html' or `latex'.
6184 The function may use the FORMAT information to return different values
6185 depending on the format. The return value will be put literally into
6186 the exported file.
6187 Org-mode has a built-in default for exporting links. If you are happy with
6188 this default, there is no need to define an export function for the link
6189 type. For a simple example of an export function, see `org-bbdb.el'."
6190 (add-to-list 'org-link-types type t)
6191 (org-make-link-regexps)
6192 (if (assoc type org-link-protocols)
6193 (setcdr (assoc type org-link-protocols) (list follow export))
6194 (push (list type follow export) org-link-protocols)))
6196 ;;;###autoload
6197 (defun org-store-link (arg)
6198 "\\<org-mode-map>Store an org-link to the current location.
6199 This link is added to `org-stored-links' and can later be inserted
6200 into an org-buffer with \\[org-insert-link].
6202 For some link types, a prefix arg is interpreted:
6203 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6204 For file links, arg negates `org-context-in-file-links'."
6205 (interactive "P")
6206 (org-load-modules-maybe)
6207 (setq org-store-link-plist nil) ; reset
6208 (let (link cpltxt desc description search txt)
6209 (cond
6211 ((run-hook-with-args-until-success 'org-store-link-functions)
6212 (setq link (plist-get org-store-link-plist :link)
6213 desc (or (plist-get org-store-link-plist :description) link)))
6215 ((eq major-mode 'calendar-mode)
6216 (let ((cd (calendar-cursor-to-date)))
6217 (setq link
6218 (format-time-string
6219 (car org-time-stamp-formats)
6220 (apply 'encode-time
6221 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6222 nil nil nil))))
6223 (org-store-link-props :type "calendar" :date cd)))
6225 ((eq major-mode 'w3-mode)
6226 (setq cpltxt (url-view-url t)
6227 link (org-make-link cpltxt))
6228 (org-store-link-props :type "w3" :url (url-view-url t)))
6230 ((eq major-mode 'w3m-mode)
6231 (setq cpltxt (or w3m-current-title w3m-current-url)
6232 link (org-make-link w3m-current-url))
6233 (org-store-link-props :type "w3m" :url (url-view-url t)))
6235 ((setq search (run-hook-with-args-until-success
6236 'org-create-file-search-functions))
6237 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6238 "::" search))
6239 (setq cpltxt (or description link)))
6241 ((eq major-mode 'image-mode)
6242 (setq cpltxt (concat "file:"
6243 (abbreviate-file-name buffer-file-name))
6244 link (org-make-link cpltxt))
6245 (org-store-link-props :type "image" :file buffer-file-name))
6247 ((eq major-mode 'dired-mode)
6248 ;; link to the file in the current line
6249 (setq cpltxt (concat "file:"
6250 (abbreviate-file-name
6251 (expand-file-name
6252 (dired-get-filename nil t))))
6253 link (org-make-link cpltxt)))
6255 ((and buffer-file-name (org-mode-p))
6256 (cond
6257 ((org-in-regexp "<<\\(.*?\\)>>")
6258 (setq cpltxt
6259 (concat "file:"
6260 (abbreviate-file-name buffer-file-name)
6261 "::" (match-string 1))
6262 link (org-make-link cpltxt)))
6263 ((and (featurep 'org-id)
6264 (or (eq org-link-to-org-use-id t)
6265 (and (eq org-link-to-org-use-id 'create-if-interactive)
6266 (interactive-p))
6267 (and org-link-to-org-use-id
6268 (condition-case nil
6269 (org-entry-get nil "ID")
6270 (error nil)))))
6271 ;; We can make a link using the ID.
6272 (setq link (condition-case nil
6273 (prog1 (org-id-store-link)
6274 (setq desc (plist-get org-store-link-plist
6275 :description)))
6276 (error
6277 ;; probably before first headline, link to file only
6278 (concat "file:"
6279 (abbreviate-file-name buffer-file-name))))))
6281 ;; Just link to current headline
6282 (setq cpltxt (concat "file:"
6283 (abbreviate-file-name buffer-file-name)))
6284 ;; Add a context search string
6285 (when (org-xor org-context-in-file-links arg)
6286 (setq txt (cond
6287 ((org-on-heading-p) nil)
6288 ((org-region-active-p)
6289 (buffer-substring (region-beginning) (region-end)))
6290 (t nil)))
6291 (when (or (null txt) (string-match "\\S-" txt))
6292 (setq cpltxt
6293 (concat cpltxt "::"
6294 (condition-case nil
6295 (org-make-org-heading-search-string txt)
6296 (error "")))
6297 desc "NONE")))
6298 (if (string-match "::\\'" cpltxt)
6299 (setq cpltxt (substring cpltxt 0 -2)))
6300 (setq link (org-make-link cpltxt)))))
6302 ((buffer-file-name (buffer-base-buffer))
6303 ;; Just link to this file here.
6304 (setq cpltxt (concat "file:"
6305 (abbreviate-file-name
6306 (buffer-file-name (buffer-base-buffer)))))
6307 ;; Add a context string
6308 (when (org-xor org-context-in-file-links arg)
6309 (setq txt (if (org-region-active-p)
6310 (buffer-substring (region-beginning) (region-end))
6311 (buffer-substring (point-at-bol) (point-at-eol))))
6312 ;; Only use search option if there is some text.
6313 (when (string-match "\\S-" txt)
6314 (setq cpltxt
6315 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6316 desc "NONE")))
6317 (setq link (org-make-link cpltxt)))
6319 ((interactive-p)
6320 (error "Cannot link to a buffer which is not visiting a file"))
6322 (t (setq link nil)))
6324 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6325 (setq link (or link cpltxt)
6326 desc (or desc cpltxt))
6327 (if (equal desc "NONE") (setq desc nil))
6329 (if (and (interactive-p) link)
6330 (progn
6331 (setq org-stored-links
6332 (cons (list link desc) org-stored-links))
6333 (message "Stored: %s" (or desc link)))
6334 (and link (org-make-link-string link desc)))))
6336 (defun org-store-link-props (&rest plist)
6337 "Store link properties, extract names and addresses."
6338 (let (x adr)
6339 (when (setq x (plist-get plist :from))
6340 (setq adr (mail-extract-address-components x))
6341 (setq plist (plist-put plist :fromname (car adr)))
6342 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6343 (when (setq x (plist-get plist :to))
6344 (setq adr (mail-extract-address-components x))
6345 (setq plist (plist-put plist :toname (car adr)))
6346 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6347 (let ((from (plist-get plist :from))
6348 (to (plist-get plist :to)))
6349 (when (and from to org-from-is-user-regexp)
6350 (setq plist
6351 (plist-put plist :fromto
6352 (if (string-match org-from-is-user-regexp from)
6353 (concat "to %t")
6354 (concat "from %f"))))))
6355 (setq org-store-link-plist plist))
6357 (defun org-add-link-props (&rest plist)
6358 "Add these properties to the link property list."
6359 (let (key value)
6360 (while plist
6361 (setq key (pop plist) value (pop plist))
6362 (setq org-store-link-plist
6363 (plist-put org-store-link-plist key value)))))
6365 (defun org-email-link-description (&optional fmt)
6366 "Return the description part of an email link.
6367 This takes information from `org-store-link-plist' and formats it
6368 according to FMT (default from `org-email-link-description-format')."
6369 (setq fmt (or fmt org-email-link-description-format))
6370 (let* ((p org-store-link-plist)
6371 (to (plist-get p :toaddress))
6372 (from (plist-get p :fromaddress))
6373 (table
6374 (list
6375 (cons "%c" (plist-get p :fromto))
6376 (cons "%F" (plist-get p :from))
6377 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6378 (cons "%T" (plist-get p :to))
6379 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6380 (cons "%s" (plist-get p :subject))
6381 (cons "%m" (plist-get p :message-id)))))
6382 (when (string-match "%c" fmt)
6383 ;; Check if the user wrote this message
6384 (if (and org-from-is-user-regexp from to
6385 (save-match-data (string-match org-from-is-user-regexp from)))
6386 (setq fmt (replace-match "to %t" t t fmt))
6387 (setq fmt (replace-match "from %f" t t fmt))))
6388 (org-replace-escapes fmt table)))
6390 (defun org-make-org-heading-search-string (&optional string heading)
6391 "Make search string for STRING or current headline."
6392 (interactive)
6393 (let ((s (or string (org-get-heading))))
6394 (unless (and string (not heading))
6395 ;; We are using a headline, clean up garbage in there.
6396 (if (string-match org-todo-regexp s)
6397 (setq s (replace-match "" t t s)))
6398 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6399 (setq s (replace-match "" t t s)))
6400 (setq s (org-trim s))
6401 (if (string-match (concat "^\\(" org-quote-string "\\|"
6402 org-comment-string "\\)") s)
6403 (setq s (replace-match "" t t s)))
6404 (while (string-match org-ts-regexp s)
6405 (setq s (replace-match "" t t s))))
6406 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6407 (setq s (replace-match " " t t s)))
6408 (or string (setq s (concat "*" s))) ; Add * for headlines
6409 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6411 (defun org-make-link (&rest strings)
6412 "Concatenate STRINGS."
6413 (apply 'concat strings))
6415 (defun org-make-link-string (link &optional description)
6416 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6417 (unless (string-match "\\S-" link)
6418 (error "Empty link"))
6419 (when (stringp description)
6420 ;; Remove brackets from the description, they are fatal.
6421 (while (string-match "\\[" description)
6422 (setq description (replace-match "{" t t description)))
6423 (while (string-match "\\]" description)
6424 (setq description (replace-match "}" t t description))))
6425 (when (equal (org-link-escape link) description)
6426 ;; No description needed, it is identical
6427 (setq description nil))
6428 (when (and (not description)
6429 (not (equal link (org-link-escape link))))
6430 (setq description (org-extract-attributes link)))
6431 (concat "[[" (org-link-escape link) "]"
6432 (if description (concat "[" description "]") "")
6433 "]"))
6435 (defconst org-link-escape-chars
6436 '((?\ . "%20")
6437 (?\[ . "%5B")
6438 (?\] . "%5D")
6439 (?\340 . "%E0") ; `a
6440 (?\342 . "%E2") ; ^a
6441 (?\347 . "%E7") ; ,c
6442 (?\350 . "%E8") ; `e
6443 (?\351 . "%E9") ; 'e
6444 (?\352 . "%EA") ; ^e
6445 (?\356 . "%EE") ; ^i
6446 (?\364 . "%F4") ; ^o
6447 (?\371 . "%F9") ; `u
6448 (?\373 . "%FB") ; ^u
6449 (?\; . "%3B")
6450 (?? . "%3F")
6451 (?= . "%3D")
6452 (?+ . "%2B")
6454 "Association list of escapes for some characters problematic in links.
6455 This is the list that is used for internal purposes.")
6457 (defconst org-link-escape-chars-browser
6458 '((?\ . "%20")) ; 32 for the SPC char
6459 "Association list of escapes for some characters problematic in links.
6460 This is the list that is used before handing over to the browser.")
6462 (defun org-link-escape (text &optional table)
6463 "Escape characters in TEXT that are problematic for links."
6464 (setq table (or table org-link-escape-chars))
6465 (when text
6466 (let ((re (mapconcat (lambda (x) (regexp-quote
6467 (char-to-string (car x))))
6468 table "\\|")))
6469 (while (string-match re text)
6470 (setq text
6471 (replace-match
6472 (cdr (assoc (string-to-char (match-string 0 text))
6473 table))
6474 t t text)))
6475 text)))
6477 (defun org-link-unescape (text &optional table)
6478 "Reverse the action of `org-link-escape'."
6479 (setq table (or table org-link-escape-chars))
6480 (when text
6481 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6482 table "\\|")))
6483 (while (string-match re text)
6484 (setq text
6485 (replace-match
6486 (char-to-string (car (rassoc (match-string 0 text) table)))
6487 t t text)))
6488 text)))
6490 (defun org-xor (a b)
6491 "Exclusive or."
6492 (if a (not b) b))
6494 (defun org-get-header (header)
6495 "Find a header field in the current buffer."
6496 (save-excursion
6497 (goto-char (point-min))
6498 (let ((case-fold-search t) s)
6499 (cond
6500 ((eq header 'from)
6501 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6502 (setq s (match-string 1)))
6503 (while (string-match "\"" s)
6504 (setq s (replace-match "" t t s)))
6505 (if (string-match "[<(].*" s)
6506 (setq s (replace-match "" t t s))))
6507 ((eq header 'message-id)
6508 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6509 (setq s (match-string 1))))
6510 ((eq header 'subject)
6511 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6512 (setq s (match-string 1)))))
6513 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6514 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6515 s)))
6518 (defun org-fixup-message-id-for-http (s)
6519 "Replace special characters in a message id, so it can be used in an http query."
6520 (while (string-match "<" s)
6521 (setq s (replace-match "%3C" t t s)))
6522 (while (string-match ">" s)
6523 (setq s (replace-match "%3E" t t s)))
6524 (while (string-match "@" s)
6525 (setq s (replace-match "%40" t t s)))
6528 ;;;###autoload
6529 (defun org-insert-link-global ()
6530 "Insert a link like Org-mode does.
6531 This command can be called in any mode to insert a link in Org-mode syntax."
6532 (interactive)
6533 (org-load-modules-maybe)
6534 (org-run-like-in-org-mode 'org-insert-link))
6536 (defun org-insert-link (&optional complete-file link-location)
6537 "Insert a link. At the prompt, enter the link.
6539 Completion can be used to insert any of the link protocol prefixes like
6540 http or ftp in use.
6542 The history can be used to select a link previously stored with
6543 `org-store-link'. When the empty string is entered (i.e. if you just
6544 press RET at the prompt), the link defaults to the most recently
6545 stored link. As SPC triggers completion in the minibuffer, you need to
6546 use M-SPC or C-q SPC to force the insertion of a space character.
6548 You will also be prompted for a description, and if one is given, it will
6549 be displayed in the buffer instead of the link.
6551 If there is already a link at point, this command will allow you to edit link
6552 and description parts.
6554 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6555 be selected using completion. The path to the file will be relative to the
6556 current directory if the file is in the current directory or a subdirectory.
6557 Otherwise, the link will be the absolute path as completed in the minibuffer
6558 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6559 option `org-link-file-path-type'.
6561 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6562 the current directory or below.
6564 With three \\[universal-argument] prefixes, negate the meaning of
6565 `org-keep-stored-link-after-insertion'.
6567 If `org-make-link-description-function' is non-nil, this function will be
6568 called with the link target, and the result will be the default
6569 link description.
6571 If the LINK-LOCATION parameter is non-nil, this value will be
6572 used as the link location instead of reading one interactively."
6573 (interactive "P")
6574 (let* ((wcf (current-window-configuration))
6575 (region (if (org-region-active-p)
6576 (buffer-substring (region-beginning) (region-end))))
6577 (remove (and region (list (region-beginning) (region-end))))
6578 (desc region)
6579 tmphist ; byte-compile incorrectly complains about this
6580 (link link-location)
6581 entry file)
6582 (cond
6583 (link-location) ; specified by arg, just use it.
6584 ((org-in-regexp org-bracket-link-regexp 1)
6585 ;; We do have a link at point, and we are going to edit it.
6586 (setq remove (list (match-beginning 0) (match-end 0)))
6587 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6588 (setq link (read-string "Link: "
6589 (org-link-unescape
6590 (org-match-string-no-properties 1)))))
6591 ((or (org-in-regexp org-angle-link-re)
6592 (org-in-regexp org-plain-link-re))
6593 ;; Convert to bracket link
6594 (setq remove (list (match-beginning 0) (match-end 0))
6595 link (read-string "Link: "
6596 (org-remove-angle-brackets (match-string 0)))))
6597 ((member complete-file '((4) (16)))
6598 ;; Completing read for file names.
6599 (setq file (read-file-name "File: "))
6600 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6601 (pwd1 (file-name-as-directory (abbreviate-file-name
6602 (expand-file-name ".")))))
6603 (cond
6604 ((equal complete-file '(16))
6605 (setq link (org-make-link
6606 "file:"
6607 (abbreviate-file-name (expand-file-name file)))))
6608 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6609 (setq link (org-make-link "file:" (match-string 1 file))))
6610 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6611 (expand-file-name file))
6612 (setq link (org-make-link
6613 "file:" (match-string 1 (expand-file-name file)))))
6614 (t (setq link (org-make-link "file:" file))))))
6616 ;; Read link, with completion for stored links.
6617 (with-output-to-temp-buffer "*Org Links*"
6618 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6619 (when org-stored-links
6620 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6621 (princ (mapconcat
6622 (lambda (x)
6623 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6624 (reverse org-stored-links) "\n"))))
6625 (let ((cw (selected-window)))
6626 (select-window (get-buffer-window "*Org Links*"))
6627 (org-fit-window-to-buffer)
6628 (setq truncate-lines t)
6629 (select-window cw))
6630 ;; Fake a link history, containing the stored links.
6631 (setq tmphist (append (mapcar 'car org-stored-links)
6632 org-insert-link-history))
6633 (unwind-protect
6634 (setq link (org-completing-read
6635 "Link: "
6636 (append
6637 (mapcar (lambda (x) (list (concat (car x) ":")))
6638 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6639 (mapcar (lambda (x) (list (concat x ":")))
6640 org-link-types))
6641 nil nil nil
6642 'tmphist
6643 (or (car (car org-stored-links)))))
6644 (set-window-configuration wcf)
6645 (kill-buffer "*Org Links*"))
6646 (setq entry (assoc link org-stored-links))
6647 (or entry (push link org-insert-link-history))
6648 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6649 (not org-keep-stored-link-after-insertion))
6650 (setq org-stored-links (delq (assoc link org-stored-links)
6651 org-stored-links)))
6652 (setq desc (or desc (nth 1 entry)))))
6654 (if (string-match org-plain-link-re link)
6655 ;; URL-like link, normalize the use of angular brackets.
6656 (setq link (org-make-link (org-remove-angle-brackets link))))
6658 ;; Check if we are linking to the current file with a search option
6659 ;; If yes, simplify the link by using only the search option.
6660 (when (and buffer-file-name
6661 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6662 (let* ((path (match-string 1 link))
6663 (case-fold-search nil)
6664 (search (match-string 2 link)))
6665 (save-match-data
6666 (if (equal (file-truename buffer-file-name) (file-truename path))
6667 ;; We are linking to this same file, with a search option
6668 (setq link search)))))
6670 ;; Check if we can/should use a relative path. If yes, simplify the link
6671 (when (string-match "^file:\\(.*\\)" link)
6672 (let* ((path (match-string 1 link))
6673 (origpath path)
6674 (case-fold-search nil))
6675 (cond
6676 ((or (eq org-link-file-path-type 'absolute)
6677 (equal complete-file '(16)))
6678 (setq path (abbreviate-file-name (expand-file-name path))))
6679 ((eq org-link-file-path-type 'noabbrev)
6680 (setq path (expand-file-name path)))
6681 ((eq org-link-file-path-type 'relative)
6682 (setq path (file-relative-name path)))
6684 (save-match-data
6685 (if (string-match (concat "^" (regexp-quote
6686 (file-name-as-directory
6687 (expand-file-name "."))))
6688 (expand-file-name path))
6689 ;; We are linking a file with relative path name.
6690 (setq path (substring (expand-file-name path)
6691 (match-end 0)))
6692 (setq path (abbreviate-file-name (expand-file-name path)))))))
6693 (setq link (concat "file:" path))
6694 (if (equal desc origpath)
6695 (setq desc path))))
6697 (if org-make-link-description-function
6698 (setq desc (funcall org-make-link-description-function link desc)))
6700 (setq desc (read-string "Description: " desc))
6701 (unless (string-match "\\S-" desc) (setq desc nil))
6702 (if remove (apply 'delete-region remove))
6703 (insert (org-make-link-string link desc))))
6705 (defun org-completing-read (&rest args)
6706 "Completing-read with SPACE being a normal character."
6707 (let ((minibuffer-local-completion-map
6708 (copy-keymap minibuffer-local-completion-map)))
6709 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6710 (apply 'org-ido-completing-read args)))
6712 (defun org-ido-completing-read (&rest args)
6713 "Completing-read using `ido-mode' speedups if available"
6714 (if (and org-completion-use-ido
6715 (fboundp 'ido-completing-read)
6716 (boundp 'ido-mode) ido-mode
6717 (listp (second args)))
6718 (apply 'ido-completing-read (concat (car args)) (cdr args))
6719 (apply 'completing-read args)))
6721 (defun org-extract-attributes (s)
6722 "Extract the attributes cookie from a string and set as text property."
6723 (let (a attr (start 0) key value)
6724 (save-match-data
6725 (when (string-match "{{\\([^}]+\\)}}$" s)
6726 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6727 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6728 (setq key (match-string 1 a) value (match-string 2 a)
6729 start (match-end 0)
6730 attr (plist-put attr (intern key) value))))
6731 (org-add-props s nil 'org-attr attr))
6734 (defun org-attributes-to-string (plist)
6735 "Format a property list into an HTML attribute list."
6736 (let ((s "") key value)
6737 (while plist
6738 (setq key (pop plist) value (pop plist))
6739 (and value
6740 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6743 ;;; Opening/following a link
6745 (defvar org-link-search-failed nil)
6747 (defun org-next-link ()
6748 "Move forward to the next link.
6749 If the link is in hidden text, expose it."
6750 (interactive)
6751 (when (and org-link-search-failed (eq this-command last-command))
6752 (goto-char (point-min))
6753 (message "Link search wrapped back to beginning of buffer"))
6754 (setq org-link-search-failed nil)
6755 (let* ((pos (point))
6756 (ct (org-context))
6757 (a (assoc :link ct)))
6758 (if a (goto-char (nth 2 a)))
6759 (if (re-search-forward org-any-link-re nil t)
6760 (progn
6761 (goto-char (match-beginning 0))
6762 (if (org-invisible-p) (org-show-context)))
6763 (goto-char pos)
6764 (setq org-link-search-failed t)
6765 (error "No further link found"))))
6767 (defun org-previous-link ()
6768 "Move backward to the previous link.
6769 If the link is in hidden text, expose it."
6770 (interactive)
6771 (when (and org-link-search-failed (eq this-command last-command))
6772 (goto-char (point-max))
6773 (message "Link search wrapped back to end of buffer"))
6774 (setq org-link-search-failed nil)
6775 (let* ((pos (point))
6776 (ct (org-context))
6777 (a (assoc :link ct)))
6778 (if a (goto-char (nth 1 a)))
6779 (if (re-search-backward org-any-link-re nil t)
6780 (progn
6781 (goto-char (match-beginning 0))
6782 (if (org-invisible-p) (org-show-context)))
6783 (goto-char pos)
6784 (setq org-link-search-failed t)
6785 (error "No further link found"))))
6787 (defun org-translate-link (s)
6788 "Translate a link string if a translation function has been defined."
6789 (if (and org-link-translation-function
6790 (fboundp org-link-translation-function)
6791 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6792 (progn
6793 (setq s (funcall org-link-translation-function
6794 (match-string 1) (match-string 2)))
6795 (concat (car s) ":" (cdr s)))
6798 (defun org-translate-link-from-planner (type path)
6799 "Translate a link from Emacs Planner syntax so that Org can follow it.
6800 This is still an experimental function, your mileage may vary."
6801 (cond
6802 ((member type '("http" "https" "news" "ftp"))
6803 ;; standard Internet links are the same.
6804 nil)
6805 ((and (equal type "irc") (string-match "^//" path))
6806 ;; Planner has two / at the beginning of an irc link, we have 1.
6807 ;; We should have zero, actually....
6808 (setq path (substring path 1)))
6809 ((and (equal type "lisp") (string-match "^/" path))
6810 ;; Planner has a slash, we do not.
6811 (setq type "elisp" path (substring path 1)))
6812 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6813 ;; A typical message link. Planner has the id after the fina slash,
6814 ;; we separate it with a hash mark
6815 (setq path (concat (match-string 1 path) "#"
6816 (org-remove-angle-brackets (match-string 2 path)))))
6818 (cons type path))
6820 (defun org-find-file-at-mouse (ev)
6821 "Open file link or URL at mouse."
6822 (interactive "e")
6823 (mouse-set-point ev)
6824 (org-open-at-point 'in-emacs))
6826 (defun org-open-at-mouse (ev)
6827 "Open file link or URL at mouse."
6828 (interactive "e")
6829 (mouse-set-point ev)
6830 (if (eq major-mode 'org-agenda-mode)
6831 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6832 (org-open-at-point))
6834 (defvar org-window-config-before-follow-link nil
6835 "The window configuration before following a link.
6836 This is saved in case the need arises to restore it.")
6838 (defvar org-open-link-marker (make-marker)
6839 "Marker pointing to the location where `org-open-at-point; was called.")
6841 ;;;###autoload
6842 (defun org-open-at-point-global ()
6843 "Follow a link like Org-mode does.
6844 This command can be called in any mode to follow a link that has
6845 Org-mode syntax."
6846 (interactive)
6847 (org-run-like-in-org-mode 'org-open-at-point))
6849 ;;;###autoload
6850 (defun org-open-link-from-string (s &optional arg)
6851 "Open a link in the string S, as if it was in Org-mode."
6852 (interactive "sLink: \nP")
6853 (with-temp-buffer
6854 (let ((org-inhibit-startup t))
6855 (org-mode)
6856 (insert s)
6857 (goto-char (point-min))
6858 (org-open-at-point arg))))
6860 (defun org-open-at-point (&optional in-emacs)
6861 "Open link at or after point.
6862 If there is no link at point, this function will search forward up to
6863 the end of the current subtree.
6864 Normally, files will be opened by an appropriate application. If the
6865 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6866 With a double prefix argument, try to open outside of Emacs, in the
6867 application the system uses for this file type."
6868 (interactive "P")
6869 (org-load-modules-maybe)
6870 (move-marker org-open-link-marker (point))
6871 (setq org-window-config-before-follow-link (current-window-configuration))
6872 (org-remove-occur-highlights nil nil t)
6873 (if (org-at-timestamp-p t)
6874 (org-follow-timestamp-link)
6875 (let (type path link line search (pos (point)))
6876 (catch 'match
6877 (save-excursion
6878 (skip-chars-forward "^]\n\r")
6879 (when (org-in-regexp org-bracket-link-regexp)
6880 (setq link (org-extract-attributes
6881 (org-link-unescape (org-match-string-no-properties 1))))
6882 (while (string-match " *\n *" link)
6883 (setq link (replace-match " " t t link)))
6884 (setq link (org-link-expand-abbrev link))
6885 (cond
6886 ((or (file-name-absolute-p link)
6887 (string-match "^\\.\\.?/" link))
6888 (setq type "file" path link))
6889 ((string-match org-link-re-with-space3 link)
6890 (setq type (match-string 1 link) path (match-string 2 link)))
6891 (t (setq type "thisfile" path link)))
6892 (throw 'match t)))
6894 (when (get-text-property (point) 'org-linked-text)
6895 (setq type "thisfile"
6896 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6897 (1+ (point)) (point))
6898 path (buffer-substring
6899 (previous-single-property-change pos 'org-linked-text)
6900 (next-single-property-change pos 'org-linked-text)))
6901 (throw 'match t))
6903 (save-excursion
6904 (when (or (org-in-regexp org-angle-link-re)
6905 (org-in-regexp org-plain-link-re))
6906 (setq type (match-string 1) path (match-string 2))
6907 (throw 'match t)))
6908 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6909 (setq type "tree-match"
6910 path (match-string 1))
6911 (throw 'match t))
6912 (save-excursion
6913 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6914 (setq type "tags"
6915 path (match-string 1))
6916 (while (string-match ":" path)
6917 (setq path (replace-match "+" t t path)))
6918 (throw 'match t))))
6919 (unless path
6920 (error "No link found"))
6921 ;; Remove any trailing spaces in path
6922 (if (string-match " +\\'" path)
6923 (setq path (replace-match "" t t path)))
6924 (if (and org-link-translation-function
6925 (fboundp org-link-translation-function))
6926 ;; Check if we need to translate the link
6927 (let ((tmp (funcall org-link-translation-function type path)))
6928 (setq type (car tmp) path (cdr tmp))))
6930 (cond
6932 ((assoc type org-link-protocols)
6933 (funcall (nth 1 (assoc type org-link-protocols)) path))
6935 ((equal type "mailto")
6936 (let ((cmd (car org-link-mailto-program))
6937 (args (cdr org-link-mailto-program)) args1
6938 (address path) (subject "") a)
6939 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6940 (setq address (match-string 1 path)
6941 subject (org-link-escape (match-string 2 path))))
6942 (while args
6943 (cond
6944 ((not (stringp (car args))) (push (pop args) args1))
6945 (t (setq a (pop args))
6946 (if (string-match "%a" a)
6947 (setq a (replace-match address t t a)))
6948 (if (string-match "%s" a)
6949 (setq a (replace-match subject t t a)))
6950 (push a args1))))
6951 (apply cmd (nreverse args1))))
6953 ((member type '("http" "https" "ftp" "news"))
6954 (browse-url (concat type ":" (org-link-escape
6955 path org-link-escape-chars-browser))))
6957 ((member type '("message"))
6958 (browse-url (concat type ":" path)))
6960 ((string= type "tags")
6961 (org-tags-view in-emacs path))
6962 ((string= type "thisfile")
6963 (if in-emacs
6964 (switch-to-buffer-other-window
6965 (org-get-buffer-for-internal-link (current-buffer)))
6966 (org-mark-ring-push))
6967 (let ((cmd `(org-link-search
6968 ,path
6969 ,(cond ((equal in-emacs '(4)) 'occur)
6970 ((equal in-emacs '(16)) 'org-occur)
6971 (t nil))
6972 ,pos)))
6973 (condition-case nil (eval cmd)
6974 (error (progn (widen) (eval cmd))))))
6976 ((string= type "tree-match")
6977 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6979 ((string= type "file")
6980 (if (string-match "::\\([0-9]+\\)\\'" path)
6981 (setq line (string-to-number (match-string 1 path))
6982 path (substring path 0 (match-beginning 0)))
6983 (if (string-match "::\\(.+\\)\\'" path)
6984 (setq search (match-string 1 path)
6985 path (substring path 0 (match-beginning 0)))))
6986 (if (string-match "[*?{]" (file-name-nondirectory path))
6987 (dired path)
6988 (org-open-file path in-emacs line search)))
6990 ((string= type "news")
6991 (require 'org-gnus)
6992 (org-gnus-follow-link path))
6994 ((string= type "shell")
6995 (let ((cmd path))
6996 (if (or (not org-confirm-shell-link-function)
6997 (funcall org-confirm-shell-link-function
6998 (format "Execute \"%s\" in shell? "
6999 (org-add-props cmd nil
7000 'face 'org-warning))))
7001 (progn
7002 (message "Executing %s" cmd)
7003 (shell-command cmd))
7004 (error "Abort"))))
7006 ((string= type "elisp")
7007 (let ((cmd path))
7008 (if (or (not org-confirm-elisp-link-function)
7009 (funcall org-confirm-elisp-link-function
7010 (format "Execute \"%s\" as elisp? "
7011 (org-add-props cmd nil
7012 'face 'org-warning))))
7013 (message "%s => %s" cmd
7014 (if (equal (string-to-char cmd) ?\()
7015 (eval (read cmd))
7016 (call-interactively (read cmd))))
7017 (error "Abort"))))
7020 (browse-url-at-point)))))
7021 (move-marker org-open-link-marker nil)
7022 (run-hook-with-args 'org-follow-link-hook))
7024 ;;;; Time estimates
7026 (defun org-get-effort (&optional pom)
7027 "Get the effort estimate for the current entry."
7028 (org-entry-get pom org-effort-property))
7030 ;;; File search
7032 (defvar org-create-file-search-functions nil
7033 "List of functions to construct the right search string for a file link.
7034 These functions are called in turn with point at the location to
7035 which the link should point.
7037 A function in the hook should first test if it would like to
7038 handle this file type, for example by checking the major-mode or
7039 the file extension. If it decides not to handle this file, it
7040 should just return nil to give other functions a chance. If it
7041 does handle the file, it must return the search string to be used
7042 when following the link. The search string will be part of the
7043 file link, given after a double colon, and `org-open-at-point'
7044 will automatically search for it. If special measures must be
7045 taken to make the search successful, another function should be
7046 added to the companion hook `org-execute-file-search-functions',
7047 which see.
7049 A function in this hook may also use `setq' to set the variable
7050 `description' to provide a suggestion for the descriptive text to
7051 be used for this link when it gets inserted into an Org-mode
7052 buffer with \\[org-insert-link].")
7054 (defvar org-execute-file-search-functions nil
7055 "List of functions to execute a file search triggered by a link.
7057 Functions added to this hook must accept a single argument, the
7058 search string that was part of the file link, the part after the
7059 double colon. The function must first check if it would like to
7060 handle this search, for example by checking the major-mode or the
7061 file extension. If it decides not to handle this search, it
7062 should just return nil to give other functions a chance. If it
7063 does handle the search, it must return a non-nil value to keep
7064 other functions from trying.
7066 Each function can access the current prefix argument through the
7067 variable `current-prefix-argument'. Note that a single prefix is
7068 used to force opening a link in Emacs, so it may be good to only
7069 use a numeric or double prefix to guide the search function.
7071 In case this is needed, a function in this hook can also restore
7072 the window configuration before `org-open-at-point' was called using:
7074 (set-window-configuration org-window-config-before-follow-link)")
7076 (defun org-link-search (s &optional type avoid-pos)
7077 "Search for a link search option.
7078 If S is surrounded by forward slashes, it is interpreted as a
7079 regular expression. In org-mode files, this will create an `org-occur'
7080 sparse tree. In ordinary files, `occur' will be used to list matches.
7081 If the current buffer is in `dired-mode', grep will be used to search
7082 in all files. If AVOID-POS is given, ignore matches near that position."
7083 (let ((case-fold-search t)
7084 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7085 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7086 (append '(("") (" ") ("\t") ("\n"))
7087 org-emphasis-alist)
7088 "\\|") "\\)"))
7089 (pos (point))
7090 (pre nil) (post nil)
7091 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7092 (cond
7093 ;; First check if there are any special
7094 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7095 ;; Now try the builtin stuff
7096 ((save-excursion
7097 (goto-char (point-min))
7098 (and
7099 (re-search-forward
7100 (concat "<<" (regexp-quote s0) ">>") nil t)
7101 (setq type 'dedicated
7102 pos (match-beginning 0))))
7103 ;; There is an exact target for this
7104 (goto-char pos))
7105 ((string-match "^/\\(.*\\)/$" s)
7106 ;; A regular expression
7107 (cond
7108 ((org-mode-p)
7109 (org-occur (match-string 1 s)))
7110 ;;((eq major-mode 'dired-mode)
7111 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7112 (t (org-do-occur (match-string 1 s)))))
7114 ;; A normal search strings
7115 (when (equal (string-to-char s) ?*)
7116 ;; Anchor on headlines, post may include tags.
7117 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7118 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7119 s (substring s 1)))
7120 (remove-text-properties
7121 0 (length s)
7122 '(face nil mouse-face nil keymap nil fontified nil) s)
7123 ;; Make a series of regular expressions to find a match
7124 (setq words (org-split-string s "[ \n\r\t]+")
7126 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7127 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7128 "\\)" markers)
7129 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7130 re2a (concat "[ \t\r\n]" re2a_)
7131 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7132 re4 (concat "[^a-zA-Z_]" re4_)
7134 re1 (concat pre re2 post)
7135 re3 (concat pre (if pre re4_ re4) post)
7136 re5 (concat pre ".*" re4)
7137 re2 (concat pre re2)
7138 re2a (concat pre (if pre re2a_ re2a))
7139 re4 (concat pre (if pre re4_ re4))
7140 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7141 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7142 re5 "\\)"
7144 (cond
7145 ((eq type 'org-occur) (org-occur reall))
7146 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7147 (t (goto-char (point-min))
7148 (setq type 'fuzzy)
7149 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7150 (org-search-not-self 1 re1 nil t)
7151 (org-search-not-self 1 re2 nil t)
7152 (org-search-not-self 1 re2a nil t)
7153 (org-search-not-self 1 re3 nil t)
7154 (org-search-not-self 1 re4 nil t)
7155 (org-search-not-self 1 re5 nil t)
7157 (goto-char (match-beginning 1))
7158 (goto-char pos)
7159 (error "No match")))))
7161 ;; Normal string-search
7162 (goto-char (point-min))
7163 (if (search-forward s nil t)
7164 (goto-char (match-beginning 0))
7165 (error "No match"))))
7166 (and (org-mode-p) (org-show-context 'link-search))
7167 type))
7169 (defun org-search-not-self (group &rest args)
7170 "Execute `re-search-forward', but only accept matches that do not
7171 enclose the position of `org-open-link-marker'."
7172 (let ((m org-open-link-marker))
7173 (catch 'exit
7174 (while (apply 're-search-forward args)
7175 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7176 (goto-char (match-end group))
7177 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7178 (> (match-beginning 0) (marker-position m))
7179 (< (match-end 0) (marker-position m)))
7180 (save-match-data
7181 (or (not (org-in-regexp
7182 org-bracket-link-analytic-regexp 1))
7183 (not (match-end 4)) ; no description
7184 (and (<= (match-beginning 4) (point))
7185 (>= (match-end 4) (point))))))
7186 (throw 'exit (point))))))))
7188 (defun org-get-buffer-for-internal-link (buffer)
7189 "Return a buffer to be used for displaying the link target of internal links."
7190 (cond
7191 ((not org-display-internal-link-with-indirect-buffer)
7192 buffer)
7193 ((string-match "(Clone)$" (buffer-name buffer))
7194 (message "Buffer is already a clone, not making another one")
7195 ;; we also do not modify visibility in this case
7196 buffer)
7197 (t ; make a new indirect buffer for displaying the link
7198 (let* ((bn (buffer-name buffer))
7199 (ibn (concat bn "(Clone)"))
7200 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7201 (with-current-buffer ib (org-overview))
7202 ib))))
7204 (defun org-do-occur (regexp &optional cleanup)
7205 "Call the Emacs command `occur'.
7206 If CLEANUP is non-nil, remove the printout of the regular expression
7207 in the *Occur* buffer. This is useful if the regex is long and not useful
7208 to read."
7209 (occur regexp)
7210 (when cleanup
7211 (let ((cwin (selected-window)) win beg end)
7212 (when (setq win (get-buffer-window "*Occur*"))
7213 (select-window win))
7214 (goto-char (point-min))
7215 (when (re-search-forward "match[a-z]+" nil t)
7216 (setq beg (match-end 0))
7217 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7218 (setq end (1- (match-beginning 0)))))
7219 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7220 (goto-char (point-min))
7221 (select-window cwin))))
7223 ;;; The mark ring for links jumps
7225 (defvar org-mark-ring nil
7226 "Mark ring for positions before jumps in Org-mode.")
7227 (defvar org-mark-ring-last-goto nil
7228 "Last position in the mark ring used to go back.")
7229 ;; Fill and close the ring
7230 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7231 (loop for i from 1 to org-mark-ring-length do
7232 (push (make-marker) org-mark-ring))
7233 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7234 org-mark-ring)
7236 (defun org-mark-ring-push (&optional pos buffer)
7237 "Put the current position or POS into the mark ring and rotate it."
7238 (interactive)
7239 (setq pos (or pos (point)))
7240 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7241 (move-marker (car org-mark-ring)
7242 (or pos (point))
7243 (or buffer (current-buffer)))
7244 (message "%s"
7245 (substitute-command-keys
7246 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7248 (defun org-mark-ring-goto (&optional n)
7249 "Jump to the previous position in the mark ring.
7250 With prefix arg N, jump back that many stored positions. When
7251 called several times in succession, walk through the entire ring.
7252 Org-mode commands jumping to a different position in the current file,
7253 or to another Org-mode file, automatically push the old position
7254 onto the ring."
7255 (interactive "p")
7256 (let (p m)
7257 (if (eq last-command this-command)
7258 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7259 (setq p org-mark-ring))
7260 (setq org-mark-ring-last-goto p)
7261 (setq m (car p))
7262 (switch-to-buffer (marker-buffer m))
7263 (goto-char m)
7264 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7266 (defun org-remove-angle-brackets (s)
7267 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7268 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7270 (defun org-add-angle-brackets (s)
7271 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7272 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7274 (defun org-remove-double-quotes (s)
7275 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7276 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7279 ;;; Following specific links
7281 (defun org-follow-timestamp-link ()
7282 (cond
7283 ((org-at-date-range-p t)
7284 (let ((org-agenda-start-on-weekday)
7285 (t1 (match-string 1))
7286 (t2 (match-string 2)))
7287 (setq t1 (time-to-days (org-time-string-to-time t1))
7288 t2 (time-to-days (org-time-string-to-time t2)))
7289 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7290 ((org-at-timestamp-p t)
7291 (org-agenda-list nil (time-to-days (org-time-string-to-time
7292 (substring (match-string 1) 0 10)))
7294 (t (error "This should not happen"))))
7297 ;;; Following file links
7298 (defvar org-wait nil)
7299 (defun org-open-file (path &optional in-emacs line search)
7300 "Open the file at PATH.
7301 First, this expands any special file name abbreviations. Then the
7302 configuration variable `org-file-apps' is checked if it contains an
7303 entry for this file type, and if yes, the corresponding command is launched.
7305 If no application is found, Emacs simply visits the file.
7307 With optional prefix argument IN-EMACS, Emacs will visit the file.
7308 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7309 and o use an external application to visit the file.
7311 Optional LINE specifies a line to go to, optional SEARCH a string to
7312 search for. If LINE or SEARCH is given, the file will always be
7313 opened in Emacs.
7314 If the file does not exist, an error is thrown."
7315 (setq in-emacs (or in-emacs line search))
7316 (let* ((file (if (equal path "")
7317 buffer-file-name
7318 (substitute-in-file-name (expand-file-name path))))
7319 (apps (append org-file-apps (org-default-apps)))
7320 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7321 (dirp (if remp nil (file-directory-p file)))
7322 (file (if (and dirp org-open-directory-means-index-dot-org)
7323 (concat (file-name-as-directory file) "index.org")
7324 file))
7325 (a-m-a-p (assq 'auto-mode apps))
7326 (dfile (downcase file))
7327 (old-buffer (current-buffer))
7328 (old-pos (point))
7329 (old-mode major-mode)
7330 ext cmd)
7331 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7332 (setq ext (match-string 1 dfile))
7333 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7334 (setq ext (match-string 1 dfile))))
7335 (cond
7336 ((equal in-emacs '(16))
7337 (setq cmd (cdr (assoc 'system apps))))
7338 (in-emacs (setq cmd 'emacs))
7340 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7341 (and dirp (cdr (assoc 'directory apps)))
7342 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7343 'string-match)
7344 (cdr (assoc ext apps))
7345 (cdr (assoc t apps))))))
7346 (when (eq cmd 'system)
7347 (setq cmd (cdr (assoc 'system apps))))
7348 (when (eq cmd 'default)
7349 (setq cmd (cdr (assoc t apps))))
7350 (when (eq cmd 'mailcap)
7351 (require 'mailcap)
7352 (mailcap-parse-mailcaps)
7353 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7354 (command (mailcap-mime-info mime-type)))
7355 (if (stringp command)
7356 (setq cmd command)
7357 (setq cmd 'emacs))))
7358 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7359 (not (file-exists-p file))
7360 (not org-open-non-existing-files))
7361 (error "No such file: %s" file))
7362 (cond
7363 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7364 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7365 (while (string-match "['\"]%s['\"]" cmd)
7366 (setq cmd (replace-match "%s" t t cmd)))
7367 (while (string-match "%s" cmd)
7368 (setq cmd (replace-match
7369 (save-match-data
7370 (shell-quote-argument
7371 (convert-standard-filename file)))
7372 t t cmd)))
7373 (save-window-excursion
7374 (start-process-shell-command cmd nil cmd)
7375 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7377 ((or (stringp cmd)
7378 (eq cmd 'emacs))
7379 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7380 (widen)
7381 (if line (goto-line line)
7382 (if search (org-link-search search))))
7383 ((consp cmd)
7384 (let ((file (convert-standard-filename file)))
7385 (eval cmd)))
7386 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7387 (and (org-mode-p) (eq old-mode 'org-mode)
7388 (or (not (equal old-buffer (current-buffer)))
7389 (not (equal old-pos (point))))
7390 (org-mark-ring-push old-pos old-buffer))))
7392 (defun org-default-apps ()
7393 "Return the default applications for this operating system."
7394 (cond
7395 ((eq system-type 'darwin)
7396 org-file-apps-defaults-macosx)
7397 ((eq system-type 'windows-nt)
7398 org-file-apps-defaults-windowsnt)
7399 (t org-file-apps-defaults-gnu)))
7401 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7402 "Convert extensions to regular expressions in the cars of LIST.
7403 Also, weed out any non-string entries, because the return value is used
7404 only for regexp matching.
7405 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7406 point to the symbol `emacs', indicating that the file should
7407 be opened in Emacs."
7408 (append
7409 (delq nil
7410 (mapcar (lambda (x)
7411 (if (not (stringp (car x)))
7413 (if (string-match "\\W" (car x))
7415 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7416 list))
7417 (if add-auto-mode
7418 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7420 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7421 (defun org-file-remote-p (file)
7422 "Test whether FILE specifies a location on a remote system.
7423 Return non-nil if the location is indeed remote.
7425 For example, the filename \"/user@host:/foo\" specifies a location
7426 on the system \"/user@host:\"."
7427 (cond ((fboundp 'file-remote-p)
7428 (file-remote-p file))
7429 ((fboundp 'tramp-handle-file-remote-p)
7430 (tramp-handle-file-remote-p file))
7431 ((and (boundp 'ange-ftp-name-format)
7432 (string-match (car ange-ftp-name-format) file))
7434 (t nil)))
7437 ;;;; Refiling
7439 (defun org-get-org-file ()
7440 "Read a filename, with default directory `org-directory'."
7441 (let ((default (or org-default-notes-file remember-data-file)))
7442 (read-file-name (format "File name [%s]: " default)
7443 (file-name-as-directory org-directory)
7444 default)))
7446 (defun org-notes-order-reversed-p ()
7447 "Check if the current file should receive notes in reversed order."
7448 (cond
7449 ((not org-reverse-note-order) nil)
7450 ((eq t org-reverse-note-order) t)
7451 ((not (listp org-reverse-note-order)) nil)
7452 (t (catch 'exit
7453 (let ((all org-reverse-note-order)
7454 entry)
7455 (while (setq entry (pop all))
7456 (if (string-match (car entry) buffer-file-name)
7457 (throw 'exit (cdr entry))))
7458 nil)))))
7460 (defvar org-refile-target-table nil
7461 "The list of refile targets, created by `org-refile'.")
7463 (defvar org-agenda-new-buffers nil
7464 "Buffers created to visit agenda files.")
7466 (defun org-get-refile-targets (&optional default-buffer)
7467 "Produce a table with refile targets."
7468 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7469 targets txt re files f desc descre fast-path-p level)
7470 (message "Getting targets...")
7471 (with-current-buffer (or default-buffer (current-buffer))
7472 (while (setq entry (pop entries))
7473 (setq files (car entry) desc (cdr entry))
7474 (setq fast-path-p nil)
7475 (cond
7476 ((null files) (setq files (list (current-buffer))))
7477 ((eq files 'org-agenda-files)
7478 (setq files (org-agenda-files 'unrestricted)))
7479 ((and (symbolp files) (fboundp files))
7480 (setq files (funcall files)))
7481 ((and (symbolp files) (boundp files))
7482 (setq files (symbol-value files))))
7483 (if (stringp files) (setq files (list files)))
7484 (cond
7485 ((eq (car desc) :tag)
7486 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7487 ((eq (car desc) :todo)
7488 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7489 ((eq (car desc) :regexp)
7490 (setq descre (cdr desc)))
7491 ((eq (car desc) :level)
7492 (setq descre (concat "^\\*\\{" (number-to-string
7493 (if org-odd-levels-only
7494 (1- (* 2 (cdr desc)))
7495 (cdr desc)))
7496 "\\}[ \t]")))
7497 ((eq (car desc) :maxlevel)
7498 (setq fast-path-p t)
7499 (setq descre (concat "^\\*\\{1," (number-to-string
7500 (if org-odd-levels-only
7501 (1- (* 2 (cdr desc)))
7502 (cdr desc)))
7503 "\\}[ \t]")))
7504 (t (error "Bad refiling target description %s" desc)))
7505 (while (setq f (pop files))
7506 (save-excursion
7507 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7508 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7509 (save-excursion
7510 (save-restriction
7511 (widen)
7512 (goto-char (point-min))
7513 (while (re-search-forward descre nil t)
7514 (goto-char (point-at-bol))
7515 (when (looking-at org-complex-heading-regexp)
7516 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7517 txt (org-link-display-format (match-string 4))
7518 re (concat "^" (regexp-quote
7519 (buffer-substring (match-beginning 1)
7520 (match-end 4)))))
7521 (if (match-end 5) (setq re (concat re "[ \t]+"
7522 (regexp-quote
7523 (match-string 5)))))
7524 (setq re (concat re "[ \t]*$"))
7525 (when org-refile-use-outline-path
7526 (setq txt (mapconcat 'org-protect-slash
7527 (append
7528 (if (eq org-refile-use-outline-path 'file)
7529 (list (file-name-nondirectory
7530 (buffer-file-name (buffer-base-buffer))))
7531 (if (eq org-refile-use-outline-path 'full-file-path)
7532 (list (buffer-file-name (buffer-base-buffer)))))
7533 (org-get-outline-path fast-path-p level txt)
7534 (list txt))
7535 "/")))
7536 (push (list txt f re (point)) targets))
7537 (goto-char (point-at-eol))))))))
7538 (message "Getting targets...done")
7539 (nreverse targets))))
7541 (defun org-protect-slash (s)
7542 (while (string-match "/" s)
7543 (setq s (replace-match "\\" t t s)))
7546 (defvar org-olpa (make-vector 20 nil))
7548 (defun org-get-outline-path (&optional fastp level heading)
7549 "Return the outline path to the current entry, as a list."
7550 (if fastp
7551 (progn
7552 (if (> level 19)
7553 (error "Outline path failure, more than 19 levels."))
7554 (loop for i from level upto 19 do
7555 (aset org-olpa i nil))
7556 (prog1
7557 (delq nil (append org-olpa nil))
7558 (aset org-olpa level heading)))
7559 (let (rtn)
7560 (save-excursion
7561 (while (org-up-heading-safe)
7562 (when (looking-at org-complex-heading-regexp)
7563 (push (org-match-string-no-properties 4) rtn)))
7564 rtn))))
7566 (defvar org-refile-history nil
7567 "History for refiling operations.")
7569 (defun org-refile (&optional goto default-buffer)
7570 "Move the entry at point to another heading.
7571 The list of target headings is compiled using the information in
7572 `org-refile-targets', which see. This list is created before each use
7573 and will therefore always be up-to-date.
7575 At the target location, the entry is filed as a subitem of the target heading.
7576 Depending on `org-reverse-note-order', the new subitem will either be the
7577 first or the last subitem.
7579 If there is an active region, all entries in that region will be moved.
7580 However, the region must fulfil the requirement that the first heading
7581 is the first one sets the top-level of the moved text - at most siblings
7582 below it are allowed.
7584 With prefix arg GOTO, the command will only visit the target location,
7585 not actually move anything.
7586 With a double prefix `C-u C-u', go to the location where the last refiling
7587 operation has put the subtree."
7588 (interactive "P")
7589 (let* ((cbuf (current-buffer))
7590 (regionp (org-region-active-p))
7591 (region-start (and regionp (region-beginning)))
7592 (region-end (and regionp (region-end)))
7593 (region-length (and regionp (- region-end region-start)))
7594 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7595 pos it nbuf file re level reversed)
7596 (when regionp (goto-char region-start)
7597 (unless (org-kill-is-subtree-p
7598 (buffer-substring region-start region-end))
7599 (error "The region is not a (sequence of) subtree(s)")))
7600 (if (equal goto '(16))
7601 (org-refile-goto-last-stored)
7602 (when (setq it (org-refile-get-location
7603 (if goto "Goto: " "Refile to: ") default-buffer))
7604 (setq file (nth 1 it)
7605 re (nth 2 it)
7606 pos (nth 3 it))
7607 (if (and (equal (buffer-file-name) file)
7608 (if regionp
7609 (and (>= pos region-start)
7610 (<= pos region-end))
7611 (and (>= pos (point))
7612 (< pos (save-excursion
7613 (org-end-of-subtree t t))))))
7614 (error "Cannot refile to position inside the tree or region"))
7616 (setq nbuf (or (find-buffer-visiting file)
7617 (find-file-noselect file)))
7618 (if goto
7619 (progn
7620 (switch-to-buffer nbuf)
7621 (goto-char pos)
7622 (org-show-context 'org-goto))
7623 (if regionp
7624 (progn
7625 (kill-new (buffer-substring region-start region-end))
7626 (org-save-markers-in-region region-start region-end))
7627 (org-copy-subtree 1 nil t))
7628 (save-excursion
7629 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7630 (find-file-noselect file))))
7631 (setq reversed (org-notes-order-reversed-p))
7632 (save-excursion
7633 (save-restriction
7634 (widen)
7635 (goto-char pos)
7636 (looking-at outline-regexp)
7637 (setq level (org-get-valid-level (funcall outline-level) 1))
7638 (goto-char
7639 (if reversed
7640 (or (outline-next-heading) (point-max))
7641 (or (save-excursion (outline-get-next-sibling))
7642 (org-end-of-subtree t t)
7643 (point-max))))
7644 (if (not (bolp)) (newline))
7645 (bookmark-set "org-refile-last-stored")
7646 (org-paste-subtree level))))
7647 (if regionp
7648 (delete-region (point) (+ (point) region-length))
7649 (org-cut-subtree))
7650 (setq org-markers-to-move nil)
7651 (message "Refiled to \"%s\"" (car it)))))))
7653 (defun org-refile-goto-last-stored ()
7654 "Go to the location where the last refile was stored."
7655 (interactive)
7656 (bookmark-jump "org-refile-last-stored")
7657 (message "This is the location of the last refile"))
7659 (defun org-refile-get-location (&optional prompt default-buffer)
7660 "Prompt the user for a refile location, using PROMPT."
7661 (let ((org-refile-targets org-refile-targets)
7662 (org-refile-use-outline-path org-refile-use-outline-path))
7663 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7664 (unless org-refile-target-table
7665 (error "No refile targets"))
7666 (let* ((cbuf (current-buffer))
7667 (cfunc (if (and org-refile-use-outline-path
7668 org-outline-path-complete-in-steps)
7669 'org-olpath-completing-read
7670 'org-ido-completing-read))
7671 (extra (if org-refile-use-outline-path "/" ""))
7672 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7673 (tbl (mapcar
7674 (lambda (x)
7675 (if (not (equal filename (nth 1 x)))
7676 (cons (concat (car x) extra " ("
7677 (file-name-nondirectory (nth 1 x)) ")")
7678 (cdr x))
7679 (cons (concat (car x) extra) (cdr x))))
7680 org-refile-target-table))
7681 (completion-ignore-case t))
7682 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7683 tbl)))
7685 (defun org-olpath-completing-read (prompt collection &rest args)
7686 "Read an outline path like a file name."
7687 (let ((thetable collection))
7688 (apply
7689 'org-ido-completing-read prompt
7690 (lambda (string predicate &optional flag)
7691 (let (rtn r s f (l (length string)))
7692 (cond
7693 ((eq flag nil)
7694 ;; try completion
7695 (try-completion string thetable))
7696 ((eq flag t)
7697 ;; all-completions
7698 (setq rtn (all-completions string thetable predicate))
7699 (mapcar
7700 (lambda (x)
7701 (setq r (substring x l))
7702 (if (string-match " ([^)]*)$" x)
7703 (setq f (match-string 0 x))
7704 (setq f ""))
7705 (if (string-match "/" r)
7706 (concat string (substring r 0 (match-end 0)) f)
7708 rtn))
7709 ((eq flag 'lambda)
7710 ;; exact match?
7711 (assoc string thetable)))
7713 args)))
7715 ;;;; Dynamic blocks
7717 (defun org-find-dblock (name)
7718 "Find the first dynamic block with name NAME in the buffer.
7719 If not found, stay at current position and return nil."
7720 (let (pos)
7721 (save-excursion
7722 (goto-char (point-min))
7723 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7724 nil t)
7725 (match-beginning 0))))
7726 (if pos (goto-char pos))
7727 pos))
7729 (defconst org-dblock-start-re
7730 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7731 "Matches the startline of a dynamic block, with parameters.")
7733 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7734 "Matches the end of a dynamic block.")
7736 (defun org-create-dblock (plist)
7737 "Create a dynamic block section, with parameters taken from PLIST.
7738 PLIST must contain a :name entry which is used as name of the block."
7739 (unless (bolp) (newline))
7740 (let ((name (plist-get plist :name)))
7741 (insert "#+BEGIN: " name)
7742 (while plist
7743 (if (eq (car plist) :name)
7744 (setq plist (cddr plist))
7745 (insert " " (prin1-to-string (pop plist)))))
7746 (insert "\n\n#+END:\n")
7747 (beginning-of-line -2)))
7749 (defun org-prepare-dblock ()
7750 "Prepare dynamic block for refresh.
7751 This empties the block, puts the cursor at the insert position and returns
7752 the property list including an extra property :name with the block name."
7753 (unless (looking-at org-dblock-start-re)
7754 (error "Not at a dynamic block"))
7755 (let* ((begdel (1+ (match-end 0)))
7756 (name (org-no-properties (match-string 1)))
7757 (params (append (list :name name)
7758 (read (concat "(" (match-string 3) ")")))))
7759 (unless (re-search-forward org-dblock-end-re nil t)
7760 (error "Dynamic block not terminated"))
7761 (setq params
7762 (append params
7763 (list :content (buffer-substring
7764 begdel (match-beginning 0)))))
7765 (delete-region begdel (match-beginning 0))
7766 (goto-char begdel)
7767 (open-line 1)
7768 params))
7770 (defun org-map-dblocks (&optional command)
7771 "Apply COMMAND to all dynamic blocks in the current buffer.
7772 If COMMAND is not given, use `org-update-dblock'."
7773 (let ((cmd (or command 'org-update-dblock))
7774 pos)
7775 (save-excursion
7776 (goto-char (point-min))
7777 (while (re-search-forward org-dblock-start-re nil t)
7778 (goto-char (setq pos (match-beginning 0)))
7779 (condition-case nil
7780 (funcall cmd)
7781 (error (message "Error during update of dynamic block")))
7782 (goto-char pos)
7783 (unless (re-search-forward org-dblock-end-re nil t)
7784 (error "Dynamic block not terminated"))))))
7786 (defun org-dblock-update (&optional arg)
7787 "User command for updating dynamic blocks.
7788 Update the dynamic block at point. With prefix ARG, update all dynamic
7789 blocks in the buffer."
7790 (interactive "P")
7791 (if arg
7792 (org-update-all-dblocks)
7793 (or (looking-at org-dblock-start-re)
7794 (org-beginning-of-dblock))
7795 (org-update-dblock)))
7797 (defun org-update-dblock ()
7798 "Update the dynamic block at point
7799 This means to empty the block, parse for parameters and then call
7800 the correct writing function."
7801 (save-window-excursion
7802 (let* ((pos (point))
7803 (line (org-current-line))
7804 (params (org-prepare-dblock))
7805 (name (plist-get params :name))
7806 (cmd (intern (concat "org-dblock-write:" name))))
7807 (message "Updating dynamic block `%s' at line %d..." name line)
7808 (funcall cmd params)
7809 (message "Updating dynamic block `%s' at line %d...done" name line)
7810 (goto-char pos))))
7812 (defun org-beginning-of-dblock ()
7813 "Find the beginning of the dynamic block at point.
7814 Error if there is no such block at point."
7815 (let ((pos (point))
7816 beg)
7817 (end-of-line 1)
7818 (if (and (re-search-backward org-dblock-start-re nil t)
7819 (setq beg (match-beginning 0))
7820 (re-search-forward org-dblock-end-re nil t)
7821 (> (match-end 0) pos))
7822 (goto-char beg)
7823 (goto-char pos)
7824 (error "Not in a dynamic block"))))
7826 (defun org-update-all-dblocks ()
7827 "Update all dynamic blocks in the buffer.
7828 This function can be used in a hook."
7829 (when (org-mode-p)
7830 (org-map-dblocks 'org-update-dblock)))
7833 ;;;; Completion
7835 (defconst org-additional-option-like-keywords
7836 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7837 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7838 "BEGIN_EXAMPLE" "END_EXAMPLE"
7839 "BEGIN_QUOTE" "END_QUOTE"
7840 "BEGIN_VERSE" "END_VERSE"
7841 "BEGIN_SRC" "END_SRC"
7842 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7844 (defcustom org-structure-template-alist
7846 ("s" "#+begin_src ?\n\n#+end_src"
7847 "<src lang=\"?\">\n\n</src>")
7848 ("e" "#+begin_example\n?\n#+end_example"
7849 "<example>\n?\n</example>")
7850 ("q" "#+begin_quote\n?\n#+end_quote"
7851 "<quote>\n?\n</quote>")
7852 ("v" "#+begin_verse\n?\n#+end_verse"
7853 "<verse>\n?\n/verse>")
7854 ("l" "#+begin_latex\n?\n#+end_latex"
7855 "<literal style=\"latex\">\n?\n</literal>")
7856 ("L" "#+latex: "
7857 "<literal style=\"latex\">?</literal>")
7858 ("h" "#+begin_html\n?\n#+end_html"
7859 "<literal style=\"html\">\n?\n</literal>")
7860 ("H" "#+html: "
7861 "<literal style=\"html\">?</literal>")
7862 ("a" "#+begin_ascii\n?\n#+end_ascii")
7863 ("A" "#+ascii: ")
7864 ("i" "#+include %file ?"
7865 "<include file=%file markup=\"?\">")
7867 "Structure completion elements.
7868 This is a list of abbreviation keys and values. The value gets inserted
7869 it you type @samp{.} followed by the key and then the completion key,
7870 usually `M-TAB'. %file will be replaced by a file name after prompting
7871 for the file using completion.
7872 There are two templates for each key, the first uses the original Org syntax,
7873 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7874 the default when the /org-mtags.el/ module has been loaded. See also the
7875 variable `org-mtags-prefer-muse-templates'.
7876 This is an experimental feature, it is undecided if it is going to stay in."
7877 :group 'org-completion
7878 :type '(repeat
7879 (string :tag "Key")
7880 (string :tag "Template")
7881 (string :tag "Muse Template")))
7883 (defun org-try-structure-completion ()
7884 "Try to complete a structure template before point.
7885 This looks for strings like \"<e\" on an otherwise empty line and
7886 expands them."
7887 (let ((l (buffer-substring (point-at-bol) (point)))
7889 (when (and (looking-at "[ \t]*$")
7890 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7891 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7892 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7893 (match-beginning 1)) a)
7894 t)))
7896 (defun org-complete-expand-structure-template (start cell)
7897 "Expand a structure template."
7898 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7899 (rpl (nth (if musep 2 1) cell)))
7900 (delete-region start (point))
7901 (when (string-match "\\`#\\+" rpl)
7902 (cond
7903 ((bolp))
7904 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7905 (delete-region (point-at-bol) (point)))
7906 (t (newline))))
7907 (setq start (point))
7908 (if (string-match "%file" rpl)
7909 (setq rpl (replace-match
7910 (concat
7911 "\""
7912 (save-match-data
7913 (abbreviate-file-name (read-file-name "Include file: ")))
7914 "\"")
7915 t t rpl)))
7916 (insert rpl)
7917 (if (re-search-backward "\\?" start t) (delete-char 1))))
7920 (defun org-complete (&optional arg)
7921 "Perform completion on word at point.
7922 At the beginning of a headline, this completes TODO keywords as given in
7923 `org-todo-keywords'.
7924 If the current word is preceded by a backslash, completes the TeX symbols
7925 that are supported for HTML support.
7926 If the current word is preceded by \"#+\", completes special words for
7927 setting file options.
7928 In the line after \"#+STARTUP:, complete valid keywords.\"
7929 At all other locations, this simply calls the value of
7930 `org-completion-fallback-command'."
7931 (interactive "P")
7932 (org-without-partial-completion
7933 (catch 'exit
7934 (let* ((a nil)
7935 (end (point))
7936 (beg1 (save-excursion
7937 (skip-chars-backward (org-re "[:alnum:]_@"))
7938 (point)))
7939 (beg (save-excursion
7940 (skip-chars-backward "a-zA-Z0-9_:$")
7941 (point)))
7942 (confirm (lambda (x) (stringp (car x))))
7943 (searchhead (equal (char-before beg) ?*))
7944 (struct
7945 (when (and (member (char-before beg1) '(?. ?<))
7946 (setq a (assoc (buffer-substring beg1 (point))
7947 org-structure-template-alist)))
7948 (org-complete-expand-structure-template (1- beg1) a)
7949 (throw 'exit t)))
7950 (tag (and (equal (char-before beg1) ?:)
7951 (equal (char-after (point-at-bol)) ?*)))
7952 (prop (and (equal (char-before beg1) ?:)
7953 (not (equal (char-after (point-at-bol)) ?*))))
7954 (texp (equal (char-before beg) ?\\))
7955 (link (equal (char-before beg) ?\[))
7956 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7957 beg)
7958 "#+"))
7959 (startup (string-match "^#\\+STARTUP:.*"
7960 (buffer-substring (point-at-bol) (point))))
7961 (completion-ignore-case opt)
7962 (type nil)
7963 (tbl nil)
7964 (table (cond
7965 (opt
7966 (setq type :opt)
7967 (require 'org-exp)
7968 (append
7969 (mapcar
7970 (lambda (x)
7971 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7972 (cons (match-string 2 x) (match-string 1 x)))
7973 (org-split-string (org-get-current-options) "\n"))
7974 (mapcar 'list org-additional-option-like-keywords)))
7975 (startup
7976 (setq type :startup)
7977 org-startup-options)
7978 (link (append org-link-abbrev-alist-local
7979 org-link-abbrev-alist))
7980 (texp
7981 (setq type :tex)
7982 org-html-entities)
7983 ((string-match "\\`\\*+[ \t]+\\'"
7984 (buffer-substring (point-at-bol) beg))
7985 (setq type :todo)
7986 (mapcar 'list org-todo-keywords-1))
7987 (searchhead
7988 (setq type :searchhead)
7989 (save-excursion
7990 (goto-char (point-min))
7991 (while (re-search-forward org-todo-line-regexp nil t)
7992 (push (list
7993 (org-make-org-heading-search-string
7994 (match-string 3) t))
7995 tbl)))
7996 tbl)
7997 (tag (setq type :tag beg beg1)
7998 (or org-tag-alist (org-get-buffer-tags)))
7999 (prop (setq type :prop beg beg1)
8000 (mapcar 'list (org-buffer-property-keys nil t t)))
8001 (t (progn
8002 (call-interactively org-completion-fallback-command)
8003 (throw 'exit nil)))))
8004 (pattern (buffer-substring-no-properties beg end))
8005 (completion (try-completion pattern table confirm)))
8006 (cond ((eq completion t)
8007 (if (not (assoc (upcase pattern) table))
8008 (message "Already complete")
8009 (if (and (equal type :opt)
8010 (not (member (car (assoc (upcase pattern) table))
8011 org-additional-option-like-keywords)))
8012 (insert (substring (cdr (assoc (upcase pattern) table))
8013 (length pattern)))
8014 (if (memq type '(:tag :prop)) (insert ":")))))
8015 ((null completion)
8016 (message "Can't find completion for \"%s\"" pattern)
8017 (ding))
8018 ((not (string= pattern completion))
8019 (delete-region beg end)
8020 (if (string-match " +$" completion)
8021 (setq completion (replace-match "" t t completion)))
8022 (insert completion)
8023 (if (get-buffer-window "*Completions*")
8024 (delete-window (get-buffer-window "*Completions*")))
8025 (if (assoc completion table)
8026 (if (eq type :todo) (insert " ")
8027 (if (memq type '(:tag :prop)) (insert ":"))))
8028 (if (and (equal type :opt) (assoc completion table))
8029 (message "%s" (substitute-command-keys
8030 "Press \\[org-complete] again to insert example settings"))))
8032 (message "Making completion list...")
8033 (let ((list (sort (all-completions pattern table confirm)
8034 'string<)))
8035 (with-output-to-temp-buffer "*Completions*"
8036 (condition-case nil
8037 ;; Protection needed for XEmacs and emacs 21
8038 (display-completion-list list pattern)
8039 (error (display-completion-list list)))))
8040 (message "Making completion list...%s" "done")))))))
8042 ;;;; TODO, DEADLINE, Comments
8044 (defun org-toggle-comment ()
8045 "Change the COMMENT state of an entry."
8046 (interactive)
8047 (save-excursion
8048 (org-back-to-heading)
8049 (let (case-fold-search)
8050 (if (looking-at (concat outline-regexp
8051 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8052 (replace-match "" t t nil 1)
8053 (if (looking-at outline-regexp)
8054 (progn
8055 (goto-char (match-end 0))
8056 (insert org-comment-string " ")))))))
8058 (defvar org-last-todo-state-is-todo nil
8059 "This is non-nil when the last TODO state change led to a TODO state.
8060 If the last change removed the TODO tag or switched to DONE, then
8061 this is nil.")
8063 (defvar org-setting-tags nil) ; dynamically skipped
8065 (defun org-parse-local-options (string var)
8066 "Parse STRING for startup setting relevant for variable VAR."
8067 (let ((rtn (symbol-value var))
8068 e opts)
8069 (save-match-data
8070 (if (or (not string) (not (string-match "\\S-" string)))
8072 (setq opts (delq nil (mapcar (lambda (x)
8073 (setq e (assoc x org-startup-options))
8074 (if (eq (nth 1 e) var) e nil))
8075 (org-split-string string "[ \t]+"))))
8076 (if (not opts)
8078 (setq rtn nil)
8079 (while (setq e (pop opts))
8080 (if (not (nth 3 e))
8081 (setq rtn (nth 2 e))
8082 (if (not (listp rtn)) (setq rtn nil))
8083 (push (nth 2 e) rtn)))
8084 rtn)))))
8086 (defvar org-blocker-hook nil
8087 "Hook for functions that are allowed to block a state change.
8089 Each function gets as its single argument a property list, see
8090 `org-trigger-hook' for more information about this list.
8092 If any of the functions in this hook returns nil, the state change
8093 is blocked.")
8095 (defvar org-trigger-hook nil
8096 "Hook for functions that are triggered by a state change.
8098 Each function gets as its single argument a property list with at least
8099 the following elements:
8101 (:type type-of-change :position pos-at-entry-start
8102 :from old-state :to new-state)
8104 Depending on the type, more properties may be present.
8106 This mechanism is currently implemented for:
8108 TODO state changes
8109 ------------------
8110 :type todo-state-change
8111 :from previous state (keyword as a string), or nil
8112 :to new state (keyword as a string), or nil")
8114 (defvar org-agenda-headline-snapshot-before-repeat)
8115 (defun org-todo (&optional arg)
8116 "Change the TODO state of an item.
8117 The state of an item is given by a keyword at the start of the heading,
8118 like
8119 *** TODO Write paper
8120 *** DONE Call mom
8122 The different keywords are specified in the variable `org-todo-keywords'.
8123 By default the available states are \"TODO\" and \"DONE\".
8124 So for this example: when the item starts with TODO, it is changed to DONE.
8125 When it starts with DONE, the DONE is removed. And when neither TODO nor
8126 DONE are present, add TODO at the beginning of the heading.
8128 With C-u prefix arg, use completion to determine the new state.
8129 With numeric prefix arg, switch to that state.
8131 For calling through lisp, arg is also interpreted in the following way:
8132 'none -> empty state
8133 \"\"(empty string) -> switch to empty state
8134 'done -> switch to DONE
8135 'nextset -> switch to the next set of keywords
8136 'previousset -> switch to the previous set of keywords
8137 \"WAITING\" -> switch to the specified keyword, but only if it
8138 really is a member of `org-todo-keywords'."
8139 (interactive "P")
8140 (save-excursion
8141 (catch 'exit
8142 (org-back-to-heading)
8143 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8144 (or (looking-at (concat " +" org-todo-regexp " *"))
8145 (looking-at " *"))
8146 (let* ((match-data (match-data))
8147 (startpos (point-at-bol))
8148 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8149 (org-log-done org-log-done)
8150 (org-log-repeat org-log-repeat)
8151 (org-todo-log-states org-todo-log-states)
8152 (this (match-string 1))
8153 (hl-pos (match-beginning 0))
8154 (head (org-get-todo-sequence-head this))
8155 (ass (assoc head org-todo-kwd-alist))
8156 (interpret (nth 1 ass))
8157 (done-word (nth 3 ass))
8158 (final-done-word (nth 4 ass))
8159 (last-state (or this ""))
8160 (completion-ignore-case t)
8161 (member (member this org-todo-keywords-1))
8162 (tail (cdr member))
8163 (state (cond
8164 ((and org-todo-key-trigger
8165 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8166 (and (not arg) org-use-fast-todo-selection
8167 (not (eq org-use-fast-todo-selection 'prefix)))))
8168 ;; Use fast selection
8169 (org-fast-todo-selection))
8170 ((and (equal arg '(4))
8171 (or (not org-use-fast-todo-selection)
8172 (not org-todo-key-trigger)))
8173 ;; Read a state with completion
8174 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8175 org-todo-keywords-1)
8176 nil t))
8177 ((eq arg 'right)
8178 (if this
8179 (if tail (car tail) nil)
8180 (car org-todo-keywords-1)))
8181 ((eq arg 'left)
8182 (if (equal member org-todo-keywords-1)
8184 (if this
8185 (nth (- (length org-todo-keywords-1) (length tail) 2)
8186 org-todo-keywords-1)
8187 (org-last org-todo-keywords-1))))
8188 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8189 (setq arg nil))) ; hack to fall back to cycling
8190 (arg
8191 ;; user or caller requests a specific state
8192 (cond
8193 ((equal arg "") nil)
8194 ((eq arg 'none) nil)
8195 ((eq arg 'done) (or done-word (car org-done-keywords)))
8196 ((eq arg 'nextset)
8197 (or (car (cdr (member head org-todo-heads)))
8198 (car org-todo-heads)))
8199 ((eq arg 'previousset)
8200 (let ((org-todo-heads (reverse org-todo-heads)))
8201 (or (car (cdr (member head org-todo-heads)))
8202 (car org-todo-heads))))
8203 ((car (member arg org-todo-keywords-1)))
8204 ((nth (1- (prefix-numeric-value arg))
8205 org-todo-keywords-1))))
8206 ((null member) (or head (car org-todo-keywords-1)))
8207 ((equal this final-done-word) nil) ;; -> make empty
8208 ((null tail) nil) ;; -> first entry
8209 ((eq interpret 'sequence)
8210 (car tail))
8211 ((memq interpret '(type priority))
8212 (if (eq this-command last-command)
8213 (car tail)
8214 (if (> (length tail) 0)
8215 (or done-word (car org-done-keywords))
8216 nil)))
8217 (t nil)))
8218 (next (if state (concat " " state " ") " "))
8219 (change-plist (list :type 'todo-state-change :from this :to state
8220 :position startpos))
8221 dolog now-done-p)
8222 (when org-blocker-hook
8223 (unless (save-excursion
8224 (save-match-data
8225 (run-hook-with-args-until-failure
8226 'org-blocker-hook change-plist)))
8227 (if (interactive-p)
8228 (error "TODO state change from %s to %s blocked" this state)
8229 ;; fail silently
8230 (message "TODO state change from %s to %s blocked" this state)
8231 (throw 'exit nil))))
8232 (store-match-data match-data)
8233 (replace-match next t t)
8234 (unless (pos-visible-in-window-p hl-pos)
8235 (message "TODO state changed to %s" (org-trim next)))
8236 (unless head
8237 (setq head (org-get-todo-sequence-head state)
8238 ass (assoc head org-todo-kwd-alist)
8239 interpret (nth 1 ass)
8240 done-word (nth 3 ass)
8241 final-done-word (nth 4 ass)))
8242 (when (memq arg '(nextset previousset))
8243 (message "Keyword-Set %d/%d: %s"
8244 (- (length org-todo-sets) -1
8245 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8246 (length org-todo-sets)
8247 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8248 (setq org-last-todo-state-is-todo
8249 (not (member state org-done-keywords)))
8250 (setq now-done-p (and (member state org-done-keywords)
8251 (not (member this org-done-keywords))))
8252 (and logging (org-local-logging logging))
8253 (when (and (or org-todo-log-states org-log-done)
8254 (not (memq arg '(nextset previousset))))
8255 ;; we need to look at recording a time and note
8256 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8257 (nth 2 (assoc this org-todo-log-states))))
8258 (when (and state
8259 (member state org-not-done-keywords)
8260 (not (member this org-not-done-keywords)))
8261 ;; This is now a todo state and was not one before
8262 ;; If there was a CLOSED time stamp, get rid of it.
8263 (org-add-planning-info nil nil 'closed))
8264 (when (and now-done-p org-log-done)
8265 ;; It is now done, and it was not done before
8266 (org-add-planning-info 'closed (org-current-time))
8267 (if (and (not dolog) (eq 'note org-log-done))
8268 (org-add-log-setup 'done state 'findpos 'note)))
8269 (when (and state dolog)
8270 ;; This is a non-nil state, and we need to log it
8271 (org-add-log-setup 'state state 'findpos dolog)))
8272 ;; Fixup tag positioning
8273 (org-todo-trigger-tag-changes state)
8274 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8275 (when org-provide-todo-statistics
8276 (org-update-parent-todo-statistics))
8277 (run-hooks 'org-after-todo-state-change-hook)
8278 (if (and arg (not (member state org-done-keywords)))
8279 (setq head (org-get-todo-sequence-head state)))
8280 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8281 ;; Do we need to trigger a repeat?
8282 (when now-done-p
8283 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8284 ;; This is for the agenda, take a snapshot of the headline.
8285 (save-match-data
8286 (setq org-agenda-headline-snapshot-before-repeat
8287 (org-get-heading))))
8288 (org-auto-repeat-maybe state))
8289 ;; Fixup cursor location if close to the keyword
8290 (if (and (outline-on-heading-p)
8291 (not (bolp))
8292 (save-excursion (beginning-of-line 1)
8293 (looking-at org-todo-line-regexp))
8294 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8295 (progn
8296 (goto-char (or (match-end 2) (match-end 1)))
8297 (just-one-space)))
8298 (when org-trigger-hook
8299 (save-excursion
8300 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8302 (defun org-update-parent-todo-statistics ()
8303 "Update any statistics cookie in the parent of the current headline."
8304 (interactive)
8305 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8306 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8307 (catch 'exit
8308 (save-excursion
8309 (setq level (org-up-heading-safe))
8310 (unless (and level
8311 (re-search-forward box-re (point-at-eol) t))
8312 (throw 'exit nil))
8313 (setq is-percent (match-end 2))
8314 (save-match-data
8315 (unless (outline-next-heading) (throw 'exit nil))
8316 (while (looking-at org-todo-line-regexp)
8317 (setq kwd (match-string 2))
8318 (and kwd (setq cnt-all (1+ cnt-all)))
8319 (and (member kwd org-done-keywords)
8320 (setq cnt-done (1+ cnt-done)))
8321 (condition-case nil
8322 (org-forward-same-level 1)
8323 (error (end-of-line 1)))))
8324 (replace-match
8325 (if is-percent
8326 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8327 (format "[%d/%d]" cnt-done cnt-all)))
8328 (run-hook-with-args 'org-after-todo-statistics-hook
8329 cnt-done (- cnt-all cnt-done))))))
8331 (defvar org-after-todo-statistics-hook nil
8332 "Hook that is called after a TODO statistics cookie has been updated.
8333 Each function is called with two arguments: the number of not-done entries
8334 and the number of done entries.
8336 For example, the following function, when added to this hook, will switch
8337 an entry to DONE when all children are done, and back to TODO when new
8338 entries are set to a TODO status. Note that this hook is only called
8339 when there is a statistics cookie in the headline!
8341 (defun org-summary-todo (n-done n-not-done)
8342 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8343 (let (org-log-done org-log-states) ; turn off logging
8344 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8347 (defun org-todo-trigger-tag-changes (state)
8348 "Apply the changes defined in `org-todo-state-tags-triggers'."
8349 (let ((l org-todo-state-tags-triggers)
8350 changes)
8351 (when (or (not state) (equal state ""))
8352 (setq changes (append changes (cdr (assoc "" l)))))
8353 (when (and (stringp state) (> (length state) 0))
8354 (setq changes (append changes (cdr (assoc state l)))))
8355 (when (member state org-not-done-keywords)
8356 (setq changes (append changes (cdr (assoc 'todo l)))))
8357 (when (member state org-done-keywords)
8358 (setq changes (append changes (cdr (assoc 'done l)))))
8359 (dolist (c changes)
8360 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8362 (defun org-local-logging (value)
8363 "Get logging settings from a property VALUE."
8364 (let* (words w a)
8365 ;; directly set the variables, they are already local.
8366 (setq org-log-done nil
8367 org-log-repeat nil
8368 org-todo-log-states nil)
8369 (setq words (org-split-string value))
8370 (while (setq w (pop words))
8371 (cond
8372 ((setq a (assoc w org-startup-options))
8373 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8374 (set (nth 1 a) (nth 2 a))))
8375 ((setq a (org-extract-log-state-settings w))
8376 (and (member (car a) org-todo-keywords-1)
8377 (push a org-todo-log-states)))))))
8379 (defun org-get-todo-sequence-head (kwd)
8380 "Return the head of the TODO sequence to which KWD belongs.
8381 If KWD is not set, check if there is a text property remembering the
8382 right sequence."
8383 (let (p)
8384 (cond
8385 ((not kwd)
8386 (or (get-text-property (point-at-bol) 'org-todo-head)
8387 (progn
8388 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8389 nil (point-at-eol)))
8390 (get-text-property p 'org-todo-head))))
8391 ((not (member kwd org-todo-keywords-1))
8392 (car org-todo-keywords-1))
8393 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8395 (defun org-fast-todo-selection ()
8396 "Fast TODO keyword selection with single keys.
8397 Returns the new TODO keyword, or nil if no state change should occur."
8398 (let* ((fulltable org-todo-key-alist)
8399 (done-keywords org-done-keywords) ;; needed for the faces.
8400 (maxlen (apply 'max (mapcar
8401 (lambda (x)
8402 (if (stringp (car x)) (string-width (car x)) 0))
8403 fulltable)))
8404 (expert nil)
8405 (fwidth (+ maxlen 3 1 3))
8406 (ncol (/ (- (window-width) 4) fwidth))
8407 tg cnt e c tbl
8408 groups ingroup)
8409 (save-window-excursion
8410 (if expert
8411 (set-buffer (get-buffer-create " *Org todo*"))
8412 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8413 (erase-buffer)
8414 (org-set-local 'org-done-keywords done-keywords)
8415 (setq tbl fulltable cnt 0)
8416 (while (setq e (pop tbl))
8417 (cond
8418 ((equal e '(:startgroup))
8419 (push '() groups) (setq ingroup t)
8420 (when (not (= cnt 0))
8421 (setq cnt 0)
8422 (insert "\n"))
8423 (insert "{ "))
8424 ((equal e '(:endgroup))
8425 (setq ingroup nil cnt 0)
8426 (insert "}\n"))
8428 (setq tg (car e) c (cdr e))
8429 (if ingroup (push tg (car groups)))
8430 (setq tg (org-add-props tg nil 'face
8431 (org-get-todo-face tg)))
8432 (if (and (= cnt 0) (not ingroup)) (insert " "))
8433 (insert "[" c "] " tg (make-string
8434 (- fwidth 4 (length tg)) ?\ ))
8435 (when (= (setq cnt (1+ cnt)) ncol)
8436 (insert "\n")
8437 (if ingroup (insert " "))
8438 (setq cnt 0)))))
8439 (insert "\n")
8440 (goto-char (point-min))
8441 (if (not expert) (org-fit-window-to-buffer))
8442 (message "[a-z..]:Set [SPC]:clear")
8443 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8444 (cond
8445 ((or (= c ?\C-g)
8446 (and (= c ?q) (not (rassoc c fulltable))))
8447 (setq quit-flag t))
8448 ((= c ?\ ) nil)
8449 ((setq e (rassoc c fulltable) tg (car e))
8451 (t (setq quit-flag t))))))
8453 (defun org-entry-is-todo-p ()
8454 (member (org-get-todo-state) org-not-done-keywords))
8456 (defun org-entry-is-done-p ()
8457 (member (org-get-todo-state) org-done-keywords))
8459 (defun org-get-todo-state ()
8460 (save-excursion
8461 (org-back-to-heading t)
8462 (and (looking-at org-todo-line-regexp)
8463 (match-end 2)
8464 (match-string 2))))
8466 (defun org-at-date-range-p (&optional inactive-ok)
8467 "Is the cursor inside a date range?"
8468 (interactive)
8469 (save-excursion
8470 (catch 'exit
8471 (let ((pos (point)))
8472 (skip-chars-backward "^[<\r\n")
8473 (skip-chars-backward "<[")
8474 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8475 (>= (match-end 0) pos)
8476 (throw 'exit t))
8477 (skip-chars-backward "^<[\r\n")
8478 (skip-chars-backward "<[")
8479 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8480 (>= (match-end 0) pos)
8481 (throw 'exit t)))
8482 nil)))
8484 (defun org-get-repeat ()
8485 "Check if there is a deadline/schedule with repeater in this entry."
8486 (save-match-data
8487 (save-excursion
8488 (org-back-to-heading t)
8489 (if (re-search-forward
8490 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8491 (match-string 1)))))
8493 (defvar org-last-changed-timestamp)
8494 (defvar org-last-inserted-timestamp)
8495 (defvar org-log-post-message)
8496 (defvar org-log-note-purpose)
8497 (defvar org-log-note-how)
8498 (defvar org-log-note-extra)
8499 (defun org-auto-repeat-maybe (done-word)
8500 "Check if the current headline contains a repeated deadline/schedule.
8501 If yes, set TODO state back to what it was and change the base date
8502 of repeating deadline/scheduled time stamps to new date.
8503 This function is run automatically after each state change to a DONE state."
8504 ;; last-state is dynamically scoped into this function
8505 (let* ((repeat (org-get-repeat))
8506 (aa (assoc last-state org-todo-kwd-alist))
8507 (interpret (nth 1 aa))
8508 (head (nth 2 aa))
8509 (whata '(("d" . day) ("m" . month) ("y" . year)))
8510 (msg "Entry repeats: ")
8511 (org-log-done nil)
8512 (org-todo-log-states nil)
8513 (nshiftmax 10) (nshift 0)
8514 re type n what ts mb0 time)
8515 (when repeat
8516 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8517 (org-todo (if (eq interpret 'type) last-state head))
8518 (when org-log-repeat
8519 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8520 (memq 'org-add-log-note post-command-hook))
8521 ;; OK, we are already setup for some record
8522 (if (eq org-log-repeat 'note)
8523 ;; make sure we take a note, not only a time stamp
8524 (setq org-log-note-how 'note))
8525 ;; Set up for taking a record
8526 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8527 'findpos org-log-repeat)))
8528 (org-back-to-heading t)
8529 (org-add-planning-info nil nil 'closed)
8530 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8531 org-deadline-time-regexp "\\)\\|\\("
8532 org-ts-regexp "\\)"))
8533 (while (re-search-forward
8534 re (save-excursion (outline-next-heading) (point)) t)
8535 (setq type (if (match-end 1) org-scheduled-string
8536 (if (match-end 3) org-deadline-string "Plain:"))
8537 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8538 mb0 (match-beginning 0))
8539 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8540 (setq n (string-to-number (match-string 2 ts))
8541 what (match-string 3 ts))
8542 (if (equal what "w") (setq n (* n 7) what "d"))
8543 ;; Preparation, see if we need to modify the start date for the change
8544 (when (match-end 1)
8545 (setq time (save-match-data (org-time-string-to-time ts)))
8546 (cond
8547 ((equal (match-string 1 ts) ".")
8548 ;; Shift starting date to today
8549 (org-timestamp-change
8550 (- (time-to-days (current-time)) (time-to-days time))
8551 'day))
8552 ((equal (match-string 1 ts) "+")
8553 (while (or (= nshift 0)
8554 (<= (time-to-days time) (time-to-days (current-time))))
8555 (when (= (incf nshift) nshiftmax)
8556 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8557 (error "Abort")))
8558 (org-timestamp-change n (cdr (assoc what whata)))
8559 (org-at-timestamp-p t)
8560 (setq ts (match-string 1))
8561 (setq time (save-match-data (org-time-string-to-time ts))))
8562 (org-timestamp-change (- n) (cdr (assoc what whata)))
8563 ;; rematch, so that we have everything in place for the real shift
8564 (org-at-timestamp-p t)
8565 (setq ts (match-string 1))
8566 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8567 (org-timestamp-change n (cdr (assoc what whata)))
8568 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8569 (setq org-log-post-message msg)
8570 (message "%s" msg))))
8572 (defun org-show-todo-tree (arg)
8573 "Make a compact tree which shows all headlines marked with TODO.
8574 The tree will show the lines where the regexp matches, and all higher
8575 headlines above the match.
8576 With a \\[universal-argument] prefix, also show the DONE entries.
8577 With a numeric prefix N, construct a sparse tree for the Nth element
8578 of `org-todo-keywords-1'."
8579 (interactive "P")
8580 (let ((case-fold-search nil)
8581 (kwd-re
8582 (cond ((null arg) org-not-done-regexp)
8583 ((equal arg '(4))
8584 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8585 (mapcar 'list org-todo-keywords-1))))
8586 (concat "\\("
8587 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8588 "\\)\\>")))
8589 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8590 (regexp-quote (nth (1- (prefix-numeric-value arg))
8591 org-todo-keywords-1)))
8592 (t (error "Invalid prefix argument: %s" arg)))))
8593 (message "%d TODO entries found"
8594 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8596 (defun org-deadline (&optional remove time)
8597 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8598 With argument REMOVE, remove any deadline from the item.
8599 When TIME is set, it should be an internal time specification, and the
8600 scheduling will use the corresponding date."
8601 (interactive "P")
8602 (if remove
8603 (progn
8604 (org-remove-timestamp-with-keyword org-deadline-string)
8605 (message "Item no longer has a deadline."))
8606 (if (org-get-repeat)
8607 (error "Cannot change deadline on task with repeater, please do that by hand")
8608 (org-add-planning-info 'deadline time 'closed)
8609 (message "Deadline on %s" org-last-inserted-timestamp))))
8611 (defun org-schedule (&optional remove time)
8612 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8613 With argument REMOVE, remove any scheduling date from the item.
8614 When TIME is set, it should be an internal time specification, and the
8615 scheduling will use the corresponding date."
8616 (interactive "P")
8617 (if remove
8618 (progn
8619 (org-remove-timestamp-with-keyword org-scheduled-string)
8620 (message "Item is no longer scheduled."))
8621 (if (org-get-repeat)
8622 (error "Cannot reschedule task with repeater, please do that by hand")
8623 (org-add-planning-info 'scheduled time 'closed)
8624 (message "Scheduled to %s" org-last-inserted-timestamp))))
8626 (defun org-remove-timestamp-with-keyword (keyword)
8627 "Remove all time stamps with KEYWORD in the current entry."
8628 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8629 beg)
8630 (save-excursion
8631 (org-back-to-heading t)
8632 (setq beg (point))
8633 (org-end-of-subtree t t)
8634 (while (re-search-backward re beg t)
8635 (replace-match "")
8636 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8637 (equal (char-before) ?\ ))
8638 (backward-delete-char 1)
8639 (if (string-match "^[ \t]*$" (buffer-substring
8640 (point-at-bol) (point-at-eol)))
8641 (delete-region (point-at-bol)
8642 (min (point-max) (1+ (point-at-eol))))))))))
8644 (defun org-add-planning-info (what &optional time &rest remove)
8645 "Insert new timestamp with keyword in the line directly after the headline.
8646 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8647 If non is given, the user is prompted for a date.
8648 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8649 be removed."
8650 (interactive)
8651 (let (org-time-was-given org-end-time-was-given ts
8652 end default-time default-input)
8654 (when (and (not time) (memq what '(scheduled deadline)))
8655 ;; Try to get a default date/time from existing timestamp
8656 (save-excursion
8657 (org-back-to-heading t)
8658 (setq end (save-excursion (outline-next-heading) (point)))
8659 (when (re-search-forward (if (eq what 'scheduled)
8660 org-scheduled-time-regexp
8661 org-deadline-time-regexp)
8662 end t)
8663 (setq ts (match-string 1)
8664 default-time
8665 (apply 'encode-time (org-parse-time-string ts))
8666 default-input (and ts (org-get-compact-tod ts))))))
8667 (when what
8668 ;; If necessary, get the time from the user
8669 (setq time (or time (org-read-date nil 'to-time nil nil
8670 default-time default-input))))
8672 (when (and org-insert-labeled-timestamps-at-point
8673 (member what '(scheduled deadline)))
8674 (insert
8675 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8676 (org-insert-time-stamp time org-time-was-given
8677 nil nil nil (list org-end-time-was-given))
8678 (setq what nil))
8679 (save-excursion
8680 (save-restriction
8681 (let (col list elt ts buffer-invisibility-spec)
8682 (org-back-to-heading t)
8683 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8684 (goto-char (match-end 1))
8685 (setq col (current-column))
8686 (goto-char (match-end 0))
8687 (if (eobp) (insert "\n") (forward-char 1))
8688 (if (and (not (looking-at outline-regexp))
8689 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8690 "[^\r\n]*"))
8691 (not (equal (match-string 1) org-clock-string)))
8692 (narrow-to-region (match-beginning 0) (match-end 0))
8693 (insert-before-markers "\n")
8694 (backward-char 1)
8695 (narrow-to-region (point) (point))
8696 (and org-adapt-indentation (org-indent-to-column col)))
8697 ;; Check if we have to remove something.
8698 (setq list (cons what remove))
8699 (while list
8700 (setq elt (pop list))
8701 (goto-char (point-min))
8702 (when (or (and (eq elt 'scheduled)
8703 (re-search-forward org-scheduled-time-regexp nil t))
8704 (and (eq elt 'deadline)
8705 (re-search-forward org-deadline-time-regexp nil t))
8706 (and (eq elt 'closed)
8707 (re-search-forward org-closed-time-regexp nil t)))
8708 (replace-match "")
8709 (if (looking-at "--+<[^>]+>") (replace-match ""))
8710 (if (looking-at " +") (replace-match ""))))
8711 (goto-char (point-max))
8712 (when what
8713 (insert
8714 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8715 (cond ((eq what 'scheduled) org-scheduled-string)
8716 ((eq what 'deadline) org-deadline-string)
8717 ((eq what 'closed) org-closed-string))
8718 " ")
8719 (setq ts (org-insert-time-stamp
8720 time
8721 (or org-time-was-given
8722 (and (eq what 'closed) org-log-done-with-time))
8723 (eq what 'closed)
8724 nil nil (list org-end-time-was-given)))
8725 (end-of-line 1))
8726 (goto-char (point-min))
8727 (widen)
8728 (if (and (looking-at "[ \t]+\n")
8729 (equal (char-before) ?\n))
8730 (delete-region (1- (point)) (point-at-eol)))
8731 ts)))))
8733 (defvar org-log-note-marker (make-marker))
8734 (defvar org-log-note-purpose nil)
8735 (defvar org-log-note-state nil)
8736 (defvar org-log-note-how nil)
8737 (defvar org-log-note-extra nil)
8738 (defvar org-log-note-window-configuration nil)
8739 (defvar org-log-note-return-to (make-marker))
8740 (defvar org-log-post-message nil
8741 "Message to be displayed after a log note has been stored.
8742 The auto-repeater uses this.")
8744 (defun org-add-note ()
8745 "Add a note to the current entry.
8746 This is done in the same way as adding a state change note."
8747 (interactive)
8748 (org-add-log-setup 'note nil 'findpos nil))
8750 (defvar org-property-end-re)
8751 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8752 "Set up the post command hook to take a note.
8753 If this is about to TODO state change, the new state is expected in STATE.
8754 When FINDPOS is non-nil, find the correct position for the note in
8755 the current entry. If not, assume that it can be inserted at point.
8756 HOW is an indicator what kind of note should be created.
8757 EXTRA is additional text that will be inserted into the notes buffer."
8758 (save-restriction
8759 (save-excursion
8760 (when findpos
8761 (org-back-to-heading t)
8762 (narrow-to-region (point) (save-excursion
8763 (outline-next-heading) (point)))
8764 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8765 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8766 "[^\r\n]*\\)?"))
8767 (goto-char (match-end 0))
8768 (when (and org-log-state-notes-insert-after-drawers
8769 (save-excursion
8770 (forward-line) (looking-at org-drawer-regexp)))
8771 (progn (forward-line)
8772 (while (looking-at org-drawer-regexp)
8773 (goto-char (match-end 0))
8774 (re-search-forward org-property-end-re (point-max) t)
8775 (forward-line))
8776 (forward-line -1)))
8777 (unless org-log-states-order-reversed
8778 (and (= (char-after) ?\n) (forward-char 1))
8779 (org-skip-over-state-notes)
8780 (skip-chars-backward " \t\n\r")))
8781 (move-marker org-log-note-marker (point))
8782 (setq org-log-note-purpose purpose
8783 org-log-note-state state
8784 org-log-note-how how
8785 org-log-note-extra extra)
8786 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8788 (defun org-skip-over-state-notes ()
8789 "Skip past the list of State notes in an entry."
8790 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8791 (while (looking-at "[ \t]*- State")
8792 (condition-case nil
8793 (org-next-item)
8794 (error (org-end-of-item)))))
8796 (defun org-add-log-note (&optional purpose)
8797 "Pop up a window for taking a note, and add this note later at point."
8798 (remove-hook 'post-command-hook 'org-add-log-note)
8799 (setq org-log-note-window-configuration (current-window-configuration))
8800 (delete-other-windows)
8801 (move-marker org-log-note-return-to (point))
8802 (switch-to-buffer (marker-buffer org-log-note-marker))
8803 (goto-char org-log-note-marker)
8804 (org-switch-to-buffer-other-window "*Org Note*")
8805 (erase-buffer)
8806 (if (memq org-log-note-how '(time state))
8807 (let (current-prefix-arg) (org-store-log-note))
8808 (let ((org-inhibit-startup t)) (org-mode))
8809 (insert (format "# Insert note for %s.
8810 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8811 (cond
8812 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8813 ((eq org-log-note-purpose 'done) "closed todo item")
8814 ((eq org-log-note-purpose 'state)
8815 (format "state change to \"%s\"" org-log-note-state))
8816 ((eq org-log-note-purpose 'note)
8817 "this entry")
8818 (t (error "This should not happen")))))
8819 (if org-log-note-extra (insert org-log-note-extra))
8820 (org-set-local 'org-finish-function 'org-store-log-note)))
8822 (defvar org-note-abort nil) ; dynamically scoped
8823 (defun org-store-log-note ()
8824 "Finish taking a log note, and insert it to where it belongs."
8825 (let ((txt (buffer-string))
8826 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8827 lines ind)
8828 (kill-buffer (current-buffer))
8829 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8830 (setq txt (replace-match "" t t txt)))
8831 (if (string-match "\\s-+\\'" txt)
8832 (setq txt (replace-match "" t t txt)))
8833 (setq lines (org-split-string txt "\n"))
8834 (when (and note (string-match "\\S-" note))
8835 (setq note
8836 (org-replace-escapes
8837 note
8838 (list (cons "%u" (user-login-name))
8839 (cons "%U" user-full-name)
8840 (cons "%t" (format-time-string
8841 (org-time-stamp-format 'long 'inactive)
8842 (current-time)))
8843 (cons "%s" (if org-log-note-state
8844 (concat "\"" org-log-note-state "\"")
8845 "")))))
8846 (if lines (setq note (concat note " \\\\")))
8847 (push note lines))
8848 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8849 (when lines
8850 (save-excursion
8851 (set-buffer (marker-buffer org-log-note-marker))
8852 (save-excursion
8853 (goto-char org-log-note-marker)
8854 (move-marker org-log-note-marker nil)
8855 (end-of-line 1)
8856 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8857 (indent-relative nil)
8858 (insert "- " (pop lines))
8859 (org-indent-line-function)
8860 (beginning-of-line 1)
8861 (looking-at "[ \t]*")
8862 (setq ind (concat (match-string 0) " "))
8863 (end-of-line 1)
8864 (while lines (insert "\n" ind (pop lines)))))))
8865 (set-window-configuration org-log-note-window-configuration)
8866 (with-current-buffer (marker-buffer org-log-note-return-to)
8867 (goto-char org-log-note-return-to))
8868 (move-marker org-log-note-return-to nil)
8869 (and org-log-post-message (message "%s" org-log-post-message)))
8871 (defun org-sparse-tree (&optional arg)
8872 "Create a sparse tree, prompt for the details.
8873 This command can create sparse trees. You first need to select the type
8874 of match used to create the tree:
8876 t Show entries with a specific TODO keyword.
8877 T Show entries selected by a tags match.
8878 p Enter a property name and its value (both with completion on existing
8879 names/values) and show entries with that property.
8880 r Show entries matching a regular expression
8881 d Show deadlines due within `org-deadline-warning-days'."
8882 (interactive "P")
8883 (let (ans kwd value)
8884 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8885 (setq ans (read-char-exclusive))
8886 (cond
8887 ((equal ans ?d)
8888 (call-interactively 'org-check-deadlines))
8889 ((equal ans ?b)
8890 (call-interactively 'org-check-before-date))
8891 ((equal ans ?t)
8892 (org-show-todo-tree '(4)))
8893 ((equal ans ?T)
8894 (call-interactively 'org-tags-sparse-tree))
8895 ((member ans '(?p ?P))
8896 (setq kwd (org-ido-completing-read "Property: "
8897 (mapcar 'list (org-buffer-property-keys))))
8898 (setq value (org-ido-completing-read "Value: "
8899 (mapcar 'list (org-property-values kwd))))
8900 (unless (string-match "\\`{.*}\\'" value)
8901 (setq value (concat "\"" value "\"")))
8902 (org-tags-sparse-tree arg (concat kwd "=" value)))
8903 ((member ans '(?r ?R ?/))
8904 (call-interactively 'org-occur))
8905 (t (error "No such sparse tree command \"%c\"" ans)))))
8907 (defvar org-occur-highlights nil
8908 "List of overlays used for occur matches.")
8909 (make-variable-buffer-local 'org-occur-highlights)
8910 (defvar org-occur-parameters nil
8911 "Parameters of the active org-occur calls.
8912 This is a list, each call to org-occur pushes as cons cell,
8913 containing the regular expression and the callback, onto the list.
8914 The list can contain several entries if `org-occur' has been called
8915 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8916 will only contain one set of parameters. When the highlights are
8917 removed (for example with `C-c C-c', or with the next edit (depending
8918 on `org-remove-highlights-with-change'), this variable is emptied
8919 as well.")
8920 (make-variable-buffer-local 'org-occur-parameters)
8922 (defun org-occur (regexp &optional keep-previous callback)
8923 "Make a compact tree which shows all matches of REGEXP.
8924 The tree will show the lines where the regexp matches, and all higher
8925 headlines above the match. It will also show the heading after the match,
8926 to make sure editing the matching entry is easy.
8927 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8928 call to `org-occur' will be kept, to allow stacking of calls to this
8929 command.
8930 If CALLBACK is non-nil, it is a function which is called to confirm
8931 that the match should indeed be shown."
8932 (interactive "sRegexp: \nP")
8933 (unless keep-previous
8934 (org-remove-occur-highlights nil nil t))
8935 (push (cons regexp callback) org-occur-parameters)
8936 (let ((cnt 0))
8937 (save-excursion
8938 (goto-char (point-min))
8939 (if (or (not keep-previous) ; do not want to keep
8940 (not org-occur-highlights)) ; no previous matches
8941 ;; hide everything
8942 (org-overview))
8943 (while (re-search-forward regexp nil t)
8944 (when (or (not callback)
8945 (save-match-data (funcall callback)))
8946 (setq cnt (1+ cnt))
8947 (when org-highlight-sparse-tree-matches
8948 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8949 (org-show-context 'occur-tree))))
8950 (when org-remove-highlights-with-change
8951 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8952 nil 'local))
8953 (unless org-sparse-tree-open-archived-trees
8954 (org-hide-archived-subtrees (point-min) (point-max)))
8955 (run-hooks 'org-occur-hook)
8956 (if (interactive-p)
8957 (message "%d match(es) for regexp %s" cnt regexp))
8958 cnt))
8960 (defun org-show-context (&optional key)
8961 "Make sure point and context and visible.
8962 How much context is shown depends upon the variables
8963 `org-show-hierarchy-above', `org-show-following-heading'. and
8964 `org-show-siblings'."
8965 (let ((heading-p (org-on-heading-p t))
8966 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8967 (following-p (org-get-alist-option org-show-following-heading key))
8968 (entry-p (org-get-alist-option org-show-entry-below key))
8969 (siblings-p (org-get-alist-option org-show-siblings key)))
8970 (catch 'exit
8971 ;; Show heading or entry text
8972 (if (and heading-p (not entry-p))
8973 (org-flag-heading nil) ; only show the heading
8974 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8975 (org-show-hidden-entry))) ; show entire entry
8976 (when following-p
8977 ;; Show next sibling, or heading below text
8978 (save-excursion
8979 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8980 (org-flag-heading nil))))
8981 (when siblings-p (org-show-siblings))
8982 (when hierarchy-p
8983 ;; show all higher headings, possibly with siblings
8984 (save-excursion
8985 (while (and (condition-case nil
8986 (progn (org-up-heading-all 1) t)
8987 (error nil))
8988 (not (bobp)))
8989 (org-flag-heading nil)
8990 (when siblings-p (org-show-siblings))))))))
8992 (defun org-reveal (&optional siblings)
8993 "Show current entry, hierarchy above it, and the following headline.
8994 This can be used to show a consistent set of context around locations
8995 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8996 not t for the search context.
8998 With optional argument SIBLINGS, on each level of the hierarchy all
8999 siblings are shown. This repairs the tree structure to what it would
9000 look like when opened with hierarchical calls to `org-cycle'."
9001 (interactive "P")
9002 (let ((org-show-hierarchy-above t)
9003 (org-show-following-heading t)
9004 (org-show-siblings (if siblings t org-show-siblings)))
9005 (org-show-context nil)))
9007 (defun org-highlight-new-match (beg end)
9008 "Highlight from BEG to END and mark the highlight is an occur headline."
9009 (let ((ov (org-make-overlay beg end)))
9010 (org-overlay-put ov 'face 'secondary-selection)
9011 (push ov org-occur-highlights)))
9013 (defun org-remove-occur-highlights (&optional beg end noremove)
9014 "Remove the occur highlights from the buffer.
9015 BEG and END are ignored. If NOREMOVE is nil, remove this function
9016 from the `before-change-functions' in the current buffer."
9017 (interactive)
9018 (unless org-inhibit-highlight-removal
9019 (mapc 'org-delete-overlay org-occur-highlights)
9020 (setq org-occur-highlights nil)
9021 (setq org-occur-parameters nil)
9022 (unless noremove
9023 (remove-hook 'before-change-functions
9024 'org-remove-occur-highlights 'local))))
9026 ;;;; Priorities
9028 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9029 "Regular expression matching the priority indicator.")
9031 (defvar org-remove-priority-next-time nil)
9033 (defun org-priority-up ()
9034 "Increase the priority of the current item."
9035 (interactive)
9036 (org-priority 'up))
9038 (defun org-priority-down ()
9039 "Decrease the priority of the current item."
9040 (interactive)
9041 (org-priority 'down))
9043 (defun org-priority (&optional action)
9044 "Change the priority of an item by ARG.
9045 ACTION can be `set', `up', `down', or a character."
9046 (interactive)
9047 (setq action (or action 'set))
9048 (let (current new news have remove)
9049 (save-excursion
9050 (org-back-to-heading)
9051 (if (looking-at org-priority-regexp)
9052 (setq current (string-to-char (match-string 2))
9053 have t)
9054 (setq current org-default-priority))
9055 (cond
9056 ((or (eq action 'set)
9057 (if (featurep 'xemacs) (characterp action) (integerp action)))
9058 (if (not (eq action 'set))
9059 (setq new action)
9060 (message "Priority %c-%c, SPC to remove: "
9061 org-highest-priority org-lowest-priority)
9062 (setq new (read-char-exclusive)))
9063 (if (and (= (upcase org-highest-priority) org-highest-priority)
9064 (= (upcase org-lowest-priority) org-lowest-priority))
9065 (setq new (upcase new)))
9066 (cond ((equal new ?\ ) (setq remove t))
9067 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9068 (error "Priority must be between `%c' and `%c'"
9069 org-highest-priority org-lowest-priority))))
9070 ((eq action 'up)
9071 (if (and (not have) (eq last-command this-command))
9072 (setq new org-lowest-priority)
9073 (setq new (if (and org-priority-start-cycle-with-default (not have))
9074 org-default-priority (1- current)))))
9075 ((eq action 'down)
9076 (if (and (not have) (eq last-command this-command))
9077 (setq new org-highest-priority)
9078 (setq new (if (and org-priority-start-cycle-with-default (not have))
9079 org-default-priority (1+ current)))))
9080 (t (error "Invalid action")))
9081 (if (or (< (upcase new) org-highest-priority)
9082 (> (upcase new) org-lowest-priority))
9083 (setq remove t))
9084 (setq news (format "%c" new))
9085 (if have
9086 (if remove
9087 (replace-match "" t t nil 1)
9088 (replace-match news t t nil 2))
9089 (if remove
9090 (error "No priority cookie found in line")
9091 (looking-at org-todo-line-regexp)
9092 (if (match-end 2)
9093 (progn
9094 (goto-char (match-end 2))
9095 (insert " [#" news "]"))
9096 (goto-char (match-beginning 3))
9097 (insert "[#" news "] ")))))
9098 (org-preserve-lc (org-set-tags nil 'align))
9099 (if remove
9100 (message "Priority removed")
9101 (message "Priority of current item set to %s" news))))
9104 (defun org-get-priority (s)
9105 "Find priority cookie and return priority."
9106 (save-match-data
9107 (if (not (string-match org-priority-regexp s))
9108 (* 1000 (- org-lowest-priority org-default-priority))
9109 (* 1000 (- org-lowest-priority
9110 (string-to-char (match-string 2 s)))))))
9112 ;;;; Tags
9114 (defvar org-agenda-archives-mode)
9115 (defun org-scan-tags (action matcher &optional todo-only)
9116 "Scan headline tags with inheritance and produce output ACTION.
9118 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9119 or `agenda' to produce an entry list for an agenda view. It can also be
9120 a Lisp form or a function that should be called at each matched headline, in
9121 this case the return value is a list of all return values from these calls.
9123 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9124 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9125 only lines with a TODO keyword are included in the output."
9126 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9127 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9128 (org-re
9129 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9130 (props (list 'face 'default
9131 'done-face 'org-done
9132 'undone-face 'default
9133 'mouse-face 'highlight
9134 'org-not-done-regexp org-not-done-regexp
9135 'org-todo-regexp org-todo-regexp
9136 'keymap org-agenda-keymap
9137 'help-echo
9138 (format "mouse-2 or RET jump to org file %s"
9139 (abbreviate-file-name
9140 (or (buffer-file-name (buffer-base-buffer))
9141 (buffer-name (buffer-base-buffer)))))))
9142 (case-fold-search nil)
9143 lspos tags tags-list
9144 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9145 (llast 0) rtn rtn1 level category i txt
9146 todo marker entry priority)
9147 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9148 (setq action (list 'lambda nil action)))
9149 (save-excursion
9150 (goto-char (point-min))
9151 (when (eq action 'sparse-tree)
9152 (org-overview)
9153 (org-remove-occur-highlights))
9154 (while (re-search-forward re nil t)
9155 (catch :skip
9156 (setq todo (if (match-end 1) (match-string 2))
9157 tags (if (match-end 4) (match-string 4)))
9158 (goto-char (setq lspos (1+ (match-beginning 0))))
9159 (setq level (org-reduced-level (funcall outline-level))
9160 category (org-get-category))
9161 (setq i llast llast level)
9162 ;; remove tag lists from same and sublevels
9163 (while (>= i level)
9164 (when (setq entry (assoc i tags-alist))
9165 (setq tags-alist (delete entry tags-alist)))
9166 (setq i (1- i)))
9167 ;; add the next tags
9168 (when tags
9169 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9170 tags-alist
9171 (cons (cons level tags) tags-alist)))
9172 ;; compile tags for current headline
9173 (setq tags-list
9174 (if org-use-tag-inheritance
9175 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9176 tags))
9177 (when org-use-tag-inheritance
9178 (setcdr (car tags-alist)
9179 (mapcar (lambda (x)
9180 (setq x (copy-sequence x))
9181 (org-add-prop-inherited x))
9182 (cdar tags-alist))))
9183 (when (and tags org-use-tag-inheritance
9184 (not (eq t org-use-tag-inheritance)))
9185 ;; selective inheritance, remove uninherited ones
9186 (setcdr (car tags-alist)
9187 (org-remove-uniherited-tags (cdar tags-alist))))
9188 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9189 (let ((case-fold-search t)) (eval matcher))
9191 (not (member org-archive-tag tags-list))
9192 ;; we have an archive tag, should we use this anyway?
9193 (or (not org-agenda-skip-archived-trees)
9194 (and (eq action 'agenda) org-agenda-archives-mode))))
9195 (unless (eq action 'sparse-tree) (org-agenda-skip))
9197 ;; select this headline
9199 (cond
9200 ((eq action 'sparse-tree)
9201 (and org-highlight-sparse-tree-matches
9202 (org-get-heading) (match-end 0)
9203 (org-highlight-new-match
9204 (match-beginning 0) (match-beginning 1)))
9205 (org-show-context 'tags-tree))
9206 ((eq action 'agenda)
9207 (setq txt (org-format-agenda-item
9209 (concat
9210 (if org-tags-match-list-sublevels
9211 (make-string (1- level) ?.) "")
9212 (org-get-heading))
9213 category tags-list)
9214 priority (org-get-priority txt))
9215 (goto-char lspos)
9216 (setq marker (org-agenda-new-marker))
9217 (org-add-props txt props
9218 'org-marker marker 'org-hd-marker marker 'org-category category
9219 'priority priority 'type "tagsmatch")
9220 (push txt rtn))
9221 ((functionp action)
9222 (save-excursion
9223 (setq rtn1 (funcall action))
9224 (push rtn1 rtn))
9225 (goto-char (point-at-eol)))
9226 (t (error "Invalid action")))
9228 ;; if we are to skip sublevels, jump to end of subtree
9229 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9230 (when (and (eq action 'sparse-tree)
9231 (not org-sparse-tree-open-archived-trees))
9232 (org-hide-archived-subtrees (point-min) (point-max)))
9233 (nreverse rtn)))
9235 (defun org-remove-uniherited-tags (tags)
9236 "Remove all tags that are not inherited from the list TAGS."
9237 (cond
9238 ((eq org-use-tag-inheritance t)
9239 (if org-tags-exclude-from-inheritance
9240 (org-delete-all org-tags-exclude-from-inheritance tags)
9241 tags))
9242 ((not org-use-tag-inheritance) nil)
9243 ((stringp org-use-tag-inheritance)
9244 (delq nil (mapcar
9245 (lambda (x)
9246 (if (and (string-match org-use-tag-inheritance x)
9247 (not (member x org-tags-exclude-from-inheritance)))
9248 x nil))
9249 tags)))
9250 ((listp org-use-tag-inheritance)
9251 (delq nil (mapcar
9252 (lambda (x)
9253 (if (member x org-use-tag-inheritance) x nil))
9254 tags)))))
9256 (defvar todo-only) ;; dynamically scoped
9258 (defun org-tags-sparse-tree (&optional todo-only match)
9259 "Create a sparse tree according to tags string MATCH.
9260 MATCH can contain positive and negative selection of tags, like
9261 \"+WORK+URGENT-WITHBOSS\".
9262 If optional argument TODO-ONLY is non-nil, only select lines that are
9263 also TODO lines."
9264 (interactive "P")
9265 (org-prepare-agenda-buffers (list (current-buffer)))
9266 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9268 (defvar org-cached-props nil)
9269 (defun org-cached-entry-get (pom property)
9270 (if (or (eq t org-use-property-inheritance)
9271 (and (stringp org-use-property-inheritance)
9272 (string-match org-use-property-inheritance property))
9273 (and (listp org-use-property-inheritance)
9274 (member property org-use-property-inheritance)))
9275 ;; Caching is not possible, check it directly
9276 (org-entry-get pom property 'inherit)
9277 ;; Get all properties, so that we can do complicated checks easily
9278 (cdr (assoc property (or org-cached-props
9279 (setq org-cached-props
9280 (org-entry-properties pom)))))))
9282 (defun org-global-tags-completion-table (&optional files)
9283 "Return the list of all tags in all agenda buffer/files."
9284 (save-excursion
9285 (org-uniquify
9286 (delq nil
9287 (apply 'append
9288 (mapcar
9289 (lambda (file)
9290 (set-buffer (find-file-noselect file))
9291 (append (org-get-buffer-tags)
9292 (mapcar (lambda (x) (if (stringp (car-safe x))
9293 (list (car-safe x)) nil))
9294 org-tag-alist)))
9295 (if (and files (car files))
9296 files
9297 (org-agenda-files))))))))
9299 (defun org-make-tags-matcher (match)
9300 "Create the TAGS//TODO matcher form for the selection string MATCH."
9301 ;; todo-only is scoped dynamically into this function, and the function
9302 ;; may change it if the matcher asks for it.
9303 (unless match
9304 ;; Get a new match request, with completion
9305 (let ((org-last-tags-completion-table
9306 (org-global-tags-completion-table)))
9307 (setq match (org-ido-completing-read
9308 "Match: " 'org-tags-completion-function nil nil nil
9309 'org-tags-history))))
9311 ;; Parse the string and create a lisp form
9312 (let ((match0 match)
9313 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9314 minus tag mm
9315 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9316 orterms term orlist re-p str-p level-p level-op time-p
9317 prop-p pn pv po cat-p gv rest)
9318 (if (string-match "/+" match)
9319 ;; match contains also a todo-matching request
9320 (progn
9321 (setq tagsmatch (substring match 0 (match-beginning 0))
9322 todomatch (substring match (match-end 0)))
9323 (if (string-match "^!" todomatch)
9324 (setq todo-only t todomatch (substring todomatch 1)))
9325 (if (string-match "^\\s-*$" todomatch)
9326 (setq todomatch nil)))
9327 ;; only matching tags
9328 (setq tagsmatch match todomatch nil))
9330 ;; Make the tags matcher
9331 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9332 (setq tagsmatcher t)
9333 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9334 (while (setq term (pop orterms))
9335 (while (and (equal (substring term -1) "\\") orterms)
9336 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9337 (while (string-match re term)
9338 (setq rest (substring term (match-end 0))
9339 minus (and (match-end 1)
9340 (equal (match-string 1 term) "-"))
9341 tag (match-string 2 term)
9342 re-p (equal (string-to-char tag) ?{)
9343 level-p (match-end 4)
9344 prop-p (match-end 5)
9345 mm (cond
9346 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9347 (level-p
9348 (setq level-op (org-op-to-function (match-string 3 term)))
9349 `(,level-op level ,(string-to-number
9350 (match-string 4 term))))
9351 (prop-p
9352 (setq pn (match-string 5 term)
9353 po (match-string 6 term)
9354 pv (match-string 7 term)
9355 cat-p (equal pn "CATEGORY")
9356 re-p (equal (string-to-char pv) ?{)
9357 str-p (equal (string-to-char pv) ?\")
9358 time-p (save-match-data
9359 (string-match "^\"[[<].*[]>]\"$" pv))
9360 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9361 (if time-p (setq pv (org-matcher-time pv)))
9362 (setq po (org-op-to-function po (if time-p 'time str-p)))
9363 (cond
9364 ((equal pn "CATEGORY")
9365 (setq gv '(get-text-property (point) 'org-category)))
9366 ((equal pn "TODO")
9367 (setq gv 'todo))
9369 (setq gv `(org-cached-entry-get nil ,pn))))
9370 (if re-p
9371 (if (eq po 'org<>)
9372 `(not (string-match ,pv (or ,gv "")))
9373 `(string-match ,pv (or ,gv "")))
9374 (if str-p
9375 `(,po (or ,gv "") ,pv)
9376 `(,po (string-to-number (or ,gv ""))
9377 ,(string-to-number pv) ))))
9378 (t `(member ,(downcase tag) tags-list)))
9379 mm (if minus (list 'not mm) mm)
9380 term rest)
9381 (push mm tagsmatcher))
9382 (push (if (> (length tagsmatcher) 1)
9383 (cons 'and tagsmatcher)
9384 (car tagsmatcher))
9385 orlist)
9386 (setq tagsmatcher nil))
9387 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9388 (setq tagsmatcher
9389 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9390 ;; Make the todo matcher
9391 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9392 (setq todomatcher t)
9393 (setq orterms (org-split-string todomatch "|") orlist nil)
9394 (while (setq term (pop orterms))
9395 (while (string-match re term)
9396 (setq minus (and (match-end 1)
9397 (equal (match-string 1 term) "-"))
9398 kwd (match-string 2 term)
9399 re-p (equal (string-to-char kwd) ?{)
9400 term (substring term (match-end 0))
9401 mm (if re-p
9402 `(string-match ,(substring kwd 1 -1) todo)
9403 (list 'equal 'todo kwd))
9404 mm (if minus (list 'not mm) mm))
9405 (push mm todomatcher))
9406 (push (if (> (length todomatcher) 1)
9407 (cons 'and todomatcher)
9408 (car todomatcher))
9409 orlist)
9410 (setq todomatcher nil))
9411 (setq todomatcher (if (> (length orlist) 1)
9412 (cons 'or orlist) (car orlist))))
9414 ;; Return the string and lisp forms of the matcher
9415 (setq matcher (if todomatcher
9416 (list 'and tagsmatcher todomatcher)
9417 tagsmatcher))
9418 (cons match0 matcher)))
9420 (defun org-op-to-function (op &optional stringp)
9421 "Turn an operator into the appropriate function."
9422 (setq op
9423 (cond
9424 ((equal op "<" ) '(< string< org-time<))
9425 ((equal op ">" ) '(> org-string> org-time>))
9426 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9427 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9428 ((member op '("=" "==")) '(= string= org-time=))
9429 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9430 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9432 (defun org<> (a b) (not (= a b)))
9433 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9434 (defun org-string>= (a b) (not (string< a b)))
9435 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9436 (defun org-string<> (a b) (not (string= a b)))
9437 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9438 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9439 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9440 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9441 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9442 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9443 (defun org-2ft (s)
9444 "Convert S to a floating point time.
9445 If S is already a number, just return it. If it is a string, parse
9446 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9447 (cond
9448 ((numberp s) s)
9449 ((stringp s)
9450 (condition-case nil
9451 (float-time (apply 'encode-time (org-parse-time-string s)))
9452 (error 0.)))
9453 (t 0.)))
9455 (defun org-time-today ()
9456 "Time in seconds today at 0:00.
9457 Returns the float number of seconds since the beginning of the
9458 epoch to the beginning of today (00:00)."
9459 (float-time (apply 'encode-time
9460 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9462 (defun org-matcher-time (s)
9463 "Interpret a time comparison value."
9464 (save-match-data
9465 (cond
9466 ((string= s "<now>") (float-time))
9467 ((string= s "<today>") (org-time-today))
9468 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9469 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9470 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9471 (+ (org-time-today)
9472 (* (string-to-number (match-string 1 s))
9473 (cdr (assoc (match-string 2 s)
9474 '(("d" . 86400.0) ("w" . 604800.0)
9475 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9476 (t (org-2ft s)))))
9478 (defun org-match-any-p (re list)
9479 "Does re match any element of list?"
9480 (setq list (mapcar (lambda (x) (string-match re x)) list))
9481 (delq nil list))
9483 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9484 (defvar org-tags-overlay (org-make-overlay 1 1))
9485 (org-detach-overlay org-tags-overlay)
9487 (defun org-get-local-tags-at (&optional pos)
9488 "Get a list of tags defined in the current headline."
9489 (org-get-tags-at pos 'local))
9491 (defun org-get-local-tags ()
9492 "Get a list of tags defined in the current headline."
9493 (org-get-tags-at nil 'local))
9495 (defun org-get-tags-at (&optional pos local)
9496 "Get a list of all headline tags applicable at POS.
9497 POS defaults to point. If tags are inherited, the list contains
9498 the targets in the same sequence as the headlines appear, i.e.
9499 the tags of the current headline come last.
9500 When LOCAL is non-nil, only return tags from the current headline,
9501 ignore inherited ones."
9502 (interactive)
9503 (let (tags ltags lastpos parent)
9504 (save-excursion
9505 (save-restriction
9506 (widen)
9507 (goto-char (or pos (point)))
9508 (save-match-data
9509 (catch 'done
9510 (condition-case nil
9511 (progn
9512 (org-back-to-heading t)
9513 (while (not (equal lastpos (point)))
9514 (setq lastpos (point))
9515 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9516 (setq ltags (org-split-string
9517 (org-match-string-no-properties 1) ":"))
9518 (when parent
9519 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9520 (setq tags (append
9521 (if parent
9522 (org-remove-uniherited-tags ltags)
9523 ltags)
9524 tags)))
9525 (or org-use-tag-inheritance (throw 'done t))
9526 (if local (throw 'done t))
9527 (org-up-heading-all 1)
9528 (setq parent t)))
9529 (error nil)))))
9530 (append (org-remove-uniherited-tags org-file-tags) tags))))
9532 (defun org-add-prop-inherited (s)
9533 (add-text-properties 0 (length s) '(inherited t) s)
9536 (defun org-toggle-tag (tag &optional onoff)
9537 "Toggle the tag TAG for the current line.
9538 If ONOFF is `on' or `off', don't toggle but set to this state."
9539 (let (res current)
9540 (save-excursion
9541 (org-back-to-heading t)
9542 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9543 (point-at-eol) t)
9544 (progn
9545 (setq current (match-string 1))
9546 (replace-match ""))
9547 (setq current ""))
9548 (setq current (nreverse (org-split-string current ":")))
9549 (cond
9550 ((eq onoff 'on)
9551 (setq res t)
9552 (or (member tag current) (push tag current)))
9553 ((eq onoff 'off)
9554 (or (not (member tag current)) (setq current (delete tag current))))
9555 (t (if (member tag current)
9556 (setq current (delete tag current))
9557 (setq res t)
9558 (push tag current))))
9559 (end-of-line 1)
9560 (if current
9561 (progn
9562 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9563 (org-set-tags nil t))
9564 (delete-horizontal-space))
9565 (run-hooks 'org-after-tags-change-hook))
9566 res))
9568 (defun org-align-tags-here (to-col)
9569 ;; Assumes that this is a headline
9570 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9571 (beginning-of-line 1)
9572 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9573 (< pos (match-beginning 2)))
9574 (progn
9575 (setq tags-l (- (match-end 2) (match-beginning 2)))
9576 (goto-char (match-beginning 1))
9577 (insert " ")
9578 (delete-region (point) (1+ (match-beginning 2)))
9579 (setq ncol (max (1+ (current-column))
9580 (1+ col)
9581 (if (> to-col 0)
9582 to-col
9583 (- (abs to-col) tags-l))))
9584 (setq p (point))
9585 (insert (make-string (- ncol (current-column)) ?\ ))
9586 (setq ncol (current-column))
9587 (when indent-tabs-mode (tabify p (point-at-eol)))
9588 (org-move-to-column (min ncol col) t))
9589 (goto-char pos))))
9591 (defun org-set-tags-command (&optional arg just-align)
9592 "Call the set-tags command for the current entry."
9593 (interactive "P")
9594 (if (org-on-heading-p)
9595 (org-set-tags arg just-align)
9596 (save-excursion
9597 (org-back-to-heading t)
9598 (org-set-tags arg just-align))))
9600 (defun org-set-tags (&optional arg just-align)
9601 "Set the tags for the current headline.
9602 With prefix ARG, realign all tags in headings in the current buffer."
9603 (interactive "P")
9604 (let* ((re (concat "^" outline-regexp))
9605 (current (org-get-tags-string))
9606 (col (current-column))
9607 (org-setting-tags t)
9608 table current-tags inherited-tags ; computed below when needed
9609 tags p0 c0 c1 rpl)
9610 (if arg
9611 (save-excursion
9612 (goto-char (point-min))
9613 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9614 (while (re-search-forward re nil t)
9615 (org-set-tags nil t)
9616 (end-of-line 1)))
9617 (message "All tags realigned to column %d" org-tags-column))
9618 (if just-align
9619 (setq tags current)
9620 ;; Get a new set of tags from the user
9621 (save-excursion
9622 (setq table (or org-tag-alist (org-get-buffer-tags))
9623 org-last-tags-completion-table table
9624 current-tags (org-split-string current ":")
9625 inherited-tags (nreverse
9626 (nthcdr (length current-tags)
9627 (nreverse (org-get-tags-at))))
9628 tags
9629 (if (or (eq t org-use-fast-tag-selection)
9630 (and org-use-fast-tag-selection
9631 (delq nil (mapcar 'cdr table))))
9632 (org-fast-tag-selection
9633 current-tags inherited-tags table
9634 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9635 (let ((org-add-colon-after-tag-completion t))
9636 (org-trim
9637 (org-without-partial-completion
9638 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9639 nil nil current 'org-tags-history)))))))
9640 (while (string-match "[-+&]+" tags)
9641 ;; No boolean logic, just a list
9642 (setq tags (replace-match ":" t t tags))))
9644 (if (string-match "\\`[\t ]*\\'" tags)
9645 (setq tags "")
9646 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9647 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9649 ;; Insert new tags at the correct column
9650 (beginning-of-line 1)
9651 (cond
9652 ((and (equal current "") (equal tags "")))
9653 ((re-search-forward
9654 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9655 (point-at-eol) t)
9656 (if (equal tags "")
9657 (setq rpl "")
9658 (goto-char (match-beginning 0))
9659 (setq c0 (current-column) p0 (point)
9660 c1 (max (1+ c0) (if (> org-tags-column 0)
9661 org-tags-column
9662 (- (- org-tags-column) (length tags))))
9663 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9664 (replace-match rpl t t)
9665 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9666 tags)
9667 (t (error "Tags alignment failed")))
9668 (org-move-to-column col)
9669 (unless just-align
9670 (run-hooks 'org-after-tags-change-hook)))))
9672 (defun org-change-tag-in-region (beg end tag off)
9673 "Add or remove TAG for each entry in the region.
9674 This works in the agenda, and also in an org-mode buffer."
9675 (interactive
9676 (list (region-beginning) (region-end)
9677 (let ((org-last-tags-completion-table
9678 (if (org-mode-p)
9679 (org-get-buffer-tags)
9680 (org-global-tags-completion-table))))
9681 (org-ido-completing-read
9682 "Tag: " 'org-tags-completion-function nil nil nil
9683 'org-tags-history))
9684 (progn
9685 (message "[s]et or [r]emove? ")
9686 (equal (read-char-exclusive) ?r))))
9687 (if (fboundp 'deactivate-mark) (deactivate-mark))
9688 (let ((agendap (equal major-mode 'org-agenda-mode))
9689 l1 l2 m buf pos newhead (cnt 0))
9690 (goto-char end)
9691 (setq l2 (1- (org-current-line)))
9692 (goto-char beg)
9693 (setq l1 (org-current-line))
9694 (loop for l from l1 to l2 do
9695 (goto-line l)
9696 (setq m (get-text-property (point) 'org-hd-marker))
9697 (when (or (and (org-mode-p) (org-on-heading-p))
9698 (and agendap m))
9699 (setq buf (if agendap (marker-buffer m) (current-buffer))
9700 pos (if agendap m (point)))
9701 (with-current-buffer buf
9702 (save-excursion
9703 (save-restriction
9704 (goto-char pos)
9705 (setq cnt (1+ cnt))
9706 (org-toggle-tag tag (if off 'off 'on))
9707 (setq newhead (org-get-heading)))))
9708 (and agendap (org-agenda-change-all-lines newhead m))))
9709 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9711 (defun org-tags-completion-function (string predicate &optional flag)
9712 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9713 (confirm (lambda (x) (stringp (car x)))))
9714 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9715 (setq s1 (match-string 1 string)
9716 s2 (match-string 2 string))
9717 (setq s1 "" s2 string))
9718 (cond
9719 ((eq flag nil)
9720 ;; try completion
9721 (setq rtn (try-completion s2 ctable confirm))
9722 (if (stringp rtn)
9723 (setq rtn
9724 (concat s1 s2 (substring rtn (length s2))
9725 (if (and org-add-colon-after-tag-completion
9726 (assoc rtn ctable))
9727 ":" ""))))
9728 rtn)
9729 ((eq flag t)
9730 ;; all-completions
9731 (all-completions s2 ctable confirm)
9733 ((eq flag 'lambda)
9734 ;; exact match?
9735 (assoc s2 ctable)))
9738 (defun org-fast-tag-insert (kwd tags face &optional end)
9739 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9740 (insert (format "%-12s" (concat kwd ":"))
9741 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9742 (or end "")))
9744 (defun org-fast-tag-show-exit (flag)
9745 (save-excursion
9746 (goto-line 3)
9747 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9748 (replace-match ""))
9749 (when flag
9750 (end-of-line 1)
9751 (org-move-to-column (- (window-width) 19) t)
9752 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9754 (defun org-set-current-tags-overlay (current prefix)
9755 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9756 (if (featurep 'xemacs)
9757 (org-overlay-display org-tags-overlay (concat prefix s)
9758 'secondary-selection)
9759 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9760 (org-overlay-display org-tags-overlay (concat prefix s)))))
9762 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9763 "Fast tag selection with single keys.
9764 CURRENT is the current list of tags in the headline, INHERITED is the
9765 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9766 possibly with grouping information. TODO-TABLE is a similar table with
9767 TODO keywords, should these have keys assigned to them.
9768 If the keys are nil, a-z are automatically assigned.
9769 Returns the new tags string, or nil to not change the current settings."
9770 (let* ((fulltable (append table todo-table))
9771 (maxlen (apply 'max (mapcar
9772 (lambda (x)
9773 (if (stringp (car x)) (string-width (car x)) 0))
9774 fulltable)))
9775 (buf (current-buffer))
9776 (expert (eq org-fast-tag-selection-single-key 'expert))
9777 (buffer-tags nil)
9778 (fwidth (+ maxlen 3 1 3))
9779 (ncol (/ (- (window-width) 4) fwidth))
9780 (i-face 'org-done)
9781 (c-face 'org-todo)
9782 tg cnt e c char c1 c2 ntable tbl rtn
9783 ov-start ov-end ov-prefix
9784 (exit-after-next org-fast-tag-selection-single-key)
9785 (done-keywords org-done-keywords)
9786 groups ingroup)
9787 (save-excursion
9788 (beginning-of-line 1)
9789 (if (looking-at
9790 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9791 (setq ov-start (match-beginning 1)
9792 ov-end (match-end 1)
9793 ov-prefix "")
9794 (setq ov-start (1- (point-at-eol))
9795 ov-end (1+ ov-start))
9796 (skip-chars-forward "^\n\r")
9797 (setq ov-prefix
9798 (concat
9799 (buffer-substring (1- (point)) (point))
9800 (if (> (current-column) org-tags-column)
9802 (make-string (- org-tags-column (current-column)) ?\ ))))))
9803 (org-move-overlay org-tags-overlay ov-start ov-end)
9804 (save-window-excursion
9805 (if expert
9806 (set-buffer (get-buffer-create " *Org tags*"))
9807 (delete-other-windows)
9808 (split-window-vertically)
9809 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9810 (erase-buffer)
9811 (org-set-local 'org-done-keywords done-keywords)
9812 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9813 (org-fast-tag-insert "Current" current c-face "\n\n")
9814 (org-fast-tag-show-exit exit-after-next)
9815 (org-set-current-tags-overlay current ov-prefix)
9816 (setq tbl fulltable char ?a cnt 0)
9817 (while (setq e (pop tbl))
9818 (cond
9819 ((equal e '(:startgroup))
9820 (push '() groups) (setq ingroup t)
9821 (when (not (= cnt 0))
9822 (setq cnt 0)
9823 (insert "\n"))
9824 (insert "{ "))
9825 ((equal e '(:endgroup))
9826 (setq ingroup nil cnt 0)
9827 (insert "}\n"))
9829 (setq tg (car e) c2 nil)
9830 (if (cdr e)
9831 (setq c (cdr e))
9832 ;; automatically assign a character.
9833 (setq c1 (string-to-char
9834 (downcase (substring
9835 tg (if (= (string-to-char tg) ?@) 1 0)))))
9836 (if (or (rassoc c1 ntable) (rassoc c1 table))
9837 (while (or (rassoc char ntable) (rassoc char table))
9838 (setq char (1+ char)))
9839 (setq c2 c1))
9840 (setq c (or c2 char)))
9841 (if ingroup (push tg (car groups)))
9842 (setq tg (org-add-props tg nil 'face
9843 (cond
9844 ((not (assoc tg table))
9845 (org-get-todo-face tg))
9846 ((member tg current) c-face)
9847 ((member tg inherited) i-face)
9848 (t nil))))
9849 (if (and (= cnt 0) (not ingroup)) (insert " "))
9850 (insert "[" c "] " tg (make-string
9851 (- fwidth 4 (length tg)) ?\ ))
9852 (push (cons tg c) ntable)
9853 (when (= (setq cnt (1+ cnt)) ncol)
9854 (insert "\n")
9855 (if ingroup (insert " "))
9856 (setq cnt 0)))))
9857 (setq ntable (nreverse ntable))
9858 (insert "\n")
9859 (goto-char (point-min))
9860 (if (not expert) (org-fit-window-to-buffer))
9861 (setq rtn
9862 (catch 'exit
9863 (while t
9864 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9865 (if groups " [!] no groups" " [!]groups")
9866 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9867 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9868 (cond
9869 ((= c ?\r) (throw 'exit t))
9870 ((= c ?!)
9871 (setq groups (not groups))
9872 (goto-char (point-min))
9873 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9874 ((= c ?\C-c)
9875 (if (not expert)
9876 (org-fast-tag-show-exit
9877 (setq exit-after-next (not exit-after-next)))
9878 (setq expert nil)
9879 (delete-other-windows)
9880 (split-window-vertically)
9881 (org-switch-to-buffer-other-window " *Org tags*")
9882 (org-fit-window-to-buffer)))
9883 ((or (= c ?\C-g)
9884 (and (= c ?q) (not (rassoc c ntable))))
9885 (org-detach-overlay org-tags-overlay)
9886 (setq quit-flag t))
9887 ((= c ?\ )
9888 (setq current nil)
9889 (if exit-after-next (setq exit-after-next 'now)))
9890 ((= c ?\t)
9891 (condition-case nil
9892 (setq tg (org-ido-completing-read
9893 "Tag: "
9894 (or buffer-tags
9895 (with-current-buffer buf
9896 (org-get-buffer-tags)))))
9897 (quit (setq tg "")))
9898 (when (string-match "\\S-" tg)
9899 (add-to-list 'buffer-tags (list tg))
9900 (if (member tg current)
9901 (setq current (delete tg current))
9902 (push tg current)))
9903 (if exit-after-next (setq exit-after-next 'now)))
9904 ((setq e (rassoc c todo-table) tg (car e))
9905 (with-current-buffer buf
9906 (save-excursion (org-todo tg)))
9907 (if exit-after-next (setq exit-after-next 'now)))
9908 ((setq e (rassoc c ntable) tg (car e))
9909 (if (member tg current)
9910 (setq current (delete tg current))
9911 (loop for g in groups do
9912 (if (member tg g)
9913 (mapc (lambda (x)
9914 (setq current (delete x current)))
9915 g)))
9916 (push tg current))
9917 (if exit-after-next (setq exit-after-next 'now))))
9919 ;; Create a sorted list
9920 (setq current
9921 (sort current
9922 (lambda (a b)
9923 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9924 (if (eq exit-after-next 'now) (throw 'exit t))
9925 (goto-char (point-min))
9926 (beginning-of-line 2)
9927 (delete-region (point) (point-at-eol))
9928 (org-fast-tag-insert "Current" current c-face)
9929 (org-set-current-tags-overlay current ov-prefix)
9930 (while (re-search-forward
9931 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9932 (setq tg (match-string 1))
9933 (add-text-properties
9934 (match-beginning 1) (match-end 1)
9935 (list 'face
9936 (cond
9937 ((member tg current) c-face)
9938 ((member tg inherited) i-face)
9939 (t (get-text-property (match-beginning 1) 'face))))))
9940 (goto-char (point-min)))))
9941 (org-detach-overlay org-tags-overlay)
9942 (if rtn
9943 (mapconcat 'identity current ":")
9944 nil))))
9946 (defun org-get-tags-string ()
9947 "Get the TAGS string in the current headline."
9948 (unless (org-on-heading-p t)
9949 (error "Not on a heading"))
9950 (save-excursion
9951 (beginning-of-line 1)
9952 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9953 (org-match-string-no-properties 1)
9954 "")))
9956 (defun org-get-tags ()
9957 "Get the list of tags specified in the current headline."
9958 (org-split-string (org-get-tags-string) ":"))
9960 (defun org-get-buffer-tags ()
9961 "Get a table of all tags used in the buffer, for completion."
9962 (let (tags)
9963 (save-excursion
9964 (goto-char (point-min))
9965 (while (re-search-forward
9966 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9967 (when (equal (char-after (point-at-bol 0)) ?*)
9968 (mapc (lambda (x) (add-to-list 'tags x))
9969 (org-split-string (org-match-string-no-properties 1) ":")))))
9970 (mapcar 'list tags)))
9972 ;;;; The mapping API
9974 ;;;###autoload
9975 (defun org-map-entries (func &optional match scope &rest skip)
9976 "Call FUNC at each headline selected by MATCH in SCOPE.
9978 FUNC is a function or a lisp form. The function will be called without
9979 arguments, with the cursor positioned at the beginning of the headline.
9980 The return values of all calls to the function will be collected and
9981 returned as a list.
9983 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9984 Only headlines that are matched by this query will be considered during
9985 the iteration. When MATCH is nil or t, all headlines will be
9986 visited by the iteration.
9988 SCOPE determines the scope of this command. It can be any of:
9990 nil The current buffer, respecting the restriction if any
9991 tree The subtree started with the entry at point
9992 file The current buffer, without restriction
9993 file-with-archives
9994 The current buffer, and any archives associated with it
9995 agenda All agenda files
9996 agenda-with-archives
9997 All agenda files with any archive files associated with them
9998 \(file1 file2 ...)
9999 If this is a list, all files in the list will be scanned
10001 The remaining args are treated as settings for the skipping facilities of
10002 the scanner. The following items can be given here:
10004 archive skip trees with the archive tag.
10005 comment skip trees with the COMMENT keyword
10006 function or Emacs Lisp form:
10007 will be used as value for `org-agenda-skip-function', so whenever
10008 the the function returns t, FUNC will not be called for that
10009 entry and search will continue from the point where the
10010 function leaves it."
10011 (let* ((org-agenda-archives-mode nil) ; just to make sure
10012 (org-agenda-skip-archived-trees (memq 'archive skip))
10013 (org-agenda-skip-comment-trees (memq 'comment skip))
10014 (org-agenda-skip-function
10015 (car (org-delete-all '(comment archive) skip)))
10016 (org-tags-match-list-sublevels t)
10017 matcher pos file res
10018 org-todo-keywords-for-agenda
10019 org-done-keywords-for-agenda
10020 org-todo-keyword-alist-for-agenda
10021 org-tag-alist-for-agenda)
10023 (cond
10024 ((eq match t) (setq matcher t))
10025 ((eq match nil) (setq matcher t))
10026 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10028 (when (eq scope 'tree)
10029 (org-back-to-heading t)
10030 (org-narrow-to-subtree)
10031 (setq scope nil))
10033 (if (not scope)
10034 (progn
10035 (org-prepare-agenda-buffers
10036 (list (buffer-file-name (current-buffer))))
10037 (org-scan-tags func matcher))
10038 ;; Get the right scope
10039 (setq pos (point))
10040 (cond
10041 ((and scope (listp scope) (symbolp (car scope)))
10042 (setq scope (eval scope)))
10043 ((eq scope 'agenda)
10044 (setq scope (org-agenda-files t)))
10045 ((eq scope 'agenda-with-archives)
10046 (setq scope (org-agenda-files t))
10047 (setq scope (org-add-archive-files scope)))
10048 ((eq scope 'file)
10049 (setq scope (list (buffer-file-name))))
10050 ((eq scope 'file-with-archives)
10051 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10052 (org-prepare-agenda-buffers scope)
10053 (while (setq file (pop scope))
10054 (with-current-buffer (org-find-base-buffer-visiting file)
10055 (save-excursion
10056 (save-restriction
10057 (widen)
10058 (goto-char (point-min))
10059 (setq res (append res (org-scan-tags func matcher)))))))
10060 res)))
10062 ;;;; Properties
10064 ;;; Setting and retrieving properties
10066 (defconst org-special-properties
10067 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10068 "TIMESTAMP" "TIMESTAMP_IA")
10069 "The special properties valid in Org-mode.
10071 These are properties that are not defined in the property drawer,
10072 but in some other way.")
10074 (defconst org-default-properties
10075 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10076 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10077 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10078 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10079 "Some properties that are used by Org-mode for various purposes.
10080 Being in this list makes sure that they are offered for completion.")
10082 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10083 "Regular expression matching the first line of a property drawer.")
10085 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10086 "Regular expression matching the first line of a property drawer.")
10088 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10089 "Regular expression matching the first line of a property drawer.")
10091 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10092 "Regular expression matching the first line of a property drawer.")
10094 (defconst org-property-drawer-re
10095 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10096 org-property-end-re "\\)\n?")
10097 "Matches an entire property drawer.")
10099 (defconst org-clock-drawer-re
10100 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10101 org-property-end-re "\\)\n?")
10102 "Matches an entire clock drawer.")
10104 (defun org-property-action ()
10105 "Do an action on properties."
10106 (interactive)
10107 (let (c)
10108 (org-at-property-p)
10109 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10110 (setq c (read-char-exclusive))
10111 (cond
10112 ((equal c ?s)
10113 (call-interactively 'org-set-property))
10114 ((equal c ?d)
10115 (call-interactively 'org-delete-property))
10116 ((equal c ?D)
10117 (call-interactively 'org-delete-property-globally))
10118 ((equal c ?c)
10119 (call-interactively 'org-compute-property-at-point))
10120 (t (error "No such property action %c" c)))))
10122 (defun org-at-property-p ()
10123 "Is the cursor in a property line?"
10124 ;; FIXME: Does not check if we are actually in the drawer.
10125 ;; FIXME: also returns true on any drawers.....
10126 ;; This is used by C-c C-c for property action.
10127 (save-excursion
10128 (beginning-of-line 1)
10129 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10131 (defun org-get-property-block (&optional beg end force)
10132 "Return the (beg . end) range of the body of the property drawer.
10133 BEG and END can be beginning and end of subtree, if not given
10134 they will be found.
10135 If the drawer does not exist and FORCE is non-nil, create the drawer."
10136 (catch 'exit
10137 (save-excursion
10138 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10139 (end (or end (progn (outline-next-heading) (point)))))
10140 (goto-char beg)
10141 (if (re-search-forward org-property-start-re end t)
10142 (setq beg (1+ (match-end 0)))
10143 (if force
10144 (save-excursion
10145 (org-insert-property-drawer)
10146 (setq end (progn (outline-next-heading) (point))))
10147 (throw 'exit nil))
10148 (goto-char beg)
10149 (if (re-search-forward org-property-start-re end t)
10150 (setq beg (1+ (match-end 0)))))
10151 (if (re-search-forward org-property-end-re end t)
10152 (setq end (match-beginning 0))
10153 (or force (throw 'exit nil))
10154 (goto-char beg)
10155 (setq end beg)
10156 (org-indent-line-function)
10157 (insert ":END:\n"))
10158 (cons beg end)))))
10160 (defun org-entry-properties (&optional pom which)
10161 "Get all properties of the entry at point-or-marker POM.
10162 This includes the TODO keyword, the tags, time strings for deadline,
10163 scheduled, and clocking, and any additional properties defined in the
10164 entry. The return value is an alist, keys may occur multiple times
10165 if the property key was used several times.
10166 POM may also be nil, in which case the current entry is used.
10167 If WHICH is nil or `all', get all properties. If WHICH is
10168 `special' or `standard', only get that subclass."
10169 (setq which (or which 'all))
10170 (org-with-point-at pom
10171 (let ((clockstr (substring org-clock-string 0 -1))
10172 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10173 beg end range props sum-props key value string clocksum)
10174 (save-excursion
10175 (when (condition-case nil (org-back-to-heading t) (error nil))
10176 (setq beg (point))
10177 (setq sum-props (get-text-property (point) 'org-summaries))
10178 (setq clocksum (get-text-property (point) :org-clock-minutes))
10179 (outline-next-heading)
10180 (setq end (point))
10181 (when (memq which '(all special))
10182 ;; Get the special properties, like TODO and tags
10183 (goto-char beg)
10184 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10185 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10186 (when (looking-at org-priority-regexp)
10187 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10188 (when (and (setq value (org-get-tags-string))
10189 (string-match "\\S-" value))
10190 (push (cons "TAGS" value) props))
10191 (when (setq value (org-get-tags-at))
10192 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10193 props))
10194 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10195 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10196 string (if (equal key clockstr)
10197 (org-no-properties
10198 (org-trim
10199 (buffer-substring
10200 (match-beginning 3) (goto-char (point-at-eol)))))
10201 (substring (org-match-string-no-properties 3) 1 -1)))
10202 (unless key
10203 (if (= (char-after (match-beginning 3)) ?\[)
10204 (setq key "TIMESTAMP_IA")
10205 (setq key "TIMESTAMP")))
10206 (when (or (equal key clockstr) (not (assoc key props)))
10207 (push (cons key string) props)))
10211 (when (memq which '(all standard))
10212 ;; Get the standard properties, like :PORP: ...
10213 (setq range (org-get-property-block beg end))
10214 (when range
10215 (goto-char (car range))
10216 (while (re-search-forward
10217 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10218 (cdr range) t)
10219 (setq key (org-match-string-no-properties 1)
10220 value (org-trim (or (org-match-string-no-properties 2) "")))
10221 (unless (member key excluded)
10222 (push (cons key (or value "")) props)))))
10223 (if clocksum
10224 (push (cons "CLOCKSUM"
10225 (org-columns-number-to-string (/ (float clocksum) 60.)
10226 'add_times))
10227 props))
10228 (unless (assoc "CATEGORY" props)
10229 (setq value (or (org-get-category)
10230 (progn (org-refresh-category-properties)
10231 (org-get-category))))
10232 (push (cons "CATEGORY" value) props))
10233 (append sum-props (nreverse props)))))))
10235 (defun org-entry-get (pom property &optional inherit)
10236 "Get value of PROPERTY for entry at point-or-marker POM.
10237 If INHERIT is non-nil and the entry does not have the property,
10238 then also check higher levels of the hierarchy.
10239 If INHERIT is the symbol `selective', use inheritance only if the setting
10240 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10241 If the property is present but empty, the return value is the empty string.
10242 If the property is not present at all, nil is returned."
10243 (org-with-point-at pom
10244 (if (and inherit (if (eq inherit 'selective)
10245 (org-property-inherit-p property)
10247 (org-entry-get-with-inheritance property)
10248 (if (member property org-special-properties)
10249 ;; We need a special property. Use brute force, get all properties.
10250 (cdr (assoc property (org-entry-properties nil 'special)))
10251 (let ((range (org-get-property-block)))
10252 (if (and range
10253 (goto-char (car range))
10254 (re-search-forward
10255 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10256 (cdr range) t))
10257 ;; Found the property, return it.
10258 (if (match-end 1)
10259 (org-match-string-no-properties 1)
10260 "")))))))
10262 (defun org-property-or-variable-value (var &optional inherit)
10263 "Check if there is a property fixing the value of VAR.
10264 If yes, return this value. If not, return the current value of the variable."
10265 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10266 (if (and prop (stringp prop) (string-match "\\S-" prop))
10267 (read prop)
10268 (symbol-value var))))
10270 (defun org-entry-delete (pom property)
10271 "Delete the property PROPERTY from entry at point-or-marker POM."
10272 (org-with-point-at pom
10273 (if (member property org-special-properties)
10274 nil ; cannot delete these properties.
10275 (let ((range (org-get-property-block)))
10276 (if (and range
10277 (goto-char (car range))
10278 (re-search-forward
10279 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10280 (cdr range) t))
10281 (progn
10282 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10284 nil)))))
10286 ;; Multi-values properties are properties that contain multiple values
10287 ;; These values are assumed to be single words, separated by whitespace.
10288 (defun org-entry-add-to-multivalued-property (pom property value)
10289 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10290 (let* ((old (org-entry-get pom property))
10291 (values (and old (org-split-string old "[ \t]"))))
10292 (setq value (org-entry-protect-space value))
10293 (unless (member value values)
10294 (setq values (cons value values))
10295 (org-entry-put pom property
10296 (mapconcat 'identity values " ")))))
10298 (defun org-entry-remove-from-multivalued-property (pom property value)
10299 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10300 (let* ((old (org-entry-get pom property))
10301 (values (and old (org-split-string old "[ \t]"))))
10302 (setq value (org-entry-protect-space value))
10303 (when (member value values)
10304 (setq values (delete value values))
10305 (org-entry-put pom property
10306 (mapconcat 'identity values " ")))))
10308 (defun org-entry-member-in-multivalued-property (pom property value)
10309 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10310 (let* ((old (org-entry-get pom property))
10311 (values (and old (org-split-string old "[ \t]"))))
10312 (setq value (org-entry-protect-space value))
10313 (member value values)))
10315 (defun org-entry-get-multivalued-property (pom property)
10316 "Return a list of values in a multivalued property."
10317 (let* ((value (org-entry-get pom property))
10318 (values (and value (org-split-string value "[ \t]"))))
10319 (mapcar 'org-entry-restore-space values)))
10321 (defun org-entry-put-multivalued-property (pom property &rest values)
10322 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10323 VALUES should be a list of strings. Spaces will be protected."
10324 (org-entry-put pom property
10325 (mapconcat 'org-entry-protect-space values " "))
10326 (let* ((value (org-entry-get pom property))
10327 (values (and value (org-split-string value "[ \t]"))))
10328 (mapcar 'org-entry-restore-space values)))
10330 (defun org-entry-protect-space (s)
10331 "Protect spaces and newline in string S."
10332 (while (string-match " " s)
10333 (setq s (replace-match "%20" t t s)))
10334 (while (string-match "\n" s)
10335 (setq s (replace-match "%0A" t t s)))
10338 (defun org-entry-restore-space (s)
10339 "Restore spaces and newline in string S."
10340 (while (string-match "%20" s)
10341 (setq s (replace-match " " t t s)))
10342 (while (string-match "%0A" s)
10343 (setq s (replace-match "\n" t t s)))
10346 (defvar org-entry-property-inherited-from (make-marker)
10347 "Marker pointing to the entry from where a property was inherited.
10348 Each call to `org-entry-get-with-inheritance' will set this marker to the
10349 location of the entry where the inheritance search matched. If there was
10350 no match, the marker will point nowhere.
10351 Note that also `org-entry-get' calls this function, if the INHERIT flag
10352 is set.")
10354 (defun org-entry-get-with-inheritance (property)
10355 "Get entry property, and search higher levels if not present."
10356 (move-marker org-entry-property-inherited-from nil)
10357 (let (tmp)
10358 (save-excursion
10359 (save-restriction
10360 (widen)
10361 (catch 'ex
10362 (while t
10363 (when (setq tmp (org-entry-get nil property))
10364 (org-back-to-heading t)
10365 (move-marker org-entry-property-inherited-from (point))
10366 (throw 'ex tmp))
10367 (or (org-up-heading-safe) (throw 'ex nil)))))
10368 (or tmp
10369 (cdr (assoc property org-file-properties))
10370 (cdr (assoc property org-global-properties))
10371 (cdr (assoc property org-global-properties-fixed))))))
10373 (defun org-entry-put (pom property value)
10374 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10375 (org-with-point-at pom
10376 (org-back-to-heading t)
10377 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10378 range)
10379 (cond
10380 ((equal property "TODO")
10381 (when (and (stringp value) (string-match "\\S-" value)
10382 (not (member value org-todo-keywords-1)))
10383 (error "\"%s\" is not a valid TODO state" value))
10384 (if (or (not value)
10385 (not (string-match "\\S-" value)))
10386 (setq value 'none))
10387 (org-todo value)
10388 (org-set-tags nil 'align))
10389 ((equal property "PRIORITY")
10390 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10391 (string-to-char value) ?\ ))
10392 (org-set-tags nil 'align))
10393 ((equal property "SCHEDULED")
10394 (if (re-search-forward org-scheduled-time-regexp end t)
10395 (cond
10396 ((eq value 'earlier) (org-timestamp-change -1 'day))
10397 ((eq value 'later) (org-timestamp-change 1 'day))
10398 (t (call-interactively 'org-schedule)))
10399 (call-interactively 'org-schedule)))
10400 ((equal property "DEADLINE")
10401 (if (re-search-forward org-deadline-time-regexp end t)
10402 (cond
10403 ((eq value 'earlier) (org-timestamp-change -1 'day))
10404 ((eq value 'later) (org-timestamp-change 1 'day))
10405 (t (call-interactively 'org-deadline)))
10406 (call-interactively 'org-deadline)))
10407 ((member property org-special-properties)
10408 (error "The %s property can not yet be set with `org-entry-put'"
10409 property))
10410 (t ; a non-special property
10411 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10412 (setq range (org-get-property-block beg end 'force))
10413 (goto-char (car range))
10414 (if (re-search-forward
10415 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10416 (progn
10417 (delete-region (match-beginning 1) (match-end 1))
10418 (goto-char (match-beginning 1)))
10419 (goto-char (cdr range))
10420 (insert "\n")
10421 (backward-char 1)
10422 (org-indent-line-function)
10423 (insert ":" property ":"))
10424 (and value (insert " " value))
10425 (org-indent-line-function)))))))
10427 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10428 "Get all property keys in the current buffer.
10429 With INCLUDE-SPECIALS, also list the special properties that reflect things
10430 like tags and TODO state.
10431 With INCLUDE-DEFAULTS, also include properties that has special meaning
10432 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10433 With INCLUDE-COLUMNS, also include property names given in COLUMN
10434 formats in the current buffer."
10435 (let (rtn range cfmt cols s p)
10436 (save-excursion
10437 (save-restriction
10438 (widen)
10439 (goto-char (point-min))
10440 (while (re-search-forward org-property-start-re nil t)
10441 (setq range (org-get-property-block))
10442 (goto-char (car range))
10443 (while (re-search-forward
10444 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10445 (cdr range) t)
10446 (add-to-list 'rtn (org-match-string-no-properties 1)))
10447 (outline-next-heading))))
10449 (when include-specials
10450 (setq rtn (append org-special-properties rtn)))
10452 (when include-defaults
10453 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10455 (when include-columns
10456 (save-excursion
10457 (save-restriction
10458 (widen)
10459 (goto-char (point-min))
10460 (while (re-search-forward
10461 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10462 nil t)
10463 (setq cfmt (match-string 2) s 0)
10464 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10465 cfmt s)
10466 (setq s (match-end 0)
10467 p (match-string 1 cfmt))
10468 (unless (or (equal p "ITEM")
10469 (member p org-special-properties))
10470 (add-to-list 'rtn (match-string 1 cfmt))))))))
10472 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10474 (defun org-property-values (key)
10475 "Return a list of all values of property KEY."
10476 (save-excursion
10477 (save-restriction
10478 (widen)
10479 (goto-char (point-min))
10480 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10481 values)
10482 (while (re-search-forward re nil t)
10483 (add-to-list 'values (org-trim (match-string 1))))
10484 (delete "" values)))))
10486 (defun org-insert-property-drawer ()
10487 "Insert a property drawer into the current entry."
10488 (interactive)
10489 (org-back-to-heading t)
10490 (looking-at outline-regexp)
10491 (let ((indent (- (match-end 0)(match-beginning 0)))
10492 (beg (point))
10493 (re (concat "^[ \t]*" org-keyword-time-regexp))
10494 end hiddenp)
10495 (outline-next-heading)
10496 (setq end (point))
10497 (goto-char beg)
10498 (while (re-search-forward re end t))
10499 (setq hiddenp (org-invisible-p))
10500 (end-of-line 1)
10501 (and (equal (char-after) ?\n) (forward-char 1))
10502 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10503 (beginning-of-line 2))
10504 (org-skip-over-state-notes)
10505 (skip-chars-backward " \t\n\r")
10506 (if (eq (char-before) ?*) (forward-char 1))
10507 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10508 (beginning-of-line 0)
10509 (org-indent-to-column indent)
10510 (beginning-of-line 2)
10511 (org-indent-to-column indent)
10512 (beginning-of-line 0)
10513 (if hiddenp
10514 (save-excursion
10515 (org-back-to-heading t)
10516 (hide-entry))
10517 (org-flag-drawer t))))
10519 (defun org-set-property (property value)
10520 "In the current entry, set PROPERTY to VALUE.
10521 When called interactively, this will prompt for a property name, offering
10522 completion on existing and default properties. And then it will prompt
10523 for a value, offering completion either on allowed values (via an inherited
10524 xxx_ALL property) or on existing values in other instances of this property
10525 in the current file."
10526 (interactive
10527 (let* ((completion-ignore-case t)
10528 (keys (org-buffer-property-keys nil t t))
10529 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10530 (prop (if (member prop0 keys)
10531 prop0
10532 (or (cdr (assoc (downcase prop0)
10533 (mapcar (lambda (x) (cons (downcase x) x))
10534 keys)))
10535 prop0)))
10536 (cur (org-entry-get nil prop))
10537 (allowed (org-property-get-allowed-values nil prop 'table))
10538 (existing (mapcar 'list (org-property-values prop)))
10539 (val (if allowed
10540 (org-completing-read "Value: " allowed nil 'req-match)
10541 (org-completing-read
10542 (concat "Value" (if (and cur (string-match "\\S-" cur))
10543 (concat "[" cur "]") "")
10544 ": ")
10545 existing nil nil "" nil cur))))
10546 (list prop (if (equal val "") cur val))))
10547 (unless (equal (org-entry-get nil property) value)
10548 (org-entry-put nil property value)))
10550 (defun org-delete-property (property)
10551 "In the current entry, delete PROPERTY."
10552 (interactive
10553 (let* ((completion-ignore-case t)
10554 (prop (org-ido-completing-read
10555 "Property: " (org-entry-properties nil 'standard))))
10556 (list prop)))
10557 (message "Property %s %s" property
10558 (if (org-entry-delete nil property)
10559 "deleted"
10560 "was not present in the entry")))
10562 (defun org-delete-property-globally (property)
10563 "Remove PROPERTY globally, from all entries."
10564 (interactive
10565 (let* ((completion-ignore-case t)
10566 (prop (org-ido-completing-read
10567 "Globally remove property: "
10568 (mapcar 'list (org-buffer-property-keys)))))
10569 (list prop)))
10570 (save-excursion
10571 (save-restriction
10572 (widen)
10573 (goto-char (point-min))
10574 (let ((cnt 0))
10575 (while (re-search-forward
10576 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10577 nil t)
10578 (setq cnt (1+ cnt))
10579 (replace-match ""))
10580 (message "Property \"%s\" removed from %d entries" property cnt)))))
10582 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10584 (defun org-compute-property-at-point ()
10585 "Compute the property at point.
10586 This looks for an enclosing column format, extracts the operator and
10587 then applies it to the property in the column format's scope."
10588 (interactive)
10589 (unless (org-at-property-p)
10590 (error "Not at a property"))
10591 (let ((prop (org-match-string-no-properties 2)))
10592 (org-columns-get-format-and-top-level)
10593 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10594 (error "No operator defined for property %s" prop))
10595 (org-columns-compute prop)))
10597 (defun org-property-get-allowed-values (pom property &optional table)
10598 "Get allowed values for the property PROPERTY.
10599 When TABLE is non-nil, return an alist that can directly be used for
10600 completion."
10601 (let (vals)
10602 (cond
10603 ((equal property "TODO")
10604 (setq vals (org-with-point-at pom
10605 (append org-todo-keywords-1 '("")))))
10606 ((equal property "PRIORITY")
10607 (let ((n org-lowest-priority))
10608 (while (>= n org-highest-priority)
10609 (push (char-to-string n) vals)
10610 (setq n (1- n)))))
10611 ((member property org-special-properties))
10613 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10615 (when (and vals (string-match "\\S-" vals))
10616 (setq vals (car (read-from-string (concat "(" vals ")"))))
10617 (setq vals (mapcar (lambda (x)
10618 (cond ((stringp x) x)
10619 ((numberp x) (number-to-string x))
10620 ((symbolp x) (symbol-name x))
10621 (t "???")))
10622 vals)))))
10623 (if table (mapcar 'list vals) vals)))
10625 (defun org-property-previous-allowed-value (&optional previous)
10626 "Switch to the next allowed value for this property."
10627 (interactive)
10628 (org-property-next-allowed-value t))
10630 (defun org-property-next-allowed-value (&optional previous)
10631 "Switch to the next allowed value for this property."
10632 (interactive)
10633 (unless (org-at-property-p)
10634 (error "Not at a property"))
10635 (let* ((key (match-string 2))
10636 (value (match-string 3))
10637 (allowed (or (org-property-get-allowed-values (point) key)
10638 (and (member value '("[ ]" "[-]" "[X]"))
10639 '("[ ]" "[X]"))))
10640 nval)
10641 (unless allowed
10642 (error "Allowed values for this property have not been defined"))
10643 (if previous (setq allowed (reverse allowed)))
10644 (if (member value allowed)
10645 (setq nval (car (cdr (member value allowed)))))
10646 (setq nval (or nval (car allowed)))
10647 (if (equal nval value)
10648 (error "Only one allowed value for this property"))
10649 (org-at-property-p)
10650 (replace-match (concat " :" key ": " nval) t t)
10651 (org-indent-line-function)
10652 (beginning-of-line 1)
10653 (skip-chars-forward " \t")))
10655 (defun org-find-entry-with-id (ident)
10656 "Locate the entry that contains the ID property with exact value IDENT.
10657 IDENT can be a string, a symbol or a number, this function will search for
10658 the string representation of it.
10659 Return the position where this entry starts, or nil if there is no such entry."
10660 (interactive "sID: ")
10661 (let ((id (cond
10662 ((stringp ident) ident)
10663 ((symbol-name ident) (symbol-name ident))
10664 ((numberp ident) (number-to-string ident))
10665 (t (error "IDENT %s must be a string, symbol or number" ident))))
10666 (case-fold-search nil))
10667 (save-excursion
10668 (save-restriction
10669 (widen)
10670 (goto-char (point-min))
10671 (when (re-search-forward
10672 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10673 nil t)
10674 (org-back-to-heading)
10675 (point))))))
10677 ;;;; Timestamps
10679 (defvar org-last-changed-timestamp nil)
10680 (defvar org-last-inserted-timestamp nil
10681 "The last time stamp inserted with `org-insert-time-stamp'.")
10682 (defvar org-time-was-given) ; dynamically scoped parameter
10683 (defvar org-end-time-was-given) ; dynamically scoped parameter
10684 (defvar org-ts-what) ; dynamically scoped parameter
10686 (defun org-time-stamp (arg &optional inactive)
10687 "Prompt for a date/time and insert a time stamp.
10688 If the user specifies a time like HH:MM, or if this command is called
10689 with a prefix argument, the time stamp will contain date and time.
10690 Otherwise, only the date will be included. All parts of a date not
10691 specified by the user will be filled in from the current date/time.
10692 So if you press just return without typing anything, the time stamp
10693 will represent the current date/time. If there is already a timestamp
10694 at the cursor, it will be modified."
10695 (interactive "P")
10696 (let* ((ts nil)
10697 (default-time
10698 ;; Default time is either today, or, when entering a range,
10699 ;; the range start.
10700 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10701 (save-excursion
10702 (re-search-backward
10703 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10704 (- (point) 20) t)))
10705 (apply 'encode-time (org-parse-time-string (match-string 1)))
10706 (current-time)))
10707 (default-input (and ts (org-get-compact-tod ts)))
10708 org-time-was-given org-end-time-was-given time)
10709 (cond
10710 ((and (org-at-timestamp-p t)
10711 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10712 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10713 (insert "--")
10714 (setq time (let ((this-command this-command))
10715 (org-read-date arg 'totime nil nil
10716 default-time default-input)))
10717 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10718 ((org-at-timestamp-p t)
10719 (setq time (let ((this-command this-command))
10720 (org-read-date arg 'totime nil nil default-time default-input)))
10721 (when (org-at-timestamp-p t) ; just to get the match data
10722 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10723 (replace-match "")
10724 (setq org-last-changed-timestamp
10725 (org-insert-time-stamp
10726 time (or org-time-was-given arg)
10727 inactive nil nil (list org-end-time-was-given))))
10728 (message "Timestamp updated"))
10730 (setq time (let ((this-command this-command))
10731 (org-read-date arg 'totime nil nil default-time default-input)))
10732 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10733 nil nil (list org-end-time-was-given))))))
10735 ;; FIXME: can we use this for something else, like computing time differences?
10736 (defun org-get-compact-tod (s)
10737 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10738 (let* ((t1 (match-string 1 s))
10739 (h1 (string-to-number (match-string 2 s)))
10740 (m1 (string-to-number (match-string 3 s)))
10741 (t2 (and (match-end 4) (match-string 5 s)))
10742 (h2 (and t2 (string-to-number (match-string 6 s))))
10743 (m2 (and t2 (string-to-number (match-string 7 s))))
10744 dh dm)
10745 (if (not t2)
10747 (setq dh (- h2 h1) dm (- m2 m1))
10748 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10749 (concat t1 "+" (number-to-string dh)
10750 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10752 (defun org-time-stamp-inactive (&optional arg)
10753 "Insert an inactive time stamp.
10754 An inactive time stamp is enclosed in square brackets instead of angle
10755 brackets. It is inactive in the sense that it does not trigger agenda entries,
10756 does not link to the calendar and cannot be changed with the S-cursor keys.
10757 So these are more for recording a certain time/date."
10758 (interactive "P")
10759 (org-time-stamp arg 'inactive))
10761 (defvar org-date-ovl (org-make-overlay 1 1))
10762 (org-overlay-put org-date-ovl 'face 'org-warning)
10763 (org-detach-overlay org-date-ovl)
10765 (defvar org-ans1) ; dynamically scoped parameter
10766 (defvar org-ans2) ; dynamically scoped parameter
10768 (defvar org-plain-time-of-day-regexp) ; defined below
10770 (defvar org-overriding-default-time nil) ; dynamically scoped
10771 (defvar org-read-date-overlay nil)
10772 (defvar org-dcst nil) ; dynamically scoped
10774 (defun org-read-date (&optional with-time to-time from-string prompt
10775 default-time default-input)
10776 "Read a date, possibly a time, and make things smooth for the user.
10777 The prompt will suggest to enter an ISO date, but you can also enter anything
10778 which will at least partially be understood by `parse-time-string'.
10779 Unrecognized parts of the date will default to the current day, month, year,
10780 hour and minute. If this command is called to replace a timestamp at point,
10781 of to enter the second timestamp of a range, the default time is taken from the
10782 existing stamp. For example,
10783 3-2-5 --> 2003-02-05
10784 feb 15 --> currentyear-02-15
10785 sep 12 9 --> 2009-09-12
10786 12:45 --> today 12:45
10787 22 sept 0:34 --> currentyear-09-22 0:34
10788 12 --> currentyear-currentmonth-12
10789 Fri --> nearest Friday (today or later)
10790 etc.
10792 Furthermore you can specify a relative date by giving, as the *first* thing
10793 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10794 change in days weeks, months, years.
10795 With a single plus or minus, the date is relative to today. With a double
10796 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10797 +4d --> four days from today
10798 +4 --> same as above
10799 +2w --> two weeks from today
10800 ++5 --> five days from default date
10802 The function understands only English month and weekday abbreviations,
10803 but this can be configured with the variables `parse-time-months' and
10804 `parse-time-weekdays'.
10806 While prompting, a calendar is popped up - you can also select the
10807 date with the mouse (button 1). The calendar shows a period of three
10808 months. To scroll it to other months, use the keys `>' and `<'.
10809 If you don't like the calendar, turn it off with
10810 \(setq org-read-date-popup-calendar nil)
10812 With optional argument TO-TIME, the date will immediately be converted
10813 to an internal time.
10814 With an optional argument WITH-TIME, the prompt will suggest to also
10815 insert a time. Note that when WITH-TIME is not set, you can still
10816 enter a time, and this function will inform the calling routine about
10817 this change. The calling routine may then choose to change the format
10818 used to insert the time stamp into the buffer to include the time.
10819 With optional argument FROM-STRING, read from this string instead from
10820 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10821 the time/date that is used for everything that is not specified by the
10822 user."
10823 (require 'parse-time)
10824 (let* ((org-time-stamp-rounding-minutes
10825 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10826 (org-dcst org-display-custom-times)
10827 (ct (org-current-time))
10828 (def (or org-overriding-default-time default-time ct))
10829 (defdecode (decode-time def))
10830 (dummy (progn
10831 (when (< (nth 2 defdecode) org-extend-today-until)
10832 (setcar (nthcdr 2 defdecode) -1)
10833 (setcar (nthcdr 1 defdecode) 59)
10834 (setq def (apply 'encode-time defdecode)
10835 defdecode (decode-time def)))))
10836 (calendar-move-hook nil)
10837 (calendar-view-diary-initially-flag nil)
10838 (view-diary-entries-initially nil)
10839 (calendar-view-holidays-initially-flag nil)
10840 (view-calendar-holidays-initially nil)
10841 (timestr (format-time-string
10842 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10843 (prompt (concat (if prompt (concat prompt " ") "")
10844 (format "Date+time [%s]: " timestr)))
10845 ans (org-ans0 "") org-ans1 org-ans2 final)
10847 (cond
10848 (from-string (setq ans from-string))
10849 (org-read-date-popup-calendar
10850 (save-excursion
10851 (save-window-excursion
10852 (calendar)
10853 (calendar-forward-day (- (time-to-days def)
10854 (calendar-absolute-from-gregorian
10855 (calendar-current-date))))
10856 (org-eval-in-calendar nil t)
10857 (let* ((old-map (current-local-map))
10858 (map (copy-keymap calendar-mode-map))
10859 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10860 (org-defkey map (kbd "RET") 'org-calendar-select)
10861 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10862 'org-calendar-select-mouse)
10863 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10864 'org-calendar-select-mouse)
10865 (org-defkey minibuffer-local-map [(meta shift left)]
10866 (lambda () (interactive)
10867 (org-eval-in-calendar '(calendar-backward-month 1))))
10868 (org-defkey minibuffer-local-map [(meta shift right)]
10869 (lambda () (interactive)
10870 (org-eval-in-calendar '(calendar-forward-month 1))))
10871 (org-defkey minibuffer-local-map [(meta shift up)]
10872 (lambda () (interactive)
10873 (org-eval-in-calendar '(calendar-backward-year 1))))
10874 (org-defkey minibuffer-local-map [(meta shift down)]
10875 (lambda () (interactive)
10876 (org-eval-in-calendar '(calendar-forward-year 1))))
10877 (org-defkey minibuffer-local-map [(shift up)]
10878 (lambda () (interactive)
10879 (org-eval-in-calendar '(calendar-backward-week 1))))
10880 (org-defkey minibuffer-local-map [(shift down)]
10881 (lambda () (interactive)
10882 (org-eval-in-calendar '(calendar-forward-week 1))))
10883 (org-defkey minibuffer-local-map [(shift left)]
10884 (lambda () (interactive)
10885 (org-eval-in-calendar '(calendar-backward-day 1))))
10886 (org-defkey minibuffer-local-map [(shift right)]
10887 (lambda () (interactive)
10888 (org-eval-in-calendar '(calendar-forward-day 1))))
10889 (org-defkey minibuffer-local-map ">"
10890 (lambda () (interactive)
10891 (org-eval-in-calendar '(scroll-calendar-left 1))))
10892 (org-defkey minibuffer-local-map "<"
10893 (lambda () (interactive)
10894 (org-eval-in-calendar '(scroll-calendar-right 1))))
10895 (unwind-protect
10896 (progn
10897 (use-local-map map)
10898 (add-hook 'post-command-hook 'org-read-date-display)
10899 (setq org-ans0 (read-string prompt default-input nil nil))
10900 ;; org-ans0: from prompt
10901 ;; org-ans1: from mouse click
10902 ;; org-ans2: from calendar motion
10903 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10904 (remove-hook 'post-command-hook 'org-read-date-display)
10905 (use-local-map old-map)
10906 (when org-read-date-overlay
10907 (org-delete-overlay org-read-date-overlay)
10908 (setq org-read-date-overlay nil)))))))
10910 (t ; Naked prompt only
10911 (unwind-protect
10912 (setq ans (read-string prompt default-input nil timestr))
10913 (when org-read-date-overlay
10914 (org-delete-overlay org-read-date-overlay)
10915 (setq org-read-date-overlay nil)))))
10917 (setq final (org-read-date-analyze ans def defdecode))
10919 (if to-time
10920 (apply 'encode-time final)
10921 (if (and (boundp 'org-time-was-given) org-time-was-given)
10922 (format "%04d-%02d-%02d %02d:%02d"
10923 (nth 5 final) (nth 4 final) (nth 3 final)
10924 (nth 2 final) (nth 1 final))
10925 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10926 (defvar def)
10927 (defvar defdecode)
10928 (defvar with-time)
10929 (defun org-read-date-display ()
10930 "Display the current date prompt interpretation in the minibuffer."
10931 (when org-read-date-display-live
10932 (when org-read-date-overlay
10933 (org-delete-overlay org-read-date-overlay))
10934 (let ((p (point)))
10935 (end-of-line 1)
10936 (while (not (equal (buffer-substring
10937 (max (point-min) (- (point) 4)) (point))
10938 " "))
10939 (insert " "))
10940 (goto-char p))
10941 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10942 " " (or org-ans1 org-ans2)))
10943 (org-end-time-was-given nil)
10944 (f (org-read-date-analyze ans def defdecode))
10945 (fmts (if org-dcst
10946 org-time-stamp-custom-formats
10947 org-time-stamp-formats))
10948 (fmt (if (or with-time
10949 (and (boundp 'org-time-was-given) org-time-was-given))
10950 (cdr fmts)
10951 (car fmts)))
10952 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10953 (when (and org-end-time-was-given
10954 (string-match org-plain-time-of-day-regexp txt))
10955 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10956 org-end-time-was-given
10957 (substring txt (match-end 0)))))
10958 (setq org-read-date-overlay
10959 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10960 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10962 (defun org-read-date-analyze (ans def defdecode)
10963 "Analyse the combined answer of the date prompt."
10964 ;; FIXME: cleanup and comment
10965 (let (delta deltan deltaw deltadef year month day
10966 hour minute second wday pm h2 m2 tl wday1
10967 iso-year iso-weekday iso-week iso-year iso-date)
10969 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10970 (setq ans "+0"))
10972 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10973 (setq ans (replace-match "" t t ans)
10974 deltan (car delta)
10975 deltaw (nth 1 delta)
10976 deltadef (nth 2 delta)))
10978 ;; Check if there is an iso week date in there
10979 ;; If yes, sore the info and postpone interpreting it until the rest
10980 ;; of the parsing is done
10981 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10982 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10983 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10984 iso-week (string-to-number (match-string 2 ans)))
10985 (setq ans (replace-match "" t t ans)))
10987 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10988 (when (string-match
10989 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10990 (setq year (if (match-end 2)
10991 (string-to-number (match-string 2 ans))
10992 (string-to-number (format-time-string "%Y")))
10993 month (string-to-number (match-string 3 ans))
10994 day (string-to-number (match-string 4 ans)))
10995 (if (< year 100) (setq year (+ 2000 year)))
10996 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10997 t nil ans)))
10998 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10999 ;; If there is a time with am/pm, and *no* time without it, we convert
11000 ;; so that matching will be successful.
11001 (loop for i from 1 to 2 do ; twice, for end time as well
11002 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11003 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11004 (setq hour (string-to-number (match-string 1 ans))
11005 minute (if (match-end 3)
11006 (string-to-number (match-string 3 ans))
11008 pm (equal ?p
11009 (string-to-char (downcase (match-string 4 ans)))))
11010 (if (and (= hour 12) (not pm))
11011 (setq hour 0)
11012 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11013 (setq ans (replace-match (format "%02d:%02d" hour minute)
11014 t t ans))))
11016 ;; Check if a time range is given as a duration
11017 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11018 (setq hour (string-to-number (match-string 1 ans))
11019 h2 (+ hour (string-to-number (match-string 3 ans)))
11020 minute (string-to-number (match-string 2 ans))
11021 m2 (+ minute (if (match-end 5) (string-to-number
11022 (match-string 5 ans))0)))
11023 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11024 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11025 t t ans)))
11027 ;; Check if there is a time range
11028 (when (boundp 'org-end-time-was-given)
11029 (setq org-time-was-given nil)
11030 (when (and (string-match org-plain-time-of-day-regexp ans)
11031 (match-end 8))
11032 (setq org-end-time-was-given (match-string 8 ans))
11033 (setq ans (concat (substring ans 0 (match-beginning 7))
11034 (substring ans (match-end 7))))))
11036 (setq tl (parse-time-string ans)
11037 day (or (nth 3 tl) (nth 3 defdecode))
11038 month (or (nth 4 tl)
11039 (if (and org-read-date-prefer-future
11040 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11041 (1+ (nth 4 defdecode))
11042 (nth 4 defdecode)))
11043 year (or (nth 5 tl)
11044 (if (and org-read-date-prefer-future
11045 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11046 (1+ (nth 5 defdecode))
11047 (nth 5 defdecode)))
11048 hour (or (nth 2 tl) (nth 2 defdecode))
11049 minute (or (nth 1 tl) (nth 1 defdecode))
11050 second (or (nth 0 tl) 0)
11051 wday (nth 6 tl))
11053 ;; Special date definitions below
11054 (cond
11055 (iso-week
11056 ;; There was an iso week
11057 (setq year (or iso-year year)
11058 day (or iso-weekday wday 1)
11059 wday nil ; to make sure that the trigger below does not match
11060 iso-date (calendar-gregorian-from-absolute
11061 (calendar-absolute-from-iso
11062 (list iso-week day year))))
11063 ; FIXME: Should we also push ISO weeks into the future?
11064 ; (when (and org-read-date-prefer-future
11065 ; (not iso-year)
11066 ; (< (calendar-absolute-from-gregorian iso-date)
11067 ; (time-to-days (current-time))))
11068 ; (setq year (1+ year)
11069 ; iso-date (calendar-gregorian-from-absolute
11070 ; (calendar-absolute-from-iso
11071 ; (list iso-week day year)))))
11072 (setq month (car iso-date)
11073 year (nth 2 iso-date)
11074 day (nth 1 iso-date)))
11075 (deltan
11076 (unless deltadef
11077 (let ((now (decode-time (current-time))))
11078 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11079 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11080 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11081 ((equal deltaw "m") (setq month (+ month deltan)))
11082 ((equal deltaw "y") (setq year (+ year deltan)))))
11083 ((and wday (not (nth 3 tl)))
11084 ;; Weekday was given, but no day, so pick that day in the week
11085 ;; on or after the derived date.
11086 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11087 (unless (equal wday wday1)
11088 (setq day (+ day (% (- wday wday1 -7) 7))))))
11089 (if (and (boundp 'org-time-was-given)
11090 (nth 2 tl))
11091 (setq org-time-was-given t))
11092 (if (< year 100) (setq year (+ 2000 year)))
11093 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11094 (list second minute hour day month year)))
11096 (defvar parse-time-weekdays)
11098 (defun org-read-date-get-relative (s today default)
11099 "Check string S for special relative date string.
11100 TODAY and DEFAULT are internal times, for today and for a default.
11101 Return shift list (N what def-flag)
11102 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11103 N is the number of WHATs to shift.
11104 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11105 the DEFAULT date rather than TODAY."
11106 (when (and
11107 (string-match
11108 (concat
11109 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11110 "\\([0-9]+\\)?"
11111 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11112 "\\([ \t]\\|$\\)") s)
11113 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11114 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11115 (string-to-char (substring (match-string 1 s) -1))
11116 ?+))
11117 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11118 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11119 (what (if (match-end 3) (match-string 3 s) "d"))
11120 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11121 (date (if rel default today))
11122 (wday (nth 6 (decode-time date)))
11123 delta)
11124 (if wday1
11125 (progn
11126 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11127 (if (= dir ?-) (setq delta (- delta 7)))
11128 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11129 (list delta "d" rel))
11130 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11132 (defun org-eval-in-calendar (form &optional keepdate)
11133 "Eval FORM in the calendar window and return to current window.
11134 Also, store the cursor date in variable org-ans2."
11135 (let ((sw (selected-window)))
11136 (select-window (get-buffer-window "*Calendar*"))
11137 (eval form)
11138 (when (and (not keepdate) (calendar-cursor-to-date))
11139 (let* ((date (calendar-cursor-to-date))
11140 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11141 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11142 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11143 (select-window sw)))
11145 (defun org-calendar-select ()
11146 "Return to `org-read-date' with the date currently selected.
11147 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11148 (interactive)
11149 (when (calendar-cursor-to-date)
11150 (let* ((date (calendar-cursor-to-date))
11151 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11152 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11153 (if (active-minibuffer-window) (exit-minibuffer))))
11155 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11156 "Insert a date stamp for the date given by the internal TIME.
11157 WITH-HM means, use the stamp format that includes the time of the day.
11158 INACTIVE means use square brackets instead of angular ones, so that the
11159 stamp will not contribute to the agenda.
11160 PRE and POST are optional strings to be inserted before and after the
11161 stamp.
11162 The command returns the inserted time stamp."
11163 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11164 stamp)
11165 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11166 (insert-before-markers (or pre ""))
11167 (insert-before-markers (setq stamp (format-time-string fmt time)))
11168 (when (listp extra)
11169 (setq extra (car extra))
11170 (if (and (stringp extra)
11171 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11172 (setq extra (format "-%02d:%02d"
11173 (string-to-number (match-string 1 extra))
11174 (string-to-number (match-string 2 extra))))
11175 (setq extra nil)))
11176 (when extra
11177 (backward-char 1)
11178 (insert-before-markers extra)
11179 (forward-char 1))
11180 (insert-before-markers (or post ""))
11181 (setq org-last-inserted-timestamp stamp)))
11183 (defun org-toggle-time-stamp-overlays ()
11184 "Toggle the use of custom time stamp formats."
11185 (interactive)
11186 (setq org-display-custom-times (not org-display-custom-times))
11187 (unless org-display-custom-times
11188 (let ((p (point-min)) (bmp (buffer-modified-p)))
11189 (while (setq p (next-single-property-change p 'display))
11190 (if (and (get-text-property p 'display)
11191 (eq (get-text-property p 'face) 'org-date))
11192 (remove-text-properties
11193 p (setq p (next-single-property-change p 'display))
11194 '(display t))))
11195 (set-buffer-modified-p bmp)))
11196 (if (featurep 'xemacs)
11197 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11198 (org-restart-font-lock)
11199 (setq org-table-may-need-update t)
11200 (if org-display-custom-times
11201 (message "Time stamps are overlayed with custom format")
11202 (message "Time stamp overlays removed")))
11204 (defun org-display-custom-time (beg end)
11205 "Overlay modified time stamp format over timestamp between BEG and END."
11206 (let* ((ts (buffer-substring beg end))
11207 t1 w1 with-hm tf time str w2 (off 0))
11208 (save-match-data
11209 (setq t1 (org-parse-time-string ts t))
11210 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11211 (setq off (- (match-end 0) (match-beginning 0)))))
11212 (setq end (- end off))
11213 (setq w1 (- end beg)
11214 with-hm (and (nth 1 t1) (nth 2 t1))
11215 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11216 time (org-fix-decoded-time t1)
11217 str (org-add-props
11218 (format-time-string
11219 (substring tf 1 -1) (apply 'encode-time time))
11220 nil 'mouse-face 'highlight)
11221 w2 (length str))
11222 (if (not (= w2 w1))
11223 (add-text-properties (1+ beg) (+ 2 beg)
11224 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11225 (if (featurep 'xemacs)
11226 (progn
11227 (put-text-property beg end 'invisible t)
11228 (put-text-property beg end 'end-glyph (make-glyph str)))
11229 (put-text-property beg end 'display str))))
11231 (defun org-translate-time (string)
11232 "Translate all timestamps in STRING to custom format.
11233 But do this only if the variable `org-display-custom-times' is set."
11234 (when org-display-custom-times
11235 (save-match-data
11236 (let* ((start 0)
11237 (re org-ts-regexp-both)
11238 t1 with-hm inactive tf time str beg end)
11239 (while (setq start (string-match re string start))
11240 (setq beg (match-beginning 0)
11241 end (match-end 0)
11242 t1 (save-match-data
11243 (org-parse-time-string (substring string beg end) t))
11244 with-hm (and (nth 1 t1) (nth 2 t1))
11245 inactive (equal (substring string beg (1+ beg)) "[")
11246 tf (funcall (if with-hm 'cdr 'car)
11247 org-time-stamp-custom-formats)
11248 time (org-fix-decoded-time t1)
11249 str (format-time-string
11250 (concat
11251 (if inactive "[" "<") (substring tf 1 -1)
11252 (if inactive "]" ">"))
11253 (apply 'encode-time time))
11254 string (replace-match str t t string)
11255 start (+ start (length str)))))))
11256 string)
11258 (defun org-fix-decoded-time (time)
11259 "Set 0 instead of nil for the first 6 elements of time.
11260 Don't touch the rest."
11261 (let ((n 0))
11262 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11264 (defun org-days-to-time (timestamp-string)
11265 "Difference between TIMESTAMP-STRING and now in days."
11266 (- (time-to-days (org-time-string-to-time timestamp-string))
11267 (time-to-days (current-time))))
11269 (defun org-deadline-close (timestamp-string &optional ndays)
11270 "Is the time in TIMESTAMP-STRING close to the current date?"
11271 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11272 (and (< (org-days-to-time timestamp-string) ndays)
11273 (not (org-entry-is-done-p))))
11275 (defun org-get-wdays (ts)
11276 "Get the deadline lead time appropriate for timestring TS."
11277 (cond
11278 ((<= org-deadline-warning-days 0)
11279 ;; 0 or negative, enforce this value no matter what
11280 (- org-deadline-warning-days))
11281 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11282 ;; lead time is specified.
11283 (floor (* (string-to-number (match-string 1 ts))
11284 (cdr (assoc (match-string 2 ts)
11285 '(("d" . 1) ("w" . 7)
11286 ("m" . 30.4) ("y" . 365.25)))))))
11287 ;; go for the default.
11288 (t org-deadline-warning-days)))
11290 (defun org-calendar-select-mouse (ev)
11291 "Return to `org-read-date' with the date currently selected.
11292 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11293 (interactive "e")
11294 (mouse-set-point ev)
11295 (when (calendar-cursor-to-date)
11296 (let* ((date (calendar-cursor-to-date))
11297 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11298 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11299 (if (active-minibuffer-window) (exit-minibuffer))))
11301 (defun org-check-deadlines (ndays)
11302 "Check if there are any deadlines due or past due.
11303 A deadline is considered due if it happens within `org-deadline-warning-days'
11304 days from today's date. If the deadline appears in an entry marked DONE,
11305 it is not shown. The prefix arg NDAYS can be used to test that many
11306 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11307 (interactive "P")
11308 (let* ((org-warn-days
11309 (cond
11310 ((equal ndays '(4)) 100000)
11311 (ndays (prefix-numeric-value ndays))
11312 (t (abs org-deadline-warning-days))))
11313 (case-fold-search nil)
11314 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11315 (callback
11316 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11318 (message "%d deadlines past-due or due within %d days"
11319 (org-occur regexp nil callback)
11320 org-warn-days)))
11322 (defun org-check-before-date (date)
11323 "Check if there are deadlines or scheduled entries before DATE."
11324 (interactive (list (org-read-date)))
11325 (let ((case-fold-search nil)
11326 (regexp (concat "\\<\\(" org-deadline-string
11327 "\\|" org-scheduled-string
11328 "\\) *<\\([^>]+\\)>"))
11329 (callback
11330 (lambda () (time-less-p
11331 (org-time-string-to-time (match-string 2))
11332 (org-time-string-to-time date)))))
11333 (message "%d entries before %s"
11334 (org-occur regexp nil callback) date)))
11336 (defun org-evaluate-time-range (&optional to-buffer)
11337 "Evaluate a time range by computing the difference between start and end.
11338 Normally the result is just printed in the echo area, but with prefix arg
11339 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11340 If the time range is actually in a table, the result is inserted into the
11341 next column.
11342 For time difference computation, a year is assumed to be exactly 365
11343 days in order to avoid rounding problems."
11344 (interactive "P")
11346 (org-clock-update-time-maybe)
11347 (save-excursion
11348 (unless (org-at-date-range-p t)
11349 (goto-char (point-at-bol))
11350 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11351 (if (not (org-at-date-range-p t))
11352 (error "Not at a time-stamp range, and none found in current line")))
11353 (let* ((ts1 (match-string 1))
11354 (ts2 (match-string 2))
11355 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11356 (match-end (match-end 0))
11357 (time1 (org-time-string-to-time ts1))
11358 (time2 (org-time-string-to-time ts2))
11359 (t1 (time-to-seconds time1))
11360 (t2 (time-to-seconds time2))
11361 (diff (abs (- t2 t1)))
11362 (negative (< (- t2 t1) 0))
11363 ;; (ys (floor (* 365 24 60 60)))
11364 (ds (* 24 60 60))
11365 (hs (* 60 60))
11366 (fy "%dy %dd %02d:%02d")
11367 (fy1 "%dy %dd")
11368 (fd "%dd %02d:%02d")
11369 (fd1 "%dd")
11370 (fh "%02d:%02d")
11371 y d h m align)
11372 (if havetime
11373 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11375 d (floor (/ diff ds)) diff (mod diff ds)
11376 h (floor (/ diff hs)) diff (mod diff hs)
11377 m (floor (/ diff 60)))
11378 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11380 d (floor (+ (/ diff ds) 0.5))
11381 h 0 m 0))
11382 (if (not to-buffer)
11383 (message "%s" (org-make-tdiff-string y d h m))
11384 (if (org-at-table-p)
11385 (progn
11386 (goto-char match-end)
11387 (setq align t)
11388 (and (looking-at " *|") (goto-char (match-end 0))))
11389 (goto-char match-end))
11390 (if (looking-at
11391 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11392 (replace-match ""))
11393 (if negative (insert " -"))
11394 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11395 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11396 (insert " " (format fh h m))))
11397 (if align (org-table-align))
11398 (message "Time difference inserted")))))
11400 (defun org-make-tdiff-string (y d h m)
11401 (let ((fmt "")
11402 (l nil))
11403 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11404 l (push y l)))
11405 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11406 l (push d l)))
11407 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11408 l (push h l)))
11409 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11410 l (push m l)))
11411 (apply 'format fmt (nreverse l))))
11413 (defun org-time-string-to-time (s)
11414 (apply 'encode-time (org-parse-time-string s)))
11416 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11417 "Convert a time stamp to an absolute day number.
11418 If there is a specifyer for a cyclic time stamp, get the closest date to
11419 DAYNR.
11420 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11421 (cond
11422 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11423 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11424 daynr
11425 (+ daynr 1000)))
11426 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11427 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11428 (time-to-days (current-time))) (match-string 0 s)
11429 prefer show-all))
11430 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11432 (defun org-days-to-iso-week (days)
11433 "Return the iso week number."
11434 (require 'cal-iso)
11435 (car (calendar-iso-from-absolute days)))
11437 (defun org-small-year-to-year (year)
11438 "Convert 2-digit years into 4-digit years.
11439 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11440 The year 2000 cannot be abbreviated. Any year larger than 99
11441 is returned unchanged."
11442 (if (< year 38)
11443 (setq year (+ 2000 year))
11444 (if (< year 100)
11445 (setq year (+ 1900 year))))
11446 year)
11448 (defun org-time-from-absolute (d)
11449 "Return the time corresponding to date D.
11450 D may be an absolute day number, or a calendar-type list (month day year)."
11451 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11452 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11454 (defun org-calendar-holiday ()
11455 "List of holidays, for Diary display in Org-mode."
11456 (require 'holidays)
11457 (let ((hl (funcall
11458 (if (fboundp 'calendar-check-holidays)
11459 'calendar-check-holidays 'check-calendar-holidays) date)))
11460 (if hl (mapconcat 'identity hl "; "))))
11462 (defun org-diary-sexp-entry (sexp entry date)
11463 "Process a SEXP diary ENTRY for DATE."
11464 (require 'diary-lib)
11465 (let ((result (if calendar-debug-sexp
11466 (let ((stack-trace-on-error t))
11467 (eval (car (read-from-string sexp))))
11468 (condition-case nil
11469 (eval (car (read-from-string sexp)))
11470 (error
11471 (beep)
11472 (message "Bad sexp at line %d in %s: %s"
11473 (org-current-line)
11474 (buffer-file-name) sexp)
11475 (sleep-for 2))))))
11476 (cond ((stringp result) result)
11477 ((and (consp result)
11478 (stringp (cdr result))) (cdr result))
11479 (result entry)
11480 (t nil))))
11482 (defun org-diary-to-ical-string (frombuf)
11483 "Get iCalendar entries from diary entries in buffer FROMBUF.
11484 This uses the icalendar.el library."
11485 (let* ((tmpdir (if (featurep 'xemacs)
11486 (temp-directory)
11487 temporary-file-directory))
11488 (tmpfile (make-temp-name
11489 (expand-file-name "orgics" tmpdir)))
11490 buf rtn b e)
11491 (save-excursion
11492 (set-buffer frombuf)
11493 (icalendar-export-region (point-min) (point-max) tmpfile)
11494 (setq buf (find-buffer-visiting tmpfile))
11495 (set-buffer buf)
11496 (goto-char (point-min))
11497 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11498 (setq b (match-beginning 0)))
11499 (goto-char (point-max))
11500 (if (re-search-backward "^END:VEVENT" nil t)
11501 (setq e (match-end 0)))
11502 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11503 (kill-buffer buf)
11504 (delete-file tmpfile)
11505 rtn))
11507 (defun org-closest-date (start current change prefer show-all)
11508 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11509 When PREFER is `past' return a date that is either CURRENT or past.
11510 When PREFER is `future', return a date that is either CURRENT or future.
11511 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11512 ;; Make the proper lists from the dates
11513 (catch 'exit
11514 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11515 dn dw sday cday n1 n2
11516 d m y y1 y2 date1 date2 nmonths nm ny m2)
11518 (setq start (org-date-to-gregorian start)
11519 current (org-date-to-gregorian
11520 (if show-all
11521 current
11522 (time-to-days (current-time))))
11523 sday (calendar-absolute-from-gregorian start)
11524 cday (calendar-absolute-from-gregorian current))
11526 (if (<= cday sday) (throw 'exit sday))
11528 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11529 (setq dn (string-to-number (match-string 1 change))
11530 dw (cdr (assoc (match-string 2 change) a1)))
11531 (error "Invalid change specifyer: %s" change))
11532 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11533 (cond
11534 ((eq dw 'day)
11535 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11536 n2 (+ n1 dn)))
11537 ((eq dw 'year)
11538 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11539 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11540 (setq date1 (list m d y1)
11541 n1 (calendar-absolute-from-gregorian date1)
11542 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11543 n2 (calendar-absolute-from-gregorian date2)))
11544 ((eq dw 'month)
11545 ;; approx number of month between the two dates
11546 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11547 ;; How often does dn fit in there?
11548 (setq d (nth 1 start) m (car start) y (nth 2 start)
11549 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11550 m (+ m nm)
11551 ny (floor (/ m 12))
11552 y (+ y ny)
11553 m (- m (* ny 12)))
11554 (while (> m 12) (setq m (- m 12) y (1+ y)))
11555 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11556 (setq m2 (+ m dn) y2 y)
11557 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11558 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11559 (while (<= n2 cday)
11560 (setq n1 n2 m m2 y y2)
11561 (setq m2 (+ m dn) y2 y)
11562 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11563 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11564 (if show-all
11565 (cond
11566 ((eq prefer 'past) n1)
11567 ((eq prefer 'future) (if (= cday n1) n1 n2))
11568 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11569 (cond
11570 ((eq prefer 'past) n1)
11571 ((eq prefer 'future) (if (= cday n1) n1 n2))
11572 (t (if (= cday n1) n1 n2)))))))
11574 (defun org-date-to-gregorian (date)
11575 "Turn any specification of DATE into a gregorian date for the calendar."
11576 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11577 ((and (listp date) (= (length date) 3)) date)
11578 ((stringp date)
11579 (setq date (org-parse-time-string date))
11580 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11581 ((listp date)
11582 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11584 (defun org-parse-time-string (s &optional nodefault)
11585 "Parse the standard Org-mode time string.
11586 This should be a lot faster than the normal `parse-time-string'.
11587 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11588 hour and minute fields will be nil if not given."
11589 (if (string-match org-ts-regexp0 s)
11590 (list 0
11591 (if (or (match-beginning 8) (not nodefault))
11592 (string-to-number (or (match-string 8 s) "0")))
11593 (if (or (match-beginning 7) (not nodefault))
11594 (string-to-number (or (match-string 7 s) "0")))
11595 (string-to-number (match-string 4 s))
11596 (string-to-number (match-string 3 s))
11597 (string-to-number (match-string 2 s))
11598 nil nil nil)
11599 (make-list 9 0)))
11601 (defun org-timestamp-up (&optional arg)
11602 "Increase the date item at the cursor by one.
11603 If the cursor is on the year, change the year. If it is on the month or
11604 the day, change that.
11605 With prefix ARG, change by that many units."
11606 (interactive "p")
11607 (org-timestamp-change (prefix-numeric-value arg)))
11609 (defun org-timestamp-down (&optional arg)
11610 "Decrease the date item at the cursor by one.
11611 If the cursor is on the year, change the year. If it is on the month or
11612 the day, change that.
11613 With prefix ARG, change by that many units."
11614 (interactive "p")
11615 (org-timestamp-change (- (prefix-numeric-value arg))))
11617 (defun org-timestamp-up-day (&optional arg)
11618 "Increase the date in the time stamp by one day.
11619 With prefix ARG, change that many days."
11620 (interactive "p")
11621 (if (and (not (org-at-timestamp-p t))
11622 (org-on-heading-p))
11623 (org-todo 'up)
11624 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11626 (defun org-timestamp-down-day (&optional arg)
11627 "Decrease the date in the time stamp by one day.
11628 With prefix ARG, change that many days."
11629 (interactive "p")
11630 (if (and (not (org-at-timestamp-p t))
11631 (org-on-heading-p))
11632 (org-todo 'down)
11633 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11635 (defun org-at-timestamp-p (&optional inactive-ok)
11636 "Determine if the cursor is in or at a timestamp."
11637 (interactive)
11638 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11639 (pos (point))
11640 (ans (or (looking-at tsr)
11641 (save-excursion
11642 (skip-chars-backward "^[<\n\r\t")
11643 (if (> (point) (point-min)) (backward-char 1))
11644 (and (looking-at tsr)
11645 (> (- (match-end 0) pos) -1))))))
11646 (and ans
11647 (boundp 'org-ts-what)
11648 (setq org-ts-what
11649 (cond
11650 ((= pos (match-beginning 0)) 'bracket)
11651 ((= pos (1- (match-end 0))) 'bracket)
11652 ((org-pos-in-match-range pos 2) 'year)
11653 ((org-pos-in-match-range pos 3) 'month)
11654 ((org-pos-in-match-range pos 7) 'hour)
11655 ((org-pos-in-match-range pos 8) 'minute)
11656 ((or (org-pos-in-match-range pos 4)
11657 (org-pos-in-match-range pos 5)) 'day)
11658 ((and (> pos (or (match-end 8) (match-end 5)))
11659 (< pos (match-end 0)))
11660 (- pos (or (match-end 8) (match-end 5))))
11661 (t 'day))))
11662 ans))
11664 (defun org-toggle-timestamp-type ()
11665 "Toggle the type (<active> or [inactive]) of a time stamp."
11666 (interactive)
11667 (when (org-at-timestamp-p t)
11668 (let ((beg (match-beginning 0)) (end (match-end 0))
11669 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11670 (save-excursion
11671 (goto-char beg)
11672 (while (re-search-forward "[][<>]" end t)
11673 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11674 t t)))
11675 (message "Timestamp is now %sactive"
11676 (if (equal (char-after beg) ?<) "" "in")))))
11678 (defun org-timestamp-change (n &optional what)
11679 "Change the date in the time stamp at point.
11680 The date will be changed by N times WHAT. WHAT can be `day', `month',
11681 `year', `minute', `second'. If WHAT is not given, the cursor position
11682 in the timestamp determines what will be changed."
11683 (let ((pos (point))
11684 with-hm inactive
11685 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11686 org-ts-what
11687 extra rem
11688 ts time time0)
11689 (if (not (org-at-timestamp-p t))
11690 (error "Not at a timestamp"))
11691 (if (and (not what) (eq org-ts-what 'bracket))
11692 (org-toggle-timestamp-type)
11693 (if (and (not what) (not (eq org-ts-what 'day))
11694 org-display-custom-times
11695 (get-text-property (point) 'display)
11696 (not (get-text-property (1- (point)) 'display)))
11697 (setq org-ts-what 'day))
11698 (setq org-ts-what (or what org-ts-what)
11699 inactive (= (char-after (match-beginning 0)) ?\[)
11700 ts (match-string 0))
11701 (replace-match "")
11702 (if (string-match
11703 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11705 (setq extra (match-string 1 ts)))
11706 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11707 (setq with-hm t))
11708 (setq time0 (org-parse-time-string ts))
11709 (when (and (eq org-ts-what 'minute)
11710 (eq current-prefix-arg nil))
11711 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11712 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11713 (setcar (cdr time0) (+ (nth 1 time0)
11714 (if (> n 0) (- rem) (- dm rem))))))
11715 (setq time
11716 (encode-time (or (car time0) 0)
11717 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11718 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11719 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11720 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11721 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11722 (nthcdr 6 time0)))
11723 (when (integerp org-ts-what)
11724 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11725 (if (eq what 'calendar)
11726 (let ((cal-date (org-get-date-from-calendar)))
11727 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11728 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11729 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11730 (setcar time0 (or (car time0) 0))
11731 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11732 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11733 (setq time (apply 'encode-time time0))))
11734 (setq org-last-changed-timestamp
11735 (org-insert-time-stamp time with-hm inactive nil nil extra))
11736 (org-clock-update-time-maybe)
11737 (goto-char pos)
11738 ;; Try to recenter the calendar window, if any
11739 (if (and org-calendar-follow-timestamp-change
11740 (get-buffer-window "*Calendar*" t)
11741 (memq org-ts-what '(day month year)))
11742 (org-recenter-calendar (time-to-days time))))))
11744 (defun org-modify-ts-extra (s pos n dm)
11745 "Change the different parts of the lead-time and repeat fields in timestamp."
11746 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11747 ng h m new rem)
11748 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11749 (cond
11750 ((or (org-pos-in-match-range pos 2)
11751 (org-pos-in-match-range pos 3))
11752 (setq m (string-to-number (match-string 3 s))
11753 h (string-to-number (match-string 2 s)))
11754 (if (org-pos-in-match-range pos 2)
11755 (setq h (+ h n))
11756 (setq n (* dm (org-no-warnings (signum n))))
11757 (when (not (= 0 (setq rem (% m dm))))
11758 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11759 (setq m (+ m n)))
11760 (if (< m 0) (setq m (+ m 60) h (1- h)))
11761 (if (> m 59) (setq m (- m 60) h (1+ h)))
11762 (setq h (min 24 (max 0 h)))
11763 (setq ng 1 new (format "-%02d:%02d" h m)))
11764 ((org-pos-in-match-range pos 6)
11765 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11766 ((org-pos-in-match-range pos 5)
11767 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11769 ((org-pos-in-match-range pos 9)
11770 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11771 ((org-pos-in-match-range pos 8)
11772 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11774 (when ng
11775 (setq s (concat
11776 (substring s 0 (match-beginning ng))
11778 (substring s (match-end ng))))))
11781 (defun org-recenter-calendar (date)
11782 "If the calendar is visible, recenter it to DATE."
11783 (let* ((win (selected-window))
11784 (cwin (get-buffer-window "*Calendar*" t))
11785 (calendar-move-hook nil))
11786 (when cwin
11787 (select-window cwin)
11788 (calendar-goto-date (if (listp date) date
11789 (calendar-gregorian-from-absolute date)))
11790 (select-window win))))
11792 (defun org-goto-calendar (&optional arg)
11793 "Go to the Emacs calendar at the current date.
11794 If there is a time stamp in the current line, go to that date.
11795 A prefix ARG can be used to force the current date."
11796 (interactive "P")
11797 (let ((tsr org-ts-regexp) diff
11798 (calendar-move-hook nil)
11799 (calendar-view-holidays-initially-flag nil)
11800 (view-calendar-holidays-initially nil)
11801 (calendar-view-diary-initially-flag nil)
11802 (view-diary-entries-initially nil))
11803 (if (or (org-at-timestamp-p)
11804 (save-excursion
11805 (beginning-of-line 1)
11806 (looking-at (concat ".*" tsr))))
11807 (let ((d1 (time-to-days (current-time)))
11808 (d2 (time-to-days
11809 (org-time-string-to-time (match-string 1)))))
11810 (setq diff (- d2 d1))))
11811 (calendar)
11812 (calendar-goto-today)
11813 (if (and diff (not arg)) (calendar-forward-day diff))))
11815 (defun org-get-date-from-calendar ()
11816 "Return a list (month day year) of date at point in calendar."
11817 (with-current-buffer "*Calendar*"
11818 (save-match-data
11819 (calendar-cursor-to-date))))
11821 (defun org-date-from-calendar ()
11822 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11823 If there is already a time stamp at the cursor position, update it."
11824 (interactive)
11825 (if (org-at-timestamp-p t)
11826 (org-timestamp-change 0 'calendar)
11827 (let ((cal-date (org-get-date-from-calendar)))
11828 (org-insert-time-stamp
11829 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11831 (defun org-minutes-to-hh:mm-string (m)
11832 "Compute H:MM from a number of minutes."
11833 (let ((h (/ m 60)))
11834 (setq m (- m (* 60 h)))
11835 (format org-time-clocksum-format h m)))
11837 (defun org-hh:mm-string-to-minutes (s)
11838 "Convert a string H:MM to a number of minutes."
11839 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11840 (+ (* (string-to-number (match-string 1 s)) 60)
11841 (string-to-number (match-string 2 s)))
11844 ;;;; Agenda files
11846 ;;;###autoload
11847 (defun org-iswitchb (&optional arg)
11848 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11849 With a prefix argument, restrict available to files.
11850 With two prefix arguments, restrict available buffers to agenda files.
11852 Due to some yet unresolved reason, the global function
11853 `iswitchb-mode' needs to be active for this function to work."
11854 (interactive "P")
11855 (require 'iswitchb)
11856 (let ((enabled iswitchb-mode) blist)
11857 (or enabled (iswitchb-mode 1))
11858 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11859 ((equal arg '(16)) (org-buffer-list 'agenda))
11860 (t (org-buffer-list))))
11861 (unwind-protect
11862 (let ((iswitchb-make-buflist-hook
11863 (lambda ()
11864 (setq iswitchb-temp-buflist
11865 (mapcar 'buffer-name blist)))))
11866 (switch-to-buffer
11867 (iswitchb-read-buffer
11868 "Switch-to: " nil t))
11869 (or enabled (iswitchb-mode -1))))))
11871 ;;;###autoload
11872 (defun org-ido-switchb (&optional arg)
11873 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
11874 With a prefix argument, restrict available to files.
11875 With two prefix arguments, restrict available buffers to agenda files."
11876 (interactive "P")
11877 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11878 ((equal arg '(16)) (org-buffer-list 'agenda))
11879 (t (org-buffer-list)))))
11880 (switch-to-buffer
11881 (org-ido-completing-read "Org buffer: "
11882 (mapcar 'buffer-name blist)
11883 nil t))))
11885 (defun org-buffer-list (&optional predicate exclude-tmp)
11886 "Return a list of Org buffers.
11887 PREDICATE can be `export', `files' or `agenda'.
11889 export restrict the list to Export buffers.
11890 files restrict the list to buffers visiting Org files.
11891 agenda restrict the list to buffers visiting agenda files.
11893 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11894 (let* ((bfn nil)
11895 (agenda-files (and (eq predicate 'agenda)
11896 (mapcar 'file-truename (org-agenda-files t))))
11897 (filter
11898 (cond
11899 ((eq predicate 'files)
11900 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11901 ((eq predicate 'export)
11902 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11903 ((eq predicate 'agenda)
11904 (lambda (b)
11905 (with-current-buffer b
11906 (and (eq major-mode 'org-mode)
11907 (setq bfn (buffer-file-name b))
11908 (member (file-truename bfn) agenda-files)))))
11909 (t (lambda (b) (with-current-buffer b
11910 (or (eq major-mode 'org-mode)
11911 (string-match "\*Org .*Export"
11912 (buffer-name b)))))))))
11913 (delq nil
11914 (mapcar
11915 (lambda(b)
11916 (if (and (funcall filter b)
11917 (or (not exclude-tmp)
11918 (not (string-match "tmp" (buffer-name b)))))
11920 nil))
11921 (buffer-list)))))
11923 (defun org-agenda-files (&optional unrestricted archives)
11924 "Get the list of agenda files.
11925 Optional UNRESTRICTED means return the full list even if a restriction
11926 is currently in place.
11927 When ARCHIVES is t, include all archive files hat are really being
11928 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11929 `org-agenda-archives-mode' is t."
11930 (let ((files
11931 (cond
11932 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11933 ((stringp org-agenda-files) (org-read-agenda-file-list))
11934 ((listp org-agenda-files) org-agenda-files)
11935 (t (error "Invalid value of `org-agenda-files'")))))
11936 (setq files (apply 'append
11937 (mapcar (lambda (f)
11938 (if (file-directory-p f)
11939 (directory-files
11940 f t org-agenda-file-regexp)
11941 (list f)))
11942 files)))
11943 (when org-agenda-skip-unavailable-files
11944 (setq files (delq nil
11945 (mapcar (function
11946 (lambda (file)
11947 (and (file-readable-p file) file)))
11948 files))))
11949 (when (or (eq archives t)
11950 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11951 (setq files (org-add-archive-files files)))
11952 files))
11954 (defun org-edit-agenda-file-list ()
11955 "Edit the list of agenda files.
11956 Depending on setup, this either uses customize to edit the variable
11957 `org-agenda-files', or it visits the file that is holding the list. In the
11958 latter case, the buffer is set up in a way that saving it automatically kills
11959 the buffer and restores the previous window configuration."
11960 (interactive)
11961 (if (stringp org-agenda-files)
11962 (let ((cw (current-window-configuration)))
11963 (find-file org-agenda-files)
11964 (org-set-local 'org-window-configuration cw)
11965 (org-add-hook 'after-save-hook
11966 (lambda ()
11967 (set-window-configuration
11968 (prog1 org-window-configuration
11969 (kill-buffer (current-buffer))))
11970 (org-install-agenda-files-menu)
11971 (message "New agenda file list installed"))
11972 nil 'local)
11973 (message "%s" (substitute-command-keys
11974 "Edit list and finish with \\[save-buffer]")))
11975 (customize-variable 'org-agenda-files)))
11977 (defun org-store-new-agenda-file-list (list)
11978 "Set new value for the agenda file list and save it correctly."
11979 (if (stringp org-agenda-files)
11980 (let ((f org-agenda-files) b)
11981 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11982 (with-temp-file f
11983 (insert (mapconcat 'identity list "\n") "\n")))
11984 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11985 (setq org-agenda-files list)
11986 (customize-save-variable 'org-agenda-files org-agenda-files))))
11988 (defun org-read-agenda-file-list ()
11989 "Read the list of agenda files from a file."
11990 (when (file-directory-p org-agenda-files)
11991 (error "`org-agenda-files' cannot be a single directory"))
11992 (when (stringp org-agenda-files)
11993 (with-temp-buffer
11994 (insert-file-contents org-agenda-files)
11995 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11998 ;;;###autoload
11999 (defun org-cycle-agenda-files ()
12000 "Cycle through the files in `org-agenda-files'.
12001 If the current buffer visits an agenda file, find the next one in the list.
12002 If the current buffer does not, find the first agenda file."
12003 (interactive)
12004 (let* ((fs (org-agenda-files t))
12005 (files (append fs (list (car fs))))
12006 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12007 file)
12008 (unless files (error "No agenda files"))
12009 (catch 'exit
12010 (while (setq file (pop files))
12011 (if (equal (file-truename file) tcf)
12012 (when (car files)
12013 (find-file (car files))
12014 (throw 'exit t))))
12015 (find-file (car fs)))
12016 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12018 (defun org-agenda-file-to-front (&optional to-end)
12019 "Move/add the current file to the top of the agenda file list.
12020 If the file is not present in the list, it is added to the front. If it is
12021 present, it is moved there. With optional argument TO-END, add/move to the
12022 end of the list."
12023 (interactive "P")
12024 (let ((org-agenda-skip-unavailable-files nil)
12025 (file-alist (mapcar (lambda (x)
12026 (cons (file-truename x) x))
12027 (org-agenda-files t)))
12028 (ctf (file-truename buffer-file-name))
12029 x had)
12030 (setq x (assoc ctf file-alist) had x)
12032 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12033 (if to-end
12034 (setq file-alist (append (delq x file-alist) (list x)))
12035 (setq file-alist (cons x (delq x file-alist))))
12036 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12037 (org-install-agenda-files-menu)
12038 (message "File %s to %s of agenda file list"
12039 (if had "moved" "added") (if to-end "end" "front"))))
12041 (defun org-remove-file (&optional file)
12042 "Remove current file from the list of files in variable `org-agenda-files'.
12043 These are the files which are being checked for agenda entries.
12044 Optional argument FILE means, use this file instead of the current."
12045 (interactive)
12046 (let* ((org-agenda-skip-unavailable-files nil)
12047 (file (or file buffer-file-name))
12048 (true-file (file-truename file))
12049 (afile (abbreviate-file-name file))
12050 (files (delq nil (mapcar
12051 (lambda (x)
12052 (if (equal true-file
12053 (file-truename x))
12054 nil x))
12055 (org-agenda-files t)))))
12056 (if (not (= (length files) (length (org-agenda-files t))))
12057 (progn
12058 (org-store-new-agenda-file-list files)
12059 (org-install-agenda-files-menu)
12060 (message "Removed file: %s" afile))
12061 (message "File was not in list: %s (not removed)" afile))))
12063 (defun org-file-menu-entry (file)
12064 (vector file (list 'find-file file) t))
12066 (defun org-check-agenda-file (file)
12067 "Make sure FILE exists. If not, ask user what to do."
12068 (when (not (file-exists-p file))
12069 (message "non-existent file %s. [R]emove from list or [A]bort?"
12070 (abbreviate-file-name file))
12071 (let ((r (downcase (read-char-exclusive))))
12072 (cond
12073 ((equal r ?r)
12074 (org-remove-file file)
12075 (throw 'nextfile t))
12076 (t (error "Abort"))))))
12078 (defun org-get-agenda-file-buffer (file)
12079 "Get a buffer visiting FILE. If the buffer needs to be created, add
12080 it to the list of buffers which might be released later."
12081 (let ((buf (org-find-base-buffer-visiting file)))
12082 (if buf
12083 buf ; just return it
12084 ;; Make a new buffer and remember it
12085 (setq buf (find-file-noselect file))
12086 (if buf (push buf org-agenda-new-buffers))
12087 buf)))
12089 (defun org-release-buffers (blist)
12090 "Release all buffers in list, asking the user for confirmation when needed.
12091 When a buffer is unmodified, it is just killed. When modified, it is saved
12092 \(if the user agrees) and then killed."
12093 (let (buf file)
12094 (while (setq buf (pop blist))
12095 (setq file (buffer-file-name buf))
12096 (when (and (buffer-modified-p buf)
12097 file
12098 (y-or-n-p (format "Save file %s? " file)))
12099 (with-current-buffer buf (save-buffer)))
12100 (kill-buffer buf))))
12102 (defun org-prepare-agenda-buffers (files)
12103 "Create buffers for all agenda files, protect archived trees and comments."
12104 (interactive)
12105 (let ((pa '(:org-archived t))
12106 (pc '(:org-comment t))
12107 (pall '(:org-archived t :org-comment t))
12108 (inhibit-read-only t)
12109 (rea (concat ":" org-archive-tag ":"))
12110 bmp file re)
12111 (save-excursion
12112 (save-restriction
12113 (while (setq file (pop files))
12114 (if (bufferp file)
12115 (set-buffer file)
12116 (org-check-agenda-file file)
12117 (set-buffer (org-get-agenda-file-buffer file)))
12118 (widen)
12119 (setq bmp (buffer-modified-p))
12120 (org-refresh-category-properties)
12121 (setq org-todo-keywords-for-agenda
12122 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12123 (setq org-done-keywords-for-agenda
12124 (append org-done-keywords-for-agenda org-done-keywords))
12125 (setq org-todo-keyword-alist-for-agenda
12126 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12127 (setq org-tag-alist-for-agenda
12128 (append org-tag-alist-for-agenda org-tag-alist))
12130 (save-excursion
12131 (remove-text-properties (point-min) (point-max) pall)
12132 (when org-agenda-skip-archived-trees
12133 (goto-char (point-min))
12134 (while (re-search-forward rea nil t)
12135 (if (org-on-heading-p t)
12136 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12137 (goto-char (point-min))
12138 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12139 (while (re-search-forward re nil t)
12140 (add-text-properties
12141 (match-beginning 0) (org-end-of-subtree t) pc)))
12142 (set-buffer-modified-p bmp))))
12143 (setq org-todo-keyword-alist-for-agenda
12144 (org-uniquify org-todo-keyword-alist-for-agenda)
12145 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12147 ;;;; Embedded LaTeX
12149 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12150 "Keymap for the minor `org-cdlatex-mode'.")
12152 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12153 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12154 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12155 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12156 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12158 (defvar org-cdlatex-texmathp-advice-is-done nil
12159 "Flag remembering if we have applied the advice to texmathp already.")
12161 (define-minor-mode org-cdlatex-mode
12162 "Toggle the minor `org-cdlatex-mode'.
12163 This mode supports entering LaTeX environment and math in LaTeX fragments
12164 in Org-mode.
12165 \\{org-cdlatex-mode-map}"
12166 nil " OCDL" nil
12167 (when org-cdlatex-mode (require 'cdlatex))
12168 (unless org-cdlatex-texmathp-advice-is-done
12169 (setq org-cdlatex-texmathp-advice-is-done t)
12170 (defadvice texmathp (around org-math-always-on activate)
12171 "Always return t in org-mode buffers.
12172 This is because we want to insert math symbols without dollars even outside
12173 the LaTeX math segments. If Orgmode thinks that point is actually inside
12174 an embedded LaTeX fragment, let texmathp do its job.
12175 \\[org-cdlatex-mode-map]"
12176 (interactive)
12177 (let (p)
12178 (cond
12179 ((not (org-mode-p)) ad-do-it)
12180 ((eq this-command 'cdlatex-math-symbol)
12181 (setq ad-return-value t
12182 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12184 (let ((p (org-inside-LaTeX-fragment-p)))
12185 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12186 (setq ad-return-value t
12187 texmathp-why '("Org-mode embedded math" . 0))
12188 (if p ad-do-it)))))))))
12190 (defun turn-on-org-cdlatex ()
12191 "Unconditionally turn on `org-cdlatex-mode'."
12192 (org-cdlatex-mode 1))
12194 (defun org-inside-LaTeX-fragment-p ()
12195 "Test if point is inside a LaTeX fragment.
12196 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12197 sequence appearing also before point.
12198 Even though the matchers for math are configurable, this function assumes
12199 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12200 delimiters are skipped when they have been removed by customization.
12201 The return value is nil, or a cons cell with the delimiter and
12202 and the position of this delimiter.
12204 This function does a reasonably good job, but can locally be fooled by
12205 for example currency specifications. For example it will assume being in
12206 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12207 fragments that are properly closed, but during editing, we have to live
12208 with the uncertainty caused by missing closing delimiters. This function
12209 looks only before point, not after."
12210 (catch 'exit
12211 (let ((pos (point))
12212 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12213 (lim (progn
12214 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12215 (point)))
12216 dd-on str (start 0) m re)
12217 (goto-char pos)
12218 (when dodollar
12219 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12220 re (nth 1 (assoc "$" org-latex-regexps)))
12221 (while (string-match re str start)
12222 (cond
12223 ((= (match-end 0) (length str))
12224 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12225 ((= (match-end 0) (- (length str) 5))
12226 (throw 'exit nil))
12227 (t (setq start (match-end 0))))))
12228 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12229 (goto-char pos)
12230 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12231 (and (match-beginning 2) (throw 'exit nil))
12232 ;; count $$
12233 (while (re-search-backward "\\$\\$" lim t)
12234 (setq dd-on (not dd-on)))
12235 (goto-char pos)
12236 (if dd-on (cons "$$" m))))))
12239 (defun org-try-cdlatex-tab ()
12240 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12241 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12242 - inside a LaTeX fragment, or
12243 - after the first word in a line, where an abbreviation expansion could
12244 insert a LaTeX environment."
12245 (when org-cdlatex-mode
12246 (cond
12247 ((save-excursion
12248 (skip-chars-backward "a-zA-Z0-9*")
12249 (skip-chars-backward " \t")
12250 (bolp))
12251 (cdlatex-tab) t)
12252 ((org-inside-LaTeX-fragment-p)
12253 (cdlatex-tab) t)
12254 (t nil))))
12256 (defun org-cdlatex-underscore-caret (&optional arg)
12257 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12258 Revert to the normal definition outside of these fragments."
12259 (interactive "P")
12260 (if (org-inside-LaTeX-fragment-p)
12261 (call-interactively 'cdlatex-sub-superscript)
12262 (let (org-cdlatex-mode)
12263 (call-interactively (key-binding (vector last-input-event))))))
12265 (defun org-cdlatex-math-modify (&optional arg)
12266 "Execute `cdlatex-math-modify' in LaTeX fragments.
12267 Revert to the normal definition outside of these fragments."
12268 (interactive "P")
12269 (if (org-inside-LaTeX-fragment-p)
12270 (call-interactively 'cdlatex-math-modify)
12271 (let (org-cdlatex-mode)
12272 (call-interactively (key-binding (vector last-input-event))))))
12274 (defvar org-latex-fragment-image-overlays nil
12275 "List of overlays carrying the images of latex fragments.")
12276 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12278 (defun org-remove-latex-fragment-image-overlays ()
12279 "Remove all overlays with LaTeX fragment images in current buffer."
12280 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12281 (setq org-latex-fragment-image-overlays nil))
12283 (defun org-preview-latex-fragment (&optional subtree)
12284 "Preview the LaTeX fragment at point, or all locally or globally.
12285 If the cursor is in a LaTeX fragment, create the image and overlay
12286 it over the source code. If there is no fragment at point, display
12287 all fragments in the current text, from one headline to the next. With
12288 prefix SUBTREE, display all fragments in the current subtree. With a
12289 double prefix `C-u C-u', or when the cursor is before the first headline,
12290 display all fragments in the buffer.
12291 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12292 (interactive "P")
12293 (org-remove-latex-fragment-image-overlays)
12294 (save-excursion
12295 (save-restriction
12296 (let (beg end at msg)
12297 (cond
12298 ((or (equal subtree '(16))
12299 (not (save-excursion
12300 (re-search-backward (concat "^" outline-regexp) nil t))))
12301 (setq beg (point-min) end (point-max)
12302 msg "Creating images for buffer...%s"))
12303 ((equal subtree '(4))
12304 (org-back-to-heading)
12305 (setq beg (point) end (org-end-of-subtree t)
12306 msg "Creating images for subtree...%s"))
12308 (if (setq at (org-inside-LaTeX-fragment-p))
12309 (goto-char (max (point-min) (- (cdr at) 2)))
12310 (org-back-to-heading))
12311 (setq beg (point) end (progn (outline-next-heading) (point))
12312 msg (if at "Creating image...%s"
12313 "Creating images for entry...%s"))))
12314 (message msg "")
12315 (narrow-to-region beg end)
12316 (goto-char beg)
12317 (org-format-latex
12318 (concat "ltxpng/" (file-name-sans-extension
12319 (file-name-nondirectory
12320 buffer-file-name)))
12321 default-directory 'overlays msg at 'forbuffer)
12322 (message msg "done. Use `C-c C-c' to remove images.")))))
12324 (defvar org-latex-regexps
12325 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12326 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12327 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12328 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12329 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12330 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12331 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12332 "Regular expressions for matching embedded LaTeX.")
12334 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12335 "Replace LaTeX fragments with links to an image, and produce images."
12336 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12337 (let* ((prefixnodir (file-name-nondirectory prefix))
12338 (absprefix (expand-file-name prefix dir))
12339 (todir (file-name-directory absprefix))
12340 (opt org-format-latex-options)
12341 (matchers (plist-get opt :matchers))
12342 (re-list org-latex-regexps)
12343 (cnt 0) txt link beg end re e checkdir
12344 m n block linkfile movefile ov)
12345 ;; Check if there are old images files with this prefix, and remove them
12346 (when (file-directory-p todir)
12347 (mapc 'delete-file
12348 (directory-files
12349 todir 'full
12350 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12351 ;; Check the different regular expressions
12352 (while (setq e (pop re-list))
12353 (setq m (car e) re (nth 1 e) n (nth 2 e)
12354 block (if (nth 3 e) "\n\n" ""))
12355 (when (member m matchers)
12356 (goto-char (point-min))
12357 (while (re-search-forward re nil t)
12358 (when (or (not at) (equal (cdr at) (match-beginning n)))
12359 (setq txt (match-string n)
12360 beg (match-beginning n) end (match-end n)
12361 cnt (1+ cnt)
12362 linkfile (format "%s_%04d.png" prefix cnt)
12363 movefile (format "%s_%04d.png" absprefix cnt)
12364 link (concat block "[[file:" linkfile "]]" block))
12365 (if msg (message msg cnt))
12366 (goto-char beg)
12367 (unless checkdir ; make sure the directory exists
12368 (setq checkdir t)
12369 (or (file-directory-p todir) (make-directory todir)))
12370 (org-create-formula-image
12371 txt movefile opt forbuffer)
12372 (if overlays
12373 (progn
12374 (setq ov (org-make-overlay beg end))
12375 (if (featurep 'xemacs)
12376 (progn
12377 (org-overlay-put ov 'invisible t)
12378 (org-overlay-put
12379 ov 'end-glyph
12380 (make-glyph (vector 'png :file movefile))))
12381 (org-overlay-put
12382 ov 'display
12383 (list 'image :type 'png :file movefile :ascent 'center)))
12384 (push ov org-latex-fragment-image-overlays)
12385 (goto-char end))
12386 (delete-region beg end)
12387 (insert link))))))))
12389 ;; This function borrows from Ganesh Swami's latex2png.el
12390 (defun org-create-formula-image (string tofile options buffer)
12391 (let* ((tmpdir (if (featurep 'xemacs)
12392 (temp-directory)
12393 temporary-file-directory))
12394 (texfilebase (make-temp-name
12395 (expand-file-name "orgtex" tmpdir)))
12396 (texfile (concat texfilebase ".tex"))
12397 (dvifile (concat texfilebase ".dvi"))
12398 (pngfile (concat texfilebase ".png"))
12399 (fnh (if (featurep 'xemacs)
12400 (font-height (get-face-font 'default))
12401 (face-attribute 'default :height nil)))
12402 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12403 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12404 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12405 "Black"))
12406 (bg (or (plist-get options (if buffer :background :html-background))
12407 "Transparent")))
12408 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12409 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12410 (with-temp-file texfile
12411 (insert org-format-latex-header
12412 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12413 (let ((dir default-directory))
12414 (condition-case nil
12415 (progn
12416 (cd tmpdir)
12417 (call-process "latex" nil nil nil texfile))
12418 (error nil))
12419 (cd dir))
12420 (if (not (file-exists-p dvifile))
12421 (progn (message "Failed to create dvi file from %s" texfile) nil)
12422 (condition-case nil
12423 (call-process "dvipng" nil nil nil
12424 "-E" "-fg" fg "-bg" bg
12425 "-D" dpi
12426 ;;"-x" scale "-y" scale
12427 "-T" "tight"
12428 "-o" pngfile
12429 dvifile)
12430 (error nil))
12431 (if (not (file-exists-p pngfile))
12432 (progn (message "Failed to create png file from %s" texfile) nil)
12433 ;; Use the requested file name and clean up
12434 (copy-file pngfile tofile 'replace)
12435 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12436 (delete-file (concat texfilebase e)))
12437 pngfile))))
12439 (defun org-dvipng-color (attr)
12440 "Return an rgb color specification for dvipng."
12441 (apply 'format "rgb %s %s %s"
12442 (mapcar 'org-normalize-color
12443 (color-values (face-attribute 'default attr nil)))))
12445 (defun org-normalize-color (value)
12446 "Return string to be used as color value for an RGB component."
12447 (format "%g" (/ value 65535.0)))
12450 ;;;; Key bindings
12452 ;; Make `C-c C-x' a prefix key
12453 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12455 ;; TAB key with modifiers
12456 (org-defkey org-mode-map "\C-i" 'org-cycle)
12457 (org-defkey org-mode-map [(tab)] 'org-cycle)
12458 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12459 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12460 (org-defkey org-mode-map "\M-\t" 'org-complete)
12461 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12462 ;; The following line is necessary under Suse GNU/Linux
12463 (unless (featurep 'xemacs)
12464 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12465 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12466 (define-key org-mode-map [backtab] 'org-shifttab)
12468 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12469 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12470 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12472 ;; Cursor keys with modifiers
12473 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12474 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12475 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12476 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12478 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12479 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12480 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12481 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12483 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12484 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12485 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12486 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12488 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12489 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12491 ;;; Extra keys for tty access.
12492 ;; We only set them when really needed because otherwise the
12493 ;; menus don't show the simple keys
12495 (when (or org-use-extra-keys
12496 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12497 (not window-system))
12498 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12499 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12500 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12501 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12502 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12503 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12504 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12505 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12506 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12507 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12508 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12509 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12510 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12511 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12512 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12513 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12514 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12515 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12516 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12517 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12518 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12519 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12521 ;; All the other keys
12523 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12524 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12525 (if (boundp 'narrow-map)
12526 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12527 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12528 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12529 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12530 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12531 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12532 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12533 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12534 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12535 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12536 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12537 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12538 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12539 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12540 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12541 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12542 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12543 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12544 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12545 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12546 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12547 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12548 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12549 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12550 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12551 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12552 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12553 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12554 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12555 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12556 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12557 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12558 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12559 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12560 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12561 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12562 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12563 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12564 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12565 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12566 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12567 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12568 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12569 (org-defkey org-mode-map "\C-c^" 'org-sort)
12570 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12571 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12572 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12573 (org-defkey org-mode-map "\C-m" 'org-return)
12574 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12575 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12576 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12577 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12578 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12579 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12580 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12581 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12582 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12583 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12584 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12585 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12586 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12587 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12588 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12589 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12591 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12592 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12593 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12594 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12596 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12597 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12598 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12599 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12600 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12601 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12602 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12603 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12604 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12605 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12606 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12607 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12609 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12610 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12611 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12613 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12615 (when (featurep 'xemacs)
12616 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12618 (defvar org-table-auto-blank-field) ; defined in org-table.el
12619 (defun org-self-insert-command (N)
12620 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12621 If the cursor is in a table looking at whitespace, the whitespace is
12622 overwritten, and the table is not marked as requiring realignment."
12623 (interactive "p")
12624 (if (and (org-table-p)
12625 (progn
12626 ;; check if we blank the field, and if that triggers align
12627 (and (featurep 'org-table) org-table-auto-blank-field
12628 (member last-command
12629 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12630 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12631 ;; got extra space, this field does not determine column width
12632 (let (org-table-may-need-update) (org-table-blank-field))
12633 ;; no extra space, this field may determine column width
12634 (org-table-blank-field)))
12636 (eq N 1)
12637 (looking-at "[^|\n]* |"))
12638 (let (org-table-may-need-update)
12639 (goto-char (1- (match-end 0)))
12640 (delete-backward-char 1)
12641 (goto-char (match-beginning 0))
12642 (self-insert-command N))
12643 (setq org-table-may-need-update t)
12644 (self-insert-command N)
12645 (org-fix-tags-on-the-fly)))
12647 (defun org-fix-tags-on-the-fly ()
12648 (when (and (equal (char-after (point-at-bol)) ?*)
12649 (org-on-heading-p))
12650 (org-align-tags-here org-tags-column)))
12652 (defun org-delete-backward-char (N)
12653 "Like `delete-backward-char', insert whitespace at field end in tables.
12654 When deleting backwards, in tables this function will insert whitespace in
12655 front of the next \"|\" separator, to keep the table aligned. The table will
12656 still be marked for re-alignment if the field did fill the entire column,
12657 because, in this case the deletion might narrow the column."
12658 (interactive "p")
12659 (if (and (org-table-p)
12660 (eq N 1)
12661 (string-match "|" (buffer-substring (point-at-bol) (point)))
12662 (looking-at ".*?|"))
12663 (let ((pos (point))
12664 (noalign (looking-at "[^|\n\r]* |"))
12665 (c org-table-may-need-update))
12666 (backward-delete-char N)
12667 (skip-chars-forward "^|")
12668 (insert " ")
12669 (goto-char (1- pos))
12670 ;; noalign: if there were two spaces at the end, this field
12671 ;; does not determine the width of the column.
12672 (if noalign (setq org-table-may-need-update c)))
12673 (backward-delete-char N)
12674 (org-fix-tags-on-the-fly)))
12676 (defun org-delete-char (N)
12677 "Like `delete-char', but insert whitespace at field end in tables.
12678 When deleting characters, in tables this function will insert whitespace in
12679 front of the next \"|\" separator, to keep the table aligned. The table will
12680 still be marked for re-alignment if the field did fill the entire column,
12681 because, in this case the deletion might narrow the column."
12682 (interactive "p")
12683 (if (and (org-table-p)
12684 (not (bolp))
12685 (not (= (char-after) ?|))
12686 (eq N 1))
12687 (if (looking-at ".*?|")
12688 (let ((pos (point))
12689 (noalign (looking-at "[^|\n\r]* |"))
12690 (c org-table-may-need-update))
12691 (replace-match (concat
12692 (substring (match-string 0) 1 -1)
12693 " |"))
12694 (goto-char pos)
12695 ;; noalign: if there were two spaces at the end, this field
12696 ;; does not determine the width of the column.
12697 (if noalign (setq org-table-may-need-update c)))
12698 (delete-char N))
12699 (delete-char N)
12700 (org-fix-tags-on-the-fly)))
12702 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12703 (put 'org-self-insert-command 'delete-selection t)
12704 (put 'orgtbl-self-insert-command 'delete-selection t)
12705 (put 'org-delete-char 'delete-selection 'supersede)
12706 (put 'org-delete-backward-char 'delete-selection 'supersede)
12708 ;; Make `flyspell-mode' delay after some commands
12709 (put 'org-self-insert-command 'flyspell-delayed t)
12710 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12711 (put 'org-delete-char 'flyspell-delayed t)
12712 (put 'org-delete-backward-char 'flyspell-delayed t)
12714 ;; Make pabbrev-mode expand after org-mode commands
12715 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12716 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12718 ;; How to do this: Measure non-white length of current string
12719 ;; If equal to column width, we should realign.
12721 (defun org-remap (map &rest commands)
12722 "In MAP, remap the functions given in COMMANDS.
12723 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12724 (let (new old)
12725 (while commands
12726 (setq old (pop commands) new (pop commands))
12727 (if (fboundp 'command-remapping)
12728 (org-defkey map (vector 'remap old) new)
12729 (substitute-key-definition old new map global-map)))))
12731 (when (eq org-enable-table-editor 'optimized)
12732 ;; If the user wants maximum table support, we need to hijack
12733 ;; some standard editing functions
12734 (org-remap org-mode-map
12735 'self-insert-command 'org-self-insert-command
12736 'delete-char 'org-delete-char
12737 'delete-backward-char 'org-delete-backward-char)
12738 (org-defkey org-mode-map "|" 'org-force-self-insert))
12740 (defun org-shiftcursor-error ()
12741 "Throw an error because Shift-Cursor command was applied in wrong context."
12742 (error "This command is active in special context like tables, headlines or timestamps"))
12744 (defun org-shifttab (&optional arg)
12745 "Global visibility cycling or move to previous table field.
12746 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12747 on context.
12748 See the individual commands for more information."
12749 (interactive "P")
12750 (cond
12751 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12752 ((integerp arg)
12753 (message "Content view to level: %d" arg)
12754 (org-content (prefix-numeric-value arg))
12755 (setq org-cycle-global-status 'overview))
12756 (t (call-interactively 'org-global-cycle))))
12758 (defun org-shiftmetaleft ()
12759 "Promote subtree or delete table column.
12760 Calls `org-promote-subtree', `org-outdent-item',
12761 or `org-table-delete-column', depending on context.
12762 See the individual commands for more information."
12763 (interactive)
12764 (cond
12765 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12766 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12767 ((org-at-item-p) (call-interactively 'org-outdent-item))
12768 (t (org-shiftcursor-error))))
12770 (defun org-shiftmetaright ()
12771 "Demote subtree or insert table column.
12772 Calls `org-demote-subtree', `org-indent-item',
12773 or `org-table-insert-column', depending on context.
12774 See the individual commands for more information."
12775 (interactive)
12776 (cond
12777 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12778 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12779 ((org-at-item-p) (call-interactively 'org-indent-item))
12780 (t (org-shiftcursor-error))))
12782 (defun org-shiftmetaup (&optional arg)
12783 "Move subtree up or kill table row.
12784 Calls `org-move-subtree-up' or `org-table-kill-row' or
12785 `org-move-item-up' depending on context. See the individual commands
12786 for more information."
12787 (interactive "P")
12788 (cond
12789 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12790 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12791 ((org-at-item-p) (call-interactively 'org-move-item-up))
12792 (t (org-shiftcursor-error))))
12793 (defun org-shiftmetadown (&optional arg)
12794 "Move subtree down or insert table row.
12795 Calls `org-move-subtree-down' or `org-table-insert-row' or
12796 `org-move-item-down', depending on context. See the individual
12797 commands for more information."
12798 (interactive "P")
12799 (cond
12800 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12801 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12802 ((org-at-item-p) (call-interactively 'org-move-item-down))
12803 (t (org-shiftcursor-error))))
12805 (defun org-metaleft (&optional arg)
12806 "Promote heading or move table column to left.
12807 Calls `org-do-promote' or `org-table-move-column', depending on context.
12808 With no specific context, calls the Emacs default `backward-word'.
12809 See the individual commands for more information."
12810 (interactive "P")
12811 (cond
12812 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12813 ((or (org-on-heading-p) (org-region-active-p))
12814 (call-interactively 'org-do-promote))
12815 ((org-at-item-p) (call-interactively 'org-outdent-item))
12816 (t (call-interactively 'backward-word))))
12818 (defun org-metaright (&optional arg)
12819 "Demote subtree or move table column to right.
12820 Calls `org-do-demote' or `org-table-move-column', depending on context.
12821 With no specific context, calls the Emacs default `forward-word'.
12822 See the individual commands for more information."
12823 (interactive "P")
12824 (cond
12825 ((org-at-table-p) (call-interactively 'org-table-move-column))
12826 ((or (org-on-heading-p) (org-region-active-p))
12827 (call-interactively 'org-do-demote))
12828 ((org-at-item-p) (call-interactively 'org-indent-item))
12829 (t (call-interactively 'forward-word))))
12831 (defun org-metaup (&optional arg)
12832 "Move subtree up or move table row up.
12833 Calls `org-move-subtree-up' or `org-table-move-row' or
12834 `org-move-item-up', depending on context. See the individual commands
12835 for more information."
12836 (interactive "P")
12837 (cond
12838 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12839 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12840 ((org-at-item-p) (call-interactively 'org-move-item-up))
12841 (t (transpose-lines 1) (beginning-of-line -1))))
12843 (defun org-metadown (&optional arg)
12844 "Move subtree down or move table row down.
12845 Calls `org-move-subtree-down' or `org-table-move-row' or
12846 `org-move-item-down', depending on context. See the individual
12847 commands for more information."
12848 (interactive "P")
12849 (cond
12850 ((org-at-table-p) (call-interactively 'org-table-move-row))
12851 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12852 ((org-at-item-p) (call-interactively 'org-move-item-down))
12853 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12855 (defun org-shiftup (&optional arg)
12856 "Increase item in timestamp or increase priority of current headline.
12857 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12858 depending on context. See the individual commands for more information."
12859 (interactive "P")
12860 (cond
12861 ((org-at-timestamp-p t)
12862 (call-interactively (if org-edit-timestamp-down-means-later
12863 'org-timestamp-down 'org-timestamp-up)))
12864 ((org-on-heading-p) (call-interactively 'org-priority-up))
12865 ((org-at-item-p) (call-interactively 'org-previous-item))
12866 ((org-clocktable-try-shift 'up arg))
12867 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12869 (defun org-shiftdown (&optional arg)
12870 "Decrease item in timestamp or decrease priority of current headline.
12871 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12872 depending on context. See the individual commands for more information."
12873 (interactive "P")
12874 (cond
12875 ((org-at-timestamp-p t)
12876 (call-interactively (if org-edit-timestamp-down-means-later
12877 'org-timestamp-up 'org-timestamp-down)))
12878 ((org-on-heading-p) (call-interactively 'org-priority-down))
12879 ((org-clocktable-try-shift 'down arg))
12880 (t (call-interactively 'org-next-item))))
12882 (defun org-shiftright (&optional arg)
12883 "Cycle the thing at point or in the current line, depending on context.
12884 Depending on context, this does one of the following:
12886 - switch a timestamp at point one day into the future
12887 - on a headline, switch to the next TODO keyword.
12888 - on an item, switch entire list to the next bullet type
12889 - on a property line, switch to the next allowed value
12890 - on a clocktable definition line, move time block into the future"
12891 (interactive "P")
12892 (cond
12893 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12894 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12895 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12896 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12897 ((org-clocktable-try-shift 'right arg))
12898 (t (org-shiftcursor-error))))
12900 (defun org-shiftleft (&optional arg)
12901 "Cycle the thing at point or in the current line, depending on context.
12902 Depending on context, this does one of the following:
12904 - switch a timestamp at point one day into the past
12905 - on a headline, switch to the previous TODO keyword.
12906 - on an item, switch entire list to the previous bullet type
12907 - on a property line, switch to the previous allowed value
12908 - on a clocktable definition line, move time block into the past"
12909 (interactive "P")
12910 (cond
12911 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12912 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12913 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12914 ((org-at-property-p)
12915 (call-interactively 'org-property-previous-allowed-value))
12916 ((org-clocktable-try-shift 'left arg))
12917 (t (org-shiftcursor-error))))
12919 (defun org-shiftcontrolright ()
12920 "Switch to next TODO set."
12921 (interactive)
12922 (cond
12923 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12924 (t (org-shiftcursor-error))))
12926 (defun org-shiftcontrolleft ()
12927 "Switch to previous TODO set."
12928 (interactive)
12929 (cond
12930 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12931 (t (org-shiftcursor-error))))
12933 (defun org-ctrl-c-ret ()
12934 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12935 (interactive)
12936 (cond
12937 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12938 (t (call-interactively 'org-insert-heading))))
12940 (defun org-copy-special ()
12941 "Copy region in table or copy current subtree.
12942 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12943 See the individual commands for more information."
12944 (interactive)
12945 (call-interactively
12946 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12948 (defun org-cut-special ()
12949 "Cut region in table or cut current subtree.
12950 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12951 See the individual commands for more information."
12952 (interactive)
12953 (call-interactively
12954 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12956 (defun org-paste-special (arg)
12957 "Paste rectangular region into table, or past subtree relative to level.
12958 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12959 See the individual commands for more information."
12960 (interactive "P")
12961 (if (org-at-table-p)
12962 (org-table-paste-rectangle)
12963 (org-paste-subtree arg)))
12965 (defun org-edit-special ()
12966 "Call a special editor for the stuff at point.
12967 When at a table, call the formula editor with `org-table-edit-formulas'.
12968 When at the first line of an src example, call `org-edit-src-code'.
12969 When in an #+include line, visit the include file. Otherwise call
12970 `ffap' to visit the file at point."
12971 (interactive)
12972 (cond
12973 ((org-at-table-p)
12974 (call-interactively 'org-table-edit-formulas))
12975 ((save-excursion
12976 (beginning-of-line 1)
12977 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12978 (find-file (org-trim (match-string 1))))
12979 ((org-edit-src-code))
12980 ((org-edit-fixed-width-region))
12981 (t (call-interactively 'ffap))))
12983 (defun org-ctrl-c-ctrl-c (&optional arg)
12984 "Set tags in headline, or update according to changed information at point.
12986 This command does many different things, depending on context:
12988 - If the cursor is in a headline, prompt for tags and insert them
12989 into the current line, aligned to `org-tags-column'. When called
12990 with prefix arg, realign all tags in the current buffer.
12992 - If the cursor is in one of the special #+KEYWORD lines, this
12993 triggers scanning the buffer for these lines and updating the
12994 information.
12996 - If the cursor is inside a table, realign the table. This command
12997 works even if the automatic table editor has been turned off.
12999 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13000 the entire table.
13002 - If the cursor is a the beginning of a dynamic block, update it.
13004 - If the cursor is inside a table created by the table.el package,
13005 activate that table.
13007 - If the current buffer is a remember buffer, close note and file
13008 it. A prefix argument of 1 files to the default location
13009 without further interaction. A prefix argument of 2 files to
13010 the currently clocking task.
13012 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13013 links in this buffer.
13015 - If the cursor is on a numbered item in a plain list, renumber the
13016 ordered list.
13018 - If the cursor is on a checkbox, toggle it."
13019 (interactive "P")
13020 (let ((org-enable-table-editor t))
13021 (cond
13022 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13023 org-occur-highlights
13024 org-latex-fragment-image-overlays)
13025 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13026 (org-remove-occur-highlights)
13027 (org-remove-latex-fragment-image-overlays)
13028 (message "Temporary highlights/overlays removed from current buffer"))
13029 ((and (local-variable-p 'org-finish-function (current-buffer))
13030 (fboundp org-finish-function))
13031 (funcall org-finish-function))
13032 ((org-at-property-p)
13033 (call-interactively 'org-property-action))
13034 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13035 ((org-on-heading-p) (call-interactively 'org-set-tags))
13036 ((org-at-table.el-p)
13037 (require 'table)
13038 (beginning-of-line 1)
13039 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13040 (call-interactively 'table-recognize-table))
13041 ((org-at-table-p)
13042 (org-table-maybe-eval-formula)
13043 (if arg
13044 (call-interactively 'org-table-recalculate)
13045 (org-table-maybe-recalculate-line))
13046 (call-interactively 'org-table-align))
13047 ((org-at-item-checkbox-p)
13048 (call-interactively 'org-toggle-checkbox))
13049 ((org-at-item-p)
13050 (call-interactively 'org-maybe-renumber-ordered-list))
13051 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13052 ;; Dynamic block
13053 (beginning-of-line 1)
13054 (save-excursion (org-update-dblock)))
13055 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13056 (cond
13057 ((equal (match-string 1) "TBLFM")
13058 ;; Recalculate the table before this line
13059 (save-excursion
13060 (beginning-of-line 1)
13061 (skip-chars-backward " \r\n\t")
13062 (if (org-at-table-p)
13063 (org-call-with-arg 'org-table-recalculate t))))
13065 ; (org-set-regexps-and-options)
13066 ; (org-restart-font-lock)
13067 (let ((org-inhibit-startup t)) (org-mode-restart))
13068 (message "Local setup has been refreshed"))))
13069 (t (error "C-c C-c can do nothing useful at this location.")))))
13071 (defun org-mode-restart ()
13072 "Restart Org-mode, to scan again for special lines.
13073 Also updates the keyword regular expressions."
13074 (interactive)
13075 (org-mode)
13076 (message "Org-mode restarted"))
13078 (defun org-kill-note-or-show-branches ()
13079 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13080 (interactive)
13081 (if (not org-finish-function)
13082 (call-interactively 'show-branches)
13083 (let ((org-note-abort t))
13084 (funcall org-finish-function))))
13086 (defun org-return (&optional indent)
13087 "Goto next table row or insert a newline.
13088 Calls `org-table-next-row' or `newline', depending on context.
13089 See the individual commands for more information."
13090 (interactive)
13091 (cond
13092 ((bobp) (if indent (newline-and-indent) (newline)))
13093 ((and (org-at-heading-p)
13094 (looking-at
13095 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13096 (org-show-entry)
13097 (end-of-line 1)
13098 (newline))
13099 ((org-at-table-p)
13100 (org-table-justify-field-maybe)
13101 (call-interactively 'org-table-next-row))
13102 (t (if indent (newline-and-indent) (newline)))))
13104 (defun org-return-indent ()
13105 "Goto next table row or insert a newline and indent.
13106 Calls `org-table-next-row' or `newline-and-indent', depending on
13107 context. See the individual commands for more information."
13108 (interactive)
13109 (org-return t))
13111 (defun org-ctrl-c-star ()
13112 "Compute table, or change heading status of lines.
13113 Calls `org-table-recalculate' or `org-toggle-region-headings',
13114 depending on context. This will also turn a plain list item or a normal
13115 line into a subheading."
13116 (interactive)
13117 (cond
13118 ((org-at-table-p)
13119 (call-interactively 'org-table-recalculate))
13120 ((org-region-active-p)
13121 ;; Convert all lines in region to list items
13122 (call-interactively 'org-toggle-region-headings))
13123 ((org-on-heading-p)
13124 (org-toggle-region-headings (point-at-bol)
13125 (min (1+ (point-at-eol)) (point-max))))
13126 ((org-at-item-p)
13127 ;; Convert to heading
13128 (let ((level (save-match-data
13129 (save-excursion
13130 (condition-case nil
13131 (progn
13132 (org-back-to-heading t)
13133 (funcall outline-level))
13134 (error 0))))))
13135 (replace-match
13136 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13137 (t (org-toggle-region-headings (point-at-bol)
13138 (min (1+ (point-at-eol)) (point-max))))))
13140 (defun org-ctrl-c-minus ()
13141 "Insert separator line in table or modify bullet status of line.
13142 Also turns a plain line or a region of lines into list items.
13143 Calls `org-table-insert-hline', `org-toggle-region-items', or
13144 `org-cycle-list-bullet', depending on context."
13145 (interactive)
13146 (cond
13147 ((org-at-table-p)
13148 (call-interactively 'org-table-insert-hline))
13149 ((org-on-heading-p)
13150 ;; Convert to item
13151 (save-excursion
13152 (beginning-of-line 1)
13153 (if (looking-at "\\*+ ")
13154 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13155 ((org-region-active-p)
13156 ;; Convert all lines in region to list items
13157 (call-interactively 'org-toggle-region-items))
13158 ((org-in-item-p)
13159 (call-interactively 'org-cycle-list-bullet))
13160 (t (org-toggle-region-items (point-at-bol)
13161 (min (1+ (point-at-eol)) (point-max))))))
13163 (defun org-toggle-region-items (beg end)
13164 "Convert all lines in region to list items.
13165 If the first line is already an item, convert all list items in the region
13166 to normal lines."
13167 (interactive "r")
13168 (let (l2 l)
13169 (save-excursion
13170 (goto-char end)
13171 (setq l2 (org-current-line))
13172 (goto-char beg)
13173 (beginning-of-line 1)
13174 (setq l (1- (org-current-line)))
13175 (if (org-at-item-p)
13176 ;; We already have items, de-itemize
13177 (while (< (setq l (1+ l)) l2)
13178 (when (org-at-item-p)
13179 (goto-char (match-beginning 2))
13180 (delete-region (match-beginning 2) (match-end 2))
13181 (and (looking-at "[ \t]+") (replace-match "")))
13182 (beginning-of-line 2))
13183 (while (< (setq l (1+ l)) l2)
13184 (unless (org-at-item-p)
13185 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13186 (replace-match "\\1- \\2")))
13187 (beginning-of-line 2))))))
13189 (defun org-toggle-region-headings (beg end)
13190 "Convert all lines in region to list items.
13191 If the first line is already an item, convert all list items in the region
13192 to normal lines."
13193 (interactive "r")
13194 (let (l2 l)
13195 (save-excursion
13196 (goto-char end)
13197 (setq l2 (org-current-line))
13198 (goto-char beg)
13199 (beginning-of-line 1)
13200 (setq l (1- (org-current-line)))
13201 (if (org-on-heading-p)
13202 ;; We already have headlines, de-star them
13203 (while (< (setq l (1+ l)) l2)
13204 (when (org-on-heading-p t)
13205 (and (looking-at outline-regexp) (replace-match "")))
13206 (beginning-of-line 2))
13207 (let* ((stars (save-excursion
13208 (re-search-backward org-complex-heading-regexp nil t)
13209 (or (match-string 1) "*")))
13210 (add-stars (if org-odd-levels-only "**" "*"))
13211 (rpl (concat stars add-stars " \\2")))
13212 (while (< (setq l (1+ l)) l2)
13213 (unless (org-on-heading-p)
13214 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13215 (replace-match rpl)))
13216 (beginning-of-line 2)))))))
13218 (defun org-meta-return (&optional arg)
13219 "Insert a new heading or wrap a region in a table.
13220 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13221 See the individual commands for more information."
13222 (interactive "P")
13223 (cond
13224 ((org-at-table-p)
13225 (call-interactively 'org-table-wrap-region))
13226 (t (call-interactively 'org-insert-heading))))
13228 ;;; Menu entries
13230 ;; Define the Org-mode menus
13231 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13232 '("Tbl"
13233 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13234 ["Next Field" org-cycle (org-at-table-p)]
13235 ["Previous Field" org-shifttab (org-at-table-p)]
13236 ["Next Row" org-return (org-at-table-p)]
13237 "--"
13238 ["Blank Field" org-table-blank-field (org-at-table-p)]
13239 ["Edit Field" org-table-edit-field (org-at-table-p)]
13240 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13241 "--"
13242 ("Column"
13243 ["Move Column Left" org-metaleft (org-at-table-p)]
13244 ["Move Column Right" org-metaright (org-at-table-p)]
13245 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13246 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13247 ("Row"
13248 ["Move Row Up" org-metaup (org-at-table-p)]
13249 ["Move Row Down" org-metadown (org-at-table-p)]
13250 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13251 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13252 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13253 "--"
13254 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13255 ("Rectangle"
13256 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13257 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13258 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13259 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13260 "--"
13261 ("Calculate"
13262 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13263 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13264 ["Edit Formulas" org-edit-special (org-at-table-p)]
13265 "--"
13266 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13267 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13268 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13269 "--"
13270 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13271 "--"
13272 ["Sum Column/Rectangle" org-table-sum
13273 (or (org-at-table-p) (org-region-active-p))]
13274 ["Which Column?" org-table-current-column (org-at-table-p)])
13275 ["Debug Formulas"
13276 org-table-toggle-formula-debugger
13277 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13278 ["Show Col/Row Numbers"
13279 org-table-toggle-coordinate-overlays
13280 :style toggle
13281 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13282 "--"
13283 ["Create" org-table-create (and (not (org-at-table-p))
13284 org-enable-table-editor)]
13285 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13286 ["Import from File" org-table-import (not (org-at-table-p))]
13287 ["Export to File" org-table-export (org-at-table-p)]
13288 "--"
13289 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13291 (easy-menu-define org-org-menu org-mode-map "Org menu"
13292 '("Org"
13293 ("Show/Hide"
13294 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13295 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13296 ["Sparse Tree..." org-sparse-tree t]
13297 ["Reveal Context" org-reveal t]
13298 ["Show All" show-all t]
13299 "--"
13300 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13301 "--"
13302 ["New Heading" org-insert-heading t]
13303 ("Navigate Headings"
13304 ["Up" outline-up-heading t]
13305 ["Next" outline-next-visible-heading t]
13306 ["Previous" outline-previous-visible-heading t]
13307 ["Next Same Level" outline-forward-same-level t]
13308 ["Previous Same Level" outline-backward-same-level t]
13309 "--"
13310 ["Jump" org-goto t])
13311 ("Edit Structure"
13312 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13313 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13314 "--"
13315 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13316 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13317 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13318 "--"
13319 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13320 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13321 ["Demote Heading" org-metaright (not (org-at-table-p))]
13322 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13323 "--"
13324 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13325 "--"
13326 ["Convert to odd levels" org-convert-to-odd-levels t]
13327 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13328 ("Editing"
13329 ["Emphasis..." org-emphasize t]
13330 ["Edit Source Example" org-edit-special t])
13331 ("Archive"
13332 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13333 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13334 ; :active t :keys "C-u C-c C-x C-a"]
13335 ["Sparse trees open ARCHIVE trees"
13336 (setq org-sparse-tree-open-archived-trees
13337 (not org-sparse-tree-open-archived-trees))
13338 :style toggle :selected org-sparse-tree-open-archived-trees]
13339 ["Cycling opens ARCHIVE trees"
13340 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13341 :style toggle :selected org-cycle-open-archived-trees]
13342 "--"
13343 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13344 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13345 ; ["Check and Move Children" (org-archive-subtree '(4))
13346 ; :active t :keys "C-u C-c C-x C-s"]
13348 "--"
13349 ("TODO Lists"
13350 ["TODO/DONE/-" org-todo t]
13351 ("Select keyword"
13352 ["Next keyword" org-shiftright (org-on-heading-p)]
13353 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13354 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13355 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13356 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13357 ["Show TODO Tree" org-show-todo-tree t]
13358 ["Global TODO list" org-todo-list t]
13359 "--"
13360 ["Set Priority" org-priority t]
13361 ["Priority Up" org-shiftup t]
13362 ["Priority Down" org-shiftdown t])
13363 ("TAGS and Properties"
13364 ["Set Tags" org-set-tags-command t]
13365 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13366 "--"
13367 ["Set property" 'org-set-property t]
13368 ["Column view of properties" org-columns t]
13369 ["Insert Column View DBlock" org-insert-columns-dblock t])
13370 ("Dates and Scheduling"
13371 ["Timestamp" org-time-stamp t]
13372 ["Timestamp (inactive)" org-time-stamp-inactive t]
13373 ("Change Date"
13374 ["1 Day Later" org-shiftright t]
13375 ["1 Day Earlier" org-shiftleft t]
13376 ["1 ... Later" org-shiftup t]
13377 ["1 ... Earlier" org-shiftdown t])
13378 ["Compute Time Range" org-evaluate-time-range t]
13379 ["Schedule Item" org-schedule t]
13380 ["Deadline" org-deadline t]
13381 "--"
13382 ["Custom time format" org-toggle-time-stamp-overlays
13383 :style radio :selected org-display-custom-times]
13384 "--"
13385 ["Goto Calendar" org-goto-calendar t]
13386 ["Date from Calendar" org-date-from-calendar t]
13387 "--"
13388 ["Start/restart timer" org-timer-start t]
13389 ["Insert timer string" org-timer t]
13390 ["Insert timer item" org-timer-item t])
13391 ("Logging work"
13392 ["Clock in" org-clock-in t]
13393 ["Clock out" org-clock-out t]
13394 ["Clock cancel" org-clock-cancel t]
13395 ["Goto running clock" org-clock-goto t]
13396 ["Display times" org-clock-display t]
13397 ["Create clock table" org-clock-report t]
13398 "--"
13399 ["Record DONE time"
13400 (progn (setq org-log-done (not org-log-done))
13401 (message "Switching to %s will %s record a timestamp"
13402 (car org-done-keywords)
13403 (if org-log-done "automatically" "not")))
13404 :style toggle :selected org-log-done])
13405 "--"
13406 ["Agenda Command..." org-agenda t]
13407 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13408 ("File List for Agenda")
13409 ("Special views current file"
13410 ["TODO Tree" org-show-todo-tree t]
13411 ["Check Deadlines" org-check-deadlines t]
13412 ["Timeline" org-timeline t]
13413 ["Tags Tree" org-tags-sparse-tree t])
13414 "--"
13415 ("Hyperlinks"
13416 ["Store Link (Global)" org-store-link t]
13417 ["Insert Link" org-insert-link t]
13418 ["Follow Link" org-open-at-point t]
13419 "--"
13420 ["Next link" org-next-link t]
13421 ["Previous link" org-previous-link t]
13422 "--"
13423 ["Descriptive Links"
13424 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13425 :style radio
13426 :selected (member '(org-link) buffer-invisibility-spec)]
13427 ["Literal Links"
13428 (progn
13429 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13430 :style radio
13431 :selected (not (member '(org-link) buffer-invisibility-spec))])
13432 "--"
13433 ["Export/Publish..." org-export t]
13434 ("LaTeX"
13435 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13436 :selected org-cdlatex-mode]
13437 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13438 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13439 ["Modify math symbol" org-cdlatex-math-modify
13440 (org-inside-LaTeX-fragment-p)]
13441 ["Export LaTeX fragments as images"
13442 (if (featurep 'org-exp)
13443 (setq org-export-with-LaTeX-fragments
13444 (not org-export-with-LaTeX-fragments))
13445 (require 'org-exp))
13446 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13447 org-export-with-LaTeX-fragments)])
13448 "--"
13449 ("Documentation"
13450 ["Show Version" org-version t]
13451 ["Info Documentation" org-info t])
13452 ("Customize"
13453 ["Browse Org Group" org-customize t]
13454 "--"
13455 ["Expand This Menu" org-create-customize-menu
13456 (fboundp 'customize-menu-create)])
13457 "--"
13458 ["Refresh setup" org-mode-restart t]
13461 (defun org-info (&optional node)
13462 "Read documentation for Org-mode in the info system.
13463 With optional NODE, go directly to that node."
13464 (interactive)
13465 (info (format "(org)%s" (or node ""))))
13467 (defun org-install-agenda-files-menu ()
13468 (let ((bl (buffer-list)))
13469 (save-excursion
13470 (while bl
13471 (set-buffer (pop bl))
13472 (if (org-mode-p) (setq bl nil)))
13473 (when (org-mode-p)
13474 (easy-menu-change
13475 '("Org") "File List for Agenda"
13476 (append
13477 (list
13478 ["Edit File List" (org-edit-agenda-file-list) t]
13479 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13480 ["Remove Current File from List" org-remove-file t]
13481 ["Cycle through agenda files" org-cycle-agenda-files t]
13482 ["Occur in all agenda files" org-occur-in-agenda-files t]
13483 "--")
13484 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13486 ;;;; Documentation
13488 ;;;###autoload
13489 (defun org-require-autoloaded-modules ()
13490 (interactive)
13491 (mapc 'require
13492 '(org-agenda org-archive org-clock org-colview
13493 org-exp org-id org-export-latex org-publish
13494 org-remember org-table)))
13496 ;;;###autoload
13497 (defun org-customize ()
13498 "Call the customize function with org as argument."
13499 (interactive)
13500 (org-load-modules-maybe)
13501 (org-require-autoloaded-modules)
13502 (customize-browse 'org))
13504 (defun org-create-customize-menu ()
13505 "Create a full customization menu for Org-mode, insert it into the menu."
13506 (interactive)
13507 (org-load-modules-maybe)
13508 (org-require-autoloaded-modules)
13509 (if (fboundp 'customize-menu-create)
13510 (progn
13511 (easy-menu-change
13512 '("Org") "Customize"
13513 `(["Browse Org group" org-customize t]
13514 "--"
13515 ,(customize-menu-create 'org)
13516 ["Set" Custom-set t]
13517 ["Save" Custom-save t]
13518 ["Reset to Current" Custom-reset-current t]
13519 ["Reset to Saved" Custom-reset-saved t]
13520 ["Reset to Standard Settings" Custom-reset-standard t]))
13521 (message "\"Org\"-menu now contains full customization menu"))
13522 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13524 ;;;; Miscellaneous stuff
13526 ;;; Generally useful functions
13528 (defun org-find-text-property-in-string (prop s)
13529 "Return the first non-nil value of property PROP in string S."
13530 (or (get-text-property 0 prop s)
13531 (get-text-property (or (next-single-property-change 0 prop s) 0)
13532 prop s)))
13534 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13535 "Display the given MESSAGE as a warning."
13536 (if (fboundp 'display-warning)
13537 (display-warning 'org message
13538 (if (featurep 'xemacs)
13539 'warning
13540 :warning))
13541 (let ((buf (get-buffer-create "*Org warnings*")))
13542 (with-current-buffer buf
13543 (goto-char (point-max))
13544 (insert "Warning (Org): " message)
13545 (unless (bolp)
13546 (newline)))
13547 (display-buffer buf)
13548 (sit-for 0))))
13550 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13551 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13552 (if (and marker (marker-buffer marker)
13553 (buffer-live-p (marker-buffer marker)))
13554 (progn
13555 (switch-to-buffer (marker-buffer marker))
13556 (if (or (> marker (point-max)) (< marker (point-min)))
13557 (widen))
13558 (goto-char marker))
13559 (if bookmark
13560 (bookmark-jump bookmark)
13561 (error "Cannot find location"))))
13563 (defun org-quote-csv-field (s)
13564 "Quote field for inclusion in CSV material."
13565 (if (string-match "[\",]" s)
13566 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13569 (defun org-plist-delete (plist property)
13570 "Delete PROPERTY from PLIST.
13571 This is in contrast to merely setting it to 0."
13572 (let (p)
13573 (while plist
13574 (if (not (eq property (car plist)))
13575 (setq p (plist-put p (car plist) (nth 1 plist))))
13576 (setq plist (cddr plist)))
13579 (defun org-force-self-insert (N)
13580 "Needed to enforce self-insert under remapping."
13581 (interactive "p")
13582 (self-insert-command N))
13584 (defun org-string-width (s)
13585 "Compute width of string, ignoring invisible characters.
13586 This ignores character with invisibility property `org-link', and also
13587 characters with property `org-cwidth', because these will become invisible
13588 upon the next fontification round."
13589 (let (b l)
13590 (when (or (eq t buffer-invisibility-spec)
13591 (assq 'org-link buffer-invisibility-spec))
13592 (while (setq b (text-property-any 0 (length s)
13593 'invisible 'org-link s))
13594 (setq s (concat (substring s 0 b)
13595 (substring s (or (next-single-property-change
13596 b 'invisible s) (length s)))))))
13597 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13598 (setq s (concat (substring s 0 b)
13599 (substring s (or (next-single-property-change
13600 b 'org-cwidth s) (length s))))))
13601 (setq l (string-width s) b -1)
13602 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13603 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13606 (defun org-get-indentation (&optional line)
13607 "Get the indentation of the current line, interpreting tabs.
13608 When LINE is given, assume it represents a line and compute its indentation."
13609 (if line
13610 (if (string-match "^ *" (org-remove-tabs line))
13611 (match-end 0))
13612 (save-excursion
13613 (beginning-of-line 1)
13614 (skip-chars-forward " \t")
13615 (current-column))))
13617 (defun org-remove-tabs (s &optional width)
13618 "Replace tabulators in S with spaces.
13619 Assumes that s is a single line, starting in column 0."
13620 (setq width (or width tab-width))
13621 (while (string-match "\t" s)
13622 (setq s (replace-match
13623 (make-string
13624 (- (* width (/ (+ (match-beginning 0) width) width))
13625 (match-beginning 0)) ?\ )
13626 t t s)))
13629 (defun org-fix-indentation (line ind)
13630 "Fix indentation in LINE.
13631 IND is a cons cell with target and minimum indentation.
13632 If the current indentation in LINE is smaller than the minimum,
13633 leave it alone. If it is larger than ind, set it to the target."
13634 (let* ((l (org-remove-tabs line))
13635 (i (org-get-indentation l))
13636 (i1 (car ind)) (i2 (cdr ind)))
13637 (if (>= i i2) (setq l (substring line i2)))
13638 (if (> i1 0)
13639 (concat (make-string i1 ?\ ) l)
13640 l)))
13642 (defun org-base-buffer (buffer)
13643 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13644 (if (not buffer)
13645 buffer
13646 (or (buffer-base-buffer buffer)
13647 buffer)))
13649 (defun org-trim (s)
13650 "Remove whitespace at beginning and end of string."
13651 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13652 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13655 (defun org-wrap (string &optional width lines)
13656 "Wrap string to either a number of lines, or a width in characters.
13657 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13658 that costs. If there is a word longer than WIDTH, the text is actually
13659 wrapped to the length of that word.
13660 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13661 many lines, whatever width that takes.
13662 The return value is a list of lines, without newlines at the end."
13663 (let* ((words (org-split-string string "[ \t\n]+"))
13664 (maxword (apply 'max (mapcar 'org-string-width words)))
13665 w ll)
13666 (cond (width
13667 (org-do-wrap words (max maxword width)))
13668 (lines
13669 (setq w maxword)
13670 (setq ll (org-do-wrap words maxword))
13671 (if (<= (length ll) lines)
13673 (setq ll words)
13674 (while (> (length ll) lines)
13675 (setq w (1+ w))
13676 (setq ll (org-do-wrap words w)))
13677 ll))
13678 (t (error "Cannot wrap this")))))
13680 (defun org-do-wrap (words width)
13681 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13682 (let (lines line)
13683 (while words
13684 (setq line (pop words))
13685 (while (and words (< (+ (length line) (length (car words))) width))
13686 (setq line (concat line " " (pop words))))
13687 (setq lines (push line lines)))
13688 (nreverse lines)))
13690 (defun org-split-string (string &optional separators)
13691 "Splits STRING into substrings at SEPARATORS.
13692 No empty strings are returned if there are matches at the beginning
13693 and end of string."
13694 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13695 (start 0)
13696 notfirst
13697 (list nil))
13698 (while (and (string-match rexp string
13699 (if (and notfirst
13700 (= start (match-beginning 0))
13701 (< start (length string)))
13702 (1+ start) start))
13703 (< (match-beginning 0) (length string)))
13704 (setq notfirst t)
13705 (or (eq (match-beginning 0) 0)
13706 (and (eq (match-beginning 0) (match-end 0))
13707 (eq (match-beginning 0) start))
13708 (setq list
13709 (cons (substring string start (match-beginning 0))
13710 list)))
13711 (setq start (match-end 0)))
13712 (or (eq start (length string))
13713 (setq list
13714 (cons (substring string start)
13715 list)))
13716 (nreverse list)))
13718 (defun org-context ()
13719 "Return a list of contexts of the current cursor position.
13720 If several contexts apply, all are returned.
13721 Each context entry is a list with a symbol naming the context, and
13722 two positions indicating start and end of the context. Possible
13723 contexts are:
13725 :headline anywhere in a headline
13726 :headline-stars on the leading stars in a headline
13727 :todo-keyword on a TODO keyword (including DONE) in a headline
13728 :tags on the TAGS in a headline
13729 :priority on the priority cookie in a headline
13730 :item on the first line of a plain list item
13731 :item-bullet on the bullet/number of a plain list item
13732 :checkbox on the checkbox in a plain list item
13733 :table in an org-mode table
13734 :table-special on a special filed in a table
13735 :table-table in a table.el table
13736 :link on a hyperlink
13737 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13738 :target on a <<target>>
13739 :radio-target on a <<<radio-target>>>
13740 :latex-fragment on a LaTeX fragment
13741 :latex-preview on a LaTeX fragment with overlayed preview image
13743 This function expects the position to be visible because it uses font-lock
13744 faces as a help to recognize the following contexts: :table-special, :link,
13745 and :keyword."
13746 (let* ((f (get-text-property (point) 'face))
13747 (faces (if (listp f) f (list f)))
13748 (p (point)) clist o)
13749 ;; First the large context
13750 (cond
13751 ((org-on-heading-p t)
13752 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13753 (when (progn
13754 (beginning-of-line 1)
13755 (looking-at org-todo-line-tags-regexp))
13756 (push (org-point-in-group p 1 :headline-stars) clist)
13757 (push (org-point-in-group p 2 :todo-keyword) clist)
13758 (push (org-point-in-group p 4 :tags) clist))
13759 (goto-char p)
13760 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13761 (if (looking-at "\\[#[A-Z0-9]\\]")
13762 (push (org-point-in-group p 0 :priority) clist)))
13764 ((org-at-item-p)
13765 (push (org-point-in-group p 2 :item-bullet) clist)
13766 (push (list :item (point-at-bol)
13767 (save-excursion (org-end-of-item) (point)))
13768 clist)
13769 (and (org-at-item-checkbox-p)
13770 (push (org-point-in-group p 0 :checkbox) clist)))
13772 ((org-at-table-p)
13773 (push (list :table (org-table-begin) (org-table-end)) clist)
13774 (if (memq 'org-formula faces)
13775 (push (list :table-special
13776 (previous-single-property-change p 'face)
13777 (next-single-property-change p 'face)) clist)))
13778 ((org-at-table-p 'any)
13779 (push (list :table-table) clist)))
13780 (goto-char p)
13782 ;; Now the small context
13783 (cond
13784 ((org-at-timestamp-p)
13785 (push (org-point-in-group p 0 :timestamp) clist))
13786 ((memq 'org-link faces)
13787 (push (list :link
13788 (previous-single-property-change p 'face)
13789 (next-single-property-change p 'face)) clist))
13790 ((memq 'org-special-keyword faces)
13791 (push (list :keyword
13792 (previous-single-property-change p 'face)
13793 (next-single-property-change p 'face)) clist))
13794 ((org-on-target-p)
13795 (push (org-point-in-group p 0 :target) clist)
13796 (goto-char (1- (match-beginning 0)))
13797 (if (looking-at org-radio-target-regexp)
13798 (push (org-point-in-group p 0 :radio-target) clist))
13799 (goto-char p))
13800 ((setq o (car (delq nil
13801 (mapcar
13802 (lambda (x)
13803 (if (memq x org-latex-fragment-image-overlays) x))
13804 (org-overlays-at (point))))))
13805 (push (list :latex-fragment
13806 (org-overlay-start o) (org-overlay-end o)) clist)
13807 (push (list :latex-preview
13808 (org-overlay-start o) (org-overlay-end o)) clist))
13809 ((org-inside-LaTeX-fragment-p)
13810 ;; FIXME: positions wrong.
13811 (push (list :latex-fragment (point) (point)) clist)))
13813 (setq clist (nreverse (delq nil clist)))
13814 clist))
13816 ;; FIXME: Compare with at-regexp-p Do we need both?
13817 (defun org-in-regexp (re &optional nlines visually)
13818 "Check if point is inside a match of regexp.
13819 Normally only the current line is checked, but you can include NLINES extra
13820 lines both before and after point into the search.
13821 If VISUALLY is set, require that the cursor is not after the match but
13822 really on, so that the block visually is on the match."
13823 (catch 'exit
13824 (let ((pos (point))
13825 (eol (point-at-eol (+ 1 (or nlines 0))))
13826 (inc (if visually 1 0)))
13827 (save-excursion
13828 (beginning-of-line (- 1 (or nlines 0)))
13829 (while (re-search-forward re eol t)
13830 (if (and (<= (match-beginning 0) pos)
13831 (>= (+ inc (match-end 0)) pos))
13832 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13834 (defun org-at-regexp-p (regexp)
13835 "Is point inside a match of REGEXP in the current line?"
13836 (catch 'exit
13837 (save-excursion
13838 (let ((pos (point)) (end (point-at-eol)))
13839 (beginning-of-line 1)
13840 (while (re-search-forward regexp end t)
13841 (if (and (<= (match-beginning 0) pos)
13842 (>= (match-end 0) pos))
13843 (throw 'exit t)))
13844 nil))))
13846 (defun org-occur-in-agenda-files (regexp &optional nlines)
13847 "Call `multi-occur' with buffers for all agenda files."
13848 (interactive "sOrg-files matching: \np")
13849 (let* ((files (org-agenda-files))
13850 (tnames (mapcar 'file-truename files))
13851 (extra org-agenda-text-search-extra-files)
13853 (when (eq (car extra) 'agenda-archives)
13854 (setq extra (cdr extra))
13855 (setq files (org-add-archive-files files)))
13856 (while (setq f (pop extra))
13857 (unless (member (file-truename f) tnames)
13858 (add-to-list 'files f 'append)
13859 (add-to-list 'tnames (file-truename f) 'append)))
13860 (multi-occur
13861 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13862 regexp)))
13864 (if (boundp 'occur-mode-find-occurrence-hook)
13865 ;; Emacs 23
13866 (add-hook 'occur-mode-find-occurrence-hook
13867 (lambda ()
13868 (when (org-mode-p)
13869 (org-reveal))))
13870 ;; Emacs 22
13871 (defadvice occur-mode-goto-occurrence
13872 (after org-occur-reveal activate)
13873 (and (org-mode-p) (org-reveal)))
13874 (defadvice occur-mode-goto-occurrence-other-window
13875 (after org-occur-reveal activate)
13876 (and (org-mode-p) (org-reveal)))
13877 (defadvice occur-mode-display-occurrence
13878 (after org-occur-reveal activate)
13879 (when (org-mode-p)
13880 (let ((pos (occur-mode-find-occurrence)))
13881 (with-current-buffer (marker-buffer pos)
13882 (save-excursion
13883 (goto-char pos)
13884 (org-reveal)))))))
13886 (defun org-uniquify (list)
13887 "Remove duplicate elements from LIST."
13888 (let (res)
13889 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13890 res))
13892 (defun org-delete-all (elts list)
13893 "Remove all elements in ELTS from LIST."
13894 (while elts
13895 (setq list (delete (pop elts) list)))
13896 list)
13898 (defun org-back-over-empty-lines ()
13899 "Move backwards over whitespace, to the beginning of the first empty line.
13900 Returns the number of empty lines passed."
13901 (let ((pos (point)))
13902 (skip-chars-backward " \t\n\r")
13903 (beginning-of-line 2)
13904 (goto-char (min (point) pos))
13905 (count-lines (point) pos)))
13907 (defun org-skip-whitespace ()
13908 (skip-chars-forward " \t\n\r"))
13910 (defun org-point-in-group (point group &optional context)
13911 "Check if POINT is in match-group GROUP.
13912 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13913 match. If the match group does ot exist or point is not inside it,
13914 return nil."
13915 (and (match-beginning group)
13916 (>= point (match-beginning group))
13917 (<= point (match-end group))
13918 (if context
13919 (list context (match-beginning group) (match-end group))
13920 t)))
13922 (defun org-switch-to-buffer-other-window (&rest args)
13923 "Switch to buffer in a second window on the current frame.
13924 In particular, do not allow pop-up frames."
13925 (let (pop-up-frames special-display-buffer-names special-display-regexps
13926 special-display-function)
13927 (apply 'switch-to-buffer-other-window args)))
13929 (defun org-combine-plists (&rest plists)
13930 "Create a single property list from all plists in PLISTS.
13931 The process starts by copying the first list, and then setting properties
13932 from the other lists. Settings in the last list are the most significant
13933 ones and overrule settings in the other lists."
13934 (let ((rtn (copy-sequence (pop plists)))
13935 p v ls)
13936 (while plists
13937 (setq ls (pop plists))
13938 (while ls
13939 (setq p (pop ls) v (pop ls))
13940 (setq rtn (plist-put rtn p v))))
13941 rtn))
13943 (defun org-move-line-down (arg)
13944 "Move the current line down. With prefix argument, move it past ARG lines."
13945 (interactive "p")
13946 (let ((col (current-column))
13947 beg end pos)
13948 (beginning-of-line 1) (setq beg (point))
13949 (beginning-of-line 2) (setq end (point))
13950 (beginning-of-line (+ 1 arg))
13951 (setq pos (move-marker (make-marker) (point)))
13952 (insert (delete-and-extract-region beg end))
13953 (goto-char pos)
13954 (org-move-to-column col)))
13956 (defun org-move-line-up (arg)
13957 "Move the current line up. With prefix argument, move it past ARG lines."
13958 (interactive "p")
13959 (let ((col (current-column))
13960 beg end pos)
13961 (beginning-of-line 1) (setq beg (point))
13962 (beginning-of-line 2) (setq end (point))
13963 (beginning-of-line (- arg))
13964 (setq pos (move-marker (make-marker) (point)))
13965 (insert (delete-and-extract-region beg end))
13966 (goto-char pos)
13967 (org-move-to-column col)))
13969 (defun org-replace-escapes (string table)
13970 "Replace %-escapes in STRING with values in TABLE.
13971 TABLE is an association list with keys like \"%a\" and string values.
13972 The sequences in STRING may contain normal field width and padding information,
13973 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13974 so values can contain further %-escapes if they are define later in TABLE."
13975 (let ((case-fold-search nil)
13976 e re rpl)
13977 (while (setq e (pop table))
13978 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13979 (while (string-match re string)
13980 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13981 (cdr e)))
13982 (setq string (replace-match rpl t t string))))
13983 string))
13986 (defun org-sublist (list start end)
13987 "Return a section of LIST, from START to END.
13988 Counting starts at 1."
13989 (let (rtn (c start))
13990 (setq list (nthcdr (1- start) list))
13991 (while (and list (<= c end))
13992 (push (pop list) rtn)
13993 (setq c (1+ c)))
13994 (nreverse rtn)))
13996 (defun org-find-base-buffer-visiting (file)
13997 "Like `find-buffer-visiting' but alway return the base buffer and
13998 not an indirect buffer."
13999 (let ((buf (find-buffer-visiting file)))
14000 (if buf
14001 (or (buffer-base-buffer buf) buf)
14002 nil)))
14004 (defun org-image-file-name-regexp ()
14005 "Return regexp matching the file names of images."
14006 (if (fboundp 'image-file-name-regexp)
14007 (image-file-name-regexp)
14008 (let ((image-file-name-extensions
14009 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14010 "xbm" "xpm" "pbm" "pgm" "ppm")))
14011 (concat "\\."
14012 (regexp-opt (nconc (mapcar 'upcase
14013 image-file-name-extensions)
14014 image-file-name-extensions)
14016 "\\'"))))
14018 (defun org-file-image-p (file)
14019 "Return non-nil if FILE is an image."
14020 (save-match-data
14021 (string-match (org-image-file-name-regexp) file)))
14023 (defun org-get-cursor-date ()
14024 "Return the date at cursor in as a time.
14025 This works in the calendar and in the agenda, anywhere else it just
14026 returns the current time."
14027 (let (date day defd)
14028 (cond
14029 ((eq major-mode 'calendar-mode)
14030 (setq date (calendar-cursor-to-date)
14031 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14032 ((eq major-mode 'org-agenda-mode)
14033 (setq day (get-text-property (point) 'day))
14034 (if day
14035 (setq date (calendar-gregorian-from-absolute day)
14036 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14037 (nth 2 date))))))
14038 (or defd (current-time))))
14040 (defvar org-agenda-action-marker (make-marker)
14041 "Marker pointing to the entry for the next agenda action.")
14043 (defun org-mark-entry-for-agenda-action ()
14044 "Mark the current entry as target of an agenda action.
14045 Agenda actions are actions executed from the agenda with the key `k',
14046 which make use of the date at the cursor."
14047 (interactive)
14048 (move-marker org-agenda-action-marker
14049 (save-excursion (org-back-to-heading t) (point))
14050 (current-buffer))
14051 (message
14052 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14054 ;;; Paragraph filling stuff.
14055 ;; We want this to be just right, so use the full arsenal.
14057 (defun org-indent-line-function ()
14058 "Indent line like previous, but further if previous was headline or item."
14059 (interactive)
14060 (let* ((pos (point))
14061 (itemp (org-at-item-p))
14062 column bpos bcol tpos tcol bullet btype bullet-type)
14063 ;; Find the previous relevant line
14064 (beginning-of-line 1)
14065 (cond
14066 ((looking-at "#") (setq column 0))
14067 ((looking-at "\\*+ ") (setq column 0))
14069 (beginning-of-line 0)
14070 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14071 (beginning-of-line 0))
14072 (cond
14073 ((looking-at "\\*+[ \t]+")
14074 (if (not org-adapt-indentation)
14075 (setq column 0)
14076 (goto-char (match-end 0))
14077 (setq column (current-column))))
14078 ((org-in-item-p)
14079 (org-beginning-of-item)
14080 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14081 (setq bpos (match-beginning 1) tpos (match-end 0)
14082 bcol (progn (goto-char bpos) (current-column))
14083 tcol (progn (goto-char tpos) (current-column))
14084 bullet (match-string 1)
14085 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14086 (if (> tcol (+ bcol org-description-max-indent))
14087 (setq tcol (+ bcol 5)))
14088 (if (not itemp)
14089 (setq column tcol)
14090 (goto-char pos)
14091 (beginning-of-line 1)
14092 (if (looking-at "\\S-")
14093 (progn
14094 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14095 (setq bullet (match-string 1)
14096 btype (if (string-match "[0-9]" bullet) "n" bullet))
14097 (setq column (if (equal btype bullet-type) bcol tcol)))
14098 (setq column (org-get-indentation)))))
14099 (t (setq column (org-get-indentation))))))
14100 (goto-char pos)
14101 (if (<= (current-column) (current-indentation))
14102 (org-indent-line-to column)
14103 (save-excursion (org-indent-line-to column)))
14104 (setq column (current-column))
14105 (beginning-of-line 1)
14106 (if (looking-at
14107 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14108 (replace-match (concat "\\1" (format org-property-format
14109 (match-string 2) (match-string 3)))
14110 t nil))
14111 (org-move-to-column column)))
14113 (defun org-set-autofill-regexps ()
14114 (interactive)
14115 ;; In the paragraph separator we include headlines, because filling
14116 ;; text in a line directly attached to a headline would otherwise
14117 ;; fill the headline as well.
14118 (org-set-local 'comment-start-skip "^#+[ \t]*")
14119 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14120 ;; The paragraph starter includes hand-formatted lists.
14121 (org-set-local 'paragraph-start
14122 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14123 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14124 ;; But only if the user has not turned off tables or fixed-width regions
14125 (org-set-local
14126 'auto-fill-inhibit-regexp
14127 (concat "\\*+ \\|#\\+"
14128 "\\|[ \t]*" org-keyword-time-regexp
14129 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14130 (concat
14131 "\\|[ \t]*["
14132 (if org-enable-table-editor "|" "")
14133 (if org-enable-fixed-width-editor ":" "")
14134 "]"))))
14135 ;; We use our own fill-paragraph function, to make sure that tables
14136 ;; and fixed-width regions are not wrapped. That function will pass
14137 ;; through to `fill-paragraph' when appropriate.
14138 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14139 ; Adaptive filling: To get full control, first make sure that
14140 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14141 (org-set-local 'adaptive-fill-regexp "\000")
14142 (org-set-local 'adaptive-fill-function
14143 'org-adaptive-fill-function)
14144 (org-set-local
14145 'align-mode-rules-list
14146 '((org-in-buffer-settings
14147 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14148 (modes . '(org-mode))))))
14150 (defun org-fill-paragraph (&optional justify)
14151 "Re-align a table, pass through to fill-paragraph if no table."
14152 (let ((table-p (org-at-table-p))
14153 (table.el-p (org-at-table.el-p)))
14154 (cond ((and (equal (char-after (point-at-bol)) ?*)
14155 (save-excursion (goto-char (point-at-bol))
14156 (looking-at outline-regexp)))
14157 t) ; skip headlines
14158 (table.el-p t) ; skip table.el tables
14159 (table-p (org-table-align) t) ; align org-mode tables
14160 (t nil)))) ; call paragraph-fill
14162 ;; For reference, this is the default value of adaptive-fill-regexp
14163 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14165 (defun org-adaptive-fill-function ()
14166 "Return a fill prefix for org-mode files.
14167 In particular, this makes sure hanging paragraphs for hand-formatted lists
14168 work correctly."
14169 (cond ((looking-at "#[ \t]+")
14170 (match-string 0))
14171 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14172 (save-excursion
14173 (if (> (match-end 1) (+ (match-beginning 1)
14174 org-description-max-indent))
14175 (goto-char (+ (match-beginning 1) 5))
14176 (goto-char (match-end 0)))
14177 (make-string (current-column) ?\ )))
14178 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14179 (save-excursion
14180 (goto-char (match-end 0))
14181 (make-string (current-column) ?\ )))
14182 (t nil)))
14184 ;;; Other stuff.
14186 (defun org-toggle-fixed-width-section (arg)
14187 "Toggle the fixed-width export.
14188 If there is no active region, the QUOTE keyword at the current headline is
14189 inserted or removed. When present, it causes the text between this headline
14190 and the next to be exported as fixed-width text, and unmodified.
14191 If there is an active region, this command adds or removes a colon as the
14192 first character of this line. If the first character of a line is a colon,
14193 this line is also exported in fixed-width font."
14194 (interactive "P")
14195 (let* ((cc 0)
14196 (regionp (org-region-active-p))
14197 (beg (if regionp (region-beginning) (point)))
14198 (end (if regionp (region-end)))
14199 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14200 (case-fold-search nil)
14201 (re "[ \t]*\\(:\\)")
14202 off)
14203 (if regionp
14204 (save-excursion
14205 (goto-char beg)
14206 (setq cc (current-column))
14207 (beginning-of-line 1)
14208 (setq off (looking-at re))
14209 (while (> nlines 0)
14210 (setq nlines (1- nlines))
14211 (beginning-of-line 1)
14212 (cond
14213 (arg
14214 (org-move-to-column cc t)
14215 (insert ":\n")
14216 (forward-line -1))
14217 ((and off (looking-at re))
14218 (replace-match "" t t nil 1))
14219 ((not off) (org-move-to-column cc t) (insert ":")))
14220 (forward-line 1)))
14221 (save-excursion
14222 (org-back-to-heading)
14223 (if (looking-at (concat outline-regexp
14224 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14225 (replace-match "" t t nil 1)
14226 (if (looking-at outline-regexp)
14227 (progn
14228 (goto-char (match-end 0))
14229 (insert org-quote-string " "))))))))
14231 ;;;; Functions extending outline functionality
14233 (defun org-beginning-of-line (&optional arg)
14234 "Go to the beginning of the current line. If that is invisible, continue
14235 to a visible line beginning. This makes the function of C-a more intuitive.
14236 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14237 first attempt, and only move to after the tags when the cursor is already
14238 beyond the end of the headline."
14239 (interactive "P")
14240 (let ((pos (point)) refpos)
14241 (beginning-of-line 1)
14242 (if (bobp)
14244 (backward-char 1)
14245 (if (org-invisible-p)
14246 (while (and (not (bobp)) (org-invisible-p))
14247 (backward-char 1)
14248 (beginning-of-line 1))
14249 (forward-char 1)))
14250 (when org-special-ctrl-a/e
14251 (cond
14252 ((and (looking-at org-complex-heading-regexp)
14253 (= (char-after (match-end 1)) ?\ ))
14254 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14255 (point-at-eol)))
14256 (goto-char
14257 (if (eq org-special-ctrl-a/e t)
14258 (cond ((> pos refpos) refpos)
14259 ((= pos (point)) refpos)
14260 (t (point)))
14261 (cond ((> pos (point)) (point))
14262 ((not (eq last-command this-command)) (point))
14263 (t refpos)))))
14264 ((org-at-item-p)
14265 (goto-char
14266 (if (eq org-special-ctrl-a/e t)
14267 (cond ((> pos (match-end 4)) (match-end 4))
14268 ((= pos (point)) (match-end 4))
14269 (t (point)))
14270 (cond ((> pos (point)) (point))
14271 ((not (eq last-command this-command)) (point))
14272 (t (match-end 4))))))))
14273 (org-no-warnings
14274 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14276 (defun org-end-of-line (&optional arg)
14277 "Go to the end of the line.
14278 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14279 first attempt, and only move to after the tags when the cursor is already
14280 beyond the end of the headline."
14281 (interactive "P")
14282 (if (or (not org-special-ctrl-a/e)
14283 (not (org-on-heading-p)))
14284 (end-of-line arg)
14285 (let ((pos (point)))
14286 (beginning-of-line 1)
14287 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14288 (if (eq org-special-ctrl-a/e t)
14289 (if (or (< pos (match-beginning 1))
14290 (= pos (match-end 0)))
14291 (goto-char (match-beginning 1))
14292 (goto-char (match-end 0)))
14293 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14294 (goto-char (match-end 0))
14295 (goto-char (match-beginning 1))))
14296 (end-of-line arg))))
14297 (org-no-warnings
14298 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14301 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14302 (define-key org-mode-map "\C-e" 'org-end-of-line)
14304 (defun org-kill-line (&optional arg)
14305 "Kill line, to tags or end of line."
14306 (interactive "P")
14307 (cond
14308 ((or (not org-special-ctrl-k)
14309 (bolp)
14310 (not (org-on-heading-p)))
14311 (call-interactively 'kill-line))
14312 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14313 (kill-region (point) (match-beginning 1))
14314 (org-set-tags nil t))
14315 (t (kill-region (point) (point-at-eol)))))
14317 (define-key org-mode-map "\C-k" 'org-kill-line)
14319 (defun org-yank (&optional arg)
14320 "Yank. If the kill is a subtree, treat it specially.
14321 This command will look at the current kill and check if is a single
14322 subtree, or a series of subtrees[1]. If it passes the test, and if the
14323 cursor is at the beginning of a line or after the stars of a currently
14324 empty headline, then the yank is handled specially. How exactly depends
14325 on the value of the following variables, both set by default.
14327 org-yank-folded-subtrees
14328 When set, the subtree(s) will be folded after insertion, but only
14329 if doing so would now swallow text after the yanked text.
14331 org-yank-adjusted-subtrees
14332 When set, the subtree will be promoted or demoted in order to
14333 fit into the local outline tree structure, which means that the level
14334 will be adjusted so that it becomes the smaller one of the two
14335 *visible* surrounding headings.
14337 Any prefix to this command will cause `yank' to be called directly with
14338 no special treatment. In particular, a simple `C-u' prefix will just
14339 plainly yank the text as it is.
14341 \[1] Basically, the test checks if the first non-white line is a heading
14342 and if there are no other headings with fewer stars."
14343 (interactive "P")
14344 (setq this-command 'yank)
14345 (if arg
14346 (call-interactively 'yank)
14347 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14348 (and (org-kill-is-subtree-p)
14349 (or (bolp)
14350 (and (looking-at "[ \t]*$")
14351 (string-match
14352 "\\`\\*+\\'"
14353 (buffer-substring (point-at-bol) (point)))))))
14354 swallowp)
14355 (cond
14356 ((and subtreep org-yank-folded-subtrees)
14357 (let ((beg (point))
14358 end)
14359 (if (and subtreep org-yank-adjusted-subtrees)
14360 (org-paste-subtree nil nil 'for-yank)
14361 (call-interactively 'yank))
14362 (setq end (point))
14363 (goto-char beg)
14364 (when (and (bolp) subtreep
14365 (not (setq swallowp
14366 (org-yank-folding-would-swallow-text beg end))))
14367 (or (looking-at outline-regexp)
14368 (re-search-forward (concat "^" outline-regexp) end t))
14369 (while (and (< (point) end) (looking-at outline-regexp))
14370 (hide-subtree)
14371 (org-cycle-show-empty-lines 'folded)
14372 (condition-case nil
14373 (outline-forward-same-level 1)
14374 (error (goto-char end)))))
14375 (when swallowp
14376 (message
14377 "Yanked text not folded because that would swallow text"))
14378 (goto-char end)
14379 (skip-chars-forward " \t\n\r")
14380 (beginning-of-line 1)
14381 (push-mark beg 'nomsg)))
14382 ((and subtreep org-yank-adjusted-subtrees)
14383 (let ((beg (point-at-bol)))
14384 (org-paste-subtree nil nil 'for-yank)
14385 (push-mark beg 'nomsg)))
14387 (call-interactively 'yank))))))
14389 (defun org-yank-folding-would-swallow-text (beg end)
14390 "Would hide-subtree at BEG swallow any text after END?"
14391 (let (level)
14392 (save-excursion
14393 (goto-char beg)
14394 (when (or (looking-at outline-regexp)
14395 (re-search-forward (concat "^" outline-regexp) end t))
14396 (setq level (org-outline-level)))
14397 (goto-char end)
14398 (skip-chars-forward " \t\r\n\v\f")
14399 (if (or (eobp)
14400 (and (bolp) (looking-at org-outline-regexp)
14401 (<= (org-outline-level) level)))
14402 nil ; Nothing would be swallowed
14403 t)))) ; something would swallow
14405 (define-key org-mode-map "\C-y" 'org-yank)
14407 (defun org-invisible-p ()
14408 "Check if point is at a character currently not visible."
14409 ;; Early versions of noutline don't have `outline-invisible-p'.
14410 (if (fboundp 'outline-invisible-p)
14411 (outline-invisible-p)
14412 (get-char-property (point) 'invisible)))
14414 (defun org-invisible-p2 ()
14415 "Check if point is at a character currently not visible."
14416 (save-excursion
14417 (if (and (eolp) (not (bobp))) (backward-char 1))
14418 ;; Early versions of noutline don't have `outline-invisible-p'.
14419 (if (fboundp 'outline-invisible-p)
14420 (outline-invisible-p)
14421 (get-char-property (point) 'invisible))))
14423 (defun org-back-to-heading (&optional invisible-ok)
14424 "Call `outline-back-to-heading', but provide a better error message."
14425 (condition-case nil
14426 (outline-back-to-heading invisible-ok)
14427 (error (error "Before first headline at position %d in buffer %s"
14428 (point) (current-buffer)))))
14430 (defun org-before-first-heading-p ()
14431 "Before first heading?"
14432 (save-excursion
14433 (null (re-search-backward "^\\*+ " nil t))))
14435 (defalias 'org-on-heading-p 'outline-on-heading-p)
14436 (defalias 'org-at-heading-p 'outline-on-heading-p)
14437 (defun org-at-heading-or-item-p ()
14438 (or (org-on-heading-p) (org-at-item-p)))
14440 (defun org-on-target-p ()
14441 (or (org-in-regexp org-radio-target-regexp)
14442 (org-in-regexp org-target-regexp)))
14444 (defun org-up-heading-all (arg)
14445 "Move to the heading line of which the present line is a subheading.
14446 This function considers both visible and invisible heading lines.
14447 With argument, move up ARG levels."
14448 (if (fboundp 'outline-up-heading-all)
14449 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14450 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14452 (defun org-up-heading-safe ()
14453 "Move to the heading line of which the present line is a subheading.
14454 This version will not throw an error. It will return the level of the
14455 headline found, or nil if no higher level is found."
14456 (let (start-level re)
14457 (org-back-to-heading t)
14458 (setq start-level (funcall outline-level))
14459 (if (equal start-level 1)
14461 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14462 (if (re-search-backward re nil t)
14463 (funcall outline-level)))))
14465 (defun org-first-sibling-p ()
14466 "Is this heading the first child of its parents?"
14467 (interactive)
14468 (let ((re (concat "^" outline-regexp))
14469 level l)
14470 (unless (org-at-heading-p t)
14471 (error "Not at a heading"))
14472 (setq level (funcall outline-level))
14473 (save-excursion
14474 (if (not (re-search-backward re nil t))
14476 (setq l (funcall outline-level))
14477 (< l level)))))
14479 (defun org-goto-sibling (&optional previous)
14480 "Goto the next sibling, even if it is invisible.
14481 When PREVIOUS is set, go to the previous sibling instead. Returns t
14482 when a sibling was found. When none is found, return nil and don't
14483 move point."
14484 (let ((fun (if previous 're-search-backward 're-search-forward))
14485 (pos (point))
14486 (re (concat "^" outline-regexp))
14487 level l)
14488 (when (condition-case nil (org-back-to-heading t) (error nil))
14489 (setq level (funcall outline-level))
14490 (catch 'exit
14491 (or previous (forward-char 1))
14492 (while (funcall fun re nil t)
14493 (setq l (funcall outline-level))
14494 (when (< l level) (goto-char pos) (throw 'exit nil))
14495 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14496 (goto-char pos)
14497 nil))))
14499 (defun org-show-siblings ()
14500 "Show all siblings of the current headline."
14501 (save-excursion
14502 (while (org-goto-sibling) (org-flag-heading nil)))
14503 (save-excursion
14504 (while (org-goto-sibling 'previous)
14505 (org-flag-heading nil))))
14507 (defun org-show-hidden-entry ()
14508 "Show an entry where even the heading is hidden."
14509 (save-excursion
14510 (org-show-entry)))
14512 (defun org-flag-heading (flag &optional entry)
14513 "Flag the current heading. FLAG non-nil means make invisible.
14514 When ENTRY is non-nil, show the entire entry."
14515 (save-excursion
14516 (org-back-to-heading t)
14517 ;; Check if we should show the entire entry
14518 (if entry
14519 (progn
14520 (org-show-entry)
14521 (save-excursion
14522 (and (outline-next-heading)
14523 (org-flag-heading nil))))
14524 (outline-flag-region (max (point-min) (1- (point)))
14525 (save-excursion (outline-end-of-heading) (point))
14526 flag))))
14528 (defun org-forward-same-level (arg)
14529 "Move forward to the ARG'th subheading at same level as this one.
14530 Stop at the first and last subheadings of a superior heading.
14531 This is like outline-forward-same-level, but invisible headings are ok."
14532 (interactive "p")
14533 (org-back-to-heading t)
14534 (while (> arg 0)
14535 (let ((point-to-move-to (save-excursion
14536 (org-get-next-sibling))))
14537 (if point-to-move-to
14538 (progn
14539 (goto-char point-to-move-to)
14540 (setq arg (1- arg)))
14541 (progn
14542 (setq arg 0)
14543 (error "No following same-level heading"))))))
14545 (defun org-get-next-sibling ()
14546 "Move to next heading of the same level, and return point.
14547 If there is no such heading, return nil.
14548 This is like outline-next-sibling, but invisible headings are ok."
14549 (let ((level (funcall outline-level)))
14550 (outline-next-heading)
14551 (while (and (not (eobp)) (> (funcall outline-level) level))
14552 (outline-next-heading))
14553 (if (or (eobp) (< (funcall outline-level) level))
14555 (point))))
14557 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14558 ;; This is an exact copy of the original function, but it uses
14559 ;; `org-back-to-heading', to make it work also in invisible
14560 ;; trees. And is uses an invisible-OK argument.
14561 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14562 (org-back-to-heading invisible-OK)
14563 (let ((first t)
14564 (level (funcall outline-level)))
14565 (while (and (not (eobp))
14566 (or first (> (funcall outline-level) level)))
14567 (setq first nil)
14568 (outline-next-heading))
14569 (unless to-heading
14570 (if (memq (preceding-char) '(?\n ?\^M))
14571 (progn
14572 ;; Go to end of line before heading
14573 (forward-char -1)
14574 (if (memq (preceding-char) '(?\n ?\^M))
14575 ;; leave blank line before heading
14576 (forward-char -1))))))
14577 (point))
14579 (defun org-show-subtree ()
14580 "Show everything after this heading at deeper levels."
14581 (outline-flag-region
14582 (point)
14583 (save-excursion
14584 (outline-end-of-subtree) (outline-next-heading) (point))
14585 nil))
14587 (defun org-show-entry ()
14588 "Show the body directly following this heading.
14589 Show the heading too, if it is currently invisible."
14590 (interactive)
14591 (save-excursion
14592 (condition-case nil
14593 (progn
14594 (org-back-to-heading t)
14595 (outline-flag-region
14596 (max (point-min) (1- (point)))
14597 (save-excursion
14598 (re-search-forward
14599 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14600 (or (match-beginning 1) (point-max)))
14601 nil))
14602 (error nil))))
14604 (defun org-make-options-regexp (kwds)
14605 "Make a regular expression for keyword lines."
14606 (concat
14608 "#?[ \t]*\\+\\("
14609 (mapconcat 'regexp-quote kwds "\\|")
14610 "\\):[ \t]*"
14611 "\\(.+\\)"))
14613 ;; Make isearch reveal the necessary context
14614 (defun org-isearch-end ()
14615 "Reveal context after isearch exits."
14616 (when isearch-success ; only if search was successful
14617 (if (featurep 'xemacs)
14618 ;; Under XEmacs, the hook is run in the correct place,
14619 ;; we directly show the context.
14620 (org-show-context 'isearch)
14621 ;; In Emacs the hook runs *before* restoring the overlays.
14622 ;; So we have to use a one-time post-command-hook to do this.
14623 ;; (Emacs 22 has a special variable, see function `org-mode')
14624 (unless (and (boundp 'isearch-mode-end-hook-quit)
14625 isearch-mode-end-hook-quit)
14626 ;; Only when the isearch was not quitted.
14627 (org-add-hook 'post-command-hook 'org-isearch-post-command
14628 'append 'local)))))
14630 (defun org-isearch-post-command ()
14631 "Remove self from hook, and show context."
14632 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14633 (org-show-context 'isearch))
14636 ;;;; Integration with and fixes for other packages
14638 ;;; Imenu support
14640 (defvar org-imenu-markers nil
14641 "All markers currently used by Imenu.")
14642 (make-variable-buffer-local 'org-imenu-markers)
14644 (defun org-imenu-new-marker (&optional pos)
14645 "Return a new marker for use by Imenu, and remember the marker."
14646 (let ((m (make-marker)))
14647 (move-marker m (or pos (point)))
14648 (push m org-imenu-markers)
14651 (defun org-imenu-get-tree ()
14652 "Produce the index for Imenu."
14653 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14654 (setq org-imenu-markers nil)
14655 (let* ((n org-imenu-depth)
14656 (re (concat "^" outline-regexp))
14657 (subs (make-vector (1+ n) nil))
14658 (last-level 0)
14659 m tree level head)
14660 (save-excursion
14661 (save-restriction
14662 (widen)
14663 (goto-char (point-max))
14664 (while (re-search-backward re nil t)
14665 (setq level (org-reduced-level (funcall outline-level)))
14666 (when (<= level n)
14667 (looking-at org-complex-heading-regexp)
14668 (setq head (org-link-display-format
14669 (org-match-string-no-properties 4))
14670 m (org-imenu-new-marker))
14671 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14672 (if (>= level last-level)
14673 (push (cons head m) (aref subs level))
14674 (push (cons head (aref subs (1+ level))) (aref subs level))
14675 (loop for i from (1+ level) to n do (aset subs i nil)))
14676 (setq last-level level)))))
14677 (aref subs 1)))
14679 (eval-after-load "imenu"
14680 '(progn
14681 (add-hook 'imenu-after-jump-hook
14682 (lambda ()
14683 (if (eq major-mode 'org-mode)
14684 (org-show-context 'org-goto))))))
14686 (defun org-link-display-format (link)
14687 "Replace a link with either the description, or the link target
14688 if no description is present"
14689 (save-match-data
14690 (if (string-match org-bracket-link-analytic-regexp link)
14691 (replace-match (or (match-string 5 link)
14692 (concat (match-string 1 link)
14693 (match-string 3 link)))
14694 nil nil link)
14695 link)))
14697 ;; Speedbar support
14699 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14700 "Overlay marking the agenda restriction line in speedbar.")
14701 (org-overlay-put org-speedbar-restriction-lock-overlay
14702 'face 'org-agenda-restriction-lock)
14703 (org-overlay-put org-speedbar-restriction-lock-overlay
14704 'help-echo "Agendas are currently limited to this item.")
14705 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14707 (defun org-speedbar-set-agenda-restriction ()
14708 "Restrict future agenda commands to the location at point in speedbar.
14709 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14710 (interactive)
14711 (require 'org-agenda)
14712 (let (p m tp np dir txt w)
14713 (cond
14714 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14715 'org-imenu t))
14716 (setq m (get-text-property p 'org-imenu-marker))
14717 (save-excursion
14718 (save-restriction
14719 (set-buffer (marker-buffer m))
14720 (goto-char m)
14721 (org-agenda-set-restriction-lock 'subtree))))
14722 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14723 'speedbar-function 'speedbar-find-file))
14724 (setq tp (previous-single-property-change
14725 (1+ p) 'speedbar-function)
14726 np (next-single-property-change
14727 tp 'speedbar-function)
14728 dir (speedbar-line-directory)
14729 txt (buffer-substring-no-properties (or tp (point-min))
14730 (or np (point-max))))
14731 (save-excursion
14732 (save-restriction
14733 (set-buffer (find-file-noselect
14734 (let ((default-directory dir))
14735 (expand-file-name txt))))
14736 (unless (org-mode-p)
14737 (error "Cannot restrict to non-Org-mode file"))
14738 (org-agenda-set-restriction-lock 'file))))
14739 (t (error "Don't know how to restrict Org-mode's agenda")))
14740 (org-move-overlay org-speedbar-restriction-lock-overlay
14741 (point-at-bol) (point-at-eol))
14742 (setq current-prefix-arg nil)
14743 (org-agenda-maybe-redo)))
14745 (eval-after-load "speedbar"
14746 '(progn
14747 (speedbar-add-supported-extension ".org")
14748 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14749 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14750 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14751 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14752 (add-hook 'speedbar-visiting-tag-hook
14753 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14756 ;;; Fixes and Hacks for problems with other packages
14758 ;; Make flyspell not check words in links, to not mess up our keymap
14759 (defun org-mode-flyspell-verify ()
14760 "Don't let flyspell put overlays at active buttons."
14761 (not (get-text-property (point) 'keymap)))
14763 ;; Make `bookmark-jump' show the jump location if it was hidden.
14764 (eval-after-load "bookmark"
14765 '(if (boundp 'bookmark-after-jump-hook)
14766 ;; We can use the hook
14767 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14768 ;; Hook not available, use advice
14769 (defadvice bookmark-jump (after org-make-visible activate)
14770 "Make the position visible."
14771 (org-bookmark-jump-unhide))))
14773 ;; Make sure saveplace show the location if it was hidden
14774 (eval-after-load "saveplace"
14775 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14776 "Make the position visible."
14777 (org-bookmark-jump-unhide)))
14779 (defun org-bookmark-jump-unhide ()
14780 "Unhide the current position, to show the bookmark location."
14781 (and (org-mode-p)
14782 (or (org-invisible-p)
14783 (save-excursion (goto-char (max (point-min) (1- (point))))
14784 (org-invisible-p)))
14785 (org-show-context 'bookmark-jump)))
14787 ;; Make session.el ignore our circular variable
14788 (eval-after-load "session"
14789 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14791 ;;;; Experimental code
14793 (defun org-closed-in-range ()
14794 "Sparse tree of items closed in a certain time range.
14795 Still experimental, may disappear in the future."
14796 (interactive)
14797 ;; Get the time interval from the user.
14798 (let* ((time1 (time-to-seconds
14799 (org-read-date nil 'to-time nil "Starting date: ")))
14800 (time2 (time-to-seconds
14801 (org-read-date nil 'to-time nil "End date:")))
14802 ;; callback function
14803 (callback (lambda ()
14804 (let ((time
14805 (time-to-seconds
14806 (apply 'encode-time
14807 (org-parse-time-string
14808 (match-string 1))))))
14809 ;; check if time in interval
14810 (and (>= time time1) (<= time time2))))))
14811 ;; make tree, check each match with the callback
14812 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14815 ;;;; Finish up
14817 (provide 'org)
14819 (run-hooks 'org-load-hook)
14821 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14823 ;;; org.el ends here