Minor changes.
[org-mode.git] / lisp / org.el
bloba008cb8e695e8444f53aad3ac26eb1c9181f0bcc
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.06b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.06b"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " id: Global id's for identifying entries" org-id)
165 (const :tag " info: Links to Info nodes" org-info)
166 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
167 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
168 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
169 (const :tag " mew Links to Mew folders/messages" org-mew)
170 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
171 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
172 (const :tag " vm: Links to VM folders/messages" org-vm)
173 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
174 (const :tag " mouse: Additional mouse support" org-mouse)
176 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
177 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
178 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
179 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
180 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
181 (const :tag "C eval: Include command output as text" org-eval)
182 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
183 (const :tag "C id: Global id's for identifying entries" org-id)
184 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
185 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
186 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
187 (const :tag "C mtags: Support for muse-like tags" org-mtags)
188 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
189 (const :tag "C registry: A registry for Org links" org-registry)
190 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
191 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
192 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
193 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
194 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
197 (defgroup org-startup nil
198 "Options concerning startup of Org-mode."
199 :tag "Org Startup"
200 :group 'org)
202 (defcustom org-startup-folded t
203 "Non-nil means, entering Org-mode will switch to OVERVIEW.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
207 #+STARTUP: fold
208 #+STARTUP: nofold
209 #+STARTUP: content"
210 :group 'org-startup
211 :type '(choice
212 (const :tag "nofold: show all" nil)
213 (const :tag "fold: overview" t)
214 (const :tag "content: all headlines" content)))
216 (defcustom org-startup-truncated t
217 "Non-nil means, entering Org-mode will set `truncate-lines'.
218 This is useful since some lines containing links can be very long and
219 uninteresting. Also tables look terrible when wrapped."
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-startup-align-all-tables nil
224 "Non-nil means, align all tables when visiting a file.
225 This is useful when the column width in tables is forced with <N> cookies
226 in table fields. Such tables will look correct only after the first re-align.
227 This can also be configured on a per-file basis by adding one of
228 the following lines anywhere in the buffer:
229 #+STARTUP: align
230 #+STARTUP: noalign"
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-insert-mode-line-in-empty-file nil
235 "Non-nil means insert the first line setting Org-mode in empty files.
236 When the function `org-mode' is called interactively in an empty file, this
237 normally means that the file name does not automatically trigger Org-mode.
238 To ensure that the file will always be in Org-mode in the future, a
239 line enforcing Org-mode will be inserted into the buffer, if this option
240 has been set."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-replace-disputed-keys nil
245 "Non-nil means use alternative key bindings for some keys.
246 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
247 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
248 If you want to use Org-mode together with one of these other modes,
249 or more generally if you would like to move some Org-mode commands to
250 other keys, set this variable and configure the keys with the variable
251 `org-disputed-keys'.
253 This option is only relevant at load-time of Org-mode, and must be set
254 *before* org.el is loaded. Changing it requires a restart of Emacs to
255 become effective."
256 :group 'org-startup
257 :type 'boolean)
259 (defcustom org-use-extra-keys nil
260 "Non-nil means use extra key sequence definitions for certain
261 commands. This happens automatically if you run XEmacs or if
262 window-system is nil. This variable lets you do the same
263 manually. You must set it before loading org.
265 Example: on Carbon Emacs 22 running graphically, with an external
266 keyboard on a Powerbook, the default way of setting M-left might
267 not work for either Alt or ESC. Setting this variable will make
268 it work for ESC."
269 :group 'org-startup
270 :type 'boolean)
272 (if (fboundp 'defvaralias)
273 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
275 (defcustom org-disputed-keys
276 '(([(shift up)] . [(meta p)])
277 ([(shift down)] . [(meta n)])
278 ([(shift left)] . [(meta -)])
279 ([(shift right)] . [(meta +)])
280 ([(control shift right)] . [(meta shift +)])
281 ([(control shift left)] . [(meta shift -)]))
282 "Keys for which Org-mode and other modes compete.
283 This is an alist, cars are the default keys, second element specifies
284 the alternative to use when `org-replace-disputed-keys' is t.
286 Keys can be specified in any syntax supported by `define-key'.
287 The value of this option takes effect only at Org-mode's startup,
288 therefore you'll have to restart Emacs to apply it after changing."
289 :group 'org-startup
290 :type 'alist)
292 (defun org-key (key)
293 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
294 Or return the original if not disputed."
295 (if org-replace-disputed-keys
296 (let* ((nkey (key-description key))
297 (x (org-find-if (lambda (x)
298 (equal (key-description (car x)) nkey))
299 org-disputed-keys)))
300 (if x (cdr x) key))
301 key))
303 (defun org-find-if (predicate seq)
304 (catch 'exit
305 (while seq
306 (if (funcall predicate (car seq))
307 (throw 'exit (car seq))
308 (pop seq)))))
310 (defun org-defkey (keymap key def)
311 "Define a key, possibly translated, as returned by `org-key'."
312 (define-key keymap (org-key key) def))
314 (defcustom org-ellipsis nil
315 "The ellipsis to use in the Org-mode outline.
316 When nil, just use the standard three dots. When a string, use that instead,
317 When a face, use the standart 3 dots, but with the specified face.
318 The change affects only Org-mode (which will then use its own display table).
319 Changing this requires executing `M-x org-mode' in a buffer to become
320 effective."
321 :group 'org-startup
322 :type '(choice (const :tag "Default" nil)
323 (face :tag "Face" :value org-warning)
324 (string :tag "String" :value "...#")))
326 (defvar org-display-table nil
327 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
329 (defgroup org-keywords nil
330 "Keywords in Org-mode."
331 :tag "Org Keywords"
332 :group 'org)
334 (defcustom org-deadline-string "DEADLINE:"
335 "String to mark deadline entries.
336 A deadline is this string, followed by a time stamp. Should be a word,
337 terminated by a colon. You can insert a schedule keyword and
338 a timestamp with \\[org-deadline].
339 Changes become only effective after restarting Emacs."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-scheduled-string "SCHEDULED:"
344 "String to mark scheduled TODO entries.
345 A schedule is this string, followed by a time stamp. Should be a word,
346 terminated by a colon. You can insert a schedule keyword and
347 a timestamp with \\[org-schedule].
348 Changes become only effective after restarting Emacs."
349 :group 'org-keywords
350 :type 'string)
352 (defcustom org-closed-string "CLOSED:"
353 "String used as the prefix for timestamps logging closing a TODO entry."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-clock-string "CLOCK:"
358 "String used as prefix for timestamps clocking work hours on an item."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-comment-string "COMMENT"
363 "Entries starting with this keyword will never be exported.
364 An entry can be toggled between COMMENT and normal with
365 \\[org-toggle-comment].
366 Changes become only effective after restarting Emacs."
367 :group 'org-keywords
368 :type 'string)
370 (defcustom org-quote-string "QUOTE"
371 "Entries starting with this keyword will be exported in fixed-width font.
372 Quoting applies only to the text in the entry following the headline, and does
373 not extend beyond the next headline, even if that is lower level.
374 An entry can be toggled between QUOTE and normal with
375 \\[org-toggle-fixed-width-section]."
376 :group 'org-keywords
377 :type 'string)
379 (defconst org-repeat-re
380 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
381 "Regular expression for specifying repeated events.
382 After a match, group 1 contains the repeat expression.")
384 (defgroup org-structure nil
385 "Options concerning the general structure of Org-mode files."
386 :tag "Org Structure"
387 :group 'org)
389 (defgroup org-reveal-location nil
390 "Options about how to make context of a location visible."
391 :tag "Org Reveal Location"
392 :group 'org-structure)
394 (defconst org-context-choice
395 '(choice
396 (const :tag "Always" t)
397 (const :tag "Never" nil)
398 (repeat :greedy t :tag "Individual contexts"
399 (cons
400 (choice :tag "Context"
401 (const agenda)
402 (const org-goto)
403 (const occur-tree)
404 (const tags-tree)
405 (const link-search)
406 (const mark-goto)
407 (const bookmark-jump)
408 (const isearch)
409 (const default))
410 (boolean))))
411 "Contexts for the reveal options.")
413 (defcustom org-show-hierarchy-above '((default . t))
414 "Non-nil means, show full hierarchy when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the hierarchy of headings
417 above the exposed location is shown.
418 Turning this off for example for sparse trees makes them very compact.
419 Instead of t, this can also be an alist specifying this option for different
420 contexts. Valid contexts are
421 agenda when exposing an entry from the agenda
422 org-goto when using the command `org-goto' on key C-c C-j
423 occur-tree when using the command `org-occur' on key C-c /
424 tags-tree when constructing a sparse tree based on tags matches
425 link-search when exposing search matches associated with a link
426 mark-goto when exposing the jump goal of a mark
427 bookmark-jump when exposing a bookmark location
428 isearch when exiting from an incremental search
429 default default for all contexts not set explicitly"
430 :group 'org-reveal-location
431 :type org-context-choice)
433 (defcustom org-show-following-heading '((default . nil))
434 "Non-nil means, show following heading when revealing a location.
435 Org-mode often shows locations in an org-mode file which might have
436 been invisible before. When this is set, the heading following the
437 match is shown.
438 Turning this off for example for sparse trees makes them very compact,
439 but makes it harder to edit the location of the match. In such a case,
440 use the command \\[org-reveal] to show more context.
441 Instead of t, this can also be an alist specifying this option for different
442 contexts. See `org-show-hierarchy-above' for valid contexts."
443 :group 'org-reveal-location
444 :type org-context-choice)
446 (defcustom org-show-siblings '((default . nil) (isearch t))
447 "Non-nil means, show all sibling heading when revealing a location.
448 Org-mode often shows locations in an org-mode file which might have
449 been invisible before. When this is set, the sibling of the current entry
450 heading are all made visible. If `org-show-hierarchy-above' is t,
451 the same happens on each level of the hierarchy above the current entry.
453 By default this is on for the isearch context, off for all other contexts.
454 Turning this off for example for sparse trees makes them very compact,
455 but makes it harder to edit the location of the match. In such a case,
456 use the command \\[org-reveal] to show more context.
457 Instead of t, this can also be an alist specifying this option for different
458 contexts. See `org-show-hierarchy-above' for valid contexts."
459 :group 'org-reveal-location
460 :type org-context-choice)
462 (defcustom org-show-entry-below '((default . nil))
463 "Non-nil means, show the entry below a headline when revealing a location.
464 Org-mode often shows locations in an org-mode file which might have
465 been invisible before. When this is set, the text below the headline that is
466 exposed is also shown.
468 By default this is off for all contexts.
469 Instead of t, this can also be an alist specifying this option for different
470 contexts. See `org-show-hierarchy-above' for valid contexts."
471 :group 'org-reveal-location
472 :type org-context-choice)
474 (defcustom org-indirect-buffer-display 'other-window
475 "How should indirect tree buffers be displayed?
476 This applies to indirect buffers created with the commands
477 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
478 Valid values are:
479 current-window Display in the current window
480 other-window Just display in another window.
481 dedicated-frame Create one new frame, and re-use it each time.
482 new-frame Make a new frame each time. Note that in this case
483 previously-made indirect buffers are kept, and you need to
484 kill these buffers yourself."
485 :group 'org-structure
486 :group 'org-agenda-windows
487 :type '(choice
488 (const :tag "In current window" current-window)
489 (const :tag "In current frame, other window" other-window)
490 (const :tag "Each time a new frame" new-frame)
491 (const :tag "One dedicated frame" dedicated-frame)))
493 (defgroup org-cycle nil
494 "Options concerning visibility cycling in Org-mode."
495 :tag "Org Cycle"
496 :group 'org-structure)
498 (defcustom org-drawers '("PROPERTIES" "CLOCK")
499 "Names of drawers. Drawers are not opened by cycling on the headline above.
500 Drawers only open with a TAB on the drawer line itself. A drawer looks like
501 this:
502 :DRAWERNAME:
503 .....
504 :END:
505 The drawer \"PROPERTIES\" is special for capturing properties through
506 the property API.
508 Drawers can be defined on the per-file basis with a line like:
510 #+DRAWERS: HIDDEN STATE PROPERTIES"
511 :group 'org-structure
512 :type '(repeat (string :tag "Drawer Name")))
514 (defcustom org-cycle-global-at-bob nil
515 "Cycle globally if cursor is at beginning of buffer and not at a headline.
516 This makes it possible to do global cycling without having to use S-TAB or
517 C-u TAB. For this special case to work, the first line of the buffer
518 must not be a headline - it may be empty ot some other text. When used in
519 this way, `org-cycle-hook' is disables temporarily, to make sure the
520 cursor stays at the beginning of the buffer.
521 When this option is nil, don't do anything special at the beginning
522 of the buffer."
523 :group 'org-cycle
524 :type 'boolean)
526 (defcustom org-cycle-emulate-tab t
527 "Where should `org-cycle' emulate TAB.
528 nil Never
529 white Only in completely white lines
530 whitestart Only at the beginning of lines, before the first non-white char
531 t Everywhere except in headlines
532 exc-hl-bol Everywhere except at the start of a headline
533 If TAB is used in a place where it does not emulate TAB, the current subtree
534 visibility is cycled."
535 :group 'org-cycle
536 :type '(choice (const :tag "Never" nil)
537 (const :tag "Only in completely white lines" white)
538 (const :tag "Before first char in a line" whitestart)
539 (const :tag "Everywhere except in headlines" t)
540 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
543 (defcustom org-cycle-separator-lines 2
544 "Number of empty lines needed to keep an empty line between collapsed trees.
545 If you leave an empty line between the end of a subtree and the following
546 headline, this empty line is hidden when the subtree is folded.
547 Org-mode will leave (exactly) one empty line visible if the number of
548 empty lines is equal or larger to the number given in this variable.
549 So the default 2 means, at least 2 empty lines after the end of a subtree
550 are needed to produce free space between a collapsed subtree and the
551 following headline.
553 Special case: when 0, never leave empty lines in collapsed view."
554 :group 'org-cycle
555 :type 'integer)
556 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
558 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
559 org-cycle-hide-drawers
560 org-cycle-show-empty-lines
561 org-optimize-window-after-visibility-change)
562 "Hook that is run after `org-cycle' has changed the buffer visibility.
563 The function(s) in this hook must accept a single argument which indicates
564 the new state that was set by the most recent `org-cycle' command. The
565 argument is a symbol. After a global state change, it can have the values
566 `overview', `content', or `all'. After a local state change, it can have
567 the values `folded', `children', or `subtree'."
568 :group 'org-cycle
569 :type 'hook)
571 (defgroup org-edit-structure nil
572 "Options concerning structure editing in Org-mode."
573 :tag "Org Edit Structure"
574 :group 'org-structure)
576 (defcustom org-odd-levels-only nil
577 "Non-nil means, skip even levels and only use odd levels for the outline.
578 This has the effect that two stars are being added/taken away in
579 promotion/demotion commands. It also influences how levels are
580 handled by the exporters.
581 Changing it requires restart of `font-lock-mode' to become effective
582 for fontification also in regions already fontified.
583 You may also set this on a per-file basis by adding one of the following
584 lines to the buffer:
586 #+STARTUP: odd
587 #+STARTUP: oddeven"
588 :group 'org-edit-structure
589 :group 'org-font-lock
590 :type 'boolean)
592 (defcustom org-adapt-indentation t
593 "Non-nil means, adapt indentation when promoting and demoting.
594 When this is set and the *entire* text in an entry is indented, the
595 indentation is increased by one space in a demotion command, and
596 decreased by one in a promotion command. If any line in the entry
597 body starts at column 0, indentation is not changed at all."
598 :group 'org-edit-structure
599 :type 'boolean)
601 (defcustom org-special-ctrl-a/e nil
602 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
603 When t, `C-a' will bring back the cursor to the beginning of the
604 headline text, i.e. after the stars and after a possible TODO keyword.
605 In an item, this will be the position after the bullet.
606 When the cursor is already at that position, another `C-a' will bring
607 it to the beginning of the line.
608 `C-e' will jump to the end of the headline, ignoring the presence of tags
609 in the headline. A second `C-e' will then jump to the true end of the
610 line, after any tags.
611 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
612 and only a directly following, identical keypress will bring the cursor
613 to the special positions."
614 :group 'org-edit-structure
615 :type '(choice
616 (const :tag "off" nil)
617 (const :tag "after bullet first" t)
618 (const :tag "border first" reversed)))
620 (if (fboundp 'defvaralias)
621 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
623 (defcustom org-special-ctrl-k nil
624 "Non-nil means `C-k' will behave specially in headlines.
625 When nil, `C-k' will call the default `kill-line' command.
626 When t, the following will happen while the cursor is in the headline:
628 - When the cursor is at the beginning of a headline, kill the entire
629 line and possible the folded subtree below the line.
630 - When in the middle of the headline text, kill the headline up to the tags.
631 - When after the headline text, kill the tags."
632 :group 'org-edit-structure
633 :type 'boolean)
635 (defcustom org-M-RET-may-split-line '((default . t))
636 "Non-nil means, M-RET will split the line at the cursor position.
637 When nil, it will go to the end of the line before making a
638 new line.
639 You may also set this option in a different way for different
640 contexts. Valid contexts are:
642 headline when creating a new headline
643 item when creating a new item
644 table in a table field
645 default the value to be used for all contexts not explicitly
646 customized"
647 :group 'org-structure
648 :group 'org-table
649 :type '(choice
650 (const :tag "Always" t)
651 (const :tag "Never" nil)
652 (repeat :greedy t :tag "Individual contexts"
653 (cons
654 (choice :tag "Context"
655 (const headline)
656 (const item)
657 (const table)
658 (const default))
659 (boolean)))))
662 (defcustom org-blank-before-new-entry '((heading . nil)
663 (plain-list-item . nil))
664 "Should `org-insert-heading' leave a blank line before new heading/item?
665 The value is an alist, with `heading' and `plain-list-item' as car,
666 and a boolean flag as cdr."
667 :group 'org-edit-structure
668 :type '(list
669 (cons (const heading) (boolean))
670 (cons (const plain-list-item) (boolean))))
672 (defcustom org-insert-heading-hook nil
673 "Hook being run after inserting a new heading."
674 :group 'org-edit-structure
675 :type 'hook)
677 (defcustom org-enable-fixed-width-editor t
678 "Non-nil means, lines starting with \":\" are treated as fixed-width.
679 This currently only means, they are never auto-wrapped.
680 When nil, such lines will be treated like ordinary lines.
681 See also the QUOTE keyword."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-edit-fixed-width-region-mode 'artist-mode
686 "The mode that should be used to edit fixed-width regions.
687 These are the regions where each line starts with a colon."
688 :group 'org-edit-structure
689 :type '(choice
690 (const artist-mode)
691 (const picture-mode)
692 (const fundamental-mode)
693 (function :tag "Other (specify)")))
695 (defcustom org-goto-auto-isearch t
696 "Non-nil means, typing characters in org-goto starts incremental search."
697 :group 'org-edit-structure
698 :type 'boolean)
700 (defgroup org-sparse-trees nil
701 "Options concerning sparse trees in Org-mode."
702 :tag "Org Sparse Trees"
703 :group 'org-structure)
705 (defcustom org-highlight-sparse-tree-matches t
706 "Non-nil means, highlight all matches that define a sparse tree.
707 The highlights will automatically disappear the next time the buffer is
708 changed by an edit command."
709 :group 'org-sparse-trees
710 :type 'boolean)
712 (defcustom org-remove-highlights-with-change t
713 "Non-nil means, any change to the buffer will remove temporary highlights.
714 Such highlights are created by `org-occur' and `org-clock-display'.
715 When nil, `C-c C-c needs to be used to get rid of the highlights.
716 The highlights created by `org-preview-latex-fragment' always need
717 `C-c C-c' to be removed."
718 :group 'org-sparse-trees
719 :group 'org-time
720 :type 'boolean)
723 (defcustom org-occur-hook '(org-first-headline-recenter)
724 "Hook that is run after `org-occur' has constructed a sparse tree.
725 This can be used to recenter the window to show as much of the structure
726 as possible."
727 :group 'org-sparse-trees
728 :type 'hook)
730 (defgroup org-plain-lists nil
731 "Options concerning plain lists in Org-mode."
732 :tag "Org Plain lists"
733 :group 'org-structure)
735 (defcustom org-cycle-include-plain-lists nil
736 "Non-nil means, include plain lists into visibility cycling.
737 This means that during cycling, plain list items will *temporarily* be
738 interpreted as outline headlines with a level given by 1000+i where i is the
739 indentation of the bullet. In all other operations, plain list items are
740 not seen as headlines. For example, you cannot assign a TODO keyword to
741 such an item."
742 :group 'org-plain-lists
743 :type 'boolean)
745 (defcustom org-plain-list-ordered-item-terminator t
746 "The character that makes a line with leading number an ordered list item.
747 Valid values are ?. and ?\). To get both terminators, use t. While
748 ?. may look nicer, it creates the danger that a line with leading
749 number may be incorrectly interpreted as an item. ?\) therefore is
750 the safe choice."
751 :group 'org-plain-lists
752 :type '(choice (const :tag "dot like in \"2.\"" ?.)
753 (const :tag "paren like in \"2)\"" ?\))
754 (const :tab "both" t)))
756 (defcustom org-empty-line-terminates-plain-lists nil
757 "Non-nil means, an empty line ends all plain list levels.
758 When nil, empty lines are part of the preceeding item."
759 :group 'org-plain-lists
760 :type 'boolean)
762 (defcustom org-auto-renumber-ordered-lists t
763 "Non-nil means, automatically renumber ordered plain lists.
764 Renumbering happens when the sequence have been changed with
765 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
766 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
767 :group 'org-plain-lists
768 :type 'boolean)
770 (defcustom org-provide-checkbox-statistics t
771 "Non-nil means, update checkbox statistics after insert and toggle.
772 When this is set, checkbox statistics is updated each time you either insert
773 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
774 with \\[org-ctrl-c-ctrl-c\\]."
775 :group 'org-plain-lists
776 :type 'boolean)
778 (defcustom org-description-max-indent 20
779 "Maximum indentation for the second line of a description list.
780 When the indentation would be larger than this, it will become
781 5 characters instead."
782 :group 'org-plain-lists
783 :type 'integer)
785 (defgroup org-imenu-and-speedbar nil
786 "Options concerning imenu and speedbar in Org-mode."
787 :tag "Org Imenu and Speedbar"
788 :group 'org-structure)
790 (defcustom org-imenu-depth 2
791 "The maximum level for Imenu access to Org-mode headlines.
792 This also applied for speedbar access."
793 :group 'org-imenu-and-speedbar
794 :type 'number)
796 (defgroup org-table nil
797 "Options concerning tables in Org-mode."
798 :tag "Org Table"
799 :group 'org)
801 (defcustom org-enable-table-editor 'optimized
802 "Non-nil means, lines starting with \"|\" are handled by the table editor.
803 When nil, such lines will be treated like ordinary lines.
805 When equal to the symbol `optimized', the table editor will be optimized to
806 do the following:
807 - Automatic overwrite mode in front of whitespace in table fields.
808 This makes the structure of the table stay in tact as long as the edited
809 field does not exceed the column width.
810 - Minimize the number of realigns. Normally, the table is aligned each time
811 TAB or RET are pressed to move to another field. With optimization this
812 happens only if changes to a field might have changed the column width.
813 Optimization requires replacing the functions `self-insert-command',
814 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
815 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
816 very good at guessing when a re-align will be necessary, but you can always
817 force one with \\[org-ctrl-c-ctrl-c].
819 If you would like to use the optimized version in Org-mode, but the
820 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
822 This variable can be used to turn on and off the table editor during a session,
823 but in order to toggle optimization, a restart is required.
825 See also the variable `org-table-auto-blank-field'."
826 :group 'org-table
827 :type '(choice
828 (const :tag "off" nil)
829 (const :tag "on" t)
830 (const :tag "on, optimized" optimized)))
832 (defcustom org-table-tab-recognizes-table.el t
833 "Non-nil means, TAB will automatically notice a table.el table.
834 When it sees such a table, it moves point into it and - if necessary -
835 calls `table-recognize-table'."
836 :group 'org-table-editing
837 :type 'boolean)
839 (defgroup org-link nil
840 "Options concerning links in Org-mode."
841 :tag "Org Link"
842 :group 'org)
844 (defvar org-link-abbrev-alist-local nil
845 "Buffer-local version of `org-link-abbrev-alist', which see.
846 The value of this is taken from the #+LINK lines.")
847 (make-variable-buffer-local 'org-link-abbrev-alist-local)
849 (defcustom org-link-abbrev-alist nil
850 "Alist of link abbreviations.
851 The car of each element is a string, to be replaced at the start of a link.
852 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
853 links in Org-mode buffers can have an optional tag after a double colon, e.g.
855 [[linkkey:tag][description]]
857 If REPLACE is a string, the tag will simply be appended to create the link.
858 If the string contains \"%s\", the tag will be inserted there.
860 REPLACE may also be a function that will be called with the tag as the
861 only argument to create the link, which should be returned as a string.
863 See the manual for examples."
864 :group 'org-link
865 :type 'alist)
867 (defcustom org-descriptive-links t
868 "Non-nil means, hide link part and only show description of bracket links.
869 Bracket links are like [[link][descritpion]]. This variable sets the initial
870 state in new org-mode buffers. The setting can then be toggled on a
871 per-buffer basis from the Org->Hyperlinks menu."
872 :group 'org-link
873 :type 'boolean)
875 (defcustom org-link-file-path-type 'adaptive
876 "How the path name in file links should be stored.
877 Valid values are:
879 relative Relative to the current directory, i.e. the directory of the file
880 into which the link is being inserted.
881 absolute Absolute path, if possible with ~ for home directory.
882 noabbrev Absolute path, no abbreviation of home directory.
883 adaptive Use relative path for files in the current directory and sub-
884 directories of it. For other files, use an absolute path."
885 :group 'org-link
886 :type '(choice
887 (const relative)
888 (const absolute)
889 (const noabbrev)
890 (const adaptive)))
892 (defcustom org-activate-links '(bracket angle plain radio tag date)
893 "Types of links that should be activated in Org-mode files.
894 This is a list of symbols, each leading to the activation of a certain link
895 type. In principle, it does not hurt to turn on most link types - there may
896 be a small gain when turning off unused link types. The types are:
898 bracket The recommended [[link][description]] or [[link]] links with hiding.
899 angular Links in angular brackes that may contain whitespace like
900 <bbdb:Carsten Dominik>.
901 plain Plain links in normal text, no whitespace, like http://google.com.
902 radio Text that is matched by a radio target, see manual for details.
903 tag Tag settings in a headline (link to tag search).
904 date Time stamps (link to calendar).
906 Changing this variable requires a restart of Emacs to become effective."
907 :group 'org-link
908 :type '(set (const :tag "Double bracket links (new style)" bracket)
909 (const :tag "Angular bracket links (old style)" angular)
910 (const :tag "Plain text links" plain)
911 (const :tag "Radio target matches" radio)
912 (const :tag "Tags" tag)
913 (const :tag "Timestamps" date)))
915 (defcustom org-make-link-description-function nil
916 "Function to use to generate link descriptions from links. If
917 nil the link location will be used. This function must take two
918 parameters; the first is the link and the second the description
919 org-insert-link has generated, and should return the description
920 to use."
921 :group 'org-link
922 :type 'function)
924 (defgroup org-link-store nil
925 "Options concerning storing links in Org-mode."
926 :tag "Org Store Link"
927 :group 'org-link)
929 (defcustom org-email-link-description-format "Email %c: %.30s"
930 "Format of the description part of a link to an email or usenet message.
931 The following %-excapes will be replaced by corresponding information:
933 %F full \"From\" field
934 %f name, taken from \"From\" field, address if no name
935 %T full \"To\" field
936 %t first name in \"To\" field, address if no name
937 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
938 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
939 %s subject
940 %m message-id.
942 You may use normal field width specification between the % and the letter.
943 This is for example useful to limit the length of the subject.
945 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
946 :group 'org-link-store
947 :type 'string)
949 (defcustom org-from-is-user-regexp
950 (let (r1 r2)
951 (when (and user-mail-address (not (string= user-mail-address "")))
952 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
953 (when (and user-full-name (not (string= user-full-name "")))
954 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
955 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
956 "Regexp mached against the \"From:\" header of an email or usenet message.
957 It should match if the message is from the user him/herself."
958 :group 'org-link-store
959 :type 'regexp)
961 (defcustom org-context-in-file-links t
962 "Non-nil means, file links from `org-store-link' contain context.
963 A search string will be added to the file name with :: as separator and
964 used to find the context when the link is activated by the command
965 `org-open-at-point'.
966 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
967 negates this setting for the duration of the command."
968 :group 'org-link-store
969 :type 'boolean)
971 (defcustom org-keep-stored-link-after-insertion nil
972 "Non-nil means, keep link in list for entire session.
974 The command `org-store-link' adds a link pointing to the current
975 location to an internal list. These links accumulate during a session.
976 The command `org-insert-link' can be used to insert links into any
977 Org-mode file (offering completion for all stored links). When this
978 option is nil, every link which has been inserted once using \\[org-insert-link]
979 will be removed from the list, to make completing the unused links
980 more efficient."
981 :group 'org-link-store
982 :type 'boolean)
984 (defgroup org-link-follow nil
985 "Options concerning following links in Org-mode."
986 :tag "Org Follow Link"
987 :group 'org-link)
989 (defcustom org-follow-link-hook nil
990 "Hook that is run after a link has been followed."
991 :group 'org-link-follow
992 :type 'hook)
994 (defcustom org-tab-follows-link nil
995 "Non-nil means, on links TAB will follow the link.
996 Needs to be set before org.el is loaded."
997 :group 'org-link-follow
998 :type 'boolean)
1000 (defcustom org-return-follows-link nil
1001 "Non-nil means, on links RET will follow the link.
1002 Needs to be set before org.el is loaded."
1003 :group 'org-link-follow
1004 :type 'boolean)
1006 (defcustom org-mouse-1-follows-link
1007 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1008 "Non-nil means, mouse-1 on a link will follow the link.
1009 A longer mouse click will still set point. Does not work on XEmacs.
1010 Needs to be set before org.el is loaded."
1011 :group 'org-link-follow
1012 :type 'boolean)
1014 (defcustom org-mark-ring-length 4
1015 "Number of different positions to be recorded in the ring
1016 Changing this requires a restart of Emacs to work correctly."
1017 :group 'org-link-follow
1018 :type 'interger)
1020 (defcustom org-link-frame-setup
1021 '((vm . vm-visit-folder-other-frame)
1022 (gnus . gnus-other-frame)
1023 (file . find-file-other-window))
1024 "Setup the frame configuration for following links.
1025 When following a link with Emacs, it may often be useful to display
1026 this link in another window or frame. This variable can be used to
1027 set this up for the different types of links.
1028 For VM, use any of
1029 `vm-visit-folder'
1030 `vm-visit-folder-other-frame'
1031 For Gnus, use any of
1032 `gnus'
1033 `gnus-other-frame'
1034 For FILE, use any of
1035 `find-file'
1036 `find-file-other-window'
1037 `find-file-other-frame'
1038 For the calendar, use the variable `calendar-setup'.
1039 For BBDB, it is currently only possible to display the matches in
1040 another window."
1041 :group 'org-link-follow
1042 :type '(list
1043 (cons (const vm)
1044 (choice
1045 (const vm-visit-folder)
1046 (const vm-visit-folder-other-window)
1047 (const vm-visit-folder-other-frame)))
1048 (cons (const gnus)
1049 (choice
1050 (const gnus)
1051 (const gnus-other-frame)))
1052 (cons (const file)
1053 (choice
1054 (const find-file)
1055 (const find-file-other-window)
1056 (const find-file-other-frame)))))
1058 (defcustom org-display-internal-link-with-indirect-buffer nil
1059 "Non-nil means, use indirect buffer to display infile links.
1060 Activating internal links (from one location in a file to another location
1061 in the same file) normally just jumps to the location. When the link is
1062 activated with a C-u prefix (or with mouse-3), the link is displayed in
1063 another window. When this option is set, the other window actually displays
1064 an indirect buffer clone of the current buffer, to avoid any visibility
1065 changes to the current buffer."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-open-non-existing-files nil
1070 "Non-nil means, `org-open-file' will open non-existing files.
1071 When nil, an error will be generated."
1072 :group 'org-link-follow
1073 :type 'boolean)
1075 (defcustom org-open-directory-means-index-dot-org nil
1076 "Non-nil means, a link to a directory really means to index.org.
1077 When nil, following a directory link will run dired or open a finder/explorer
1078 window on that directory."
1079 :group 'org-link-follow
1080 :type 'boolean)
1082 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1083 "Function and arguments to call for following mailto links.
1084 This is a list with the first element being a lisp function, and the
1085 remaining elements being arguments to the function. In string arguments,
1086 %a will be replaced by the address, and %s will be replaced by the subject
1087 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1088 :group 'org-link-follow
1089 :type '(choice
1090 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1091 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1092 (const :tag "message-mail" (message-mail "%a" "%s"))
1093 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1095 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1096 "Non-nil means, ask for confirmation before executing shell links.
1097 Shell links can be dangerous: just think about a link
1099 [[shell:rm -rf ~/*][Google Search]]
1101 This link would show up in your Org-mode document as \"Google Search\",
1102 but really it would remove your entire home directory.
1103 Therefore we advise against setting this variable to nil.
1104 Just change it to `y-or-n-p' of you want to confirm with a
1105 single keystroke rather than having to type \"yes\"."
1106 :group 'org-link-follow
1107 :type '(choice
1108 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1109 (const :tag "with y-or-n (faster)" y-or-n-p)
1110 (const :tag "no confirmation (dangerous)" nil)))
1112 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1113 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1114 Elisp links can be dangerous: just think about a link
1116 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1118 This link would show up in your Org-mode document as \"Google Search\",
1119 but really it would remove your entire home directory.
1120 Therefore we advise against setting this variable to nil.
1121 Just change it to `y-or-n-p' of you want to confirm with a
1122 single keystroke rather than having to type \"yes\"."
1123 :group 'org-link-follow
1124 :type '(choice
1125 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1126 (const :tag "with y-or-n (faster)" y-or-n-p)
1127 (const :tag "no confirmation (dangerous)" nil)))
1129 (defconst org-file-apps-defaults-gnu
1130 '((remote . emacs)
1131 (t . mailcap))
1132 "Default file applications on a UNIX or GNU/Linux system.
1133 See `org-file-apps'.")
1135 (defconst org-file-apps-defaults-macosx
1136 '((remote . emacs)
1137 (t . "open %s")
1138 ("ps" . "gv %s")
1139 ("ps.gz" . "gv %s")
1140 ("eps" . "gv %s")
1141 ("eps.gz" . "gv %s")
1142 ("dvi" . "xdvi %s")
1143 ("fig" . "xfig %s"))
1144 "Default file applications on a MacOS X system.
1145 The system \"open\" is known as a default, but we use X11 applications
1146 for some files for which the OS does not have a good default.
1147 See `org-file-apps'.")
1149 (defconst org-file-apps-defaults-windowsnt
1150 (list
1151 '(remote . emacs)
1152 (cons t
1153 (list (if (featurep 'xemacs)
1154 'mswindows-shell-execute
1155 'w32-shell-execute)
1156 "open" 'file)))
1157 "Default file applications on a Windows NT system.
1158 The system \"open\" is used for most files.
1159 See `org-file-apps'.")
1161 (defcustom org-file-apps
1163 ("txt" . emacs)
1164 ("tex" . emacs)
1165 ("ltx" . emacs)
1166 ("org" . emacs)
1167 ("el" . emacs)
1168 ("bib" . emacs)
1170 "External applications for opening `file:path' items in a document.
1171 Org-mode uses system defaults for different file types, but
1172 you can use this variable to set the application for a given file
1173 extension. The entries in this list are cons cells where the car identifies
1174 files and the cdr the corresponding command. Possible values for the
1175 file identifier are
1176 \"ext\" A string identifying an extension
1177 `directory' Matches a directory
1178 `remote' Matches a remote file, accessible through tramp or efs.
1179 Remote files most likely should be visited through Emacs
1180 because external applications cannot handle such paths.
1181 t Default for all remaining files
1183 Possible values for the command are:
1184 `emacs' The file will be visited by the current Emacs process.
1185 `default' Use the default application for this file type.
1186 string A command to be executed by a shell; %s will be replaced
1187 by the path to the file.
1188 sexp A Lisp form which will be evaluated. The file path will
1189 be available in the Lisp variable `file'.
1190 For more examples, see the system specific constants
1191 `org-file-apps-defaults-macosx'
1192 `org-file-apps-defaults-windowsnt'
1193 `org-file-apps-defaults-gnu'."
1194 :group 'org-link-follow
1195 :type '(repeat
1196 (cons (choice :value ""
1197 (string :tag "Extension")
1198 (const :tag "Default for unrecognized files" t)
1199 (const :tag "Remote file" remote)
1200 (const :tag "Links to a directory" directory))
1201 (choice :value ""
1202 (const :tag "Visit with Emacs" emacs)
1203 (const :tag "Use system default" default)
1204 (string :tag "Command")
1205 (sexp :tag "Lisp form")))))
1207 (defgroup org-refile nil
1208 "Options concerning refiling entries in Org-mode."
1209 :tag "Org Remember"
1210 :group 'org)
1212 (defcustom org-directory "~/org"
1213 "Directory with org files.
1214 This directory will be used as default to prompt for org files.
1215 Used by the hooks for remember.el."
1216 :group 'org-refile
1217 :group 'org-remember
1218 :type 'directory)
1220 (defcustom org-default-notes-file "~/.notes"
1221 "Default target for storing notes.
1222 Used by the hooks for remember.el. This can be a string, or nil to mean
1223 the value of `remember-data-file'.
1224 You can set this on a per-template basis with the variable
1225 `org-remember-templates'."
1226 :group 'org-refile
1227 :group 'org-remember
1228 :type '(choice
1229 (const :tag "Default from remember-data-file" nil)
1230 file))
1232 (defcustom org-goto-interface 'outline
1233 "The default interface to be used for `org-goto'.
1234 Allowed vaues are:
1235 outline The interface shows an outline of the relevant file
1236 and the correct heading is found by moving through
1237 the outline or by searching with incremental search.
1238 outline-path-completion Headlines in the current buffer are offered via
1239 completion."
1240 :group 'org-refile
1241 :type '(choice
1242 (const :tag "Outline" outline)
1243 (const :tag "Outline-path-completion" outline-path-completion)))
1245 (defcustom org-reverse-note-order nil
1246 "Non-nil means, store new notes at the beginning of a file or entry.
1247 When nil, new notes will be filed to the end of a file or entry.
1248 This can also be a list with cons cells of regular expressions that
1249 are matched against file names, and values."
1250 :group 'org-remember
1251 :type '(choice
1252 (const :tag "Reverse always" t)
1253 (const :tag "Reverse never" nil)
1254 (repeat :tag "By file name regexp"
1255 (cons regexp boolean))))
1257 (defcustom org-refile-targets nil
1258 "Targets for refiling entries with \\[org-refile].
1259 This is list of cons cells. Each cell contains:
1260 - a specification of the files to be considered, either a list of files,
1261 or a symbol whose function or variable value will be used to retrieve
1262 a file name or a list of file names. Nil means, refile to a different
1263 heading in the current buffer.
1264 - A specification of how to find candidate refile targets. This may be
1265 any of
1266 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1267 This tag has to be present in all target headlines, inheritance will
1268 not be considered.
1269 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1270 todo keyword.
1271 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1272 headlines that are refiling targets.
1273 - a cons cell (:level . N). Any headline of level N is considered a target.
1274 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1276 When this variable is nil, all top-level headlines in the current buffer
1277 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1278 :group 'org-remember
1279 :type '(repeat
1280 (cons
1281 (choice :value org-agenda-files
1282 (const :tag "All agenda files" org-agenda-files)
1283 (const :tag "Current buffer" nil)
1284 (function) (variable) (file))
1285 (choice :tag "Identify target headline by"
1286 (cons :tag "Specific tag" (const :tag) (string))
1287 (cons :tag "TODO keyword" (const :todo) (string))
1288 (cons :tag "Regular expression" (const :regexp) (regexp))
1289 (cons :tag "Level number" (const :level) (integer))
1290 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1292 (defcustom org-refile-use-outline-path nil
1293 "Non-nil means, provide refile targets as paths.
1294 So a level 3 headline will be available as level1/level2/level3.
1295 When the value is `file', also include the file name (without directory)
1296 into the path. When `full-file-path', include the full file path."
1297 :group 'org-remember
1298 :type '(choice
1299 (const :tag "Not" nil)
1300 (const :tag "Yes" t)
1301 (const :tag "Start with file name" file)
1302 (const :tag "Start with full file path" full-file-path)))
1304 (defgroup org-todo nil
1305 "Options concerning TODO items in Org-mode."
1306 :tag "Org TODO"
1307 :group 'org)
1309 (defgroup org-progress nil
1310 "Options concerning Progress logging in Org-mode."
1311 :tag "Org Progress"
1312 :group 'org-time)
1314 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1315 "List of TODO entry keyword sequences and their interpretation.
1316 \\<org-mode-map>This is a list of sequences.
1318 Each sequence starts with a symbol, either `sequence' or `type',
1319 indicating if the keywords should be interpreted as a sequence of
1320 action steps, or as different types of TODO items. The first
1321 keywords are states requiring action - these states will select a headline
1322 for inclusion into the global TODO list Org-mode produces. If one of
1323 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1324 signify that no further action is necessary. If \"|\" is not found,
1325 the last keyword is treated as the only DONE state of the sequence.
1327 The command \\[org-todo] cycles an entry through these states, and one
1328 additional state where no keyword is present. For details about this
1329 cycling, see the manual.
1331 TODO keywords and interpretation can also be set on a per-file basis with
1332 the special #+SEQ_TODO and #+TYP_TODO lines.
1334 Each keyword can optionally specify a character for fast state selection
1335 \(in combination with the variable `org-use-fast-todo-selection')
1336 and specifiers for state change logging, using the same syntax
1337 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1338 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1339 indicates to record a time stamp each time this state is selected.
1341 Each keyword may also specify if a timestamp or a note should be
1342 recorded when entering or leaving the state, by adding additional
1343 characters in the parenthesis after the keyword. This looks like this:
1344 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1345 record only the time of the state change. With X and Y being either
1346 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1347 Y when leaving the state if and only if the *target* state does not
1348 define X. You may omit any of the fast-selection key or X or /Y,
1349 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1351 For backward compatibility, this variable may also be just a list
1352 of keywords - in this case the interptetation (sequence or type) will be
1353 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1354 :group 'org-todo
1355 :group 'org-keywords
1356 :type '(choice
1357 (repeat :tag "Old syntax, just keywords"
1358 (string :tag "Keyword"))
1359 (repeat :tag "New syntax"
1360 (cons
1361 (choice
1362 :tag "Interpretation"
1363 (const :tag "Sequence (cycling hits every state)" sequence)
1364 (const :tag "Type (cycling directly to DONE)" type))
1365 (repeat
1366 (string :tag "Keyword"))))))
1368 (defvar org-todo-keywords-1 nil
1369 "All TODO and DONE keywords active in a buffer.")
1370 (make-variable-buffer-local 'org-todo-keywords-1)
1371 (defvar org-todo-keywords-for-agenda nil)
1372 (defvar org-done-keywords-for-agenda nil)
1373 (defvar org-todo-keyword-alist-for-agenda nil)
1374 (defvar org-tag-alist-for-agenda nil)
1375 (defvar org-agenda-contributing-files nil)
1376 (defvar org-not-done-keywords nil)
1377 (make-variable-buffer-local 'org-not-done-keywords)
1378 (defvar org-done-keywords nil)
1379 (make-variable-buffer-local 'org-done-keywords)
1380 (defvar org-todo-heads nil)
1381 (make-variable-buffer-local 'org-todo-heads)
1382 (defvar org-todo-sets nil)
1383 (make-variable-buffer-local 'org-todo-sets)
1384 (defvar org-todo-log-states nil)
1385 (make-variable-buffer-local 'org-todo-log-states)
1386 (defvar org-todo-kwd-alist nil)
1387 (make-variable-buffer-local 'org-todo-kwd-alist)
1388 (defvar org-todo-key-alist nil)
1389 (make-variable-buffer-local 'org-todo-key-alist)
1390 (defvar org-todo-key-trigger nil)
1391 (make-variable-buffer-local 'org-todo-key-trigger)
1393 (defcustom org-todo-interpretation 'sequence
1394 "Controls how TODO keywords are interpreted.
1395 This variable is in principle obsolete and is only used for
1396 backward compatibility, if the interpretation of todo keywords is
1397 not given already in `org-todo-keywords'. See that variable for
1398 more information."
1399 :group 'org-todo
1400 :group 'org-keywords
1401 :type '(choice (const sequence)
1402 (const type)))
1404 (defcustom org-use-fast-todo-selection 'prefix
1405 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1406 This variable describes if and under what circumstances the cycling
1407 mechanism for TODO keywords will be replaced by a single-key, direct
1408 selection scheme.
1410 When nil, fast selection is never used.
1412 When the symbol `prefix', it will be used when `org-todo' is called with
1413 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1414 in an agenda buffer.
1416 When t, fast selection is used by default. In this case, the prefix
1417 argument forces cycling instead.
1419 In all cases, the special interface is only used if access keys have actually
1420 been assigned by the user, i.e. if keywords in the configuration are followed
1421 by a letter in parenthesis, like TODO(t)."
1422 :group 'org-todo
1423 :type '(choice
1424 (const :tag "Never" nil)
1425 (const :tag "By default" t)
1426 (const :tag "Only with C-u C-c C-t" prefix)))
1428 (defcustom org-provide-todo-statistics t
1429 "Non-nil means, update todo statistics after insert and toggle.
1430 When this is set, todo statistics is updated in the parent of the current
1431 entry each time a todo state is changed."
1432 :group 'org-todo
1433 :type 'boolean)
1435 (defcustom org-after-todo-state-change-hook nil
1436 "Hook which is run after the state of a TODO item was changed.
1437 The new state (a string with a TODO keyword, or nil) is available in the
1438 Lisp variable `state'."
1439 :group 'org-todo
1440 :type 'hook)
1442 (defcustom org-log-done nil
1443 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1444 When equal to the list (done), also prompt for a closing note.
1445 This can also be configured on a per-file basis by adding one of
1446 the following lines anywhere in the buffer:
1448 #+STARTUP: logdone
1449 #+STARTUP: lognotedone
1450 #+STARTUP: nologdone"
1451 :group 'org-todo
1452 :group 'org-progress
1453 :type '(choice
1454 (const :tag "No logging" nil)
1455 (const :tag "Record CLOSED timestamp" time)
1456 (const :tag "Record CLOSED timestamp with closing note." note)))
1458 ;; Normalize old uses of org-log-done.
1459 (cond
1460 ((eq org-log-done t) (setq org-log-done 'time))
1461 ((and (listp org-log-done) (memq 'done org-log-done))
1462 (setq org-log-done 'note)))
1464 (defcustom org-log-note-clock-out nil
1465 "Non-nil means, record a note when clocking out of an item.
1466 This can also be configured on a per-file basis by adding one of
1467 the following lines anywhere in the buffer:
1469 #+STARTUP: lognoteclock-out
1470 #+STARTUP: nolognoteclock-out"
1471 :group 'org-todo
1472 :group 'org-progress
1473 :type 'boolean)
1475 (defcustom org-log-done-with-time t
1476 "Non-nil means, the CLOSED time stamp will contain date and time.
1477 When nil, only the date will be recorded."
1478 :group 'org-progress
1479 :type 'boolean)
1481 (defcustom org-log-note-headings
1482 '((done . "CLOSING NOTE %t")
1483 (state . "State %-12s %t")
1484 (note . "Note taken on %t")
1485 (clock-out . ""))
1486 "Headings for notes added to entries.
1487 The value is an alist, with the car being a symbol indicating the note
1488 context, and the cdr is the heading to be used. The heading may also be the
1489 empty string.
1490 %t in the heading will be replaced by a time stamp.
1491 %s will be replaced by the new TODO state, in double quotes.
1492 %u will be replaced by the user name.
1493 %U will be replaced by the full user name."
1494 :group 'org-todo
1495 :group 'org-progress
1496 :type '(list :greedy t
1497 (cons (const :tag "Heading when closing an item" done) string)
1498 (cons (const :tag
1499 "Heading when changing todo state (todo sequence only)"
1500 state) string)
1501 (cons (const :tag "Heading when just taking a note" note) string)
1502 (cons (const :tag "Heading when clocking out" clock-out) string)))
1504 (unless (assq 'note org-log-note-headings)
1505 (push '(note . "%t") org-log-note-headings))
1507 (defcustom org-log-states-order-reversed t
1508 "Non-nil means, the latest state change note will be directly after heading.
1509 When nil, the notes will be orderer according to time."
1510 :group 'org-todo
1511 :group 'org-progress
1512 :type 'boolean)
1514 (defcustom org-log-repeat 'time
1515 "Non-nil means, record moving through the DONE state when triggering repeat.
1516 An auto-repeating tasks is immediately switched back to TODO when marked
1517 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1518 the TODO keyword definition, or recording a closing note by setting
1519 `org-log-done', there will be no record of the task moving through DONE.
1520 This variable forces taking a note anyway. Possible values are:
1522 nil Don't force a record
1523 time Record a time stamp
1524 note Record a note
1526 This option can also be set with on a per-file-basis with
1528 #+STARTUP: logrepeat
1529 #+STARTUP: lognoterepeat
1530 #+STARTUP: nologrepeat
1532 You can have local logging settings for a subtree by setting the LOGGING
1533 property to one or more of these keywords."
1534 :group 'org-todo
1535 :group 'org-progress
1536 :type '(choice
1537 (const :tag "Don't force a record" nil)
1538 (const :tag "Force recording the DONE state" time)
1539 (const :tag "Force recording a note with the DONE state" note)))
1542 (defgroup org-priorities nil
1543 "Priorities in Org-mode."
1544 :tag "Org Priorities"
1545 :group 'org-todo)
1547 (defcustom org-highest-priority ?A
1548 "The highest priority of TODO items. A character like ?A, ?B etc.
1549 Must have a smaller ASCII number than `org-lowest-priority'."
1550 :group 'org-priorities
1551 :type 'character)
1553 (defcustom org-lowest-priority ?C
1554 "The lowest priority of TODO items. A character like ?A, ?B etc.
1555 Must have a larger ASCII number than `org-highest-priority'."
1556 :group 'org-priorities
1557 :type 'character)
1559 (defcustom org-default-priority ?B
1560 "The default priority of TODO items.
1561 This is the priority an item get if no explicit priority is given."
1562 :group 'org-priorities
1563 :type 'character)
1565 (defcustom org-priority-start-cycle-with-default t
1566 "Non-nil means, start with default priority when starting to cycle.
1567 When this is nil, the first step in the cycle will be (depending on the
1568 command used) one higher or lower that the default priority."
1569 :group 'org-priorities
1570 :type 'boolean)
1572 (defgroup org-time nil
1573 "Options concerning time stamps and deadlines in Org-mode."
1574 :tag "Org Time"
1575 :group 'org)
1577 (defcustom org-insert-labeled-timestamps-at-point nil
1578 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1579 When nil, these labeled time stamps are forces into the second line of an
1580 entry, just after the headline. When scheduling from the global TODO list,
1581 the time stamp will always be forced into the second line."
1582 :group 'org-time
1583 :type 'boolean)
1585 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1586 "Formats for `format-time-string' which are used for time stamps.
1587 It is not recommended to change this constant.")
1589 (defcustom org-time-stamp-rounding-minutes '(0 5)
1590 "Number of minutes to round time stamps to.
1591 These are two values, the first applies when first creating a time stamp.
1592 The second applies when changing it with the commands `S-up' and `S-down'.
1593 When changing the time stamp, this means that it will change in steps
1594 of N minutes, as given by the second value.
1596 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1597 numbers should be factors of 60, so for example 5, 10, 15.
1599 When this is larger than 1, you can still force an exact time-stamp by using
1600 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1601 and by using a prefix arg to `S-up/down' to specify the exact number
1602 of minutes to shift."
1603 :group 'org-time
1604 :get '(lambda (var) ; Make sure all entries have 5 elements
1605 (if (integerp (default-value var))
1606 (list (default-value var) 5)
1607 (default-value var)))
1608 :type '(list
1609 (integer :tag "when inserting times")
1610 (integer :tag "when modifying times")))
1612 ;; Normalize old customizations of this variable.
1613 (when (integerp org-time-stamp-rounding-minutes)
1614 (setq org-time-stamp-rounding-minutes
1615 (list org-time-stamp-rounding-minutes
1616 org-time-stamp-rounding-minutes)))
1618 (defcustom org-display-custom-times nil
1619 "Non-nil means, overlay custom formats over all time stamps.
1620 The formats are defined through the variable `org-time-stamp-custom-formats'.
1621 To turn this on on a per-file basis, insert anywhere in the file:
1622 #+STARTUP: customtime"
1623 :group 'org-time
1624 :set 'set-default
1625 :type 'sexp)
1626 (make-variable-buffer-local 'org-display-custom-times)
1628 (defcustom org-time-stamp-custom-formats
1629 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1630 "Custom formats for time stamps. See `format-time-string' for the syntax.
1631 These are overlayed over the default ISO format if the variable
1632 `org-display-custom-times' is set. Time like %H:%M should be at the
1633 end of the second format."
1634 :group 'org-time
1635 :type 'sexp)
1637 (defun org-time-stamp-format (&optional long inactive)
1638 "Get the right format for a time string."
1639 (let ((f (if long (cdr org-time-stamp-formats)
1640 (car org-time-stamp-formats))))
1641 (if inactive
1642 (concat "[" (substring f 1 -1) "]")
1643 f)))
1645 (defcustom org-time-clocksum-format "%d:%02d"
1646 "The format string used when creating CLOCKSUM lines, or when
1647 org-mode generates a time duration."
1648 :group 'org-time
1649 :type 'string)
1651 (defcustom org-deadline-warning-days 14
1652 "No. of days before expiration during which a deadline becomes active.
1653 This variable governs the display in sparse trees and in the agenda.
1654 When 0 or negative, it means use this number (the absolute value of it)
1655 even if a deadline has a different individual lead time specified."
1656 :group 'org-time
1657 :group 'org-agenda-daily/weekly
1658 :type 'number)
1660 (defcustom org-read-date-prefer-future t
1661 "Non-nil means, assume future for incomplete date input from user.
1662 This affects the following situations:
1663 1. The user gives a day, but no month.
1664 For example, if today is the 15th, and you enter \"3\", Org-mode will
1665 read this as the third of *next* month. However, if you enter \"17\",
1666 it will be considered as *this* month.
1667 2. The user gives a month but not a year.
1668 For example, if it is april and you enter \"feb 2\", this will be read
1669 as feb 2, *next* year. \"May 5\", however, will be this year.
1671 Currently this does not work for ISO week specifications.
1673 When this option is nil, the current month and year will always be used
1674 as defaults."
1675 :group 'org-time
1676 :type 'boolean)
1678 (defcustom org-read-date-display-live t
1679 "Non-nil means, display current interpretation of date prompt live.
1680 This display will be in an overlay, in the minibuffer."
1681 :group 'org-time
1682 :type 'boolean)
1684 (defcustom org-read-date-popup-calendar t
1685 "Non-nil means, pop up a calendar when prompting for a date.
1686 In the calendar, the date can be selected with mouse-1. However, the
1687 minibuffer will also be active, and you can simply enter the date as well.
1688 When nil, only the minibuffer will be available."
1689 :group 'org-time
1690 :type 'boolean)
1691 (if (fboundp 'defvaralias)
1692 (defvaralias 'org-popup-calendar-for-date-prompt
1693 'org-read-date-popup-calendar))
1695 (defcustom org-extend-today-until 0
1696 "The hour when your day really ends. Must be an integer.
1697 This has influence for the following applications:
1698 - When switching the agenda to \"today\". It it is still earlier than
1699 the time given here, the day recognized as TODAY is actually yesterday.
1700 - When a date is read from the user and it is still before the time given
1701 here, the current date and time will be assumed to be yesterday, 23:59.
1702 Also, timestamps inserted in remember templates follow this rule.
1704 IMPORTANT: This is a feature whose implementation is and likely will
1705 remain incomplete. Really, it is only here because past midnight seems to
1706 ne the favorite working time of John Wiegley :-)"
1707 :group 'org-time
1708 :type 'number)
1710 (defcustom org-edit-timestamp-down-means-later nil
1711 "Non-nil means, S-down will increase the time in a time stamp.
1712 When nil, S-up will increase."
1713 :group 'org-time
1714 :type 'boolean)
1716 (defcustom org-calendar-follow-timestamp-change t
1717 "Non-nil means, make the calendar window follow timestamp changes.
1718 When a timestamp is modified and the calendar window is visible, it will be
1719 moved to the new date."
1720 :group 'org-time
1721 :type 'boolean)
1723 (defgroup org-tags nil
1724 "Options concerning tags in Org-mode."
1725 :tag "Org Tags"
1726 :group 'org)
1728 (defcustom org-tag-alist nil
1729 "List of tags allowed in Org-mode files.
1730 When this list is nil, Org-mode will base TAG input on what is already in the
1731 buffer.
1732 The value of this variable is an alist, the car of each entry must be a
1733 keyword as a string, the cdr may be a character that is used to select
1734 that tag through the fast-tag-selection interface.
1735 See the manual for details."
1736 :group 'org-tags
1737 :type '(repeat
1738 (choice
1739 (cons (string :tag "Tag name")
1740 (character :tag "Access char"))
1741 (const :tag "Start radio group" (:startgroup))
1742 (const :tag "End radio group" (:endgroup)))))
1744 (defvar org-file-tags nil
1745 "List of tags that can be inherited by all entries in the file.
1746 The tags will be inherited if the variable `org-use-tag-inheritance'
1747 says they should be.
1748 This variable is populated from #+TAG lines.")
1750 (defcustom org-use-fast-tag-selection 'auto
1751 "Non-nil means, use fast tag selection scheme.
1752 This is a special interface to select and deselect tags with single keys.
1753 When nil, fast selection is never used.
1754 When the symbol `auto', fast selection is used if and only if selection
1755 characters for tags have been configured, either through the variable
1756 `org-tag-alist' or through a #+TAGS line in the buffer.
1757 When t, fast selection is always used and selection keys are assigned
1758 automatically if necessary."
1759 :group 'org-tags
1760 :type '(choice
1761 (const :tag "Always" t)
1762 (const :tag "Never" nil)
1763 (const :tag "When selection characters are configured" 'auto)))
1765 (defcustom org-fast-tag-selection-single-key nil
1766 "Non-nil means, fast tag selection exits after first change.
1767 When nil, you have to press RET to exit it.
1768 During fast tag selection, you can toggle this flag with `C-c'.
1769 This variable can also have the value `expert'. In this case, the window
1770 displaying the tags menu is not even shown, until you press C-c again."
1771 :group 'org-tags
1772 :type '(choice
1773 (const :tag "No" nil)
1774 (const :tag "Yes" t)
1775 (const :tag "Expert" expert)))
1777 (defvar org-fast-tag-selection-include-todo nil
1778 "Non-nil means, fast tags selection interface will also offer TODO states.
1779 This is an undocumented feature, you should not rely on it.")
1781 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1782 "The column to which tags should be indented in a headline.
1783 If this number is positive, it specifies the column. If it is negative,
1784 it means that the tags should be flushright to that column. For example,
1785 -80 works well for a normal 80 character screen."
1786 :group 'org-tags
1787 :type 'integer)
1789 (defcustom org-auto-align-tags t
1790 "Non-nil means, realign tags after pro/demotion of TODO state change.
1791 These operations change the length of a headline and therefore shift
1792 the tags around. With this options turned on, after each such operation
1793 the tags are again aligned to `org-tags-column'."
1794 :group 'org-tags
1795 :type 'boolean)
1797 (defcustom org-use-tag-inheritance t
1798 "Non-nil means, tags in levels apply also for sublevels.
1799 When nil, only the tags directly given in a specific line apply there.
1800 If this option is t, a match early-on in a tree can lead to a large
1801 number of matches in the subtree. If you only want to see the first
1802 match in a tree during a search, check out the variable
1803 `org-tags-match-list-sublevels'.
1805 This may also be a list of tags that should be inherited, or a regexp that
1806 matches tags that should be inherited."
1807 :group 'org-tags
1808 :type '(choice
1809 (const :tag "Not" nil)
1810 (const :tag "Always" t)
1811 (repeat :tag "Specific tags" (string :tag "Tag"))
1812 (regexp :tag "Tags matched by regexp")))
1814 (defun org-tag-inherit-p (tag)
1815 "Check if TAG is one that should be inherited."
1816 (cond
1817 ((eq org-use-tag-inheritance t) t)
1818 ((not org-use-tag-inheritance) nil)
1819 ((stringp org-use-tag-inheritance)
1820 (string-match org-use-tag-inheritance tag))
1821 ((listp org-use-tag-inheritance)
1822 (member tag org-use-tag-inheritance))
1823 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1825 (defcustom org-tags-match-list-sublevels t
1826 "Non-nil means list also sublevels of headlines matching tag search.
1827 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1828 the sublevels of a headline matching a tag search often also match
1829 the same search. Listing all of them can create very long lists.
1830 Setting this variable to nil causes subtrees of a match to be skipped.
1831 This option is off by default, because inheritance in on. If you turn
1832 inheritance off, you very likely want to turn this option on.
1834 As a special case, if the tag search is restricted to TODO items, the
1835 value of this variable is ignored and sublevels are always checked, to
1836 make sure all corresponding TODO items find their way into the list."
1837 :group 'org-tags
1838 :type 'boolean)
1840 (defvar org-tags-history nil
1841 "History of minibuffer reads for tags.")
1842 (defvar org-last-tags-completion-table nil
1843 "The last used completion table for tags.")
1844 (defvar org-after-tags-change-hook nil
1845 "Hook that is run after the tags in a line have changed.")
1847 (defgroup org-properties nil
1848 "Options concerning properties in Org-mode."
1849 :tag "Org Properties"
1850 :group 'org)
1852 (defcustom org-property-format "%-10s %s"
1853 "How property key/value pairs should be formatted by `indent-line'.
1854 When `indent-line' hits a property definition, it will format the line
1855 according to this format, mainly to make sure that the values are
1856 lined-up with respect to each other."
1857 :group 'org-properties
1858 :type 'string)
1860 (defcustom org-use-property-inheritance nil
1861 "Non-nil means, properties apply also for sublevels.
1863 This setting is chiefly used during property searches. Turning it on can
1864 cause significant overhead when doing a search, which is why it is not
1865 on by default.
1867 When nil, only the properties directly given in the current entry count.
1868 When t, every property is inherited. The value may also be a list of
1869 properties that should have inheritance, or a regular expression matching
1870 properties that should be inherited.
1872 However, note that some special properties use inheritance under special
1873 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1874 and the properties ending in \"_ALL\" when they are used as descriptor
1875 for valid values of a property.
1877 Note for programmers:
1878 When querying an entry with `org-entry-get', you can control if inheritance
1879 should be used. By default, `org-entry-get' looks only at the local
1880 properties. You can request inheritance by setting the inherit argument
1881 to t (to force inheritance) or to `selective' (to respect the setting
1882 in this variable)."
1883 :group 'org-properties
1884 :type '(choice
1885 (const :tag "Not" nil)
1886 (const :tag "Always" t)
1887 (repeat :tag "Specific properties" (string :tag "Property"))
1888 (regexp :tag "Properties matched by regexp")))
1890 (defun org-property-inherit-p (property)
1891 "Check if PROPERTY is one that should be inherited."
1892 (cond
1893 ((eq org-use-property-inheritance t) t)
1894 ((not org-use-property-inheritance) nil)
1895 ((stringp org-use-property-inheritance)
1896 (string-match org-use-property-inheritance property))
1897 ((listp org-use-property-inheritance)
1898 (member property org-use-property-inheritance))
1899 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1901 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1902 "The default column format, if no other format has been defined.
1903 This variable can be set on the per-file basis by inserting a line
1905 #+COLUMNS: %25ITEM ....."
1906 :group 'org-properties
1907 :type 'string)
1909 (defcustom org-columns-ellipses ".."
1910 "The ellipses to be used when a field in column view is truncated.
1911 When this is the empty string, as many characters as possible are shown,
1912 but then there will be no visual indication that the field has been truncated.
1913 When this is a string of length N, the last N characters of a truncated
1914 field are replaced by this string. If the column is narrower than the
1915 ellipses string, only part of the ellipses string will be shown."
1916 :group 'org-properties
1917 :type 'string)
1919 (defcustom org-columns-modify-value-for-display-function nil
1920 "Function that modifies values for display in column view.
1921 For example, it can be used to cut out a certain part from a time stamp.
1922 The function must take 2 argments:
1924 column-title The tite of the column (*not* the property name)
1925 value The value that should be modified.
1927 The function should return the value that should be displayed,
1928 or nil if the normal value should be used."
1929 :group 'org-properties
1930 :type 'function)
1932 (defcustom org-effort-property "Effort"
1933 "The property that is being used to keep track of effort estimates.
1934 Effort estimates given in this property need to have the format H:MM."
1935 :group 'org-properties
1936 :group 'org-progress
1937 :type '(string :tag "Property"))
1939 (defconst org-global-properties-fixed
1940 '(("VISIBILITY_ALL" . "folded children content all"))
1941 "List of property/value pairs that can be inherited by any entry.
1942 These are fixed values, for the preset properties.")
1945 (defcustom org-global-properties nil
1946 "List of property/value pairs that can be inherited by any entry.
1947 You can set buffer-local values for this by adding lines like
1949 #+PROPERTY: NAME VALUE"
1950 :group 'org-properties
1951 :type '(repeat
1952 (cons (string :tag "Property")
1953 (string :tag "Value"))))
1955 (defvar org-file-properties nil
1956 "List of property/value pairs that can be inherited by any entry.
1957 Valid for the current buffer.
1958 This variable is populated from #+PROPERTY lines.")
1959 (make-variable-buffer-local 'org-file-properties)
1961 (defgroup org-agenda nil
1962 "Options concerning agenda views in Org-mode."
1963 :tag "Org Agenda"
1964 :group 'org)
1966 (defvar org-category nil
1967 "Variable used by org files to set a category for agenda display.
1968 Such files should use a file variable to set it, for example
1970 # -*- mode: org; org-category: \"ELisp\"
1972 or contain a special line
1974 #+CATEGORY: ELisp
1976 If the file does not specify a category, then file's base name
1977 is used instead.")
1978 (make-variable-buffer-local 'org-category)
1979 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1981 (defcustom org-agenda-files nil
1982 "The files to be used for agenda display.
1983 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1984 \\[org-remove-file]. You can also use customize to edit the list.
1986 If an entry is a directory, all files in that directory that are matched by
1987 `org-agenda-file-regexp' will be part of the file list.
1989 If the value of the variable is not a list but a single file name, then
1990 the list of agenda files is actually stored and maintained in that file, one
1991 agenda file per line."
1992 :group 'org-agenda
1993 :type '(choice
1994 (repeat :tag "List of files and directories" file)
1995 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1997 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1998 "Regular expression to match files for `org-agenda-files'.
1999 If any element in the list in that variable contains a directory instead
2000 of a normal file, all files in that directory that are matched by this
2001 regular expression will be included."
2002 :group 'org-agenda
2003 :type 'regexp)
2005 (defcustom org-agenda-text-search-extra-files nil
2006 "List of extra files to be searched by text search commands.
2007 These files will be search in addition to the agenda files by the
2008 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2009 Note that these files will only be searched for text search commands,
2010 not for the other agenda views like todo lists, tag searches or the weekly
2011 agenda. This variable is intended to list notes and possibly archive files
2012 that should also be searched by these two commands.
2013 In fact, if the first element in the list is the symbol `agenda-archives',
2014 than all archive files of all agenda files will be added to the search
2015 scope."
2016 :group 'org-agenda
2017 :type '(set :greedy t
2018 (const :tag "Agenda Archives" agenda-archives)
2019 (repeat :inline t (file))))
2021 (if (fboundp 'defvaralias)
2022 (defvaralias 'org-agenda-multi-occur-extra-files
2023 'org-agenda-text-search-extra-files))
2025 (defcustom org-agenda-skip-unavailable-files nil
2026 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2027 A nil value means to remove them, after a query, from the list."
2028 :group 'org-agenda
2029 :type 'boolean)
2031 (defcustom org-calendar-to-agenda-key [?c]
2032 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2033 The command `org-calendar-goto-agenda' will be bound to this key. The
2034 default is the character `c' because then `c' can be used to switch back and
2035 forth between agenda and calendar."
2036 :group 'org-agenda
2037 :type 'sexp)
2039 (defcustom org-calendar-agenda-action-key [?k]
2040 "The key to be installed in `calendar-mode-map' for agenda-action.
2041 The command `org-agenda-action' will be bound to this key. The
2042 default is the character `k' because we use the same key in the agenda."
2043 :group 'org-agenda
2044 :type 'sexp)
2046 (eval-after-load "calendar"
2047 '(progn
2048 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2049 'org-calendar-goto-agenda)
2050 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2051 'org-agenda-action)))
2053 (defgroup org-latex nil
2054 "Options for embedding LaTeX code into Org-mode."
2055 :tag "Org LaTeX"
2056 :group 'org)
2058 (defcustom org-format-latex-options
2059 '(:foreground default :background default :scale 1.0
2060 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2061 :matchers ("begin" "$" "$$" "\\(" "\\["))
2062 "Options for creating images from LaTeX fragments.
2063 This is a property list with the following properties:
2064 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2065 `default' means use the foreground of the default face.
2066 :background the background color, or \"Transparent\".
2067 `default' means use the background of the default face.
2068 :scale a scaling factor for the size of the images.
2069 :html-foreground, :html-background, :html-scale
2070 the same numbers for HTML export.
2071 :matchers a list indicating which matchers should be used to
2072 find LaTeX fragments. Valid members of this list are:
2073 \"begin\" find environments
2074 \"$\" find math expressions surrounded by $...$
2075 \"$$\" find math expressions surrounded by $$....$$
2076 \"\\(\" find math expressions surrounded by \\(...\\)
2077 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2078 :group 'org-latex
2079 :type 'plist)
2081 (defcustom org-format-latex-header "\\documentclass{article}
2082 \\usepackage{fullpage} % do not remove
2083 \\usepackage{amssymb}
2084 \\usepackage[usenames]{color}
2085 \\usepackage{amsmath}
2086 \\usepackage{latexsym}
2087 \\usepackage[mathscr]{eucal}
2088 \\pagestyle{empty} % do not remove"
2089 "The document header used for processing LaTeX fragments."
2090 :group 'org-latex
2091 :type 'string)
2094 (defgroup org-font-lock nil
2095 "Font-lock settings for highlighting in Org-mode."
2096 :tag "Org Font Lock"
2097 :group 'org)
2099 (defcustom org-level-color-stars-only nil
2100 "Non-nil means fontify only the stars in each headline.
2101 When nil, the entire headline is fontified.
2102 Changing it requires restart of `font-lock-mode' to become effective
2103 also in regions already fontified."
2104 :group 'org-font-lock
2105 :type 'boolean)
2107 (defcustom org-hide-leading-stars nil
2108 "Non-nil means, hide the first N-1 stars in a headline.
2109 This works by using the face `org-hide' for these stars. This
2110 face is white for a light background, and black for a dark
2111 background. You may have to customize the face `org-hide' to
2112 make this work.
2113 Changing it requires restart of `font-lock-mode' to become effective
2114 also in regions already fontified.
2115 You may also set this on a per-file basis by adding one of the following
2116 lines to the buffer:
2118 #+STARTUP: hidestars
2119 #+STARTUP: showstars"
2120 :group 'org-font-lock
2121 :type 'boolean)
2123 (defcustom org-fontify-done-headline nil
2124 "Non-nil means, change the face of a headline if it is marked DONE.
2125 Normally, only the TODO/DONE keyword indicates the state of a headline.
2126 When this is non-nil, the headline after the keyword is set to the
2127 `org-headline-done' as an additional indication."
2128 :group 'org-font-lock
2129 :type 'boolean)
2131 (defcustom org-fontify-emphasized-text t
2132 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2133 Changing this variable requires a restart of Emacs to take effect."
2134 :group 'org-font-lock
2135 :type 'boolean)
2137 (defcustom org-highlight-latex-fragments-and-specials nil
2138 "Non-nil means, fontify what is treated specially by the exporters."
2139 :group 'org-font-lock
2140 :type 'boolean)
2142 (defcustom org-hide-emphasis-markers nil
2143 "Non-nil mean font-lock should hide the emphasis marker characters."
2144 :group 'org-font-lock
2145 :type 'boolean)
2147 (defvar org-emph-re nil
2148 "Regular expression for matching emphasis.")
2149 (defvar org-verbatim-re nil
2150 "Regular expression for matching verbatim text.")
2151 (defvar org-emphasis-regexp-components) ; defined just below
2152 (defvar org-emphasis-alist) ; defined just below
2153 (defun org-set-emph-re (var val)
2154 "Set variable and compute the emphasis regular expression."
2155 (set var val)
2156 (when (and (boundp 'org-emphasis-alist)
2157 (boundp 'org-emphasis-regexp-components)
2158 org-emphasis-alist org-emphasis-regexp-components)
2159 (let* ((e org-emphasis-regexp-components)
2160 (pre (car e))
2161 (post (nth 1 e))
2162 (border (nth 2 e))
2163 (body (nth 3 e))
2164 (nl (nth 4 e))
2165 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2166 (body1 (concat body "*?"))
2167 (markers (mapconcat 'car org-emphasis-alist ""))
2168 (vmarkers (mapconcat
2169 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2170 org-emphasis-alist "")))
2171 ;; make sure special characters appear at the right position in the class
2172 (if (string-match "\\^" markers)
2173 (setq markers (concat (replace-match "" t t markers) "^")))
2174 (if (string-match "-" markers)
2175 (setq markers (concat (replace-match "" t t markers) "-")))
2176 (if (string-match "\\^" vmarkers)
2177 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2178 (if (string-match "-" vmarkers)
2179 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2180 (if (> nl 0)
2181 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2182 (int-to-string nl) "\\}")))
2183 ;; Make the regexp
2184 (setq org-emph-re
2185 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2186 "\\("
2187 "\\([" markers "]\\)"
2188 "\\("
2189 "[^" border "]\\|"
2190 "[^" border (if (and nil stacked) markers) "]"
2191 body1
2192 "[^" border (if (and nil stacked) markers) "]"
2193 "\\)"
2194 "\\3\\)"
2195 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2196 (setq org-verbatim-re
2197 (concat "\\([" pre "]\\|^\\)"
2198 "\\("
2199 "\\([" vmarkers "]\\)"
2200 "\\("
2201 "[^" border "]\\|"
2202 "[^" border "]"
2203 body1
2204 "[^" border "]"
2205 "\\)"
2206 "\\3\\)"
2207 "\\([" post "]\\|$\\)")))))
2209 (defcustom org-emphasis-regexp-components
2210 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2211 "Components used to build the regular expression for emphasis.
2212 This is a list with 6 entries. Terminology: In an emphasis string
2213 like \" *strong word* \", we call the initial space PREMATCH, the final
2214 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2215 and \"trong wor\" is the body. The different components in this variable
2216 specify what is allowed/forbidden in each part:
2218 pre Chars allowed as prematch. Beginning of line will be allowed too.
2219 post Chars allowed as postmatch. End of line will be allowed too.
2220 border The chars *forbidden* as border characters.
2221 body-regexp A regexp like \".\" to match a body character. Don't use
2222 non-shy groups here, and don't allow newline here.
2223 newline The maximum number of newlines allowed in an emphasis exp.
2225 Use customize to modify this, or restart Emacs after changing it."
2226 :group 'org-font-lock
2227 :set 'org-set-emph-re
2228 :type '(list
2229 (sexp :tag "Allowed chars in pre ")
2230 (sexp :tag "Allowed chars in post ")
2231 (sexp :tag "Forbidden chars in border ")
2232 (sexp :tag "Regexp for body ")
2233 (integer :tag "number of newlines allowed")
2234 (option (boolean :tag "Please ignore this button"))))
2236 (defcustom org-emphasis-alist
2237 `(("*" bold "<b>" "</b>")
2238 ("/" italic "<i>" "</i>")
2239 ("_" underline "<u>" "</u>")
2240 ("=" org-code "<code>" "</code>" verbatim)
2241 ("~" org-verbatim "" "" verbatim)
2242 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2243 "<del>" "</del>")
2245 "Special syntax for emphasized text.
2246 Text starting and ending with a special character will be emphasized, for
2247 example *bold*, _underlined_ and /italic/. This variable sets the marker
2248 characters, the face to be used by font-lock for highlighting in Org-mode
2249 Emacs buffers, and the HTML tags to be used for this.
2250 Use customize to modify this, or restart Emacs after changing it."
2251 :group 'org-font-lock
2252 :set 'org-set-emph-re
2253 :type '(repeat
2254 (list
2255 (string :tag "Marker character")
2256 (choice
2257 (face :tag "Font-lock-face")
2258 (plist :tag "Face property list"))
2259 (string :tag "HTML start tag")
2260 (string :tag "HTML end tag")
2261 (option (const verbatim)))))
2263 ;;; Miscellaneous options
2265 (defgroup org-completion nil
2266 "Completion in Org-mode."
2267 :tag "Org Completion"
2268 :group 'org)
2270 (defcustom org-completion-fallback-command 'hippie-expand
2271 "The expansion command called by \\[org-complete] in normal context.
2272 Normal means, no org-mode-specific context."
2273 :group 'org-completion
2274 :type 'function)
2276 ;;; Functions and variables from ther packages
2277 ;; Declared here to avoid compiler warnings
2279 ;; XEmacs only
2280 (defvar outline-mode-menu-heading)
2281 (defvar outline-mode-menu-show)
2282 (defvar outline-mode-menu-hide)
2283 (defvar zmacs-regions) ; XEmacs regions
2285 ;; Emacs only
2286 (defvar mark-active)
2288 ;; Various packages
2289 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2290 (declare-function calendar-forward-day "cal-move" (arg))
2291 (declare-function calendar-goto-date "cal-move" (date))
2292 (declare-function calendar-goto-today "cal-move" ())
2293 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2294 (defvar calc-embedded-close-formula)
2295 (defvar calc-embedded-open-formula)
2296 (declare-function cdlatex-tab "ext:cdlatex" ())
2297 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2298 (defvar font-lock-unfontify-region-function)
2299 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2300 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2301 (defvar iswitchb-temp-buflist)
2302 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2303 (declare-function org-agenda-skip "org-agenda" ())
2304 (declare-function org-format-agenda-item "org-agenda"
2305 (extra txt &optional category tags dotime noprefix remove-re))
2306 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2307 (declare-function org-agenda-change-all-lines "org-agenda"
2308 (newhead hdmarker &optional fixface))
2309 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2310 (declare-function org-agenda-maybe-redo "org-agenda" ())
2311 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2312 (beg end))
2313 (declare-function parse-time-string "parse-time" (string))
2314 (declare-function remember "remember" (&optional initial))
2315 (declare-function remember-buffer-desc "remember" ())
2316 (declare-function remember-finalize "remember" ())
2317 (defvar remember-save-after-remembering)
2318 (defvar remember-data-file)
2319 (defvar remember-register)
2320 (defvar remember-buffer)
2321 (defvar remember-handler-functions)
2322 (defvar remember-annotation-functions)
2323 (defvar texmathp-why)
2324 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2325 (declare-function table--at-cell-p "table" (position &optional object at-column))
2327 (defvar w3m-current-url)
2328 (defvar w3m-current-title)
2330 (defvar org-latex-regexps)
2332 ;;; Autoload and prepare some org modules
2334 ;; Some table stuff that needs to be defined here, because it is used
2335 ;; by the functions setting up org-mode or checking for table context.
2337 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2338 "Detects an org-type or table-type table.")
2339 (defconst org-table-line-regexp "^[ \t]*|"
2340 "Detects an org-type table line.")
2341 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2342 "Detects an org-type table line.")
2343 (defconst org-table-hline-regexp "^[ \t]*|-"
2344 "Detects an org-type table hline.")
2345 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2346 "Detects a table-type table hline.")
2347 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2348 "Searching from within a table (any type) this finds the first line
2349 outside the table.")
2351 ;; Autoload the functions in org-table.el that are needed by functions here.
2353 (eval-and-compile
2354 (org-autoload "org-table"
2355 '(org-table-align org-table-begin org-table-blank-field
2356 org-table-convert org-table-convert-region org-table-copy-down
2357 org-table-copy-region org-table-create
2358 org-table-create-or-convert-from-region
2359 org-table-create-with-table.el org-table-current-dline
2360 org-table-cut-region org-table-delete-column org-table-edit-field
2361 org-table-edit-formulas org-table-end org-table-eval-formula
2362 org-table-export org-table-field-info
2363 org-table-get-stored-formulas org-table-goto-column
2364 org-table-hline-and-move org-table-import org-table-insert-column
2365 org-table-insert-hline org-table-insert-row org-table-iterate
2366 org-table-justify-field-maybe org-table-kill-row
2367 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2368 org-table-move-column org-table-move-column-left
2369 org-table-move-column-right org-table-move-row
2370 org-table-move-row-down org-table-move-row-up
2371 org-table-next-field org-table-next-row org-table-paste-rectangle
2372 org-table-previous-field org-table-recalculate
2373 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2374 org-table-toggle-coordinate-overlays
2375 org-table-toggle-formula-debugger org-table-wrap-region
2376 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2378 (defun org-at-table-p (&optional table-type)
2379 "Return t if the cursor is inside an org-type table.
2380 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2381 (if org-enable-table-editor
2382 (save-excursion
2383 (beginning-of-line 1)
2384 (looking-at (if table-type org-table-any-line-regexp
2385 org-table-line-regexp)))
2386 nil))
2387 (defsubst org-table-p () (org-at-table-p))
2389 (defun org-at-table.el-p ()
2390 "Return t if and only if we are at a table.el table."
2391 (and (org-at-table-p 'any)
2392 (save-excursion
2393 (goto-char (org-table-begin 'any))
2394 (looking-at org-table1-hline-regexp))))
2395 (defun org-table-recognize-table.el ()
2396 "If there is a table.el table nearby, recognize it and move into it."
2397 (if org-table-tab-recognizes-table.el
2398 (if (org-at-table.el-p)
2399 (progn
2400 (beginning-of-line 1)
2401 (if (looking-at org-table-dataline-regexp)
2403 (if (looking-at org-table1-hline-regexp)
2404 (progn
2405 (beginning-of-line 2)
2406 (if (looking-at org-table-any-border-regexp)
2407 (beginning-of-line -1)))))
2408 (if (re-search-forward "|" (org-table-end t) t)
2409 (progn
2410 (require 'table)
2411 (if (table--at-cell-p (point))
2413 (message "recognizing table.el table...")
2414 (table-recognize-table)
2415 (message "recognizing table.el table...done")))
2416 (error "This should not happen..."))
2418 nil)
2419 nil))
2421 (defun org-at-table-hline-p ()
2422 "Return t if the cursor is inside a hline in a table."
2423 (if org-enable-table-editor
2424 (save-excursion
2425 (beginning-of-line 1)
2426 (looking-at org-table-hline-regexp))
2427 nil))
2429 (defvar org-table-clean-did-remove-column nil)
2431 (defun org-table-map-tables (function)
2432 "Apply FUNCTION to the start of all tables in the buffer."
2433 (save-excursion
2434 (save-restriction
2435 (widen)
2436 (goto-char (point-min))
2437 (while (re-search-forward org-table-any-line-regexp nil t)
2438 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2439 (beginning-of-line 1)
2440 (if (looking-at org-table-line-regexp)
2441 (save-excursion (funcall function)))
2442 (re-search-forward org-table-any-border-regexp nil 1))))
2443 (message "Mapping tables: done"))
2445 ;; Declare and autoload functions from org-exp.el
2447 (declare-function org-default-export-plist "org-exp")
2448 (declare-function org-infile-export-plist "org-exp")
2449 (declare-function org-get-current-options "org-exp")
2450 (eval-and-compile
2451 (org-autoload "org-exp"
2452 '(org-export org-export-as-ascii org-export-visible
2453 org-insert-export-options-template org-export-as-html-and-open
2454 org-export-as-html-batch org-export-as-html-to-buffer
2455 org-replace-region-by-html org-export-region-as-html
2456 org-export-as-html org-export-icalendar-this-file
2457 org-export-icalendar-all-agenda-files
2458 org-table-clean-before-export
2459 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2461 ;; Declare and autoload functions from org-exp.el
2463 (eval-and-compile
2464 (org-autoload "org-exp"
2465 '(org-agenda org-agenda-list org-search-view
2466 org-todo-list org-tags-view org-agenda-list-stuck-projects
2467 org-diary org-agenda-to-appt)))
2469 ;; Autoload org-remember
2471 (eval-and-compile
2472 (org-autoload "org-remember"
2473 '(org-remember-insinuate org-remember-annotation
2474 org-remember-apply-template org-remember org-remember-handler)))
2476 ;; Autoload org-clock.el
2479 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2480 (beg end))
2481 (declare-function org-update-mode-line "org-clock" ())
2482 (defvar org-clock-start-time)
2483 (defvar org-clock-marker (make-marker)
2484 "Marker recording the last clock-in.")
2486 (eval-and-compile
2487 (org-autoload
2488 "org-clock"
2489 '(org-clock-in org-clock-out org-clock-cancel
2490 org-clock-goto org-clock-sum org-clock-display
2491 org-remove-clock-overlays org-clock-report
2492 org-clocktable-shift org-dblock-write:clocktable
2493 org-get-clocktable)))
2495 (defun org-clock-update-time-maybe ()
2496 "If this is a CLOCK line, update it and return t.
2497 Otherwise, return nil."
2498 (interactive)
2499 (save-excursion
2500 (beginning-of-line 1)
2501 (skip-chars-forward " \t")
2502 (when (looking-at org-clock-string)
2503 (let ((re (concat "[ \t]*" org-clock-string
2504 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2505 "\\([ \t]*=>.*\\)?\\)?"))
2506 ts te h m s)
2507 (cond
2508 ((not (looking-at re))
2509 nil)
2510 ((not (match-end 2))
2511 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2512 (> org-clock-marker (point))
2513 (<= org-clock-marker (point-at-eol)))
2514 ;; The clock is running here
2515 (setq org-clock-start-time
2516 (apply 'encode-time
2517 (org-parse-time-string (match-string 1))))
2518 (org-update-mode-line)))
2520 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2521 (end-of-line 1)
2522 (setq ts (match-string 1)
2523 te (match-string 3))
2524 (setq s (- (time-to-seconds
2525 (apply 'encode-time (org-parse-time-string te)))
2526 (time-to-seconds
2527 (apply 'encode-time (org-parse-time-string ts))))
2528 h (floor (/ s 3600))
2529 s (- s (* 3600 h))
2530 m (floor (/ s 60))
2531 s (- s (* 60 s)))
2532 (insert " => " (format "%2d:%02d" h m))
2533 t))))))
2535 (defun org-check-running-clock ()
2536 "Check if the current buffer contains the running clock.
2537 If yes, offer to stop it and to save the buffer with the changes."
2538 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2539 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2540 (buffer-name))))
2541 (org-clock-out)
2542 (when (y-or-n-p "Save changed buffer?")
2543 (save-buffer))))
2545 (defun org-clocktable-try-shift (dir n)
2546 "Check if this line starts a clock table, if yes, shift the time block."
2547 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2548 (org-clocktable-shift dir n)))
2550 ;; Autoload archiving code
2551 ;; The stuff that is needed for cycling and tags has to be defined here.
2553 (defgroup org-archive nil
2554 "Options concerning archiving in Org-mode."
2555 :tag "Org Archive"
2556 :group 'org-structure)
2558 (defcustom org-archive-location "%s_archive::"
2559 "The location where subtrees should be archived.
2561 Otherwise, the value of this variable is a string, consisting of two
2562 parts, separated by a double-colon.
2564 The first part is a file name - when omitted, archiving happens in the same
2565 file. %s will be replaced by the current file name (without directory part).
2566 Archiving to a different file is useful to keep archived entries from
2567 contributing to the Org-mode Agenda.
2569 The part after the double colon is a headline. The archived entries will be
2570 filed under that headline. When omitted, the subtrees are simply filed away
2571 at the end of the file, as top-level entries.
2573 Here are a few examples:
2574 \"%s_archive::\"
2575 If the current file is Projects.org, archive in file
2576 Projects.org_archive, as top-level trees. This is the default.
2578 \"::* Archived Tasks\"
2579 Archive in the current file, under the top-level headline
2580 \"* Archived Tasks\".
2582 \"~/org/archive.org::\"
2583 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2585 \"basement::** Finished Tasks\"
2586 Archive in file ./basement (relative path), as level 3 trees
2587 below the level 2 heading \"** Finished Tasks\".
2589 You may set this option on a per-file basis by adding to the buffer a
2590 line like
2592 #+ARCHIVE: basement::** Finished Tasks
2594 You may also define it locally for a subtree by setting an ARCHIVE property
2595 in the entry. If such a property is found in an entry, or anywhere up
2596 the hierarchy, it will be used."
2597 :group 'org-archive
2598 :type 'string)
2600 (defcustom org-archive-tag "ARCHIVE"
2601 "The tag that marks a subtree as archived.
2602 An archived subtree does not open during visibility cycling, and does
2603 not contribute to the agenda listings.
2604 After changing this, font-lock must be restarted in the relevant buffers to
2605 get the proper fontification."
2606 :group 'org-archive
2607 :group 'org-keywords
2608 :type 'string)
2610 (defcustom org-agenda-skip-archived-trees t
2611 "Non-nil means, the agenda will skip any items located in archived trees.
2612 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2613 variable is no longer recommended, you should leave it at the value t.
2614 Instead, use the key `v' to cycle the archives-mode in the agenda."
2615 :group 'org-archive
2616 :group 'org-agenda-skip
2617 :type 'boolean)
2619 (defcustom org-cycle-open-archived-trees nil
2620 "Non-nil means, `org-cycle' will open archived trees.
2621 An archived tree is a tree marked with the tag ARCHIVE.
2622 When nil, archived trees will stay folded. You can still open them with
2623 normal outline commands like `show-all', but not with the cycling commands."
2624 :group 'org-archive
2625 :group 'org-cycle
2626 :type 'boolean)
2628 (defcustom org-sparse-tree-open-archived-trees nil
2629 "Non-nil means sparse tree construction shows matches in archived trees.
2630 When nil, matches in these trees are highlighted, but the trees are kept in
2631 collapsed state."
2632 :group 'org-archive
2633 :group 'org-sparse-trees
2634 :type 'boolean)
2636 (defun org-cycle-hide-archived-subtrees (state)
2637 "Re-hide all archived subtrees after a visibility state change."
2638 (when (and (not org-cycle-open-archived-trees)
2639 (not (memq state '(overview folded))))
2640 (save-excursion
2641 (let* ((globalp (memq state '(contents all)))
2642 (beg (if globalp (point-min) (point)))
2643 (end (if globalp (point-max) (org-end-of-subtree t))))
2644 (org-hide-archived-subtrees beg end)
2645 (goto-char beg)
2646 (if (looking-at (concat ".*:" org-archive-tag ":"))
2647 (message "%s" (substitute-command-keys
2648 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2650 (defun org-force-cycle-archived ()
2651 "Cycle subtree even if it is archived."
2652 (interactive)
2653 (setq this-command 'org-cycle)
2654 (let ((org-cycle-open-archived-trees t))
2655 (call-interactively 'org-cycle)))
2657 (defun org-hide-archived-subtrees (beg end)
2658 "Re-hide all archived subtrees after a visibility state change."
2659 (save-excursion
2660 (let* ((re (concat ":" org-archive-tag ":")))
2661 (goto-char beg)
2662 (while (re-search-forward re end t)
2663 (and (org-on-heading-p) (hide-subtree))
2664 (org-end-of-subtree t)))))
2666 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2668 (eval-and-compile
2669 (org-autoload "org-archive"
2670 '(org-add-archive-files org-archive-subtree
2671 org-archive-to-archive-sibling org-toggle-archive-tag)))
2673 ;; Autoload Column View Code
2675 (declare-function org-columns-number-to-string "org-colview")
2676 (declare-function org-columns-get-format-and-top-level "org-colview")
2677 (declare-function org-columns-compute "org-colview")
2679 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2680 '(org-columns-number-to-string org-columns-get-format-and-top-level
2681 org-columns-compute org-agenda-columns org-columns-remove-overlays
2682 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2684 ;; Autoload ID code
2686 (org-autoload "org-id"
2687 '(org-id-get-create org-id-new org-id-copy org-id-get
2688 org-id-get-with-outline-path-completion
2689 org-id-get-with-outline-drilling
2690 org-id-goto org-id-find))
2692 ;;; Variables for pre-computed regular expressions, all buffer local
2694 (defvar org-drawer-regexp nil
2695 "Matches first line of a hidden block.")
2696 (make-variable-buffer-local 'org-drawer-regexp)
2697 (defvar org-todo-regexp nil
2698 "Matches any of the TODO state keywords.")
2699 (make-variable-buffer-local 'org-todo-regexp)
2700 (defvar org-not-done-regexp nil
2701 "Matches any of the TODO state keywords except the last one.")
2702 (make-variable-buffer-local 'org-not-done-regexp)
2703 (defvar org-todo-line-regexp nil
2704 "Matches a headline and puts TODO state into group 2 if present.")
2705 (make-variable-buffer-local 'org-todo-line-regexp)
2706 (defvar org-complex-heading-regexp nil
2707 "Matches a headline and puts everything into groups:
2708 group 1: the stars
2709 group 2: The todo keyword, maybe
2710 group 3: Priority cookie
2711 group 4: True headline
2712 group 5: Tags")
2713 (make-variable-buffer-local 'org-complex-heading-regexp)
2714 (defvar org-todo-line-tags-regexp nil
2715 "Matches a headline and puts TODO state into group 2 if present.
2716 Also put tags into group 4 if tags are present.")
2717 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2718 (defvar org-nl-done-regexp nil
2719 "Matches newline followed by a headline with the DONE keyword.")
2720 (make-variable-buffer-local 'org-nl-done-regexp)
2721 (defvar org-looking-at-done-regexp nil
2722 "Matches the DONE keyword a point.")
2723 (make-variable-buffer-local 'org-looking-at-done-regexp)
2724 (defvar org-ds-keyword-length 12
2725 "Maximum length of the Deadline and SCHEDULED keywords.")
2726 (make-variable-buffer-local 'org-ds-keyword-length)
2727 (defvar org-deadline-regexp nil
2728 "Matches the DEADLINE keyword.")
2729 (make-variable-buffer-local 'org-deadline-regexp)
2730 (defvar org-deadline-time-regexp nil
2731 "Matches the DEADLINE keyword together with a time stamp.")
2732 (make-variable-buffer-local 'org-deadline-time-regexp)
2733 (defvar org-deadline-line-regexp nil
2734 "Matches the DEADLINE keyword and the rest of the line.")
2735 (make-variable-buffer-local 'org-deadline-line-regexp)
2736 (defvar org-scheduled-regexp nil
2737 "Matches the SCHEDULED keyword.")
2738 (make-variable-buffer-local 'org-scheduled-regexp)
2739 (defvar org-scheduled-time-regexp nil
2740 "Matches the SCHEDULED keyword together with a time stamp.")
2741 (make-variable-buffer-local 'org-scheduled-time-regexp)
2742 (defvar org-closed-time-regexp nil
2743 "Matches the CLOSED keyword together with a time stamp.")
2744 (make-variable-buffer-local 'org-closed-time-regexp)
2746 (defvar org-keyword-time-regexp nil
2747 "Matches any of the 4 keywords, together with the time stamp.")
2748 (make-variable-buffer-local 'org-keyword-time-regexp)
2749 (defvar org-keyword-time-not-clock-regexp nil
2750 "Matches any of the 3 keywords, together with the time stamp.")
2751 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2752 (defvar org-maybe-keyword-time-regexp nil
2753 "Matches a timestamp, possibly preceeded by a keyword.")
2754 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2755 (defvar org-planning-or-clock-line-re nil
2756 "Matches a line with planning or clock info.")
2757 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2759 (defconst org-plain-time-of-day-regexp
2760 (concat
2761 "\\(\\<[012]?[0-9]"
2762 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2763 "\\(--?"
2764 "\\(\\<[012]?[0-9]"
2765 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2766 "\\)?")
2767 "Regular expression to match a plain time or time range.
2768 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2769 groups carry important information:
2770 0 the full match
2771 1 the first time, range or not
2772 8 the second time, if it is a range.")
2774 (defconst org-plain-time-extension-regexp
2775 (concat
2776 "\\(\\<[012]?[0-9]"
2777 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2778 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2779 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2780 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2781 groups carry important information:
2782 0 the full match
2783 7 hours of duration
2784 9 minutes of duration")
2786 (defconst org-stamp-time-of-day-regexp
2787 (concat
2788 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2789 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2790 "\\(--?"
2791 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2792 "Regular expression to match a timestamp time or time range.
2793 After a match, the following groups carry important information:
2794 0 the full match
2795 1 date plus weekday, for backreferencing to make sure both times on same day
2796 2 the first time, range or not
2797 4 the second time, if it is a range.")
2799 (defconst org-startup-options
2800 '(("fold" org-startup-folded t)
2801 ("overview" org-startup-folded t)
2802 ("nofold" org-startup-folded nil)
2803 ("showall" org-startup-folded nil)
2804 ("content" org-startup-folded content)
2805 ("hidestars" org-hide-leading-stars t)
2806 ("showstars" org-hide-leading-stars nil)
2807 ("odd" org-odd-levels-only t)
2808 ("oddeven" org-odd-levels-only nil)
2809 ("align" org-startup-align-all-tables t)
2810 ("noalign" org-startup-align-all-tables nil)
2811 ("customtime" org-display-custom-times t)
2812 ("logdone" org-log-done time)
2813 ("lognotedone" org-log-done note)
2814 ("nologdone" org-log-done nil)
2815 ("lognoteclock-out" org-log-note-clock-out t)
2816 ("nolognoteclock-out" org-log-note-clock-out nil)
2817 ("logrepeat" org-log-repeat state)
2818 ("lognoterepeat" org-log-repeat note)
2819 ("nologrepeat" org-log-repeat nil)
2820 ("constcgs" constants-unit-system cgs)
2821 ("constSI" constants-unit-system SI))
2822 "Variable associated with STARTUP options for org-mode.
2823 Each element is a list of three items: The startup options as written
2824 in the #+STARTUP line, the corresponding variable, and the value to
2825 set this variable to if the option is found. An optional forth element PUSH
2826 means to push this value onto the list in the variable.")
2828 (defun org-set-regexps-and-options ()
2829 "Precompute regular expressions for current buffer."
2830 (when (org-mode-p)
2831 (org-set-local 'org-todo-kwd-alist nil)
2832 (org-set-local 'org-todo-key-alist nil)
2833 (org-set-local 'org-todo-key-trigger nil)
2834 (org-set-local 'org-todo-keywords-1 nil)
2835 (org-set-local 'org-done-keywords nil)
2836 (org-set-local 'org-todo-heads nil)
2837 (org-set-local 'org-todo-sets nil)
2838 (org-set-local 'org-todo-log-states nil)
2839 (org-set-local 'org-file-properties nil)
2840 (org-set-local 'org-file-tags nil)
2841 (let ((re (org-make-options-regexp
2842 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2843 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2844 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2845 (splitre "[ \t]+")
2846 kwds kws0 kwsa key log value cat arch tags const links hw dws
2847 tail sep kws1 prio props ftags drawers
2848 ext-setup-or-nil setup-contents (start 0))
2849 (save-excursion
2850 (save-restriction
2851 (widen)
2852 (goto-char (point-min))
2853 (while (or (and ext-setup-or-nil
2854 (string-match re ext-setup-or-nil start)
2855 (setq start (match-end 0)))
2856 (and (setq ext-setup-or-nil nil start 0)
2857 (re-search-forward re nil t)))
2858 (setq key (upcase (match-string 1 ext-setup-or-nil))
2859 value (org-match-string-no-properties 2 ext-setup-or-nil))
2860 (cond
2861 ((equal key "CATEGORY")
2862 (if (string-match "[ \t]+$" value)
2863 (setq value (replace-match "" t t value)))
2864 (setq cat value))
2865 ((member key '("SEQ_TODO" "TODO"))
2866 (push (cons 'sequence (org-split-string value splitre)) kwds))
2867 ((equal key "TYP_TODO")
2868 (push (cons 'type (org-split-string value splitre)) kwds))
2869 ((equal key "TAGS")
2870 (setq tags (append tags (org-split-string value splitre))))
2871 ((equal key "COLUMNS")
2872 (org-set-local 'org-columns-default-format value))
2873 ((equal key "LINK")
2874 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2875 (push (cons (match-string 1 value)
2876 (org-trim (match-string 2 value)))
2877 links)))
2878 ((equal key "PRIORITIES")
2879 (setq prio (org-split-string value " +")))
2880 ((equal key "PROPERTY")
2881 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2882 (push (cons (match-string 1 value) (match-string 2 value))
2883 props)))
2884 ((equal key "FILETAGS")
2885 (when (string-match "\\S-" value)
2886 (setq ftags
2887 (append
2888 ftags
2889 (apply 'append
2890 (mapcar (lambda (x) (org-split-string x ":"))
2891 (org-split-string value)))))))
2892 ((equal key "DRAWERS")
2893 (setq drawers (org-split-string value splitre)))
2894 ((equal key "CONSTANTS")
2895 (setq const (append const (org-split-string value splitre))))
2896 ((equal key "STARTUP")
2897 (let ((opts (org-split-string value splitre))
2898 l var val)
2899 (while (setq l (pop opts))
2900 (when (setq l (assoc l org-startup-options))
2901 (setq var (nth 1 l) val (nth 2 l))
2902 (if (not (nth 3 l))
2903 (set (make-local-variable var) val)
2904 (if (not (listp (symbol-value var)))
2905 (set (make-local-variable var) nil))
2906 (set (make-local-variable var) (symbol-value var))
2907 (add-to-list var val))))))
2908 ((equal key "ARCHIVE")
2909 (string-match " *$" value)
2910 (setq arch (replace-match "" t t value))
2911 (remove-text-properties 0 (length arch)
2912 '(face t fontified t) arch))
2913 ((equal key "SETUPFILE")
2914 (setq setup-contents (org-file-contents
2915 (expand-file-name
2916 (org-remove-double-quotes value))
2917 'noerror))
2918 (if (not ext-setup-or-nil)
2919 (setq ext-setup-or-nil setup-contents start 0)
2920 (setq ext-setup-or-nil
2921 (concat (substring ext-setup-or-nil 0 start)
2922 "\n" setup-contents "\n"
2923 (substring ext-setup-or-nil start)))))
2924 ))))
2925 (when cat
2926 (org-set-local 'org-category (intern cat))
2927 (push (cons "CATEGORY" cat) props))
2928 (when prio
2929 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2930 (setq prio (mapcar 'string-to-char prio))
2931 (org-set-local 'org-highest-priority (nth 0 prio))
2932 (org-set-local 'org-lowest-priority (nth 1 prio))
2933 (org-set-local 'org-default-priority (nth 2 prio)))
2934 (and props (org-set-local 'org-file-properties (nreverse props)))
2935 (and ftags (org-set-local 'org-file-tags ftags))
2936 (and drawers (org-set-local 'org-drawers drawers))
2937 (and arch (org-set-local 'org-archive-location arch))
2938 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2939 ;; Process the TODO keywords
2940 (unless kwds
2941 ;; Use the global values as if they had been given locally.
2942 (setq kwds (default-value 'org-todo-keywords))
2943 (if (stringp (car kwds))
2944 (setq kwds (list (cons org-todo-interpretation
2945 (default-value 'org-todo-keywords)))))
2946 (setq kwds (reverse kwds)))
2947 (setq kwds (nreverse kwds))
2948 (let (inter kws kw)
2949 (while (setq kws (pop kwds))
2950 (setq inter (pop kws) sep (member "|" kws)
2951 kws0 (delete "|" (copy-sequence kws))
2952 kwsa nil
2953 kws1 (mapcar
2954 (lambda (x)
2955 ;; 1 2
2956 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2957 (progn
2958 (setq kw (match-string 1 x)
2959 key (and (match-end 2) (match-string 2 x))
2960 log (org-extract-log-state-settings x))
2961 (push (cons kw (and key (string-to-char key))) kwsa)
2962 (and log (push log org-todo-log-states))
2964 (error "Invalid TODO keyword %s" x)))
2965 kws0)
2966 kwsa (if kwsa (append '((:startgroup))
2967 (nreverse kwsa)
2968 '((:endgroup))))
2969 hw (car kws1)
2970 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2971 tail (list inter hw (car dws) (org-last dws)))
2972 (add-to-list 'org-todo-heads hw 'append)
2973 (push kws1 org-todo-sets)
2974 (setq org-done-keywords (append org-done-keywords dws nil))
2975 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2976 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2977 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2978 (setq org-todo-sets (nreverse org-todo-sets)
2979 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2980 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2981 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2982 ;; Process the constants
2983 (when const
2984 (let (e cst)
2985 (while (setq e (pop const))
2986 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2987 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2988 (setq org-table-formula-constants-local cst)))
2990 ;; Process the tags.
2991 (when tags
2992 (let (e tgs)
2993 (while (setq e (pop tags))
2994 (cond
2995 ((equal e "{") (push '(:startgroup) tgs))
2996 ((equal e "}") (push '(:endgroup) tgs))
2997 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2998 (push (cons (match-string 1 e)
2999 (string-to-char (match-string 2 e)))
3000 tgs))
3001 (t (push (list e) tgs))))
3002 (org-set-local 'org-tag-alist nil)
3003 (while (setq e (pop tgs))
3004 (or (and (stringp (car e))
3005 (assoc (car e) org-tag-alist))
3006 (push e org-tag-alist)))))
3008 ;; Compute the regular expressions and other local variables
3009 (if (not org-done-keywords)
3010 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3011 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3012 (length org-scheduled-string)
3013 (length org-clock-string)
3014 (length org-closed-string)))
3015 org-drawer-regexp
3016 (concat "^[ \t]*:\\("
3017 (mapconcat 'regexp-quote org-drawers "\\|")
3018 "\\):[ \t]*$")
3019 org-not-done-keywords
3020 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3021 org-todo-regexp
3022 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3023 "\\|") "\\)\\>")
3024 org-not-done-regexp
3025 (concat "\\<\\("
3026 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3027 "\\)\\>")
3028 org-todo-line-regexp
3029 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3030 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3031 "\\)\\>\\)?[ \t]*\\(.*\\)")
3032 org-complex-heading-regexp
3033 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3034 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3035 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3036 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3037 org-nl-done-regexp
3038 (concat "\n\\*+[ \t]+"
3039 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3040 "\\)" "\\>")
3041 org-todo-line-tags-regexp
3042 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3043 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3044 (org-re
3045 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3046 org-looking-at-done-regexp
3047 (concat "^" "\\(?:"
3048 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3049 "\\>")
3050 org-deadline-regexp (concat "\\<" org-deadline-string)
3051 org-deadline-time-regexp
3052 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3053 org-deadline-line-regexp
3054 (concat "\\<\\(" org-deadline-string "\\).*")
3055 org-scheduled-regexp
3056 (concat "\\<" org-scheduled-string)
3057 org-scheduled-time-regexp
3058 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3059 org-closed-time-regexp
3060 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3061 org-keyword-time-regexp
3062 (concat "\\<\\(" org-scheduled-string
3063 "\\|" org-deadline-string
3064 "\\|" org-closed-string
3065 "\\|" org-clock-string "\\)"
3066 " *[[<]\\([^]>]+\\)[]>]")
3067 org-keyword-time-not-clock-regexp
3068 (concat "\\<\\(" org-scheduled-string
3069 "\\|" org-deadline-string
3070 "\\|" org-closed-string
3071 "\\)"
3072 " *[[<]\\([^]>]+\\)[]>]")
3073 org-maybe-keyword-time-regexp
3074 (concat "\\(\\<\\(" org-scheduled-string
3075 "\\|" org-deadline-string
3076 "\\|" org-closed-string
3077 "\\|" org-clock-string "\\)\\)?"
3078 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3079 org-planning-or-clock-line-re
3080 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3081 "\\|" org-deadline-string
3082 "\\|" org-closed-string "\\|" org-clock-string
3083 "\\)\\>\\)")
3085 (org-compute-latex-and-specials-regexp)
3086 (org-set-font-lock-defaults))))
3088 (defun org-file-contents (file &optional noerror)
3089 "Return the contents of FILE, as a string."
3090 (if (or (not file)
3091 (not (file-readable-p file)))
3092 (if noerror
3093 (progn
3094 (message "Cannot read file %s" file)
3095 (ding) (sit-for 2)
3097 (error "Cannot read file %s" file))
3098 (with-temp-buffer
3099 (insert-file-contents file)
3100 (buffer-string))))
3102 (defun org-extract-log-state-settings (x)
3103 "Extract the log state setting from a TODO keyword string.
3104 This will extract info from a string like \"WAIT(w@/!)\"."
3105 (let (kw key log1 log2)
3106 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3107 (setq kw (match-string 1 x)
3108 key (and (match-end 2) (match-string 2 x))
3109 log1 (and (match-end 3) (match-string 3 x))
3110 log2 (and (match-end 4) (match-string 4 x)))
3111 (and (or log1 log2)
3112 (list kw
3113 (and log1 (if (equal log1 "!") 'time 'note))
3114 (and log2 (if (equal log2 "!") 'time 'note)))))))
3116 (defun org-remove-keyword-keys (list)
3117 "Remove a pair of parenthesis at the end of each string in LIST."
3118 (mapcar (lambda (x)
3119 (if (string-match "(.*)$" x)
3120 (substring x 0 (match-beginning 0))
3122 list))
3124 ;; FIXME: this could be done much better, using second characters etc.
3125 (defun org-assign-fast-keys (alist)
3126 "Assign fast keys to a keyword-key alist.
3127 Respect keys that are already there."
3128 (let (new e k c c1 c2 (char ?a))
3129 (while (setq e (pop alist))
3130 (cond
3131 ((equal e '(:startgroup)) (push e new))
3132 ((equal e '(:endgroup)) (push e new))
3134 (setq k (car e) c2 nil)
3135 (if (cdr e)
3136 (setq c (cdr e))
3137 ;; automatically assign a character.
3138 (setq c1 (string-to-char
3139 (downcase (substring
3140 k (if (= (string-to-char k) ?@) 1 0)))))
3141 (if (or (rassoc c1 new) (rassoc c1 alist))
3142 (while (or (rassoc char new) (rassoc char alist))
3143 (setq char (1+ char)))
3144 (setq c2 c1))
3145 (setq c (or c2 char)))
3146 (push (cons k c) new))))
3147 (nreverse new)))
3149 ;;; Some variables used in various places
3151 (defvar org-window-configuration nil
3152 "Used in various places to store a window configuration.")
3153 (defvar org-finish-function nil
3154 "Function to be called when `C-c C-c' is used.
3155 This is for getting out of special buffers like remember.")
3158 ;; FIXME: Occasionally check by commenting these, to make sure
3159 ;; no other functions uses these, forgetting to let-bind them.
3160 (defvar entry)
3161 (defvar state)
3162 (defvar last-state)
3163 (defvar date)
3164 (defvar description)
3166 ;; Defined somewhere in this file, but used before definition.
3167 (defvar org-html-entities)
3168 (defvar org-struct-menu)
3169 (defvar org-org-menu)
3170 (defvar org-tbl-menu)
3171 (defvar org-agenda-keymap)
3173 ;;;; Define the Org-mode
3175 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3176 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3179 ;; We use a before-change function to check if a table might need
3180 ;; an update.
3181 (defvar org-table-may-need-update t
3182 "Indicates that a table might need an update.
3183 This variable is set by `org-before-change-function'.
3184 `org-table-align' sets it back to nil.")
3185 (defun org-before-change-function (beg end)
3186 "Every change indicates that a table might need an update."
3187 (setq org-table-may-need-update t))
3188 (defvar org-mode-map)
3189 (defvar org-mode-hook nil)
3190 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3191 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3192 (defvar org-table-buffer-is-an nil)
3193 (defconst org-outline-regexp "\\*+ ")
3195 ;;;###autoload
3196 (define-derived-mode org-mode outline-mode "Org"
3197 "Outline-based notes management and organizer, alias
3198 \"Carsten's outline-mode for keeping track of everything.\"
3200 Org-mode develops organizational tasks around a NOTES file which
3201 contains information about projects as plain text. Org-mode is
3202 implemented on top of outline-mode, which is ideal to keep the content
3203 of large files well structured. It supports ToDo items, deadlines and
3204 time stamps, which magically appear in the diary listing of the Emacs
3205 calendar. Tables are easily created with a built-in table editor.
3206 Plain text URL-like links connect to websites, emails (VM), Usenet
3207 messages (Gnus), BBDB entries, and any files related to the project.
3208 For printing and sharing of notes, an Org-mode file (or a part of it)
3209 can be exported as a structured ASCII or HTML file.
3211 The following commands are available:
3213 \\{org-mode-map}"
3215 ;; Get rid of Outline menus, they are not needed
3216 ;; Need to do this here because define-derived-mode sets up
3217 ;; the keymap so late. Still, it is a waste to call this each time
3218 ;; we switch another buffer into org-mode.
3219 (if (featurep 'xemacs)
3220 (when (boundp 'outline-mode-menu-heading)
3221 ;; Assume this is Greg's port, it used easymenu
3222 (easy-menu-remove outline-mode-menu-heading)
3223 (easy-menu-remove outline-mode-menu-show)
3224 (easy-menu-remove outline-mode-menu-hide))
3225 (define-key org-mode-map [menu-bar headings] 'undefined)
3226 (define-key org-mode-map [menu-bar hide] 'undefined)
3227 (define-key org-mode-map [menu-bar show] 'undefined))
3229 (org-load-modules-maybe)
3230 (easy-menu-add org-org-menu)
3231 (easy-menu-add org-tbl-menu)
3232 (org-install-agenda-files-menu)
3233 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3234 (org-add-to-invisibility-spec '(org-cwidth))
3235 (when (featurep 'xemacs)
3236 (org-set-local 'line-move-ignore-invisible t))
3237 (org-set-local 'outline-regexp org-outline-regexp)
3238 (org-set-local 'outline-level 'org-outline-level)
3239 (when (and org-ellipsis
3240 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3241 (fboundp 'make-glyph-code))
3242 (unless org-display-table
3243 (setq org-display-table (make-display-table)))
3244 (set-display-table-slot
3245 org-display-table 4
3246 (vconcat (mapcar
3247 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3248 org-ellipsis)))
3249 (if (stringp org-ellipsis) org-ellipsis "..."))))
3250 (setq buffer-display-table org-display-table))
3251 (org-set-regexps-and-options)
3252 ;; Calc embedded
3253 (org-set-local 'calc-embedded-open-mode "# ")
3254 (modify-syntax-entry ?# "<")
3255 (modify-syntax-entry ?@ "w")
3256 (if org-startup-truncated (setq truncate-lines t))
3257 (org-set-local 'font-lock-unfontify-region-function
3258 'org-unfontify-region)
3259 ;; Activate before-change-function
3260 (org-set-local 'org-table-may-need-update t)
3261 (org-add-hook 'before-change-functions 'org-before-change-function nil
3262 'local)
3263 ;; Check for running clock before killing a buffer
3264 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3265 ;; Paragraphs and auto-filling
3266 (org-set-autofill-regexps)
3267 (setq indent-line-function 'org-indent-line-function)
3268 (org-update-radio-target-regexp)
3270 ;; Comment characters
3271 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3272 (org-set-local 'comment-padding " ")
3274 ;; Align options lines
3275 (org-set-local
3276 'align-mode-rules-list
3277 '((org-in-buffer-settings
3278 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3279 (modes . '(org-mode)))))
3281 ;; Imenu
3282 (org-set-local 'imenu-create-index-function
3283 'org-imenu-get-tree)
3285 ;; Make isearch reveal context
3286 (if (or (featurep 'xemacs)
3287 (not (boundp 'outline-isearch-open-invisible-function)))
3288 ;; Emacs 21 and XEmacs make use of the hook
3289 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3290 ;; Emacs 22 deals with this through a special variable
3291 (org-set-local 'outline-isearch-open-invisible-function
3292 (lambda (&rest ignore) (org-show-context 'isearch))))
3294 ;; If empty file that did not turn on org-mode automatically, make it to.
3295 (if (and org-insert-mode-line-in-empty-file
3296 (interactive-p)
3297 (= (point-min) (point-max)))
3298 (insert "# -*- mode: org -*-\n\n"))
3300 (unless org-inhibit-startup
3301 (when org-startup-align-all-tables
3302 (let ((bmp (buffer-modified-p)))
3303 (org-table-map-tables 'org-table-align)
3304 (set-buffer-modified-p bmp)))
3305 (org-set-startup-visibility)))
3307 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3309 (defun org-current-time ()
3310 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3311 (if (> (car org-time-stamp-rounding-minutes) 1)
3312 (let ((r (car org-time-stamp-rounding-minutes))
3313 (time (decode-time)))
3314 (apply 'encode-time
3315 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3316 (nthcdr 2 time))))
3317 (current-time)))
3319 ;;;; Font-Lock stuff, including the activators
3321 (defvar org-mouse-map (make-sparse-keymap))
3322 (org-defkey org-mouse-map
3323 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3324 (org-defkey org-mouse-map
3325 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3326 (when org-mouse-1-follows-link
3327 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3328 (when org-tab-follows-link
3329 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3330 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3331 (when org-return-follows-link
3332 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3333 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3335 (require 'font-lock)
3337 (defconst org-non-link-chars "]\t\n\r<>")
3338 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3339 "shell" "elisp"))
3340 (defvar org-link-types-re nil
3341 "Matches a link that has a url-like prefix like \"http:\"")
3342 (defvar org-link-re-with-space nil
3343 "Matches a link with spaces, optional angular brackets around it.")
3344 (defvar org-link-re-with-space2 nil
3345 "Matches a link with spaces, optional angular brackets around it.")
3346 (defvar org-angle-link-re nil
3347 "Matches link with angular brackets, spaces are allowed.")
3348 (defvar org-plain-link-re nil
3349 "Matches plain link, without spaces.")
3350 (defvar org-bracket-link-regexp nil
3351 "Matches a link in double brackets.")
3352 (defvar org-bracket-link-analytic-regexp nil
3353 "Regular expression used to analyze links.
3354 Here is what the match groups contain after a match:
3355 1: http:
3356 2: http
3357 3: path
3358 4: [desc]
3359 5: desc")
3360 (defvar org-any-link-re nil
3361 "Regular expression matching any link.")
3363 (defun org-make-link-regexps ()
3364 "Update the link regular expressions.
3365 This should be called after the variable `org-link-types' has changed."
3366 (setq org-link-types-re
3367 (concat
3368 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3369 org-link-re-with-space
3370 (concat
3371 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3372 "\\([^" org-non-link-chars " ]"
3373 "[^" org-non-link-chars "]*"
3374 "[^" org-non-link-chars " ]\\)>?")
3375 org-link-re-with-space2
3376 (concat
3377 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3378 "\\([^" org-non-link-chars " ]"
3379 "[^]\t\n\r]*"
3380 "[^" org-non-link-chars " ]\\)>?")
3381 org-angle-link-re
3382 (concat
3383 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3384 "\\([^" org-non-link-chars " ]"
3385 "[^" org-non-link-chars "]*"
3386 "\\)>")
3387 org-plain-link-re
3388 (concat
3389 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3390 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3391 org-bracket-link-regexp
3392 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3393 org-bracket-link-analytic-regexp
3394 (concat
3395 "\\[\\["
3396 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3397 "\\([^]]+\\)"
3398 "\\]"
3399 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3400 "\\]")
3401 org-any-link-re
3402 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3403 org-angle-link-re "\\)\\|\\("
3404 org-plain-link-re "\\)")))
3406 (org-make-link-regexps)
3408 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3409 "Regular expression for fast time stamp matching.")
3410 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3411 "Regular expression for fast time stamp matching.")
3412 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3413 "Regular expression matching time strings for analysis.
3414 This one does not require the space after the date, so it can be used
3415 on a string that terminates immediately after the date.")
3416 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3417 "Regular expression matching time strings for analysis.")
3418 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3419 "Regular expression matching time stamps, with groups.")
3420 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3421 "Regular expression matching time stamps (also [..]), with groups.")
3422 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3423 "Regular expression matching a time stamp range.")
3424 (defconst org-tr-regexp-both
3425 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3426 "Regular expression matching a time stamp range.")
3427 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3428 org-ts-regexp "\\)?")
3429 "Regular expression matching a time stamp or time stamp range.")
3430 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3431 org-ts-regexp-both "\\)?")
3432 "Regular expression matching a time stamp or time stamp range.
3433 The time stamps may be either active or inactive.")
3435 (defvar org-emph-face nil)
3437 (defun org-do-emphasis-faces (limit)
3438 "Run through the buffer and add overlays to links."
3439 (let (rtn)
3440 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3441 (if (not (= (char-after (match-beginning 3))
3442 (char-after (match-beginning 4))))
3443 (progn
3444 (setq rtn t)
3445 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3446 'face
3447 (nth 1 (assoc (match-string 3)
3448 org-emphasis-alist)))
3449 (add-text-properties (match-beginning 2) (match-end 2)
3450 '(font-lock-multiline t))
3451 (when org-hide-emphasis-markers
3452 (add-text-properties (match-end 4) (match-beginning 5)
3453 '(invisible org-link))
3454 (add-text-properties (match-beginning 3) (match-end 3)
3455 '(invisible org-link)))))
3456 (backward-char 1))
3457 rtn))
3459 (defun org-emphasize (&optional char)
3460 "Insert or change an emphasis, i.e. a font like bold or italic.
3461 If there is an active region, change that region to a new emphasis.
3462 If there is no region, just insert the marker characters and position
3463 the cursor between them.
3464 CHAR should be either the marker character, or the first character of the
3465 HTML tag associated with that emphasis. If CHAR is a space, the means
3466 to remove the emphasis of the selected region.
3467 If char is not given (for example in an interactive call) it
3468 will be prompted for."
3469 (interactive)
3470 (let ((eal org-emphasis-alist) e det
3471 (erc org-emphasis-regexp-components)
3472 (prompt "")
3473 (string "") beg end move tag c s)
3474 (if (org-region-active-p)
3475 (setq beg (region-beginning) end (region-end)
3476 string (buffer-substring beg end))
3477 (setq move t))
3479 (while (setq e (pop eal))
3480 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3481 c (aref tag 0))
3482 (push (cons c (string-to-char (car e))) det)
3483 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3484 (substring tag 1)))))
3485 (unless char
3486 (message "%s" (concat "Emphasis marker or tag:" prompt))
3487 (setq char (read-char-exclusive)))
3488 (setq char (or (cdr (assoc char det)) char))
3489 (if (equal char ?\ )
3490 (setq s "" move nil)
3491 (unless (assoc (char-to-string char) org-emphasis-alist)
3492 (error "No such emphasis marker: \"%c\"" char))
3493 (setq s (char-to-string char)))
3494 (while (and (> (length string) 1)
3495 (equal (substring string 0 1) (substring string -1))
3496 (assoc (substring string 0 1) org-emphasis-alist))
3497 (setq string (substring string 1 -1)))
3498 (setq string (concat s string s))
3499 (if beg (delete-region beg end))
3500 (unless (or (bolp)
3501 (string-match (concat "[" (nth 0 erc) "\n]")
3502 (char-to-string (char-before (point)))))
3503 (insert " "))
3504 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3505 (char-to-string (char-after (point))))
3506 (insert " ") (backward-char 1))
3507 (insert string)
3508 (and move (backward-char 1))))
3510 (defconst org-nonsticky-props
3511 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3514 (defun org-activate-plain-links (limit)
3515 "Run through the buffer and add overlays to links."
3516 (catch 'exit
3517 (let (f)
3518 (while (re-search-forward org-plain-link-re limit t)
3519 (setq f (get-text-property (match-beginning 0) 'face))
3520 (if (or (eq f 'org-tag)
3521 (and (listp f) (memq 'org-tag f)))
3523 (add-text-properties (match-beginning 0) (match-end 0)
3524 (list 'mouse-face 'highlight
3525 'rear-nonsticky org-nonsticky-props
3526 'keymap org-mouse-map
3528 (throw 'exit t))))))
3530 (defun org-activate-code (limit)
3531 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3532 (progn
3533 (remove-text-properties (match-beginning 0) (match-end 0)
3534 '(display t invisible t intangible t))
3535 t)))
3537 (defun org-activate-angle-links (limit)
3538 "Run through the buffer and add overlays to links."
3539 (if (re-search-forward org-angle-link-re limit t)
3540 (progn
3541 (add-text-properties (match-beginning 0) (match-end 0)
3542 (list 'mouse-face 'highlight
3543 'rear-nonsticky org-nonsticky-props
3544 'keymap org-mouse-map
3546 t)))
3548 (defun org-activate-bracket-links (limit)
3549 "Run through the buffer and add overlays to bracketed links."
3550 (if (re-search-forward org-bracket-link-regexp limit t)
3551 (let* ((help (concat "LINK: "
3552 (org-match-string-no-properties 1)))
3553 ;; FIXME: above we should remove the escapes.
3554 ;; but that requires another match, protecting match data,
3555 ;; a lot of overhead for font-lock.
3556 (ip (org-maybe-intangible
3557 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3558 'keymap org-mouse-map 'mouse-face 'highlight
3559 'font-lock-multiline t 'help-echo help)))
3560 (vp (list 'rear-nonsticky org-nonsticky-props
3561 'keymap org-mouse-map 'mouse-face 'highlight
3562 ' font-lock-multiline t 'help-echo help)))
3563 ;; We need to remove the invisible property here. Table narrowing
3564 ;; may have made some of this invisible.
3565 (remove-text-properties (match-beginning 0) (match-end 0)
3566 '(invisible nil))
3567 (if (match-end 3)
3568 (progn
3569 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3570 (add-text-properties (match-beginning 3) (match-end 3) vp)
3571 (add-text-properties (match-end 3) (match-end 0) ip))
3572 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3573 (add-text-properties (match-beginning 1) (match-end 1) vp)
3574 (add-text-properties (match-end 1) (match-end 0) ip))
3575 t)))
3577 (defun org-activate-dates (limit)
3578 "Run through the buffer and add overlays to dates."
3579 (if (re-search-forward org-tsr-regexp-both limit t)
3580 (progn
3581 (add-text-properties (match-beginning 0) (match-end 0)
3582 (list 'mouse-face 'highlight
3583 'rear-nonsticky org-nonsticky-props
3584 'keymap org-mouse-map))
3585 (when org-display-custom-times
3586 (if (match-end 3)
3587 (org-display-custom-time (match-beginning 3) (match-end 3)))
3588 (org-display-custom-time (match-beginning 1) (match-end 1)))
3589 t)))
3591 (defvar org-target-link-regexp nil
3592 "Regular expression matching radio targets in plain text.")
3593 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3594 "Regular expression matching a link target.")
3595 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3596 "Regular expression matching a radio target.")
3597 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3598 "Regular expression matching any target.")
3600 (defun org-activate-target-links (limit)
3601 "Run through the buffer and add overlays to target matches."
3602 (when org-target-link-regexp
3603 (let ((case-fold-search t))
3604 (if (re-search-forward org-target-link-regexp limit t)
3605 (progn
3606 (add-text-properties (match-beginning 0) (match-end 0)
3607 (list 'mouse-face 'highlight
3608 'rear-nonsticky org-nonsticky-props
3609 'keymap org-mouse-map
3610 'help-echo "Radio target link"
3611 'org-linked-text t))
3612 t)))))
3614 (defun org-update-radio-target-regexp ()
3615 "Find all radio targets in this file and update the regular expression."
3616 (interactive)
3617 (when (memq 'radio org-activate-links)
3618 (setq org-target-link-regexp
3619 (org-make-target-link-regexp (org-all-targets 'radio)))
3620 (org-restart-font-lock)))
3622 (defun org-hide-wide-columns (limit)
3623 (let (s e)
3624 (setq s (text-property-any (point) (or limit (point-max))
3625 'org-cwidth t))
3626 (when s
3627 (setq e (next-single-property-change s 'org-cwidth))
3628 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3629 (goto-char e)
3630 t)))
3632 (defvar org-latex-and-specials-regexp nil
3633 "Regular expression for highlighting export special stuff.")
3634 (defvar org-match-substring-regexp)
3635 (defvar org-match-substring-with-braces-regexp)
3636 (defvar org-export-html-special-string-regexps)
3638 (defun org-compute-latex-and-specials-regexp ()
3639 "Compute regular expression for stuff treated specially by exporters."
3640 (if (not org-highlight-latex-fragments-and-specials)
3641 (org-set-local 'org-latex-and-specials-regexp nil)
3642 (require 'org-exp)
3643 (let*
3644 ((matchers (plist-get org-format-latex-options :matchers))
3645 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3646 org-latex-regexps)))
3647 (options (org-combine-plists (org-default-export-plist)
3648 (org-infile-export-plist)))
3649 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3650 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3651 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3652 (org-export-html-expand (plist-get options :expand-quoted-html))
3653 (org-export-with-special-strings (plist-get options :special-strings))
3654 (re-sub
3655 (cond
3656 ((equal org-export-with-sub-superscripts '{})
3657 (list org-match-substring-with-braces-regexp))
3658 (org-export-with-sub-superscripts
3659 (list org-match-substring-regexp))
3660 (t nil)))
3661 (re-latex
3662 (if org-export-with-LaTeX-fragments
3663 (mapcar (lambda (x) (nth 1 x)) latexs)))
3664 (re-macros
3665 (if org-export-with-TeX-macros
3666 (list (concat "\\\\"
3667 (regexp-opt
3668 (append (mapcar 'car org-html-entities)
3669 (if (boundp 'org-latex-entities)
3670 org-latex-entities nil))
3671 'words))) ; FIXME
3673 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3674 (re-special (if org-export-with-special-strings
3675 (mapcar (lambda (x) (car x))
3676 org-export-html-special-string-regexps)))
3677 (re-rest
3678 (delq nil
3679 (list
3680 (if org-export-html-expand "@<[^>\n]+>")
3681 ))))
3682 (org-set-local
3683 'org-latex-and-specials-regexp
3684 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3685 re-rest) "\\|")))))
3687 (defun org-do-latex-and-special-faces (limit)
3688 "Run through the buffer and add overlays to links."
3689 (when org-latex-and-specials-regexp
3690 (let (rtn d)
3691 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3692 limit t))
3693 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3694 'face))
3695 '(org-code org-verbatim underline)))
3696 (progn
3697 (setq rtn t
3698 d (cond ((member (char-after (1+ (match-beginning 0)))
3699 '(?_ ?^)) 1)
3700 (t 0)))
3701 (font-lock-prepend-text-property
3702 (+ d (match-beginning 0)) (match-end 0)
3703 'face 'org-latex-and-export-specials)
3704 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3705 '(font-lock-multiline t)))))
3706 rtn)))
3708 (defun org-restart-font-lock ()
3709 "Restart font-lock-mode, to force refontification."
3710 (when (and (boundp 'font-lock-mode) font-lock-mode)
3711 (font-lock-mode -1)
3712 (font-lock-mode 1)))
3714 (defun org-all-targets (&optional radio)
3715 "Return a list of all targets in this file.
3716 With optional argument RADIO, only find radio targets."
3717 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3718 rtn)
3719 (save-excursion
3720 (goto-char (point-min))
3721 (while (re-search-forward re nil t)
3722 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3723 rtn)))
3725 (defun org-make-target-link-regexp (targets)
3726 "Make regular expression matching all strings in TARGETS.
3727 The regular expression finds the targets also if there is a line break
3728 between words."
3729 (and targets
3730 (concat
3731 "\\<\\("
3732 (mapconcat
3733 (lambda (x)
3734 (while (string-match " +" x)
3735 (setq x (replace-match "\\s-+" t t x)))
3737 targets
3738 "\\|")
3739 "\\)\\>")))
3741 (defun org-activate-tags (limit)
3742 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3743 (progn
3744 (add-text-properties (match-beginning 1) (match-end 1)
3745 (list 'mouse-face 'highlight
3746 'rear-nonsticky org-nonsticky-props
3747 'keymap org-mouse-map))
3748 t)))
3750 (defun org-outline-level ()
3751 (save-excursion
3752 (looking-at outline-regexp)
3753 (if (match-beginning 1)
3754 (+ (org-get-string-indentation (match-string 1)) 1000)
3755 (1- (- (match-end 0) (match-beginning 0))))))
3757 (defvar org-font-lock-keywords nil)
3759 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3760 "Regular expression matching a property line.")
3762 (defvar org-font-lock-hook nil
3763 "Functions to be called for special font lock stuff.")
3765 (defun org-font-lock-hook (limit)
3766 (run-hook-with-args 'org-font-lock-hook limit))
3768 (defun org-set-font-lock-defaults ()
3769 (let* ((em org-fontify-emphasized-text)
3770 (lk org-activate-links)
3771 (org-font-lock-extra-keywords
3772 (list
3773 ;; Call the hook
3774 '(org-font-lock-hook)
3775 ;; Headlines
3776 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3777 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3778 ;; Table lines
3779 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3780 (1 'org-table t))
3781 ;; Table internals
3782 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3783 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3784 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3785 ;; Drawers
3786 (list org-drawer-regexp '(0 'org-special-keyword t))
3787 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3788 ;; Properties
3789 (list org-property-re
3790 '(1 'org-special-keyword t)
3791 '(3 'org-property-value t))
3792 (if org-format-transports-properties-p
3793 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3794 ;; Links
3795 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3796 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3797 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3798 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3799 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3800 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3801 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3802 '(org-hide-wide-columns (0 nil append))
3803 ;; TODO lines
3804 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3805 '(1 (org-get-todo-face 1) t))
3806 ;; DONE
3807 (if org-fontify-done-headline
3808 (list (concat "^[*]+ +\\<\\("
3809 (mapconcat 'regexp-quote org-done-keywords "\\|")
3810 "\\)\\(.*\\)")
3811 '(2 'org-headline-done t))
3812 nil)
3813 ;; Priorities
3814 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3815 ;; Special keywords
3816 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3817 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3818 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3819 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3820 ;; Emphasis
3821 (if em
3822 (if (featurep 'xemacs)
3823 '(org-do-emphasis-faces (0 nil append))
3824 '(org-do-emphasis-faces)))
3825 ;; Checkboxes
3826 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3827 2 'bold prepend)
3828 (if org-provide-checkbox-statistics
3829 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3830 (0 (org-get-checkbox-statistics-face) t)))
3831 ;; Description list items
3832 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3833 2 'bold prepend)
3834 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3835 '(1 'org-archived prepend))
3836 ;; Specials
3837 '(org-do-latex-and-special-faces)
3838 ;; Code
3839 '(org-activate-code (1 'org-code t))
3840 ;; COMMENT
3841 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3842 "\\|" org-quote-string "\\)\\>")
3843 '(1 'org-special-keyword t))
3844 '("^#.*" (0 'font-lock-comment-face t))
3846 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3847 ;; Now set the full font-lock-keywords
3848 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3849 (org-set-local 'font-lock-defaults
3850 '(org-font-lock-keywords t nil nil backward-paragraph))
3851 (kill-local-variable 'font-lock-keywords) nil))
3853 (defvar org-m nil)
3854 (defvar org-l nil)
3855 (defvar org-f nil)
3856 (defun org-get-level-face (n)
3857 "Get the right face for match N in font-lock matching of healdines."
3858 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3859 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3860 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3861 (cond
3862 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3863 ((eq n 2) org-f)
3864 (t (if org-level-color-stars-only nil org-f))))
3866 (defun org-get-todo-face (kwd)
3867 "Get the right face for a TODO keyword KWD.
3868 If KWD is a number, get the corresponding match group."
3869 (if (numberp kwd) (setq kwd (match-string kwd)))
3870 (or (cdr (assoc kwd org-todo-keyword-faces))
3871 (and (member kwd org-done-keywords) 'org-done)
3872 'org-todo))
3874 (defun org-unfontify-region (beg end &optional maybe_loudly)
3875 "Remove fontification and activation overlays from links."
3876 (font-lock-default-unfontify-region beg end)
3877 (let* ((buffer-undo-list t)
3878 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3879 (inhibit-modification-hooks t)
3880 deactivate-mark buffer-file-name buffer-file-truename)
3881 (remove-text-properties beg end
3882 '(mouse-face t keymap t org-linked-text t
3883 invisible t intangible t))))
3885 ;;;; Visibility cycling, including org-goto and indirect buffer
3887 ;;; Cycling
3889 (defvar org-cycle-global-status nil)
3890 (make-variable-buffer-local 'org-cycle-global-status)
3891 (defvar org-cycle-subtree-status nil)
3892 (make-variable-buffer-local 'org-cycle-subtree-status)
3894 ;;;###autoload
3895 (defun org-cycle (&optional arg)
3896 "Visibility cycling for Org-mode.
3898 - When this function is called with a prefix argument, rotate the entire
3899 buffer through 3 states (global cycling)
3900 1. OVERVIEW: Show only top-level headlines.
3901 2. CONTENTS: Show all headlines of all levels, but no body text.
3902 3. SHOW ALL: Show everything.
3903 When called with two C-c C-u prefixes, switch to the startup visibility,
3904 determined by the variable `org-startup-folded', and by any VISIBILITY
3905 properties in the buffer.
3907 - When point is at the beginning of a headline, rotate the subtree started
3908 by this line through 3 different states (local cycling)
3909 1. FOLDED: Only the main headline is shown.
3910 2. CHILDREN: The main headline and the direct children are shown.
3911 From this state, you can move to one of the children
3912 and zoom in further.
3913 3. SUBTREE: Show the entire subtree, including body text.
3915 - When there is a numeric prefix, go up to a heading with level ARG, do
3916 a `show-subtree' and return to the previous cursor position. If ARG
3917 is negative, go up that many levels.
3919 - When point is not at the beginning of a headline, execute the global
3920 binding for TAB, which is re-indenting the line. See the option
3921 `org-cycle-emulate-tab' for details.
3923 - Special case: if point is at the beginning of the buffer and there is
3924 no headline in line 1, this function will act as if called with prefix arg.
3925 But only if also the variable `org-cycle-global-at-bob' is t."
3926 (interactive "P")
3927 (org-load-modules-maybe)
3928 (let* ((outline-regexp
3929 (if (and (org-mode-p) org-cycle-include-plain-lists)
3930 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3931 outline-regexp))
3932 (bob-special (and org-cycle-global-at-bob (bobp)
3933 (not (looking-at outline-regexp))))
3934 (org-cycle-hook
3935 (if bob-special
3936 (delq 'org-optimize-window-after-visibility-change
3937 (copy-sequence org-cycle-hook))
3938 org-cycle-hook))
3939 (pos (point)))
3941 (if (or bob-special (equal arg '(4)))
3942 ;; special case: use global cycling
3943 (setq arg t))
3945 (cond
3947 ((equal arg '(16))
3948 (org-set-startup-visibility)
3949 (message "Startup visibility, plus VISIBILITY properties."))
3951 ((org-at-table-p 'any)
3952 ;; Enter the table or move to the next field in the table
3953 (or (org-table-recognize-table.el)
3954 (progn
3955 (if arg (org-table-edit-field t)
3956 (org-table-justify-field-maybe)
3957 (call-interactively 'org-table-next-field)))))
3959 ((eq arg t) ;; Global cycling
3961 (cond
3962 ((and (eq last-command this-command)
3963 (eq org-cycle-global-status 'overview))
3964 ;; We just created the overview - now do table of contents
3965 ;; This can be slow in very large buffers, so indicate action
3966 (message "CONTENTS...")
3967 (org-content)
3968 (message "CONTENTS...done")
3969 (setq org-cycle-global-status 'contents)
3970 (run-hook-with-args 'org-cycle-hook 'contents))
3972 ((and (eq last-command this-command)
3973 (eq org-cycle-global-status 'contents))
3974 ;; We just showed the table of contents - now show everything
3975 (show-all)
3976 (message "SHOW ALL")
3977 (setq org-cycle-global-status 'all)
3978 (run-hook-with-args 'org-cycle-hook 'all))
3981 ;; Default action: go to overview
3982 (org-overview)
3983 (message "OVERVIEW")
3984 (setq org-cycle-global-status 'overview)
3985 (run-hook-with-args 'org-cycle-hook 'overview))))
3987 ((and org-drawers org-drawer-regexp
3988 (save-excursion
3989 (beginning-of-line 1)
3990 (looking-at org-drawer-regexp)))
3991 ;; Toggle block visibility
3992 (org-flag-drawer
3993 (not (get-char-property (match-end 0) 'invisible))))
3995 ((integerp arg)
3996 ;; Show-subtree, ARG levels up from here.
3997 (save-excursion
3998 (org-back-to-heading)
3999 (outline-up-heading (if (< arg 0) (- arg)
4000 (- (funcall outline-level) arg)))
4001 (org-show-subtree)))
4003 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4004 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4005 ;; At a heading: rotate between three different views
4006 (org-back-to-heading)
4007 (let ((goal-column 0) eoh eol eos)
4008 ;; First, some boundaries
4009 (save-excursion
4010 (org-back-to-heading)
4011 (save-excursion
4012 (beginning-of-line 2)
4013 (while (and (not (eobp)) ;; this is like `next-line'
4014 (get-char-property (1- (point)) 'invisible))
4015 (beginning-of-line 2)) (setq eol (point)))
4016 (outline-end-of-heading) (setq eoh (point))
4017 (org-end-of-subtree t)
4018 (unless (eobp)
4019 (skip-chars-forward " \t\n")
4020 (beginning-of-line 1) ; in case this is an item
4022 (setq eos (1- (point))))
4023 ;; Find out what to do next and set `this-command'
4024 (cond
4025 ((= eos eoh)
4026 ;; Nothing is hidden behind this heading
4027 (message "EMPTY ENTRY")
4028 (setq org-cycle-subtree-status nil)
4029 (save-excursion
4030 (goto-char eos)
4031 (outline-next-heading)
4032 (if (org-invisible-p) (org-flag-heading nil))))
4033 ((or (>= eol eos)
4034 (not (string-match "\\S-" (buffer-substring eol eos))))
4035 ;; Entire subtree is hidden in one line: open it
4036 (org-show-entry)
4037 (show-children)
4038 (message "CHILDREN")
4039 (save-excursion
4040 (goto-char eos)
4041 (outline-next-heading)
4042 (if (org-invisible-p) (org-flag-heading nil)))
4043 (setq org-cycle-subtree-status 'children)
4044 (run-hook-with-args 'org-cycle-hook 'children))
4045 ((and (eq last-command this-command)
4046 (eq org-cycle-subtree-status 'children))
4047 ;; We just showed the children, now show everything.
4048 (org-show-subtree)
4049 (message "SUBTREE")
4050 (setq org-cycle-subtree-status 'subtree)
4051 (run-hook-with-args 'org-cycle-hook 'subtree))
4053 ;; Default action: hide the subtree.
4054 (hide-subtree)
4055 (message "FOLDED")
4056 (setq org-cycle-subtree-status 'folded)
4057 (run-hook-with-args 'org-cycle-hook 'folded)))))
4059 ;; TAB emulation and template completion
4060 (buffer-read-only (org-back-to-heading))
4062 ((org-try-structure-completion))
4064 ((org-try-cdlatex-tab))
4066 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4067 (or (not (bolp))
4068 (not (looking-at outline-regexp))))
4069 (call-interactively (global-key-binding "\t")))
4071 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4072 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4073 (or (and (eq org-cycle-emulate-tab 'white)
4074 (= (match-end 0) (point-at-eol)))
4075 (and (eq org-cycle-emulate-tab 'whitestart)
4076 (>= (match-end 0) pos))))
4078 (eq org-cycle-emulate-tab t))
4079 (call-interactively (global-key-binding "\t")))
4081 (t (save-excursion
4082 (org-back-to-heading)
4083 (org-cycle))))))
4085 ;;;###autoload
4086 (defun org-global-cycle (&optional arg)
4087 "Cycle the global visibility. For details see `org-cycle'.
4088 With C-u prefix arg, switch to startup visibility.
4089 With a numeric prefix, show all headlines up to that level."
4090 (interactive "P")
4091 (let ((org-cycle-include-plain-lists
4092 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4093 (cond
4094 ((integerp arg)
4095 (show-all)
4096 (hide-sublevels arg)
4097 (setq org-cycle-global-status 'contents))
4098 ((equal arg '(4))
4099 (org-set-startup-visibility)
4100 (message "Startup visibility, plus VISIBILITY properties."))
4102 (org-cycle '(4))))))
4104 (defun org-set-startup-visibility ()
4105 "Set the visibility required by startup options and properties."
4106 (cond
4107 ((eq org-startup-folded t)
4108 (org-cycle '(4)))
4109 ((eq org-startup-folded 'content)
4110 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4111 (org-cycle '(4)) (org-cycle '(4)))))
4112 (org-set-visibility-according-to-property 'no-cleanup)
4113 (org-cycle-hide-archived-subtrees 'all)
4114 (org-cycle-hide-drawers 'all)
4115 (org-cycle-show-empty-lines 'all))
4117 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4118 "Switch subtree visibilities according to :VISIBILITY: property."
4119 (interactive)
4120 (let (state)
4121 (save-excursion
4122 (goto-char (point-min))
4123 (while (re-search-forward
4124 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4125 nil t)
4126 (setq state (match-string 1))
4127 (save-excursion
4128 (org-back-to-heading t)
4129 (hide-subtree)
4130 (org-reveal)
4131 (cond
4132 ((equal state '("fold" "folded"))
4133 (hide-subtree))
4134 ((equal state "children")
4135 (org-show-hidden-entry)
4136 (show-children))
4137 ((equal state "content")
4138 (save-excursion
4139 (save-restriction
4140 (org-narrow-to-subtree)
4141 (org-content))))
4142 ((member state '("all" "showall"))
4143 (show-subtree)))))
4144 (unless no-cleanup
4145 (org-cycle-hide-archived-subtrees 'all)
4146 (org-cycle-hide-drawers 'all)
4147 (org-cycle-show-empty-lines 'all)))))
4149 (defun org-overview ()
4150 "Switch to overview mode, shoing only top-level headlines.
4151 Really, this shows all headlines with level equal or greater than the level
4152 of the first headline in the buffer. This is important, because if the
4153 first headline is not level one, then (hide-sublevels 1) gives confusing
4154 results."
4155 (interactive)
4156 (let ((level (save-excursion
4157 (goto-char (point-min))
4158 (if (re-search-forward (concat "^" outline-regexp) nil t)
4159 (progn
4160 (goto-char (match-beginning 0))
4161 (funcall outline-level))))))
4162 (and level (hide-sublevels level))))
4164 (defun org-content (&optional arg)
4165 "Show all headlines in the buffer, like a table of contents.
4166 With numerical argument N, show content up to level N."
4167 (interactive "P")
4168 (save-excursion
4169 ;; Visit all headings and show their offspring
4170 (and (integerp arg) (org-overview))
4171 (goto-char (point-max))
4172 (catch 'exit
4173 (while (and (progn (condition-case nil
4174 (outline-previous-visible-heading 1)
4175 (error (goto-char (point-min))))
4177 (looking-at outline-regexp))
4178 (if (integerp arg)
4179 (show-children (1- arg))
4180 (show-branches))
4181 (if (bobp) (throw 'exit nil))))))
4184 (defun org-optimize-window-after-visibility-change (state)
4185 "Adjust the window after a change in outline visibility.
4186 This function is the default value of the hook `org-cycle-hook'."
4187 (when (get-buffer-window (current-buffer))
4188 (cond
4189 ; ((eq state 'overview) (org-first-headline-recenter 1))
4190 ; ((eq state 'overview) (org-beginning-of-line))
4191 ((eq state 'content) nil)
4192 ((eq state 'all) nil)
4193 ((eq state 'folded) nil)
4194 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4195 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4197 (defun org-compact-display-after-subtree-move ()
4198 (let (beg end)
4199 (save-excursion
4200 (if (org-up-heading-safe)
4201 (progn
4202 (hide-subtree)
4203 (show-entry)
4204 (show-children)
4205 (org-cycle-show-empty-lines 'children)
4206 (org-cycle-hide-drawers 'children))
4207 (org-overview)))))
4209 (defun org-cycle-show-empty-lines (state)
4210 "Show empty lines above all visible headlines.
4211 The region to be covered depends on STATE when called through
4212 `org-cycle-hook'. Lisp program can use t for STATE to get the
4213 entire buffer covered. Note that an empty line is only shown if there
4214 are at least `org-cycle-separator-lines' empty lines before the headeline."
4215 (when (> org-cycle-separator-lines 0)
4216 (save-excursion
4217 (let* ((n org-cycle-separator-lines)
4218 (re (cond
4219 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4220 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4221 (t (let ((ns (number-to-string (- n 2))))
4222 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4223 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4224 beg end)
4225 (cond
4226 ((memq state '(overview contents t))
4227 (setq beg (point-min) end (point-max)))
4228 ((memq state '(children folded))
4229 (setq beg (point) end (progn (org-end-of-subtree t t)
4230 (beginning-of-line 2)
4231 (point)))))
4232 (when beg
4233 (goto-char beg)
4234 (while (re-search-forward re end t)
4235 (if (not (get-char-property (match-end 1) 'invisible))
4236 (outline-flag-region
4237 (match-beginning 1) (match-end 1) nil)))))))
4238 ;; Never hide empty lines at the end of the file.
4239 (save-excursion
4240 (goto-char (point-max))
4241 (outline-previous-heading)
4242 (outline-end-of-heading)
4243 (if (and (looking-at "[ \t\n]+")
4244 (= (match-end 0) (point-max)))
4245 (outline-flag-region (point) (match-end 0) nil))))
4247 (defun org-show-empty-lines-in-parent ()
4248 "Move to the parent and re-show empty lines before visible headlines."
4249 (save-excursion
4250 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4251 (org-cycle-show-empty-lines context))))
4253 (defun org-cycle-hide-drawers (state)
4254 "Re-hide all drawers after a visibility state change."
4255 (when (and (org-mode-p)
4256 (not (memq state '(overview folded))))
4257 (save-excursion
4258 (let* ((globalp (memq state '(contents all)))
4259 (beg (if globalp (point-min) (point)))
4260 (end (if globalp (point-max) (org-end-of-subtree t))))
4261 (goto-char beg)
4262 (while (re-search-forward org-drawer-regexp end t)
4263 (org-flag-drawer t))))))
4265 (defun org-flag-drawer (flag)
4266 (save-excursion
4267 (beginning-of-line 1)
4268 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4269 (let ((b (match-end 0))
4270 (outline-regexp org-outline-regexp))
4271 (if (re-search-forward
4272 "^[ \t]*:END:"
4273 (save-excursion (outline-next-heading) (point)) t)
4274 (outline-flag-region b (point-at-eol) flag)
4275 (error ":END: line missing"))))))
4277 (defun org-subtree-end-visible-p ()
4278 "Is the end of the current subtree visible?"
4279 (pos-visible-in-window-p
4280 (save-excursion (org-end-of-subtree t) (point))))
4282 (defun org-first-headline-recenter (&optional N)
4283 "Move cursor to the first headline and recenter the headline.
4284 Optional argument N means, put the headline into the Nth line of the window."
4285 (goto-char (point-min))
4286 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4287 (beginning-of-line)
4288 (recenter (prefix-numeric-value N))))
4290 ;;; Org-goto
4292 (defvar org-goto-window-configuration nil)
4293 (defvar org-goto-marker nil)
4294 (defvar org-goto-map
4295 (let ((map (make-sparse-keymap)))
4296 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4297 (while (setq cmd (pop cmds))
4298 (substitute-key-definition cmd cmd map global-map)))
4299 (suppress-keymap map)
4300 (org-defkey map "\C-m" 'org-goto-ret)
4301 (org-defkey map [(return)] 'org-goto-ret)
4302 (org-defkey map [(left)] 'org-goto-left)
4303 (org-defkey map [(right)] 'org-goto-right)
4304 (org-defkey map [(control ?g)] 'org-goto-quit)
4305 (org-defkey map "\C-i" 'org-cycle)
4306 (org-defkey map [(tab)] 'org-cycle)
4307 (org-defkey map [(down)] 'outline-next-visible-heading)
4308 (org-defkey map [(up)] 'outline-previous-visible-heading)
4309 (if org-goto-auto-isearch
4310 (if (fboundp 'define-key-after)
4311 (define-key-after map [t] 'org-goto-local-auto-isearch)
4312 nil)
4313 (org-defkey map "q" 'org-goto-quit)
4314 (org-defkey map "n" 'outline-next-visible-heading)
4315 (org-defkey map "p" 'outline-previous-visible-heading)
4316 (org-defkey map "f" 'outline-forward-same-level)
4317 (org-defkey map "b" 'outline-backward-same-level)
4318 (org-defkey map "u" 'outline-up-heading))
4319 (org-defkey map "/" 'org-occur)
4320 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4321 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4322 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4323 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4324 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4325 map))
4327 (defconst org-goto-help
4328 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4329 RET=jump to location [Q]uit and return to previous location
4330 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4332 (defvar org-goto-start-pos) ; dynamically scoped parameter
4334 ;; FIXME: Docstring doe not mention both interfaces
4335 (defun org-goto (&optional alternative-interface)
4336 "Look up a different location in the current file, keeping current visibility.
4338 When you want look-up or go to a different location in a document, the
4339 fastest way is often to fold the entire buffer and then dive into the tree.
4340 This method has the disadvantage, that the previous location will be folded,
4341 which may not be what you want.
4343 This command works around this by showing a copy of the current buffer
4344 in an indirect buffer, in overview mode. You can dive into the tree in
4345 that copy, use org-occur and incremental search to find a location.
4346 When pressing RET or `Q', the command returns to the original buffer in
4347 which the visibility is still unchanged. After RET is will also jump to
4348 the location selected in the indirect buffer and expose the
4349 the headline hierarchy above."
4350 (interactive "P")
4351 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4352 (org-refile-use-outline-path t)
4353 (interface
4354 (if (not alternative-interface)
4355 org-goto-interface
4356 (if (eq org-goto-interface 'outline)
4357 'outline-path-completion
4358 'outline)))
4359 (org-goto-start-pos (point))
4360 (selected-point
4361 (if (eq interface 'outline)
4362 (car (org-get-location (current-buffer) org-goto-help))
4363 (nth 3 (org-refile-get-location "Goto: ")))))
4364 (if selected-point
4365 (progn
4366 (org-mark-ring-push org-goto-start-pos)
4367 (goto-char selected-point)
4368 (if (or (org-invisible-p) (org-invisible-p2))
4369 (org-show-context 'org-goto)))
4370 (message "Quit"))))
4372 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4373 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4374 (defvar org-goto-local-auto-isearch-map) ; defined below
4376 (defun org-get-location (buf help)
4377 "Let the user select a location in the Org-mode buffer BUF.
4378 This function uses a recursive edit. It returns the selected position
4379 or nil."
4380 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4381 (isearch-hide-immediately nil)
4382 (isearch-search-fun-function
4383 (lambda () 'org-goto-local-search-headings))
4384 (org-goto-selected-point org-goto-exit-command))
4385 (save-excursion
4386 (save-window-excursion
4387 (delete-other-windows)
4388 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4389 (switch-to-buffer
4390 (condition-case nil
4391 (make-indirect-buffer (current-buffer) "*org-goto*")
4392 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4393 (with-output-to-temp-buffer "*Help*"
4394 (princ help))
4395 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4396 (setq buffer-read-only nil)
4397 (let ((org-startup-truncated t)
4398 (org-startup-folded nil)
4399 (org-startup-align-all-tables nil))
4400 (org-mode)
4401 (org-overview))
4402 (setq buffer-read-only t)
4403 (if (and (boundp 'org-goto-start-pos)
4404 (integer-or-marker-p org-goto-start-pos))
4405 (let ((org-show-hierarchy-above t)
4406 (org-show-siblings t)
4407 (org-show-following-heading t))
4408 (goto-char org-goto-start-pos)
4409 (and (org-invisible-p) (org-show-context)))
4410 (goto-char (point-min)))
4411 (org-beginning-of-line)
4412 (message "Select location and press RET")
4413 (use-local-map org-goto-map)
4414 (recursive-edit)
4416 (kill-buffer "*org-goto*")
4417 (cons org-goto-selected-point org-goto-exit-command)))
4419 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4420 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4421 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4422 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4424 (defun org-goto-local-search-headings (string bound noerror)
4425 "Search and make sure that any matches are in headlines."
4426 (catch 'return
4427 (while (if isearch-forward
4428 (search-forward string bound noerror)
4429 (search-backward string bound noerror))
4430 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4431 (and (member :headline context)
4432 (not (member :tags context))))
4433 (throw 'return (point))))))
4435 (defun org-goto-local-auto-isearch ()
4436 "Start isearch."
4437 (interactive)
4438 (goto-char (point-min))
4439 (let ((keys (this-command-keys)))
4440 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4441 (isearch-mode t)
4442 (isearch-process-search-char (string-to-char keys)))))
4444 (defun org-goto-ret (&optional arg)
4445 "Finish `org-goto' by going to the new location."
4446 (interactive "P")
4447 (setq org-goto-selected-point (point)
4448 org-goto-exit-command 'return)
4449 (throw 'exit nil))
4451 (defun org-goto-left ()
4452 "Finish `org-goto' by going to the new location."
4453 (interactive)
4454 (if (org-on-heading-p)
4455 (progn
4456 (beginning-of-line 1)
4457 (setq org-goto-selected-point (point)
4458 org-goto-exit-command 'left)
4459 (throw 'exit nil))
4460 (error "Not on a heading")))
4462 (defun org-goto-right ()
4463 "Finish `org-goto' by going to the new location."
4464 (interactive)
4465 (if (org-on-heading-p)
4466 (progn
4467 (setq org-goto-selected-point (point)
4468 org-goto-exit-command 'right)
4469 (throw 'exit nil))
4470 (error "Not on a heading")))
4472 (defun org-goto-quit ()
4473 "Finish `org-goto' without cursor motion."
4474 (interactive)
4475 (setq org-goto-selected-point nil)
4476 (setq org-goto-exit-command 'quit)
4477 (throw 'exit nil))
4479 ;;; Indirect buffer display of subtrees
4481 (defvar org-indirect-dedicated-frame nil
4482 "This is the frame being used for indirect tree display.")
4483 (defvar org-last-indirect-buffer nil)
4485 (defun org-tree-to-indirect-buffer (&optional arg)
4486 "Create indirect buffer and narrow it to current subtree.
4487 With numerical prefix ARG, go up to this level and then take that tree.
4488 If ARG is negative, go up that many levels.
4489 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4490 indirect buffer previously made with this command, to avoid proliferation of
4491 indirect buffers. However, when you call the command with a `C-u' prefix, or
4492 when `org-indirect-buffer-display' is `new-frame', the last buffer
4493 is kept so that you can work with several indirect buffers at the same time.
4494 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4495 requests that a new frame be made for the new buffer, so that the dedicated
4496 frame is not changed."
4497 (interactive "P")
4498 (let ((cbuf (current-buffer))
4499 (cwin (selected-window))
4500 (pos (point))
4501 beg end level heading ibuf)
4502 (save-excursion
4503 (org-back-to-heading t)
4504 (when (numberp arg)
4505 (setq level (org-outline-level))
4506 (if (< arg 0) (setq arg (+ level arg)))
4507 (while (> (setq level (org-outline-level)) arg)
4508 (outline-up-heading 1 t)))
4509 (setq beg (point)
4510 heading (org-get-heading))
4511 (org-end-of-subtree t) (setq end (point)))
4512 (if (and (buffer-live-p org-last-indirect-buffer)
4513 (not (eq org-indirect-buffer-display 'new-frame))
4514 (not arg))
4515 (kill-buffer org-last-indirect-buffer))
4516 (setq ibuf (org-get-indirect-buffer cbuf)
4517 org-last-indirect-buffer ibuf)
4518 (cond
4519 ((or (eq org-indirect-buffer-display 'new-frame)
4520 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4521 (select-frame (make-frame))
4522 (delete-other-windows)
4523 (switch-to-buffer ibuf)
4524 (org-set-frame-title heading))
4525 ((eq org-indirect-buffer-display 'dedicated-frame)
4526 (raise-frame
4527 (select-frame (or (and org-indirect-dedicated-frame
4528 (frame-live-p org-indirect-dedicated-frame)
4529 org-indirect-dedicated-frame)
4530 (setq org-indirect-dedicated-frame (make-frame)))))
4531 (delete-other-windows)
4532 (switch-to-buffer ibuf)
4533 (org-set-frame-title (concat "Indirect: " heading)))
4534 ((eq org-indirect-buffer-display 'current-window)
4535 (switch-to-buffer ibuf))
4536 ((eq org-indirect-buffer-display 'other-window)
4537 (pop-to-buffer ibuf))
4538 (t (error "Invalid value.")))
4539 (if (featurep 'xemacs)
4540 (save-excursion (org-mode) (turn-on-font-lock)))
4541 (narrow-to-region beg end)
4542 (show-all)
4543 (goto-char pos)
4544 (and (window-live-p cwin) (select-window cwin))))
4546 (defun org-get-indirect-buffer (&optional buffer)
4547 (setq buffer (or buffer (current-buffer)))
4548 (let ((n 1) (base (buffer-name buffer)) bname)
4549 (while (buffer-live-p
4550 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4551 (setq n (1+ n)))
4552 (condition-case nil
4553 (make-indirect-buffer buffer bname 'clone)
4554 (error (make-indirect-buffer buffer bname)))))
4556 (defun org-set-frame-title (title)
4557 "Set the title of the current frame to the string TITLE."
4558 ;; FIXME: how to name a single frame in XEmacs???
4559 (unless (featurep 'xemacs)
4560 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4562 ;;;; Structure editing
4564 ;;; Inserting headlines
4566 (defun org-insert-heading (&optional force-heading)
4567 "Insert a new heading or item with same depth at point.
4568 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4569 If point is at the beginning of a headline, insert a sibling before the
4570 current headline. If point is not at the beginning, do not split the line,
4571 but create the new hedline after the current line."
4572 (interactive "P")
4573 (if (= (buffer-size) 0)
4574 (insert "\n* ")
4575 (when (or force-heading (not (org-insert-item)))
4576 (let* ((head (save-excursion
4577 (condition-case nil
4578 (progn
4579 (org-back-to-heading)
4580 (match-string 0))
4581 (error "*"))))
4582 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4583 pos)
4584 (cond
4585 ((and (org-on-heading-p) (bolp)
4586 (or (bobp)
4587 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4588 ;; insert before the current line
4589 (open-line (if blank 2 1)))
4590 ((and (bolp)
4591 (or (bobp)
4592 (save-excursion
4593 (backward-char 1) (not (org-invisible-p)))))
4594 ;; insert right here
4595 nil)
4597 ;; in the middle of the line
4598 (org-show-entry)
4599 (let ((split
4600 (org-get-alist-option org-M-RET-may-split-line 'headline))
4601 tags pos)
4602 (if (org-on-heading-p)
4603 (progn
4604 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4605 (setq tags (and (match-end 2) (match-string 2)))
4606 (and (match-end 1)
4607 (delete-region (match-beginning 1) (match-end 1)))
4608 (setq pos (point-at-bol))
4609 (or split (end-of-line 1))
4610 (delete-horizontal-space)
4611 (newline (if blank 2 1))
4612 (when tags
4613 (save-excursion
4614 (goto-char pos)
4615 (end-of-line 1)
4616 (insert " " tags)
4617 (org-set-tags nil 'align))))
4618 (or split (end-of-line 1))
4619 (newline (if blank 2 1))))))
4620 (insert head) (just-one-space)
4621 (setq pos (point))
4622 (end-of-line 1)
4623 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4624 (run-hooks 'org-insert-heading-hook)))))
4626 (defun org-get-heading (&optional no-tags)
4627 "Return the heading of the current entry, without the stars."
4628 (save-excursion
4629 (org-back-to-heading t)
4630 (if (looking-at
4631 (if no-tags
4632 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4633 "\\*+[ \t]+\\([^\r\n]*\\)"))
4634 (match-string 1) "")))
4636 (defun org-insert-heading-after-current ()
4637 "Insert a new heading with same level as current, after current subtree."
4638 (interactive)
4639 (org-back-to-heading)
4640 (org-insert-heading)
4641 (org-move-subtree-down)
4642 (end-of-line 1))
4644 (defun org-insert-todo-heading (arg)
4645 "Insert a new heading with the same level and TODO state as current heading.
4646 If the heading has no TODO state, or if the state is DONE, use the first
4647 state (TODO by default). Also with prefix arg, force first state."
4648 (interactive "P")
4649 (when (not (org-insert-item 'checkbox))
4650 (org-insert-heading)
4651 (save-excursion
4652 (org-back-to-heading)
4653 (outline-previous-heading)
4654 (looking-at org-todo-line-regexp))
4655 (if (or arg
4656 (not (match-beginning 2))
4657 (member (match-string 2) org-done-keywords))
4658 (insert (car org-todo-keywords-1) " ")
4659 (insert (match-string 2) " "))
4660 (when org-provide-todo-statistics
4661 (org-update-parent-todo-statistics))))
4663 (defun org-insert-subheading (arg)
4664 "Insert a new subheading and demote it.
4665 Works for outline headings and for plain lists alike."
4666 (interactive "P")
4667 (org-insert-heading arg)
4668 (cond
4669 ((org-on-heading-p) (org-do-demote))
4670 ((org-at-item-p) (org-indent-item 1))))
4672 (defun org-insert-todo-subheading (arg)
4673 "Insert a new subheading with TODO keyword or checkbox and demote it.
4674 Works for outline headings and for plain lists alike."
4675 (interactive "P")
4676 (org-insert-todo-heading arg)
4677 (cond
4678 ((org-on-heading-p) (org-do-demote))
4679 ((org-at-item-p) (org-indent-item 1))))
4681 ;;; Promotion and Demotion
4683 (defun org-promote-subtree ()
4684 "Promote the entire subtree.
4685 See also `org-promote'."
4686 (interactive)
4687 (save-excursion
4688 (org-map-tree 'org-promote))
4689 (org-fix-position-after-promote))
4691 (defun org-demote-subtree ()
4692 "Demote the entire subtree. See `org-demote'.
4693 See also `org-promote'."
4694 (interactive)
4695 (save-excursion
4696 (org-map-tree 'org-demote))
4697 (org-fix-position-after-promote))
4700 (defun org-do-promote ()
4701 "Promote the current heading higher up the tree.
4702 If the region is active in `transient-mark-mode', promote all headings
4703 in the region."
4704 (interactive)
4705 (save-excursion
4706 (if (org-region-active-p)
4707 (org-map-region 'org-promote (region-beginning) (region-end))
4708 (org-promote)))
4709 (org-fix-position-after-promote))
4711 (defun org-do-demote ()
4712 "Demote the current heading lower down the tree.
4713 If the region is active in `transient-mark-mode', demote all headings
4714 in the region."
4715 (interactive)
4716 (save-excursion
4717 (if (org-region-active-p)
4718 (org-map-region 'org-demote (region-beginning) (region-end))
4719 (org-demote)))
4720 (org-fix-position-after-promote))
4722 (defun org-fix-position-after-promote ()
4723 "Make sure that after pro/demotion cursor position is right."
4724 (let ((pos (point)))
4725 (when (save-excursion
4726 (beginning-of-line 1)
4727 (looking-at org-todo-line-regexp)
4728 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4729 (cond ((eobp) (insert " "))
4730 ((eolp) (insert " "))
4731 ((equal (char-after) ?\ ) (forward-char 1))))))
4733 (defun org-reduced-level (l)
4734 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4736 (defun org-get-valid-level (level &optional change)
4737 "Rectify a level change under the influence of `org-odd-levels-only'
4738 LEVEL is a current level, CHANGE is by how much the level should be
4739 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4740 even level numbers will become the next higher odd number."
4741 (if org-odd-levels-only
4742 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4743 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4744 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4745 (max 1 (+ level change))))
4747 (if (boundp 'define-obsolete-function-alias)
4748 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4749 (define-obsolete-function-alias 'org-get-legal-level
4750 'org-get-valid-level)
4751 (define-obsolete-function-alias 'org-get-legal-level
4752 'org-get-valid-level "23.1")))
4754 (defun org-promote ()
4755 "Promote the current heading higher up the tree.
4756 If the region is active in `transient-mark-mode', promote all headings
4757 in the region."
4758 (org-back-to-heading t)
4759 (let* ((level (save-match-data (funcall outline-level)))
4760 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4761 (diff (abs (- level (length up-head) -1))))
4762 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4763 (replace-match up-head nil t)
4764 ;; Fixup tag positioning
4765 (and org-auto-align-tags (org-set-tags nil t))
4766 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4768 (defun org-demote ()
4769 "Demote the current heading lower down the tree.
4770 If the region is active in `transient-mark-mode', demote all headings
4771 in the region."
4772 (org-back-to-heading t)
4773 (let* ((level (save-match-data (funcall outline-level)))
4774 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4775 (diff (abs (- level (length down-head) -1))))
4776 (replace-match down-head nil t)
4777 ;; Fixup tag positioning
4778 (and org-auto-align-tags (org-set-tags nil t))
4779 (if org-adapt-indentation (org-fixup-indentation diff))))
4781 (defun org-map-tree (fun)
4782 "Call FUN for every heading underneath the current one."
4783 (org-back-to-heading)
4784 (let ((level (funcall outline-level)))
4785 (save-excursion
4786 (funcall fun)
4787 (while (and (progn
4788 (outline-next-heading)
4789 (> (funcall outline-level) level))
4790 (not (eobp)))
4791 (funcall fun)))))
4793 (defun org-map-region (fun beg end)
4794 "Call FUN for every heading between BEG and END."
4795 (let ((org-ignore-region t))
4796 (save-excursion
4797 (setq end (copy-marker end))
4798 (goto-char beg)
4799 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4800 (< (point) end))
4801 (funcall fun))
4802 (while (and (progn
4803 (outline-next-heading)
4804 (< (point) end))
4805 (not (eobp)))
4806 (funcall fun)))))
4808 (defun org-fixup-indentation (diff)
4809 "Change the indentation in the current entry by DIFF
4810 However, if any line in the current entry has no indentation, or if it
4811 would end up with no indentation after the change, nothing at all is done."
4812 (save-excursion
4813 (let ((end (save-excursion (outline-next-heading)
4814 (point-marker)))
4815 (prohibit (if (> diff 0)
4816 "^\\S-"
4817 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4818 col)
4819 (unless (save-excursion (end-of-line 1)
4820 (re-search-forward prohibit end t))
4821 (while (and (< (point) end)
4822 (re-search-forward "^[ \t]+" end t))
4823 (goto-char (match-end 0))
4824 (setq col (current-column))
4825 (if (< diff 0) (replace-match ""))
4826 (indent-to (+ diff col))))
4827 (move-marker end nil))))
4829 (defun org-convert-to-odd-levels ()
4830 "Convert an org-mode file with all levels allowed to one with odd levels.
4831 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4832 level 5 etc."
4833 (interactive)
4834 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4835 (let ((org-odd-levels-only nil) n)
4836 (save-excursion
4837 (goto-char (point-min))
4838 (while (re-search-forward "^\\*\\*+ " nil t)
4839 (setq n (- (length (match-string 0)) 2))
4840 (while (>= (setq n (1- n)) 0)
4841 (org-demote))
4842 (end-of-line 1))))))
4845 (defun org-convert-to-oddeven-levels ()
4846 "Convert an org-mode file with only odd levels to one with odd and even levels.
4847 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4848 section with an even level, conversion would destroy the structure of the file. An error
4849 is signaled in this case."
4850 (interactive)
4851 (goto-char (point-min))
4852 ;; First check if there are no even levels
4853 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4854 (org-show-context t)
4855 (error "Not all levels are odd in this file. Conversion not possible."))
4856 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4857 (let ((org-odd-levels-only nil) n)
4858 (save-excursion
4859 (goto-char (point-min))
4860 (while (re-search-forward "^\\*\\*+ " nil t)
4861 (setq n (/ (1- (length (match-string 0))) 2))
4862 (while (>= (setq n (1- n)) 0)
4863 (org-promote))
4864 (end-of-line 1))))))
4866 (defun org-tr-level (n)
4867 "Make N odd if required."
4868 (if org-odd-levels-only (1+ (/ n 2)) n))
4870 ;;; Vertical tree motion, cutting and pasting of subtrees
4872 (defun org-move-subtree-up (&optional arg)
4873 "Move the current subtree up past ARG headlines of the same level."
4874 (interactive "p")
4875 (org-move-subtree-down (- (prefix-numeric-value arg))))
4877 (defun org-move-subtree-down (&optional arg)
4878 "Move the current subtree down past ARG headlines of the same level."
4879 (interactive "p")
4880 (setq arg (prefix-numeric-value arg))
4881 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4882 'outline-get-last-sibling))
4883 (ins-point (make-marker))
4884 (cnt (abs arg))
4885 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4886 ;; Select the tree
4887 (org-back-to-heading)
4888 (setq beg0 (point))
4889 (save-excursion
4890 (setq ne-beg (org-back-over-empty-lines))
4891 (setq beg (point)))
4892 (save-match-data
4893 (save-excursion (outline-end-of-heading)
4894 (setq folded (org-invisible-p)))
4895 (outline-end-of-subtree))
4896 (outline-next-heading)
4897 (setq ne-end (org-back-over-empty-lines))
4898 (setq end (point))
4899 (goto-char beg0)
4900 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4901 ;; include less whitespace
4902 (save-excursion
4903 (goto-char beg)
4904 (forward-line (- ne-beg ne-end))
4905 (setq beg (point))))
4906 ;; Find insertion point, with error handling
4907 (while (> cnt 0)
4908 (or (and (funcall movfunc) (looking-at outline-regexp))
4909 (progn (goto-char beg0)
4910 (error "Cannot move past superior level or buffer limit")))
4911 (setq cnt (1- cnt)))
4912 (if (> arg 0)
4913 ;; Moving forward - still need to move over subtree
4914 (progn (org-end-of-subtree t t)
4915 (save-excursion
4916 (org-back-over-empty-lines)
4917 (or (bolp) (newline)))))
4918 (setq ne-ins (org-back-over-empty-lines))
4919 (move-marker ins-point (point))
4920 (setq txt (buffer-substring beg end))
4921 (org-save-markers-in-region beg end)
4922 (delete-region beg end)
4923 (outline-flag-region (1- beg) beg nil)
4924 (outline-flag-region (1- (point)) (point) nil)
4925 (let ((bbb (point)))
4926 (insert-before-markers txt)
4927 (org-reinstall-markers-in-region bbb)
4928 (move-marker ins-point bbb))
4929 (or (bolp) (insert "\n"))
4930 (setq ins-end (point))
4931 (goto-char ins-point)
4932 (org-skip-whitespace)
4933 (when (and (< arg 0)
4934 (org-first-sibling-p)
4935 (> ne-ins ne-beg))
4936 ;; Move whitespace back to beginning
4937 (save-excursion
4938 (goto-char ins-end)
4939 (let ((kill-whole-line t))
4940 (kill-line (- ne-ins ne-beg)) (point)))
4941 (insert (make-string (- ne-ins ne-beg) ?\n)))
4942 (move-marker ins-point nil)
4943 (org-compact-display-after-subtree-move)
4944 (org-show-empty-lines-in-parent)
4945 (unless folded
4946 (org-show-entry)
4947 (show-children)
4948 (org-cycle-hide-drawers 'children))))
4950 (defvar org-subtree-clip ""
4951 "Clipboard for cut and paste of subtrees.
4952 This is actually only a copy of the kill, because we use the normal kill
4953 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4955 (defvar org-subtree-clip-folded nil
4956 "Was the last copied subtree folded?
4957 This is used to fold the tree back after pasting.")
4959 (defun org-cut-subtree (&optional n)
4960 "Cut the current subtree into the clipboard.
4961 With prefix arg N, cut this many sequential subtrees.
4962 This is a short-hand for marking the subtree and then cutting it."
4963 (interactive "p")
4964 (org-copy-subtree n 'cut))
4966 (defun org-copy-subtree (&optional n cut force-store-markers)
4967 "Cut the current subtree into the clipboard.
4968 With prefix arg N, cut this many sequential subtrees.
4969 This is a short-hand for marking the subtree and then copying it.
4970 If CUT is non-nil, actually cut the subtree.
4971 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4972 of some markers in the region, even if CUT is non-nil. This is
4973 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4974 (interactive "p")
4975 (let (beg end folded (beg0 (point)))
4976 (if (interactive-p)
4977 (org-back-to-heading nil) ; take what looks like a subtree
4978 (org-back-to-heading t)) ; take what is really there
4979 (org-back-over-empty-lines)
4980 (setq beg (point))
4981 (skip-chars-forward " \t\r\n")
4982 (save-match-data
4983 (save-excursion (outline-end-of-heading)
4984 (setq folded (org-invisible-p)))
4985 (condition-case nil
4986 (outline-forward-same-level (1- n))
4987 (error nil))
4988 (org-end-of-subtree t t))
4989 (org-back-over-empty-lines)
4990 (setq end (point))
4991 (goto-char beg0)
4992 (when (> end beg)
4993 (setq org-subtree-clip-folded folded)
4994 (when (or cut force-store-markers)
4995 (org-save-markers-in-region beg end))
4996 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4997 (setq org-subtree-clip (current-kill 0))
4998 (message "%s: Subtree(s) with %d characters"
4999 (if cut "Cut" "Copied")
5000 (length org-subtree-clip)))))
5002 (defun org-paste-subtree (&optional level tree)
5003 "Paste the clipboard as a subtree, with modification of headline level.
5004 The entire subtree is promoted or demoted in order to match a new headline
5005 level. By default, the new level is derived from the visible headings
5006 before and after the insertion point, and taken to be the inferior headline
5007 level of the two. So if the previous visible heading is level 3 and the
5008 next is level 4 (or vice versa), level 4 will be used for insertion.
5009 This makes sure that the subtree remains an independent subtree and does
5010 not swallow low level entries.
5012 You can also force a different level, either by using a numeric prefix
5013 argument, or by inserting the heading marker by hand. For example, if the
5014 cursor is after \"*****\", then the tree will be shifted to level 5.
5016 If you want to insert the tree as is, just use \\[yank].
5018 If optional TREE is given, use this text instead of the kill ring."
5019 (interactive "P")
5020 (unless (org-kill-is-subtree-p tree)
5021 (error "%s"
5022 (substitute-command-keys
5023 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5024 (let* ((visp (not (org-invisible-p)))
5025 (txt (or tree (and kill-ring (current-kill 0))))
5026 (^re (concat "^\\(" outline-regexp "\\)"))
5027 (re (concat "\\(" outline-regexp "\\)"))
5028 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5030 (old-level (if (string-match ^re txt)
5031 (- (match-end 0) (match-beginning 0) 1)
5032 -1))
5033 (force-level (cond (level (prefix-numeric-value level))
5034 ((string-match
5035 ^re_ (buffer-substring (point-at-bol) (point)))
5036 (- (match-end 1) (match-beginning 1)))
5037 (t nil)))
5038 (previous-level (save-excursion
5039 (condition-case nil
5040 (progn
5041 (outline-previous-visible-heading 1)
5042 (if (looking-at re)
5043 (- (match-end 0) (match-beginning 0) 1)
5045 (error 1))))
5046 (next-level (save-excursion
5047 (condition-case nil
5048 (progn
5049 (or (looking-at outline-regexp)
5050 (outline-next-visible-heading 1))
5051 (if (looking-at re)
5052 (- (match-end 0) (match-beginning 0) 1)
5054 (error 1))))
5055 (new-level (or force-level (max previous-level next-level)))
5056 (shift (if (or (= old-level -1)
5057 (= new-level -1)
5058 (= old-level new-level))
5060 (- new-level old-level)))
5061 (delta (if (> shift 0) -1 1))
5062 (func (if (> shift 0) 'org-demote 'org-promote))
5063 (org-odd-levels-only nil)
5064 beg end)
5065 ;; Remove the forced level indicator
5066 (if force-level
5067 (delete-region (point-at-bol) (point)))
5068 ;; Paste
5069 (beginning-of-line 1)
5070 (org-back-over-empty-lines)
5071 (setq beg (point))
5072 (insert-before-markers txt)
5073 (unless (string-match "\n\\'" txt) (insert "\n"))
5074 (org-reinstall-markers-in-region beg)
5075 (setq end (point))
5076 (goto-char beg)
5077 (skip-chars-forward " \t\n\r")
5078 (setq beg (point))
5079 (if (and (org-invisible-p) visp)
5080 (save-excursion (outline-show-heading)))
5081 ;; Shift if necessary
5082 (unless (= shift 0)
5083 (save-restriction
5084 (narrow-to-region beg end)
5085 (while (not (= shift 0))
5086 (org-map-region func (point-min) (point-max))
5087 (setq shift (+ delta shift)))
5088 (goto-char (point-min))))
5089 (when (interactive-p)
5090 (message "Clipboard pasted as level %d subtree" new-level))
5091 (if (and kill-ring
5092 (eq org-subtree-clip (current-kill 0))
5093 org-subtree-clip-folded)
5094 ;; The tree was folded before it was killed/copied
5095 (hide-subtree))))
5097 (defun org-kill-is-subtree-p (&optional txt)
5098 "Check if the current kill is an outline subtree, or a set of trees.
5099 Returns nil if kill does not start with a headline, or if the first
5100 headline level is not the largest headline level in the tree.
5101 So this will actually accept several entries of equal levels as well,
5102 which is OK for `org-paste-subtree'.
5103 If optional TXT is given, check this string instead of the current kill."
5104 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5105 (start-level (and kill
5106 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5107 org-outline-regexp "\\)")
5108 kill)
5109 (- (match-end 2) (match-beginning 2) 1)))
5110 (re (concat "^" org-outline-regexp))
5111 (start (1+ (match-beginning 2))))
5112 (if (not start-level)
5113 (progn
5114 nil) ;; does not even start with a heading
5115 (catch 'exit
5116 (while (setq start (string-match re kill (1+ start)))
5117 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5118 (throw 'exit nil)))
5119 t))))
5121 (defvar org-markers-to-move nil
5122 "Markers that should be moved with a cut-and-paste operation.
5123 Those markers are stored together with their positions relative to
5124 the start of the region.")
5126 (defun org-save-markers-in-region (beg end)
5127 "Check markers in region.
5128 If these markers are between BEG and END, record their position relative
5129 to BEG, so that after moving the block of text, we can put the markers back
5130 into place.
5131 This function gets called just before an entry or tree gets cut from the
5132 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5133 called immediately, to move the markers with the entries."
5134 (setq org-markers-to-move nil)
5135 (when (featurep 'org-clock)
5136 (org-clock-save-markers-for-cut-and-paste beg end))
5137 (when (featurep 'org-agenda)
5138 (org-agenda-save-markers-for-cut-and-paste beg end)))
5140 (defun org-check-and-save-marker (marker beg end)
5141 "Check if MARKER is between BEG and END.
5142 If yes, remember the marker and the distance to BEG."
5143 (when (and (marker-buffer marker)
5144 (equal (marker-buffer marker) (current-buffer)))
5145 (if (and (>= marker beg) (< marker end))
5146 (push (cons marker (- marker beg)) org-markers-to-move))))
5148 (defun org-reinstall-markers-in-region (beg)
5149 "Move all remembered markers to their position relative to BEG."
5150 (mapc (lambda (x)
5151 (move-marker (car x) (+ beg (cdr x))))
5152 org-markers-to-move)
5153 (setq org-markers-to-move nil))
5155 (defun org-narrow-to-subtree ()
5156 "Narrow buffer to the current subtree."
5157 (interactive)
5158 (save-excursion
5159 (save-match-data
5160 (narrow-to-region
5161 (progn (org-back-to-heading) (point))
5162 (progn (org-end-of-subtree t) (point))))))
5165 ;;; Outline Sorting
5167 (defun org-sort (with-case)
5168 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5169 Optional argument WITH-CASE means sort case-sensitively."
5170 (interactive "P")
5171 (if (org-at-table-p)
5172 (org-call-with-arg 'org-table-sort-lines with-case)
5173 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5175 (defun org-sort-remove-invisible (s)
5176 (remove-text-properties 0 (length s) org-rm-props s)
5177 (while (string-match org-bracket-link-regexp s)
5178 (setq s (replace-match (if (match-end 2)
5179 (match-string 3 s)
5180 (match-string 1 s)) t t s)))
5183 (defvar org-priority-regexp) ; defined later in the file
5185 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5186 "Sort entries on a certain level of an outline tree.
5187 If there is an active region, the entries in the region are sorted.
5188 Else, if the cursor is before the first entry, sort the top-level items.
5189 Else, the children of the entry at point are sorted.
5191 Sorting can be alphabetically, numerically, and by date/time as given by
5192 the first time stamp in the entry. The command prompts for the sorting
5193 type unless it has been given to the function through the SORTING-TYPE
5194 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5195 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5196 called with point at the beginning of the record. It must return either
5197 a string or a number that should serve as the sorting key for that record.
5199 Comparing entries ignores case by default. However, with an optional argument
5200 WITH-CASE, the sorting considers case as well."
5201 (interactive "P")
5202 (let ((case-func (if with-case 'identity 'downcase))
5203 start beg end stars re re2
5204 txt what tmp plain-list-p)
5205 ;; Find beginning and end of region to sort
5206 (cond
5207 ((org-region-active-p)
5208 ;; we will sort the region
5209 (setq end (region-end)
5210 what "region")
5211 (goto-char (region-beginning))
5212 (if (not (org-on-heading-p)) (outline-next-heading))
5213 (setq start (point)))
5214 ((org-at-item-p)
5215 ;; we will sort this plain list
5216 (org-beginning-of-item-list) (setq start (point))
5217 (org-end-of-item-list) (setq end (point))
5218 (goto-char start)
5219 (setq plain-list-p t
5220 what "plain list"))
5221 ((or (org-on-heading-p)
5222 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5223 ;; we will sort the children of the current headline
5224 (org-back-to-heading)
5225 (setq start (point)
5226 end (progn (org-end-of-subtree t t)
5227 (org-back-over-empty-lines)
5228 (point))
5229 what "children")
5230 (goto-char start)
5231 (show-subtree)
5232 (outline-next-heading))
5234 ;; we will sort the top-level entries in this file
5235 (goto-char (point-min))
5236 (or (org-on-heading-p) (outline-next-heading))
5237 (setq start (point) end (point-max) what "top-level")
5238 (goto-char start)
5239 (show-all)))
5241 (setq beg (point))
5242 (if (>= beg end) (error "Nothing to sort"))
5244 (unless plain-list-p
5245 (looking-at "\\(\\*+\\)")
5246 (setq stars (match-string 1)
5247 re (concat "^" (regexp-quote stars) " +")
5248 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5249 txt (buffer-substring beg end))
5250 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5251 (if (and (not (equal stars "*")) (string-match re2 txt))
5252 (error "Region to sort contains a level above the first entry")))
5254 (unless sorting-type
5255 (message
5256 (if plain-list-p
5257 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5258 "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:")
5259 what)
5260 (setq sorting-type (read-char-exclusive))
5262 (and (= (downcase sorting-type) ?f)
5263 (setq getkey-func
5264 (completing-read "Sort using function: "
5265 obarray 'fboundp t nil nil))
5266 (setq getkey-func (intern getkey-func)))
5268 (and (= (downcase sorting-type) ?r)
5269 (setq property
5270 (completing-read "Property: "
5271 (mapcar 'list (org-buffer-property-keys t))
5272 nil t))))
5274 (message "Sorting entries...")
5276 (save-restriction
5277 (narrow-to-region start end)
5279 (let ((dcst (downcase sorting-type))
5280 (now (current-time)))
5281 (sort-subr
5282 (/= dcst sorting-type)
5283 ;; This function moves to the beginning character of the "record" to
5284 ;; be sorted.
5285 (if plain-list-p
5286 (lambda nil
5287 (if (org-at-item-p) t (goto-char (point-max))))
5288 (lambda nil
5289 (if (re-search-forward re nil t)
5290 (goto-char (match-beginning 0))
5291 (goto-char (point-max)))))
5292 ;; This function moves to the last character of the "record" being
5293 ;; sorted.
5294 (if plain-list-p
5295 'org-end-of-item
5296 (lambda nil
5297 (save-match-data
5298 (condition-case nil
5299 (outline-forward-same-level 1)
5300 (error
5301 (goto-char (point-max)))))))
5303 ;; This function returns the value that gets sorted against.
5304 (if plain-list-p
5305 (lambda nil
5306 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5307 (cond
5308 ((= dcst ?n)
5309 (string-to-number (buffer-substring (match-end 0)
5310 (point-at-eol))))
5311 ((= dcst ?a)
5312 (buffer-substring (match-end 0) (point-at-eol)))
5313 ((= dcst ?t)
5314 (if (re-search-forward org-ts-regexp
5315 (point-at-eol) t)
5316 (org-time-string-to-time (match-string 0))
5317 now))
5318 ((= dcst ?f)
5319 (if getkey-func
5320 (progn
5321 (setq tmp (funcall getkey-func))
5322 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5323 tmp)
5324 (error "Invalid key function `%s'" getkey-func)))
5325 (t (error "Invalid sorting type `%c'" sorting-type)))))
5326 (lambda nil
5327 (cond
5328 ((= dcst ?n)
5329 (if (looking-at org-complex-heading-regexp)
5330 (string-to-number (match-string 4))
5331 nil))
5332 ((= dcst ?a)
5333 (if (looking-at org-complex-heading-regexp)
5334 (funcall case-func (match-string 4))
5335 nil))
5336 ((= dcst ?t)
5337 (if (re-search-forward org-ts-regexp
5338 (save-excursion
5339 (forward-line 2)
5340 (point)) t)
5341 (org-time-string-to-time (match-string 0))
5342 now))
5343 ((= dcst ?p)
5344 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5345 (string-to-char (match-string 2))
5346 org-default-priority))
5347 ((= dcst ?r)
5348 (or (org-entry-get nil property) ""))
5349 ((= dcst ?o)
5350 (if (looking-at org-complex-heading-regexp)
5351 (- 9999 (length (member (match-string 2)
5352 org-todo-keywords-1)))))
5353 ((= dcst ?f)
5354 (if getkey-func
5355 (progn
5356 (setq tmp (funcall getkey-func))
5357 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5358 tmp)
5359 (error "Invalid key function `%s'" getkey-func)))
5360 (t (error "Invalid sorting type `%c'" sorting-type)))))
5362 (cond
5363 ((= dcst ?a) 'string<)
5364 ((= dcst ?t) 'time-less-p)
5365 (t nil)))))
5366 (message "Sorting entries...done")))
5368 (defun org-do-sort (table what &optional with-case sorting-type)
5369 "Sort TABLE of WHAT according to SORTING-TYPE.
5370 The user will be prompted for the SORTING-TYPE if the call to this
5371 function does not specify it. WHAT is only for the prompt, to indicate
5372 what is being sorted. The sorting key will be extracted from
5373 the car of the elements of the table.
5374 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5375 (unless sorting-type
5376 (message
5377 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5378 what)
5379 (setq sorting-type (read-char-exclusive)))
5380 (let ((dcst (downcase sorting-type))
5381 extractfun comparefun)
5382 ;; Define the appropriate functions
5383 (cond
5384 ((= dcst ?n)
5385 (setq extractfun 'string-to-number
5386 comparefun (if (= dcst sorting-type) '< '>)))
5387 ((= dcst ?a)
5388 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5389 (lambda(x) (downcase (org-sort-remove-invisible x))))
5390 comparefun (if (= dcst sorting-type)
5391 'string<
5392 (lambda (a b) (and (not (string< a b))
5393 (not (string= a b)))))))
5394 ((= dcst ?t)
5395 (setq extractfun
5396 (lambda (x)
5397 (if (string-match org-ts-regexp x)
5398 (time-to-seconds
5399 (org-time-string-to-time (match-string 0 x)))
5401 comparefun (if (= dcst sorting-type) '< '>)))
5402 (t (error "Invalid sorting type `%c'" sorting-type)))
5404 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5405 table)
5406 (lambda (a b) (funcall comparefun (car a) (car b))))))
5408 ;;; Editing source examples
5410 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5411 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5412 (defvar org-edit-src-force-single-line nil)
5413 (defvar org-edit-src-from-org-mode nil)
5414 (defvar org-edit-src-picture nil)
5416 (define-minor-mode org-exit-edit-mode
5417 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5419 (defun org-edit-src-code ()
5420 "Edit the source code example at point.
5421 An indirect buffer is created, and that buffer is then narrowed to the
5422 example at point and switched to the correct language mode. When done,
5423 exit by killing the buffer with \\[org-edit-src-exit]."
5424 (interactive)
5425 (let ((line (org-current-line))
5426 (case-fold-search t)
5427 (msg (substitute-command-keys
5428 "Edit, then exit with C-c ' (C-c and single quote)"))
5429 (info (org-edit-src-find-region-and-lang))
5430 (org-mode-p (eq major-mode 'org-mode))
5431 beg end lang lang-f single)
5432 (if (not info)
5434 (setq beg (nth 0 info)
5435 end (nth 1 info)
5436 lang (nth 2 info)
5437 single (nth 3 info)
5438 lang-f (intern (concat lang "-mode")))
5439 (unless (functionp lang-f)
5440 (error "No such language mode: %s" lang-f))
5441 (goto-line line)
5442 (if (get-buffer "*Org Edit Src Example*")
5443 (kill-buffer "*Org Edit Src Example*"))
5444 (switch-to-buffer (make-indirect-buffer (current-buffer)
5445 "*Org Edit Src Example*"))
5446 (narrow-to-region beg end)
5447 (remove-text-properties beg end '(display nil invisible nil
5448 intangible nil))
5449 (let ((org-inhibit-startup t))
5450 (funcall lang-f))
5451 (set (make-local-variable 'org-edit-src-force-single-line) single)
5452 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5453 (when org-mode-p
5454 (goto-char (point-min))
5455 (while (re-search-forward "^," nil t)
5456 (replace-match "")))
5457 (goto-line line)
5458 (org-exit-edit-mode)
5459 (org-set-local 'header-line-format msg)
5460 (message "%s" msg)
5461 t)))
5463 (defun org-edit-fixed-width-region ()
5464 "Edit the fixed-width ascii drawing at point.
5465 This must be a region where each line starts with ca colon followed by
5466 a space character.
5467 An indirect buffer is created, and that buffer is then narrowed to the
5468 example at point and switched to artist-mode. When done,
5469 exit by killing the buffer with \\[org-edit-src-exit]."
5470 (interactive)
5471 (let ((line (org-current-line))
5472 (case-fold-search t)
5473 (msg (substitute-command-keys
5474 "Edit, then exit with C-c ' (C-c and single quote)"))
5475 (org-mode-p (eq major-mode 'org-mode))
5476 beg end lang lang-f)
5477 (beginning-of-line 1)
5478 (if (looking-at "[ \t]*[^:\n \t]")
5480 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5481 (setq beg (point) end (match-end 0))
5482 (save-excursion
5483 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5484 (setq beg (point-at-bol 2))
5485 (setq beg (point))))
5486 (save-excursion
5487 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5488 (setq end (match-beginning 0))
5489 (setq end (point))))
5490 (goto-line line)
5491 (if (get-buffer "*Org Edit Picture*")
5492 (kill-buffer "*Org Edit Picture*"))
5493 (switch-to-buffer (make-indirect-buffer (current-buffer)
5494 "*Org Edit Picture*"))
5495 (narrow-to-region beg end)
5496 (remove-text-properties beg end '(display nil invisible nil
5497 intangible nil))
5498 (when (fboundp 'font-lock-unfontify-region)
5499 (font-lock-unfontify-region (point-min) (point-max)))
5500 (cond
5501 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5502 (fundamental-mode)
5503 (artist-mode 1))
5504 (t (funcall org-edit-fixed-width-region-mode)))
5505 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5506 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5507 (set (make-local-variable 'org-edit-src-picture) t)
5508 (goto-char (point-min))
5509 (while (re-search-forward "^[ \t]*: " nil t)
5510 (replace-match ""))
5511 (goto-line line)
5512 (org-exit-edit-mode)
5513 (org-set-local 'header-line-format msg)
5514 (message "%s" msg)
5515 t))))
5517 (defun org-edit-src-find-region-and-lang ()
5518 "Find the region and language for a local edit.
5519 Return a list with beginning and end of the region, a string representing
5520 the language, a switch telling of the content should be in a single line."
5521 (let ((re-list
5523 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5524 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5525 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5526 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5527 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5528 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5529 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5530 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5531 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5532 ("^#\\+html:" "\n" "html" single-line)
5533 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5534 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5535 ("^#\\+latex:" "\n" "latex" single-line)
5536 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5537 ("^#\\+ascii:" "\n" "ascii" single-line)
5539 (pos (point))
5540 re re1 re2 single beg end lang)
5541 (catch 'exit
5542 (while (setq entry (pop re-list))
5543 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5544 single (nth 3 entry))
5545 (save-excursion
5546 (if (or (looking-at re1)
5547 (re-search-backward re1 nil t))
5548 (progn
5549 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5550 (if (and (re-search-forward re2 nil t)
5551 (>= (match-end 0) pos))
5552 (throw 'exit (list beg (match-beginning 0) lang single))))
5553 (if (or (looking-at re2)
5554 (re-search-forward re2 nil t))
5555 (progn
5556 (setq end (match-beginning 0))
5557 (if (and (re-search-backward re1 nil t)
5558 (<= (match-beginning 0) pos))
5559 (throw 'exit
5560 (list (match-end 0) end
5561 (org-edit-src-get-lang lang) single)))))))))))
5563 (defun org-edit-src-get-lang (lang)
5564 "Extract the src language."
5565 (let ((m (match-string 0)))
5566 (cond
5567 ((stringp lang) lang)
5568 ((integerp lang) (match-string lang))
5569 ((and (eq lang lang)
5570 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5571 (match-string 1 m))
5572 ((and (eq lang lang)
5573 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5574 (match-string 1 m))
5575 (t "fundamental"))))
5577 (defun org-edit-src-exit ()
5578 "Exit special edit and protect problematic lines."
5579 (interactive)
5580 (unless (buffer-base-buffer (current-buffer))
5581 (error "This is not an indirect buffer, something is wrong..."))
5582 (unless (> (point-min) 1)
5583 (error "This buffer is not narrowed, something is wrong..."))
5584 (goto-char (point-min))
5585 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5586 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5587 (when (org-bound-and-true-p org-edit-src-force-single-line)
5588 (goto-char (point-min))
5589 (while (re-search-forward "\n" nil t)
5590 (replace-match " "))
5591 (goto-char (point-min))
5592 (if (looking-at "\\s-*") (replace-match " "))
5593 (if (re-search-forward "\\s-+\\'" nil t)
5594 (replace-match "")))
5595 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5596 (goto-char (point-min))
5597 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5598 (replace-match ",\\1"))
5599 (when font-lock-mode
5600 (font-lock-unfontify-region (point-min) (point-max)))
5601 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5602 (when (org-bound-and-true-p org-edit-src-picture)
5603 (goto-char (point-min))
5604 (while (re-search-forward "^" nil t)
5605 (replace-match ": "))
5606 (when font-lock-mode
5607 (font-lock-unfontify-region (point-min) (point-max)))
5608 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5609 (kill-buffer (current-buffer))
5610 (and (org-mode-p) (org-restart-font-lock)))
5612 ;;;; Plain list items, including checkboxes
5614 ;;; Plain list items
5616 (defun org-at-item-p ()
5617 "Is point in a line starting a hand-formatted item?"
5618 (let ((llt org-plain-list-ordered-item-terminator))
5619 (save-excursion
5620 (goto-char (point-at-bol))
5621 (looking-at
5622 (cond
5623 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5624 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5625 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5626 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5628 (defun org-in-item-p ()
5629 "It the cursor inside a plain list item.
5630 Does not have to be the first line."
5631 (save-excursion
5632 (condition-case nil
5633 (progn
5634 (org-beginning-of-item)
5635 (org-at-item-p)
5637 (error nil))))
5639 (defun org-insert-item (&optional checkbox)
5640 "Insert a new item at the current level.
5641 Return t when things worked, nil when we are not in an item."
5642 (when (save-excursion
5643 (condition-case nil
5644 (progn
5645 (org-beginning-of-item)
5646 (org-at-item-p)
5647 (if (org-invisible-p) (error "Invisible item"))
5649 (error nil)))
5650 (let* ((bul (match-string 0))
5651 (descp (save-excursion (goto-char (match-beginning 0))
5652 (beginning-of-line 1)
5653 (save-match-data
5654 (looking-at "[ \t]*.*? ::"))))
5655 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5656 (match-end 0)))
5657 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5658 pos)
5659 (if descp (setq checkbox nil))
5660 (cond
5661 ((and (org-at-item-p) (<= (point) eow))
5662 ;; before the bullet
5663 (beginning-of-line 1)
5664 (open-line (if blank 2 1)))
5665 ((<= (point) eow)
5666 (beginning-of-line 1))
5668 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5669 (end-of-line 1)
5670 (delete-horizontal-space))
5671 (newline (if blank 2 1))))
5672 (insert bul
5673 (if checkbox "[ ]" "")
5674 (if descp (concat (if checkbox " " "")
5675 (read-string "Term: ") " :: ") ""))
5676 (just-one-space)
5677 (setq pos (point))
5678 (end-of-line 1)
5679 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5680 (org-maybe-renumber-ordered-list)
5681 (and checkbox (org-update-checkbox-count-maybe))
5684 ;;; Checkboxes
5686 (defun org-at-item-checkbox-p ()
5687 "Is point at a line starting a plain-list item with a checklet?"
5688 (and (org-at-item-p)
5689 (save-excursion
5690 (goto-char (match-end 0))
5691 (skip-chars-forward " \t")
5692 (looking-at "\\[[- X]\\]"))))
5694 (defun org-toggle-checkbox (&optional arg)
5695 "Toggle the checkbox in the current line."
5696 (interactive "P")
5697 (catch 'exit
5698 (let (beg end status (firstnew 'unknown))
5699 (cond
5700 ((org-region-active-p)
5701 (setq beg (region-beginning) end (region-end)))
5702 ((org-on-heading-p)
5703 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5704 ((org-at-item-checkbox-p)
5705 (let ((pos (point)))
5706 (replace-match
5707 (cond (arg "[-]")
5708 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5709 (t "[ ]"))
5710 t t)
5711 (goto-char pos))
5712 (throw 'exit t))
5713 (t (error "Not at a checkbox or heading, and no active region")))
5714 (save-excursion
5715 (goto-char beg)
5716 (while (< (point) end)
5717 (when (org-at-item-checkbox-p)
5718 (setq status (equal (match-string 0) "[X]"))
5719 (when (eq firstnew 'unknown)
5720 (setq firstnew (not status)))
5721 (replace-match
5722 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5723 (beginning-of-line 2)))))
5724 (org-update-checkbox-count-maybe))
5726 (defun org-update-checkbox-count-maybe ()
5727 "Update checkbox statistics unless turned off by user."
5728 (when org-provide-checkbox-statistics
5729 (org-update-checkbox-count)))
5731 (defun org-update-checkbox-count (&optional all)
5732 "Update the checkbox statistics in the current section.
5733 This will find all statistic cookies like [57%] and [6/12] and update them
5734 with the current numbers. With optional prefix argument ALL, do this for
5735 the whole buffer."
5736 (interactive "P")
5737 (save-excursion
5738 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5739 (beg (condition-case nil
5740 (progn (outline-back-to-heading) (point))
5741 (error (point-min))))
5742 (end (move-marker (make-marker)
5743 (progn (outline-next-heading) (point))))
5744 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5745 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5746 (re-find (concat re "\\|" re-box))
5747 beg-cookie end-cookie is-percent c-on c-off lim
5748 eline curr-ind next-ind continue-from startsearch
5749 (cstat 0)
5751 (when all
5752 (goto-char (point-min))
5753 (outline-next-heading)
5754 (setq beg (point) end (point-max)))
5755 (goto-char end)
5756 ;; find each statistic cookie
5757 (while (re-search-backward re-find beg t)
5758 (setq beg-cookie (match-beginning 1)
5759 end-cookie (match-end 1)
5760 cstat (+ cstat (if end-cookie 1 0))
5761 startsearch (point-at-eol)
5762 continue-from (point-at-bol)
5763 is-percent (match-beginning 2)
5764 lim (cond
5765 ((org-on-heading-p) (outline-next-heading) (point))
5766 ((org-at-item-p) (org-end-of-item) (point))
5767 (t nil))
5768 c-on 0
5769 c-off 0)
5770 (when lim
5771 ;; find first checkbox for this cookie and gather
5772 ;; statistics from all that are at this indentation level
5773 (goto-char startsearch)
5774 (if (re-search-forward re-box lim t)
5775 (progn
5776 (org-beginning-of-item)
5777 (setq curr-ind (org-get-indentation))
5778 (setq next-ind curr-ind)
5779 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5780 (save-excursion (end-of-line) (setq eline (point)))
5781 (if (re-search-forward re-box eline t)
5782 (if (member (match-string 2) '("[ ]" "[-]"))
5783 (setq c-off (1+ c-off))
5784 (setq c-on (1+ c-on))
5787 (org-end-of-item)
5788 (setq next-ind (org-get-indentation))
5790 (goto-char continue-from)
5791 ;; update cookie
5792 (when end-cookie
5793 (delete-region beg-cookie end-cookie)
5794 (goto-char beg-cookie)
5795 (insert
5796 (if is-percent
5797 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5798 (format "[%d/%d]" c-on (+ c-on c-off)))))
5799 ;; update items checkbox if it has one
5800 (when (org-at-item-p)
5801 (org-beginning-of-item)
5802 (when (and (> (+ c-on c-off) 0)
5803 (re-search-forward re-box (point-at-eol) t))
5804 (setq beg-cookie (match-beginning 2)
5805 end-cookie (match-end 2))
5806 (delete-region beg-cookie end-cookie)
5807 (goto-char beg-cookie)
5808 (cond ((= c-off 0) (insert "[X]"))
5809 ((= c-on 0) (insert "[ ]"))
5810 (t (insert "[-]")))
5812 (goto-char continue-from))
5813 (when (interactive-p)
5814 (message "Checkbox satistics updated %s (%d places)"
5815 (if all "in entire file" "in current outline entry") cstat)))))
5817 (defun org-get-checkbox-statistics-face ()
5818 "Select the face for checkbox statistics.
5819 The face will be `org-done' when all relevant boxes are checked. Otherwise
5820 it will be `org-todo'."
5821 (if (match-end 1)
5822 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5823 (if (and (> (match-end 2) (match-beginning 2))
5824 (equal (match-string 2) (match-string 3)))
5825 'org-done
5826 'org-todo)))
5828 (defun org-get-indentation (&optional line)
5829 "Get the indentation of the current line, interpreting tabs.
5830 When LINE is given, assume it represents a line and compute its indentation."
5831 (if line
5832 (if (string-match "^ *" (org-remove-tabs line))
5833 (match-end 0))
5834 (save-excursion
5835 (beginning-of-line 1)
5836 (skip-chars-forward " \t")
5837 (current-column))))
5839 (defun org-remove-tabs (s &optional width)
5840 "Replace tabulators in S with spaces.
5841 Assumes that s is a single line, starting in column 0."
5842 (setq width (or width tab-width))
5843 (while (string-match "\t" s)
5844 (setq s (replace-match
5845 (make-string
5846 (- (* width (/ (+ (match-beginning 0) width) width))
5847 (match-beginning 0)) ?\ )
5848 t t s)))
5851 (defun org-fix-indentation (line ind)
5852 "Fix indentation in LINE.
5853 IND is a cons cell with target and minimum indentation.
5854 If the current indenation in LINE is smaller than the minimum,
5855 leave it alone. If it is larger than ind, set it to the target."
5856 (let* ((l (org-remove-tabs line))
5857 (i (org-get-indentation l))
5858 (i1 (car ind)) (i2 (cdr ind)))
5859 (if (>= i i2) (setq l (substring line i2)))
5860 (if (> i1 0)
5861 (concat (make-string i1 ?\ ) l)
5862 l)))
5864 (defun org-beginning-of-item ()
5865 "Go to the beginning of the current hand-formatted item.
5866 If the cursor is not in an item, throw an error."
5867 (interactive)
5868 (let ((pos (point))
5869 (limit (save-excursion
5870 (condition-case nil
5871 (progn
5872 (org-back-to-heading)
5873 (beginning-of-line 2) (point))
5874 (error (point-min)))))
5875 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5876 ind ind1)
5877 (if (org-at-item-p)
5878 (beginning-of-line 1)
5879 (beginning-of-line 1)
5880 (skip-chars-forward " \t")
5881 (setq ind (current-column))
5882 (if (catch 'exit
5883 (while t
5884 (beginning-of-line 0)
5885 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5887 (if (looking-at "[ \t]*$")
5888 (setq ind1 ind-empty)
5889 (skip-chars-forward " \t")
5890 (setq ind1 (current-column)))
5891 (if (< ind1 ind)
5892 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5894 (goto-char pos)
5895 (error "Not in an item")))))
5897 (defun org-end-of-item ()
5898 "Go to the end of the current hand-formatted item.
5899 If the cursor is not in an item, throw an error."
5900 (interactive)
5901 (let* ((pos (point))
5902 ind1
5903 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5904 (limit (save-excursion (outline-next-heading) (point)))
5905 (ind (save-excursion
5906 (org-beginning-of-item)
5907 (skip-chars-forward " \t")
5908 (current-column)))
5909 (end (catch 'exit
5910 (while t
5911 (beginning-of-line 2)
5912 (if (eobp) (throw 'exit (point)))
5913 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5914 (if (looking-at "[ \t]*$")
5915 (setq ind1 ind-empty)
5916 (skip-chars-forward " \t")
5917 (setq ind1 (current-column)))
5918 (if (<= ind1 ind)
5919 (throw 'exit (point-at-bol)))))))
5920 (if end
5921 (goto-char end)
5922 (goto-char pos)
5923 (error "Not in an item"))))
5925 (defun org-next-item ()
5926 "Move to the beginning of the next item in the current plain list.
5927 Error if not at a plain list, or if this is the last item in the list."
5928 (interactive)
5929 (let (ind ind1 (pos (point)))
5930 (org-beginning-of-item)
5931 (setq ind (org-get-indentation))
5932 (org-end-of-item)
5933 (setq ind1 (org-get-indentation))
5934 (unless (and (org-at-item-p) (= ind ind1))
5935 (goto-char pos)
5936 (error "On last item"))))
5938 (defun org-previous-item ()
5939 "Move to the beginning of the previous item in the current plain list.
5940 Error if not at a plain list, or if this is the first item in the list."
5941 (interactive)
5942 (let (beg ind ind1 (pos (point)))
5943 (org-beginning-of-item)
5944 (setq beg (point))
5945 (setq ind (org-get-indentation))
5946 (goto-char beg)
5947 (catch 'exit
5948 (while t
5949 (beginning-of-line 0)
5950 (if (looking-at "[ \t]*$")
5952 (if (<= (setq ind1 (org-get-indentation)) ind)
5953 (throw 'exit t)))))
5954 (condition-case nil
5955 (if (or (not (org-at-item-p))
5956 (< ind1 (1- ind)))
5957 (error "")
5958 (org-beginning-of-item))
5959 (error (goto-char pos)
5960 (error "On first item")))))
5962 (defun org-first-list-item-p ()
5963 "Is this heading the item in a plain list?"
5964 (unless (org-at-item-p)
5965 (error "Not at a plain list item"))
5966 (org-beginning-of-item)
5967 (= (point) (save-excursion (org-beginning-of-item-list))))
5969 (defun org-move-item-down ()
5970 "Move the plain list item at point down, i.e. swap with following item.
5971 Subitems (items with larger indentation) are considered part of the item,
5972 so this really moves item trees."
5973 (interactive)
5974 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5975 (org-beginning-of-item)
5976 (setq beg0 (point))
5977 (save-excursion
5978 (setq ne-beg (org-back-over-empty-lines))
5979 (setq beg (point)))
5980 (goto-char beg0)
5981 (setq ind (org-get-indentation))
5982 (org-end-of-item)
5983 (setq end0 (point))
5984 (setq ind1 (org-get-indentation))
5985 (setq ne-end (org-back-over-empty-lines))
5986 (setq end (point))
5987 (goto-char beg0)
5988 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5989 ;; include less whitespace
5990 (save-excursion
5991 (goto-char beg)
5992 (forward-line (- ne-beg ne-end))
5993 (setq beg (point))))
5994 (goto-char end0)
5995 (if (and (org-at-item-p) (= ind ind1))
5996 (progn
5997 (org-end-of-item)
5998 (org-back-over-empty-lines)
5999 (setq txt (buffer-substring beg end))
6000 (save-excursion
6001 (delete-region beg end))
6002 (setq pos (point))
6003 (insert txt)
6004 (goto-char pos) (org-skip-whitespace)
6005 (org-maybe-renumber-ordered-list))
6006 (goto-char pos)
6007 (error "Cannot move this item further down"))))
6009 (defun org-move-item-up (arg)
6010 "Move the plain list item at point up, i.e. swap with previous item.
6011 Subitems (items with larger indentation) are considered part of the item,
6012 so this really moves item trees."
6013 (interactive "p")
6014 (let (beg beg0 end ind ind1 (pos (point)) txt
6015 ne-beg ne-ins ins-end)
6016 (org-beginning-of-item)
6017 (setq beg0 (point))
6018 (setq ind (org-get-indentation))
6019 (save-excursion
6020 (setq ne-beg (org-back-over-empty-lines))
6021 (setq beg (point)))
6022 (goto-char beg0)
6023 (org-end-of-item)
6024 (org-back-over-empty-lines)
6025 (setq end (point))
6026 (goto-char beg0)
6027 (catch 'exit
6028 (while t
6029 (beginning-of-line 0)
6030 (if (looking-at "[ \t]*$")
6031 (if org-empty-line-terminates-plain-lists
6032 (progn
6033 (goto-char pos)
6034 (error "Cannot move this item further up"))
6035 nil)
6036 (if (<= (setq ind1 (org-get-indentation)) ind)
6037 (throw 'exit t)))))
6038 (condition-case nil
6039 (org-beginning-of-item)
6040 (error (goto-char beg0)
6041 (error "Cannot move this item further up")))
6042 (setq ind1 (org-get-indentation))
6043 (if (and (org-at-item-p) (= ind ind1))
6044 (progn
6045 (setq ne-ins (org-back-over-empty-lines))
6046 (setq txt (buffer-substring beg end))
6047 (save-excursion
6048 (delete-region beg end))
6049 (setq pos (point))
6050 (insert txt)
6051 (setq ins-end (point))
6052 (goto-char pos) (org-skip-whitespace)
6054 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
6055 ;; Move whitespace back to beginning
6056 (save-excursion
6057 (goto-char ins-end)
6058 (let ((kill-whole-line t))
6059 (kill-line (- ne-ins ne-beg)) (point)))
6060 (insert (make-string (- ne-ins ne-beg) ?\n)))
6062 (org-maybe-renumber-ordered-list))
6063 (goto-char pos)
6064 (error "Cannot move this item further up"))))
6066 (defun org-maybe-renumber-ordered-list ()
6067 "Renumber the ordered list at point if setup allows it.
6068 This tests the user option `org-auto-renumber-ordered-lists' before
6069 doing the renumbering."
6070 (interactive)
6071 (when (and org-auto-renumber-ordered-lists
6072 (org-at-item-p))
6073 (if (match-beginning 3)
6074 (org-renumber-ordered-list 1)
6075 (org-fix-bullet-type))))
6077 (defun org-maybe-renumber-ordered-list-safe ()
6078 (condition-case nil
6079 (save-excursion
6080 (org-maybe-renumber-ordered-list))
6081 (error nil)))
6083 (defun org-cycle-list-bullet (&optional which)
6084 "Cycle through the different itemize/enumerate bullets.
6085 This cycle the entire list level through the sequence:
6087 `-' -> `+' -> `*' -> `1.' -> `1)'
6089 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6090 0 meand `-', 1 means `+' etc."
6091 (interactive "P")
6092 (org-preserve-lc
6093 (org-beginning-of-item-list)
6094 (org-at-item-p)
6095 (beginning-of-line 1)
6096 (let ((current (match-string 0))
6097 (prevp (eq which 'previous))
6098 new)
6099 (setq new (cond
6100 ((and (numberp which)
6101 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6102 ((string-match "-" current) (if prevp "1)" "+"))
6103 ((string-match "\\+" current)
6104 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6105 ((string-match "\\*" current) (if prevp "+" "1."))
6106 ((string-match "\\." current) (if prevp "*" "1)"))
6107 ((string-match ")" current) (if prevp "1." "-"))
6108 (t (error "This should not happen"))))
6109 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6110 (org-fix-bullet-type)
6111 (org-maybe-renumber-ordered-list))))
6113 (defun org-get-string-indentation (s)
6114 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6115 (let ((n -1) (i 0) (w tab-width) c)
6116 (catch 'exit
6117 (while (< (setq n (1+ n)) (length s))
6118 (setq c (aref s n))
6119 (cond ((= c ?\ ) (setq i (1+ i)))
6120 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6121 (t (throw 'exit t)))))
6124 (defun org-renumber-ordered-list (arg)
6125 "Renumber an ordered plain list.
6126 Cursor needs to be in the first line of an item, the line that starts
6127 with something like \"1.\" or \"2)\"."
6128 (interactive "p")
6129 (unless (and (org-at-item-p)
6130 (match-beginning 3))
6131 (error "This is not an ordered list"))
6132 (let ((line (org-current-line))
6133 (col (current-column))
6134 (ind (org-get-string-indentation
6135 (buffer-substring (point-at-bol) (match-beginning 3))))
6136 ;; (term (substring (match-string 3) -1))
6137 ind1 (n (1- arg))
6138 fmt bobp)
6139 ;; find where this list begins
6140 (org-beginning-of-item-list)
6141 (setq bobp (bobp))
6142 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6143 (setq fmt (concat "%d" (match-string 1)))
6144 (beginning-of-line 0)
6145 ;; walk forward and replace these numbers
6146 (catch 'exit
6147 (while t
6148 (catch 'next
6149 (if bobp (setq bobp nil) (beginning-of-line 2))
6150 (if (eobp) (throw 'exit nil))
6151 (if (looking-at "[ \t]*$") (throw 'next nil))
6152 (skip-chars-forward " \t") (setq ind1 (current-column))
6153 (if (> ind1 ind) (throw 'next t))
6154 (if (< ind1 ind) (throw 'exit t))
6155 (if (not (org-at-item-p)) (throw 'exit nil))
6156 (delete-region (match-beginning 2) (match-end 2))
6157 (goto-char (match-beginning 2))
6158 (insert (format fmt (setq n (1+ n)))))))
6159 (goto-line line)
6160 (org-move-to-column col)))
6162 (defun org-fix-bullet-type ()
6163 "Make sure all items in this list have the same bullet as the firsst item."
6164 (interactive)
6165 (unless (org-at-item-p) (error "This is not a list"))
6166 (let ((line (org-current-line))
6167 (col (current-column))
6168 (ind (current-indentation))
6169 ind1 bullet)
6170 ;; find where this list begins
6171 (org-beginning-of-item-list)
6172 (beginning-of-line 1)
6173 ;; find out what the bullet type is
6174 (looking-at "[ \t]*\\(\\S-+\\)")
6175 (setq bullet (match-string 1))
6176 ;; walk forward and replace these numbers
6177 (beginning-of-line 0)
6178 (catch 'exit
6179 (while t
6180 (catch 'next
6181 (beginning-of-line 2)
6182 (if (eobp) (throw 'exit nil))
6183 (if (looking-at "[ \t]*$") (throw 'next nil))
6184 (skip-chars-forward " \t") (setq ind1 (current-column))
6185 (if (> ind1 ind) (throw 'next t))
6186 (if (< ind1 ind) (throw 'exit t))
6187 (if (not (org-at-item-p)) (throw 'exit nil))
6188 (skip-chars-forward " \t")
6189 (looking-at "\\S-+")
6190 (replace-match bullet))))
6191 (goto-line line)
6192 (org-move-to-column col)
6193 (if (string-match "[0-9]" bullet)
6194 (org-renumber-ordered-list 1))))
6196 (defun org-beginning-of-item-list ()
6197 "Go to the beginning of the current item list.
6198 I.e. to the first item in this list."
6199 (interactive)
6200 (org-beginning-of-item)
6201 (let ((pos (point-at-bol))
6202 (ind (org-get-indentation))
6203 ind1)
6204 ;; find where this list begins
6205 (catch 'exit
6206 (while t
6207 (catch 'next
6208 (beginning-of-line 0)
6209 (if (looking-at "[ \t]*$")
6210 (throw (if (bobp) 'exit 'next) t))
6211 (skip-chars-forward " \t") (setq ind1 (current-column))
6212 (if (or (< ind1 ind)
6213 (and (= ind1 ind)
6214 (not (org-at-item-p)))
6215 (and (= (point-at-bol) (point-min))
6216 (setq pos (point-min))))
6217 (throw 'exit t)
6218 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6219 (goto-char pos)))
6222 (defun org-end-of-item-list ()
6223 "Go to the end of the current item list.
6224 I.e. to the text after the last item."
6225 (interactive)
6226 (org-beginning-of-item)
6227 (let ((pos (point-at-bol))
6228 (ind (org-get-indentation))
6229 ind1)
6230 ;; find where this list begins
6231 (catch 'exit
6232 (while t
6233 (catch 'next
6234 (beginning-of-line 2)
6235 (if (looking-at "[ \t]*$")
6236 (throw (if (eobp) 'exit 'next) t))
6237 (skip-chars-forward " \t") (setq ind1 (current-column))
6238 (if (or (< ind1 ind)
6239 (and (= ind1 ind)
6240 (not (org-at-item-p)))
6241 (eobp))
6242 (progn
6243 (setq pos (point-at-bol))
6244 (throw 'exit t))))))
6245 (goto-char pos)))
6248 (defvar org-last-indent-begin-marker (make-marker))
6249 (defvar org-last-indent-end-marker (make-marker))
6251 (defun org-outdent-item (arg)
6252 "Outdent a local list item."
6253 (interactive "p")
6254 (org-indent-item (- arg)))
6256 (defun org-indent-item (arg)
6257 "Indent a local list item."
6258 (interactive "p")
6259 (unless (org-at-item-p)
6260 (error "Not on an item"))
6261 (save-excursion
6262 (let (beg end ind ind1 tmp delta ind-down ind-up)
6263 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6264 (setq beg org-last-indent-begin-marker
6265 end org-last-indent-end-marker)
6266 (org-beginning-of-item)
6267 (setq beg (move-marker org-last-indent-begin-marker (point)))
6268 (org-end-of-item)
6269 (setq end (move-marker org-last-indent-end-marker (point))))
6270 (goto-char beg)
6271 (setq tmp (org-item-indent-positions)
6272 ind (car tmp)
6273 ind-down (nth 2 tmp)
6274 ind-up (nth 1 tmp)
6275 delta (if (> arg 0)
6276 (if ind-down (- ind-down ind) 2)
6277 (if ind-up (- ind-up ind) -2)))
6278 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6279 (while (< (point) end)
6280 (beginning-of-line 1)
6281 (skip-chars-forward " \t") (setq ind1 (current-column))
6282 (delete-region (point-at-bol) (point))
6283 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6284 (beginning-of-line 2))))
6285 (org-fix-bullet-type)
6286 (org-maybe-renumber-ordered-list-safe)
6287 (save-excursion
6288 (beginning-of-line 0)
6289 (condition-case nil (org-beginning-of-item) (error nil))
6290 (org-maybe-renumber-ordered-list-safe)))
6292 (defun org-item-indent-positions ()
6293 "Return indentation for plain list items.
6294 This returns a list with three values: The current indentation, the
6295 parent indentation and the indentation a child should habe.
6296 Assumes cursor in item line."
6297 (let* ((bolpos (point-at-bol))
6298 (ind (org-get-indentation))
6299 ind-down ind-up pos)
6300 (save-excursion
6301 (org-beginning-of-item-list)
6302 (skip-chars-backward "\n\r \t")
6303 (when (org-in-item-p)
6304 (org-beginning-of-item)
6305 (setq ind-up (org-get-indentation))))
6306 (setq pos (point))
6307 (save-excursion
6308 (cond
6309 ((and (condition-case nil (progn (org-previous-item) t)
6310 (error nil))
6311 (or (forward-char 1) t)
6312 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6313 (setq ind-down (org-get-indentation)))
6314 ((and (goto-char pos)
6315 (org-at-item-p))
6316 (goto-char (match-end 0))
6317 (skip-chars-forward " \t")
6318 (setq ind-down (current-column)))))
6319 (list ind ind-up ind-down)))
6321 ;;; The orgstruct minor mode
6323 ;; Define a minor mode which can be used in other modes in order to
6324 ;; integrate the org-mode structure editing commands.
6326 ;; This is really a hack, because the org-mode structure commands use
6327 ;; keys which normally belong to the major mode. Here is how it
6328 ;; works: The minor mode defines all the keys necessary to operate the
6329 ;; structure commands, but wraps the commands into a function which
6330 ;; tests if the cursor is currently at a headline or a plain list
6331 ;; item. If that is the case, the structure command is used,
6332 ;; temporarily setting many Org-mode variables like regular
6333 ;; expressions for filling etc. However, when any of those keys is
6334 ;; used at a different location, function uses `key-binding' to look
6335 ;; up if the key has an associated command in another currently active
6336 ;; keymap (minor modes, major mode, global), and executes that
6337 ;; command. There might be problems if any of the keys is otherwise
6338 ;; used as a prefix key.
6340 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6341 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6342 ;; addresses this by checking explicitly for both bindings.
6344 (defvar orgstruct-mode-map (make-sparse-keymap)
6345 "Keymap for the minor `orgstruct-mode'.")
6347 (defvar org-local-vars nil
6348 "List of local variables, for use by `orgstruct-mode'")
6350 ;;;###autoload
6351 (define-minor-mode orgstruct-mode
6352 "Toggle the minor more `orgstruct-mode'.
6353 This mode is for using Org-mode structure commands in other modes.
6354 The following key behave as if Org-mode was active, if the cursor
6355 is on a headline, or on a plain list item (both in the definition
6356 of Org-mode).
6358 M-up Move entry/item up
6359 M-down Move entry/item down
6360 M-left Promote
6361 M-right Demote
6362 M-S-up Move entry/item up
6363 M-S-down Move entry/item down
6364 M-S-left Promote subtree
6365 M-S-right Demote subtree
6366 M-q Fill paragraph and items like in Org-mode
6367 C-c ^ Sort entries
6368 C-c - Cycle list bullet
6369 TAB Cycle item visibility
6370 M-RET Insert new heading/item
6371 S-M-RET Insert new TODO heading / Chekbox item
6372 C-c C-c Set tags / toggle checkbox"
6373 nil " OrgStruct" nil
6374 (org-load-modules-maybe)
6375 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6377 ;;;###autoload
6378 (defun turn-on-orgstruct ()
6379 "Unconditionally turn on `orgstruct-mode'."
6380 (orgstruct-mode 1))
6382 ;;;###autoload
6383 (defun turn-on-orgstruct++ ()
6384 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6385 In addition to setting orgstruct-mode, this also exports all indentation and
6386 autofilling variables from org-mode into the buffer. Note that turning
6387 off orgstruct-mode will *not* remove these additional settings."
6388 (orgstruct-mode 1)
6389 (let (var val)
6390 (mapc
6391 (lambda (x)
6392 (when (string-match
6393 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6394 (symbol-name (car x)))
6395 (setq var (car x) val (nth 1 x))
6396 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6397 org-local-vars)))
6399 (defun orgstruct-error ()
6400 "Error when there is no default binding for a structure key."
6401 (interactive)
6402 (error "This key has no function outside structure elements"))
6404 (defun orgstruct-setup ()
6405 "Setup orgstruct keymaps."
6406 (let ((nfunc 0)
6407 (bindings
6408 (list
6409 '([(meta up)] org-metaup)
6410 '([(meta down)] org-metadown)
6411 '([(meta left)] org-metaleft)
6412 '([(meta right)] org-metaright)
6413 '([(meta shift up)] org-shiftmetaup)
6414 '([(meta shift down)] org-shiftmetadown)
6415 '([(meta shift left)] org-shiftmetaleft)
6416 '([(meta shift right)] org-shiftmetaright)
6417 '([(shift up)] org-shiftup)
6418 '([(shift down)] org-shiftdown)
6419 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6420 '("\M-q" fill-paragraph)
6421 '("\C-c^" org-sort)
6422 '("\C-c-" org-cycle-list-bullet)))
6423 elt key fun cmd)
6424 (while (setq elt (pop bindings))
6425 (setq nfunc (1+ nfunc))
6426 (setq key (org-key (car elt))
6427 fun (nth 1 elt)
6428 cmd (orgstruct-make-binding fun nfunc key))
6429 (org-defkey orgstruct-mode-map key cmd))
6431 ;; Special treatment needed for TAB and RET
6432 (org-defkey orgstruct-mode-map [(tab)]
6433 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6434 (org-defkey orgstruct-mode-map "\C-i"
6435 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6437 (org-defkey orgstruct-mode-map "\M-\C-m"
6438 (orgstruct-make-binding 'org-insert-heading 105
6439 "\M-\C-m" [(meta return)]))
6440 (org-defkey orgstruct-mode-map [(meta return)]
6441 (orgstruct-make-binding 'org-insert-heading 106
6442 [(meta return)] "\M-\C-m"))
6444 (org-defkey orgstruct-mode-map [(shift meta return)]
6445 (orgstruct-make-binding 'org-insert-todo-heading 107
6446 [(meta return)] "\M-\C-m"))
6448 (unless org-local-vars
6449 (setq org-local-vars (org-get-local-variables)))
6453 (defun orgstruct-make-binding (fun n &rest keys)
6454 "Create a function for binding in the structure minor mode.
6455 FUN is the command to call inside a table. N is used to create a unique
6456 command name. KEYS are keys that should be checked in for a command
6457 to execute outside of tables."
6458 (eval
6459 (list 'defun
6460 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6461 '(arg)
6462 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6463 "Outside of structure, run the binding of `"
6464 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6465 "'.")
6466 '(interactive "p")
6467 (list 'if
6468 '(org-context-p 'headline 'item)
6469 (list 'org-run-like-in-org-mode (list 'quote fun))
6470 (list 'let '(orgstruct-mode)
6471 (list 'call-interactively
6472 (append '(or)
6473 (mapcar (lambda (k)
6474 (list 'key-binding k))
6475 keys)
6476 '('orgstruct-error))))))))
6478 (defun org-context-p (&rest contexts)
6479 "Check if local context is any of CONTEXTS.
6480 Possible values in the list of contexts are `table', `headline', and `item'."
6481 (let ((pos (point)))
6482 (goto-char (point-at-bol))
6483 (prog1 (or (and (memq 'table contexts)
6484 (looking-at "[ \t]*|"))
6485 (and (memq 'headline contexts)
6486 ;;????????? (looking-at "\\*+"))
6487 (looking-at outline-regexp))
6488 (and (memq 'item contexts)
6489 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6490 (goto-char pos))))
6492 (defun org-get-local-variables ()
6493 "Return a list of all local variables in an org-mode buffer."
6494 (let (varlist)
6495 (with-current-buffer (get-buffer-create "*Org tmp*")
6496 (erase-buffer)
6497 (org-mode)
6498 (setq varlist (buffer-local-variables)))
6499 (kill-buffer "*Org tmp*")
6500 (delq nil
6501 (mapcar
6502 (lambda (x)
6503 (setq x
6504 (if (symbolp x)
6505 (list x)
6506 (list (car x) (list 'quote (cdr x)))))
6507 (if (string-match
6508 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6509 (symbol-name (car x)))
6510 x nil))
6511 varlist))))
6513 ;;;###autoload
6514 (defun org-run-like-in-org-mode (cmd)
6515 (org-load-modules-maybe)
6516 (unless org-local-vars
6517 (setq org-local-vars (org-get-local-variables)))
6518 (eval (list 'let org-local-vars
6519 (list 'call-interactively (list 'quote cmd)))))
6521 ;;;; Archiving
6523 (defun org-get-category (&optional pos)
6524 "Get the category applying to position POS."
6525 (get-text-property (or pos (point)) 'org-category))
6527 (defun org-refresh-category-properties ()
6528 "Refresh category text properties in the buffer."
6529 (let ((def-cat (cond
6530 ((null org-category)
6531 (if buffer-file-name
6532 (file-name-sans-extension
6533 (file-name-nondirectory buffer-file-name))
6534 "???"))
6535 ((symbolp org-category) (symbol-name org-category))
6536 (t org-category)))
6537 beg end cat pos optionp)
6538 (org-unmodified
6539 (save-excursion
6540 (save-restriction
6541 (widen)
6542 (goto-char (point-min))
6543 (put-text-property (point) (point-max) 'org-category def-cat)
6544 (while (re-search-forward
6545 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6546 (setq pos (match-end 0)
6547 optionp (equal (char-after (match-beginning 0)) ?#)
6548 cat (org-trim (match-string 2)))
6549 (if optionp
6550 (setq beg (point-at-bol) end (point-max))
6551 (org-back-to-heading t)
6552 (setq beg (point) end (org-end-of-subtree t t)))
6553 (put-text-property beg end 'org-category cat)
6554 (goto-char pos)))))))
6557 ;;;; Link Stuff
6559 ;;; Link abbreviations
6561 (defun org-link-expand-abbrev (link)
6562 "Apply replacements as defined in `org-link-abbrev-alist."
6563 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6564 (let* ((key (match-string 1 link))
6565 (as (or (assoc key org-link-abbrev-alist-local)
6566 (assoc key org-link-abbrev-alist)))
6567 (tag (and (match-end 2) (match-string 3 link)))
6568 rpl)
6569 (if (not as)
6570 link
6571 (setq rpl (cdr as))
6572 (cond
6573 ((symbolp rpl) (funcall rpl tag))
6574 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6575 (t (concat rpl tag)))))
6576 link))
6578 ;;; Storing and inserting links
6580 (defvar org-insert-link-history nil
6581 "Minibuffer history for links inserted with `org-insert-link'.")
6583 (defvar org-stored-links nil
6584 "Contains the links stored with `org-store-link'.")
6586 (defvar org-store-link-plist nil
6587 "Plist with info about the most recently link created with `org-store-link'.")
6589 (defvar org-link-protocols nil
6590 "Link protocols added to Org-mode using `org-add-link-type'.")
6592 (defvar org-store-link-functions nil
6593 "List of functions that are called to create and store a link.
6594 Each function will be called in turn until one returns a non-nil
6595 value. Each function should check if it is responsible for creating
6596 this link (for example by looking at the major mode).
6597 If not, it must exit and return nil.
6598 If yes, it should return a non-nil value after a calling
6599 `org-store-link-props' with a list of properties and values.
6600 Special properties are:
6602 :type The link prefix. like \"http\". This must be given.
6603 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6604 This is obligatory as well.
6605 :description Optional default description for the second pair
6606 of brackets in an Org-mode link. The user can still change
6607 this when inserting this link into an Org-mode buffer.
6609 In addition to these, any additional properties can be specified
6610 and then used in remember templates.")
6612 (defun org-add-link-type (type &optional follow export)
6613 "Add TYPE to the list of `org-link-types'.
6614 Re-compute all regular expressions depending on `org-link-types'
6616 FOLLOW and EXPORT are two functions.
6618 FOLLOW should take the link path as the single argument and do whatever
6619 is necessary to follow the link, for example find a file or display
6620 a mail message.
6622 EXPORT should format the link path for export to one of the export formats.
6623 It should be a function accepting three arguments:
6625 path the path of the link, the text after the prefix (like \"http:\")
6626 desc the description of the link, if any, nil if there was no descripton
6627 format the export format, a symbol like `html' or `latex'.
6629 The function may use the FORMAT information to return different values
6630 depending on the format. The return value will be put literally into
6631 the exported file.
6632 Org-mode has a built-in default for exporting links. If you are happy with
6633 this default, there is no need to define an export function for the link
6634 type. For a simple example of an export function, see `org-bbdb.el'."
6635 (add-to-list 'org-link-types type t)
6636 (org-make-link-regexps)
6637 (if (assoc type org-link-protocols)
6638 (setcdr (assoc type org-link-protocols) (list follow export))
6639 (push (list type follow export) org-link-protocols)))
6642 ;;;###autoload
6643 (defun org-store-link (arg)
6644 "\\<org-mode-map>Store an org-link to the current location.
6645 This link is added to `org-stored-links' and can later be inserted
6646 into an org-buffer with \\[org-insert-link].
6648 For some link types, a prefix arg is interpreted:
6649 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6650 For file links, arg negates `org-context-in-file-links'."
6651 (interactive "P")
6652 (org-load-modules-maybe)
6653 (setq org-store-link-plist nil) ; reset
6654 (let (link cpltxt desc description search txt)
6655 (cond
6657 ((run-hook-with-args-until-success 'org-store-link-functions)
6658 (setq link (plist-get org-store-link-plist :link)
6659 desc (or (plist-get org-store-link-plist :description) link)))
6661 ((eq major-mode 'calendar-mode)
6662 (let ((cd (calendar-cursor-to-date)))
6663 (setq link
6664 (format-time-string
6665 (car org-time-stamp-formats)
6666 (apply 'encode-time
6667 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6668 nil nil nil))))
6669 (org-store-link-props :type "calendar" :date cd)))
6671 ((eq major-mode 'w3-mode)
6672 (setq cpltxt (url-view-url t)
6673 link (org-make-link cpltxt))
6674 (org-store-link-props :type "w3" :url (url-view-url t)))
6676 ((eq major-mode 'w3m-mode)
6677 (setq cpltxt (or w3m-current-title w3m-current-url)
6678 link (org-make-link w3m-current-url))
6679 (org-store-link-props :type "w3m" :url (url-view-url t)))
6681 ((setq search (run-hook-with-args-until-success
6682 'org-create-file-search-functions))
6683 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6684 "::" search))
6685 (setq cpltxt (or description link)))
6687 ((eq major-mode 'image-mode)
6688 (setq cpltxt (concat "file:"
6689 (abbreviate-file-name buffer-file-name))
6690 link (org-make-link cpltxt))
6691 (org-store-link-props :type "image" :file buffer-file-name))
6693 ((eq major-mode 'dired-mode)
6694 ;; link to the file in the current line
6695 (setq cpltxt (concat "file:"
6696 (abbreviate-file-name
6697 (expand-file-name
6698 (dired-get-filename nil t))))
6699 link (org-make-link cpltxt)))
6701 ((and buffer-file-name (org-mode-p))
6702 ;; Just link to current headline
6703 (setq cpltxt (concat "file:"
6704 (abbreviate-file-name buffer-file-name)))
6705 ;; Add a context search string
6706 (when (org-xor org-context-in-file-links arg)
6707 ;; Check if we are on a target
6708 (if (org-in-regexp "<<\\(.*?\\)>>")
6709 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6710 (setq txt (cond
6711 ((org-on-heading-p) nil)
6712 ((org-region-active-p)
6713 (buffer-substring (region-beginning) (region-end)))
6714 (t nil)))
6715 (when (or (null txt) (string-match "\\S-" txt))
6716 (setq cpltxt
6717 (concat cpltxt "::"
6718 (condition-case nil
6719 (org-make-org-heading-search-string txt)
6720 (error "")))
6721 desc "NONE"))))
6722 (if (string-match "::\\'" cpltxt)
6723 (setq cpltxt (substring cpltxt 0 -2)))
6724 (setq link (org-make-link cpltxt)))
6726 ((buffer-file-name (buffer-base-buffer))
6727 ;; Just link to this file here.
6728 (setq cpltxt (concat "file:"
6729 (abbreviate-file-name
6730 (buffer-file-name (buffer-base-buffer)))))
6731 ;; Add a context string
6732 (when (org-xor org-context-in-file-links arg)
6733 (setq txt (if (org-region-active-p)
6734 (buffer-substring (region-beginning) (region-end))
6735 (buffer-substring (point-at-bol) (point-at-eol))))
6736 ;; Only use search option if there is some text.
6737 (when (string-match "\\S-" txt)
6738 (setq cpltxt
6739 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6740 desc "NONE")))
6741 (setq link (org-make-link cpltxt)))
6743 ((interactive-p)
6744 (error "Cannot link to a buffer which is not visiting a file"))
6746 (t (setq link nil)))
6748 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6749 (setq link (or link cpltxt)
6750 desc (or desc cpltxt))
6751 (if (equal desc "NONE") (setq desc nil))
6753 (if (and (interactive-p) link)
6754 (progn
6755 (setq org-stored-links
6756 (cons (list link desc) org-stored-links))
6757 (message "Stored: %s" (or desc link)))
6758 (and link (org-make-link-string link desc)))))
6760 (defun org-store-link-props (&rest plist)
6761 "Store link properties, extract names and addresses."
6762 (let (x adr)
6763 (when (setq x (plist-get plist :from))
6764 (setq adr (mail-extract-address-components x))
6765 (plist-put plist :fromname (car adr))
6766 (plist-put plist :fromaddress (nth 1 adr)))
6767 (when (setq x (plist-get plist :to))
6768 (setq adr (mail-extract-address-components x))
6769 (plist-put plist :toname (car adr))
6770 (plist-put plist :toaddress (nth 1 adr))))
6771 (let ((from (plist-get plist :from))
6772 (to (plist-get plist :to)))
6773 (when (and from to org-from-is-user-regexp)
6774 (plist-put plist :fromto
6775 (if (string-match org-from-is-user-regexp from)
6776 (concat "to %t")
6777 (concat "from %f")))))
6778 (setq org-store-link-plist plist))
6780 (defun org-add-link-props (&rest plist)
6781 "Add these properties to the link property list."
6782 (let (key value)
6783 (while plist
6784 (setq key (pop plist) value (pop plist))
6785 (setq org-store-link-plist
6786 (plist-put org-store-link-plist key value)))))
6788 (defun org-email-link-description (&optional fmt)
6789 "Return the description part of an email link.
6790 This takes information from `org-store-link-plist' and formats it
6791 according to FMT (default from `org-email-link-description-format')."
6792 (setq fmt (or fmt org-email-link-description-format))
6793 (let* ((p org-store-link-plist)
6794 (to (plist-get p :toaddress))
6795 (from (plist-get p :fromaddress))
6796 (table
6797 (list
6798 (cons "%c" (plist-get p :fromto))
6799 (cons "%F" (plist-get p :from))
6800 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6801 (cons "%T" (plist-get p :to))
6802 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6803 (cons "%s" (plist-get p :subject))
6804 (cons "%m" (plist-get p :message-id)))))
6805 (when (string-match "%c" fmt)
6806 ;; Check if the user wrote this message
6807 (if (and org-from-is-user-regexp from to
6808 (save-match-data (string-match org-from-is-user-regexp from)))
6809 (setq fmt (replace-match "to %t" t t fmt))
6810 (setq fmt (replace-match "from %f" t t fmt))))
6811 (org-replace-escapes fmt table)))
6813 (defun org-make-org-heading-search-string (&optional string heading)
6814 "Make search string for STRING or current headline."
6815 (interactive)
6816 (let ((s (or string (org-get-heading))))
6817 (unless (and string (not heading))
6818 ;; We are using a headline, clean up garbage in there.
6819 (if (string-match org-todo-regexp s)
6820 (setq s (replace-match "" t t s)))
6821 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6822 (setq s (replace-match "" t t s)))
6823 (setq s (org-trim s))
6824 (if (string-match (concat "^\\(" org-quote-string "\\|"
6825 org-comment-string "\\)") s)
6826 (setq s (replace-match "" t t s)))
6827 (while (string-match org-ts-regexp s)
6828 (setq s (replace-match "" t t s))))
6829 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6830 (setq s (replace-match " " t t s)))
6831 (or string (setq s (concat "*" s))) ; Add * for headlines
6832 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6834 (defun org-make-link (&rest strings)
6835 "Concatenate STRINGS."
6836 (apply 'concat strings))
6838 (defun org-make-link-string (link &optional description)
6839 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6840 (unless (string-match "\\S-" link)
6841 (error "Empty link"))
6842 (when (stringp description)
6843 ;; Remove brackets from the description, they are fatal.
6844 (while (string-match "\\[" description)
6845 (setq description (replace-match "{" t t description)))
6846 (while (string-match "\\]" description)
6847 (setq description (replace-match "}" t t description))))
6848 (when (equal (org-link-escape link) description)
6849 ;; No description needed, it is identical
6850 (setq description nil))
6851 (when (and (not description)
6852 (not (equal link (org-link-escape link))))
6853 (setq description (org-extract-attributes link)))
6854 (concat "[[" (org-link-escape link) "]"
6855 (if description (concat "[" description "]") "")
6856 "]"))
6858 (defconst org-link-escape-chars
6859 '((?\ . "%20")
6860 (?\[ . "%5B")
6861 (?\] . "%5D")
6862 (?\340 . "%E0") ; `a
6863 (?\342 . "%E2") ; ^a
6864 (?\347 . "%E7") ; ,c
6865 (?\350 . "%E8") ; `e
6866 (?\351 . "%E9") ; 'e
6867 (?\352 . "%EA") ; ^e
6868 (?\356 . "%EE") ; ^i
6869 (?\364 . "%F4") ; ^o
6870 (?\371 . "%F9") ; `u
6871 (?\373 . "%FB") ; ^u
6872 (?\; . "%3B")
6873 (?? . "%3F")
6874 (?= . "%3D")
6875 (?+ . "%2B")
6877 "Association list of escapes for some characters problematic in links.
6878 This is the list that is used for internal purposes.")
6880 (defconst org-link-escape-chars-browser
6881 '((?\ . "%20")) ; 32 for the SPC char
6882 "Association list of escapes for some characters problematic in links.
6883 This is the list that is used before handing over to the browser.")
6885 (defun org-link-escape (text &optional table)
6886 "Escape charaters in TEXT that are problematic for links."
6887 (setq table (or table org-link-escape-chars))
6888 (when text
6889 (let ((re (mapconcat (lambda (x) (regexp-quote
6890 (char-to-string (car x))))
6891 table "\\|")))
6892 (while (string-match re text)
6893 (setq text
6894 (replace-match
6895 (cdr (assoc (string-to-char (match-string 0 text))
6896 table))
6897 t t text)))
6898 text)))
6900 (defun org-link-unescape (text &optional table)
6901 "Reverse the action of `org-link-escape'."
6902 (setq table (or table org-link-escape-chars))
6903 (when text
6904 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6905 table "\\|")))
6906 (while (string-match re text)
6907 (setq text
6908 (replace-match
6909 (char-to-string (car (rassoc (match-string 0 text) table)))
6910 t t text)))
6911 text)))
6913 (defun org-xor (a b)
6914 "Exclusive or."
6915 (if a (not b) b))
6917 (defun org-get-header (header)
6918 "Find a header field in the current buffer."
6919 (save-excursion
6920 (goto-char (point-min))
6921 (let ((case-fold-search t) s)
6922 (cond
6923 ((eq header 'from)
6924 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6925 (setq s (match-string 1)))
6926 (while (string-match "\"" s)
6927 (setq s (replace-match "" t t s)))
6928 (if (string-match "[<(].*" s)
6929 (setq s (replace-match "" t t s))))
6930 ((eq header 'message-id)
6931 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6932 (setq s (match-string 1))))
6933 ((eq header 'subject)
6934 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6935 (setq s (match-string 1)))))
6936 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6937 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6938 s)))
6941 (defun org-fixup-message-id-for-http (s)
6942 "Replace special characters in a message id, so it can be used in an http query."
6943 (while (string-match "<" s)
6944 (setq s (replace-match "%3C" t t s)))
6945 (while (string-match ">" s)
6946 (setq s (replace-match "%3E" t t s)))
6947 (while (string-match "@" s)
6948 (setq s (replace-match "%40" t t s)))
6951 ;;;###autoload
6952 (defun org-insert-link-global ()
6953 "Insert a link like Org-mode does.
6954 This command can be called in any mode to insert a link in Org-mode syntax."
6955 (interactive)
6956 (org-load-modules-maybe)
6957 (org-run-like-in-org-mode 'org-insert-link))
6959 (defun org-insert-link (&optional complete-file link-location)
6960 "Insert a link. At the prompt, enter the link.
6962 Completion can be used to select a link previously stored with
6963 `org-store-link'. When the empty string is entered (i.e. if you just
6964 press RET at the prompt), the link defaults to the most recently
6965 stored link. As SPC triggers completion in the minibuffer, you need to
6966 use M-SPC or C-q SPC to force the insertion of a space character.
6968 You will also be prompted for a description, and if one is given, it will
6969 be displayed in the buffer instead of the link.
6971 If there is already a link at point, this command will allow you to edit link
6972 and description parts.
6974 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6975 be selected using completion. The path to the file will be relative to the
6976 current directory if the file is in the current directory or a subdirectory.
6977 Otherwise, the link will be the absolute path as completed in the minibuffer
6978 \(i.e. normally ~/path/to/file).
6980 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6981 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6982 of `org-keep-stored-link-after-insertion'.
6984 If `org-make-link-description-function' is non-nil, this function will be
6985 called with the link target, and the result will be the default
6986 link description.
6988 If the LINK-LOCATION parameter is non-nil, this value will be
6989 used as the link location instead of reading one interactively."
6990 (interactive "P")
6991 (let* ((wcf (current-window-configuration))
6992 (region (if (org-region-active-p)
6993 (buffer-substring (region-beginning) (region-end))))
6994 (remove (and region (list (region-beginning) (region-end))))
6995 (desc region)
6996 tmphist ; byte-compile incorrectly complains about this
6997 (link link-location)
6998 entry file)
6999 (cond
7000 (link-location) ; specified by arg, just use it.
7001 ((org-in-regexp org-bracket-link-regexp 1)
7002 ;; We do have a link at point, and we are going to edit it.
7003 (setq remove (list (match-beginning 0) (match-end 0)))
7004 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7005 (setq link (read-string "Link: "
7006 (org-link-unescape
7007 (org-match-string-no-properties 1)))))
7008 ((or (org-in-regexp org-angle-link-re)
7009 (org-in-regexp org-plain-link-re))
7010 ;; Convert to bracket link
7011 (setq remove (list (match-beginning 0) (match-end 0))
7012 link (read-string "Link: "
7013 (org-remove-angle-brackets (match-string 0)))))
7014 ((equal complete-file '(4))
7015 ;; Completing read for file names.
7016 (setq file (read-file-name "File: "))
7017 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7018 (pwd1 (file-name-as-directory (abbreviate-file-name
7019 (expand-file-name ".")))))
7020 (cond
7021 ((equal complete-file '(16))
7022 (setq link (org-make-link
7023 "file:"
7024 (abbreviate-file-name (expand-file-name file)))))
7025 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7026 (setq link (org-make-link "file:" (match-string 1 file))))
7027 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7028 (expand-file-name file))
7029 (setq link (org-make-link
7030 "file:" (match-string 1 (expand-file-name file)))))
7031 (t (setq link (org-make-link "file:" file))))))
7033 ;; Read link, with completion for stored links.
7034 (with-output-to-temp-buffer "*Org Links*"
7035 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7036 (when org-stored-links
7037 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7038 (princ (mapconcat
7039 (lambda (x)
7040 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7041 (reverse org-stored-links) "\n"))))
7042 (let ((cw (selected-window)))
7043 (select-window (get-buffer-window "*Org Links*"))
7044 (shrink-window-if-larger-than-buffer)
7045 (setq truncate-lines t)
7046 (select-window cw))
7047 ;; Fake a link history, containing the stored links.
7048 (setq tmphist (append (mapcar 'car org-stored-links)
7049 org-insert-link-history))
7050 (unwind-protect
7051 (setq link (org-completing-read
7052 "Link: "
7053 (append
7054 (mapcar (lambda (x) (list (concat (car x) ":")))
7055 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7056 (mapcar (lambda (x) (list (concat x ":")))
7057 org-link-types))
7058 nil nil nil
7059 'tmphist
7060 (or (car (car org-stored-links)))))
7061 (set-window-configuration wcf)
7062 (kill-buffer "*Org Links*"))
7063 (setq entry (assoc link org-stored-links))
7064 (or entry (push link org-insert-link-history))
7065 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7066 (not org-keep-stored-link-after-insertion))
7067 (setq org-stored-links (delq (assoc link org-stored-links)
7068 org-stored-links)))
7069 (setq desc (or desc (nth 1 entry)))))
7071 (if (string-match org-plain-link-re link)
7072 ;; URL-like link, normalize the use of angular brackets.
7073 (setq link (org-make-link (org-remove-angle-brackets link))))
7075 ;; Check if we are linking to the current file with a search option
7076 ;; If yes, simplify the link by using only the search option.
7077 (when (and buffer-file-name
7078 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7079 (let* ((path (match-string 1 link))
7080 (case-fold-search nil)
7081 (search (match-string 2 link)))
7082 (save-match-data
7083 (if (equal (file-truename buffer-file-name) (file-truename path))
7084 ;; We are linking to this same file, with a search option
7085 (setq link search)))))
7087 ;; Check if we can/should use a relative path. If yes, simplify the link
7088 (when (string-match "\\<file:\\(.*\\)" link)
7089 (let* ((path (match-string 1 link))
7090 (origpath path)
7091 (case-fold-search nil))
7092 (cond
7093 ((eq org-link-file-path-type 'absolute)
7094 (setq path (abbreviate-file-name (expand-file-name path))))
7095 ((eq org-link-file-path-type 'noabbrev)
7096 (setq path (expand-file-name path)))
7097 ((eq org-link-file-path-type 'relative)
7098 (setq path (file-relative-name path)))
7100 (save-match-data
7101 (if (string-match (concat "^" (regexp-quote
7102 (file-name-as-directory
7103 (expand-file-name "."))))
7104 (expand-file-name path))
7105 ;; We are linking a file with relative path name.
7106 (setq path (substring (expand-file-name path)
7107 (match-end 0)))))))
7108 (setq link (concat "file:" path))
7109 (if (equal desc origpath)
7110 (setq desc path))))
7112 (if org-make-link-description-function
7113 (setq desc (funcall org-make-link-description-function link desc)))
7115 (setq desc (read-string "Description: " desc))
7116 (unless (string-match "\\S-" desc) (setq desc nil))
7117 (if remove (apply 'delete-region remove))
7118 (insert (org-make-link-string link desc))))
7120 (defun org-completing-read (&rest args)
7121 (let ((minibuffer-local-completion-map
7122 (copy-keymap minibuffer-local-completion-map)))
7123 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7124 (apply 'completing-read args)))
7126 (defun org-extract-attributes (s)
7127 "Extract the attributes cookie from a string and set as text property."
7128 (let (a attr (start 0) key value)
7129 (save-match-data
7130 (when (string-match "{{\\([^}]+\\)}}$" s)
7131 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7132 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7133 (setq key (match-string 1 a) value (match-string 2 a)
7134 start (match-end 0)
7135 attr (plist-put attr (intern key) value))))
7136 (org-add-props s nil 'org-attributes attr))
7139 (defun org-attributes-to-string (plist)
7140 "Format a property list into an HTML attribute list."
7141 (let ((s "") key value)
7142 (while plist
7143 (setq key (pop plist) value (pop plist))
7144 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7147 ;;; Opening/following a link
7149 (defvar org-link-search-failed nil)
7151 (defun org-next-link ()
7152 "Move forward to the next link.
7153 If the link is in hidden text, expose it."
7154 (interactive)
7155 (when (and org-link-search-failed (eq this-command last-command))
7156 (goto-char (point-min))
7157 (message "Link search wrapped back to beginning of buffer"))
7158 (setq org-link-search-failed nil)
7159 (let* ((pos (point))
7160 (ct (org-context))
7161 (a (assoc :link ct)))
7162 (if a (goto-char (nth 2 a)))
7163 (if (re-search-forward org-any-link-re nil t)
7164 (progn
7165 (goto-char (match-beginning 0))
7166 (if (org-invisible-p) (org-show-context)))
7167 (goto-char pos)
7168 (setq org-link-search-failed t)
7169 (error "No further link found"))))
7171 (defun org-previous-link ()
7172 "Move backward to the previous link.
7173 If the link is in hidden text, expose it."
7174 (interactive)
7175 (when (and org-link-search-failed (eq this-command last-command))
7176 (goto-char (point-max))
7177 (message "Link search wrapped back to end of buffer"))
7178 (setq org-link-search-failed nil)
7179 (let* ((pos (point))
7180 (ct (org-context))
7181 (a (assoc :link ct)))
7182 (if a (goto-char (nth 1 a)))
7183 (if (re-search-backward org-any-link-re nil t)
7184 (progn
7185 (goto-char (match-beginning 0))
7186 (if (org-invisible-p) (org-show-context)))
7187 (goto-char pos)
7188 (setq org-link-search-failed t)
7189 (error "No further link found"))))
7191 (defun org-find-file-at-mouse (ev)
7192 "Open file link or URL at mouse."
7193 (interactive "e")
7194 (mouse-set-point ev)
7195 (org-open-at-point 'in-emacs))
7197 (defun org-open-at-mouse (ev)
7198 "Open file link or URL at mouse."
7199 (interactive "e")
7200 (mouse-set-point ev)
7201 (org-open-at-point))
7203 (defvar org-window-config-before-follow-link nil
7204 "The window configuration before following a link.
7205 This is saved in case the need arises to restore it.")
7207 (defvar org-open-link-marker (make-marker)
7208 "Marker pointing to the location where `org-open-at-point; was called.")
7210 ;;;###autoload
7211 (defun org-open-at-point-global ()
7212 "Follow a link like Org-mode does.
7213 This command can be called in any mode to follow a link that has
7214 Org-mode syntax."
7215 (interactive)
7216 (org-run-like-in-org-mode 'org-open-at-point))
7218 ;;;###autoload
7219 (defun org-open-link-from-string (s &optional arg)
7220 "Open a link in the string S, as if it was in Org-mode."
7221 (interactive "sLink: \nP")
7222 (with-temp-buffer
7223 (let ((org-inhibit-startup t))
7224 (org-mode)
7225 (insert s)
7226 (goto-char (point-min))
7227 (org-open-at-point arg))))
7229 (defun org-open-at-point (&optional in-emacs)
7230 "Open link at or after point.
7231 If there is no link at point, this function will search forward up to
7232 the end of the current subtree.
7233 Normally, files will be opened by an appropriate application. If the
7234 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7235 (interactive "P")
7236 (org-load-modules-maybe)
7237 (move-marker org-open-link-marker (point))
7238 (setq org-window-config-before-follow-link (current-window-configuration))
7239 (org-remove-occur-highlights nil nil t)
7240 (if (org-at-timestamp-p t)
7241 (org-follow-timestamp-link)
7242 (let (type path link line search (pos (point)))
7243 (catch 'match
7244 (save-excursion
7245 (skip-chars-forward "^]\n\r")
7246 (when (org-in-regexp org-bracket-link-regexp)
7247 (setq link (org-extract-attributes
7248 (org-link-unescape (org-match-string-no-properties 1))))
7249 (while (string-match " *\n *" link)
7250 (setq link (replace-match " " t t link)))
7251 (setq link (org-link-expand-abbrev link))
7252 (cond
7253 ((or (file-name-absolute-p link)
7254 (string-match "^\\.\\.?/" link))
7255 (setq type "file" path link))
7256 ((string-match org-link-re-with-space2 link)
7257 (setq type (match-string 1 link) path (match-string 2 link)))
7258 (t (setq type "thisfile" path link)))
7259 (throw 'match t)))
7261 (when (get-text-property (point) 'org-linked-text)
7262 (setq type "thisfile"
7263 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7264 (1+ (point)) (point))
7265 path (buffer-substring
7266 (previous-single-property-change pos 'org-linked-text)
7267 (next-single-property-change pos 'org-linked-text)))
7268 (throw 'match t))
7270 (save-excursion
7271 (when (or (org-in-regexp org-angle-link-re)
7272 (org-in-regexp org-plain-link-re))
7273 (setq type (match-string 1) path (match-string 2))
7274 (throw 'match t)))
7275 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7276 (setq type "tree-match"
7277 path (match-string 1))
7278 (throw 'match t))
7279 (save-excursion
7280 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7281 (setq type "tags"
7282 path (match-string 1))
7283 (while (string-match ":" path)
7284 (setq path (replace-match "+" t t path)))
7285 (throw 'match t))))
7286 (unless path
7287 (error "No link found"))
7288 ;; Remove any trailing spaces in path
7289 (if (string-match " +\\'" path)
7290 (setq path (replace-match "" t t path)))
7292 (cond
7294 ((assoc type org-link-protocols)
7295 (funcall (nth 1 (assoc type org-link-protocols)) path))
7297 ((equal type "mailto")
7298 (let ((cmd (car org-link-mailto-program))
7299 (args (cdr org-link-mailto-program)) args1
7300 (address path) (subject "") a)
7301 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7302 (setq address (match-string 1 path)
7303 subject (org-link-escape (match-string 2 path))))
7304 (while args
7305 (cond
7306 ((not (stringp (car args))) (push (pop args) args1))
7307 (t (setq a (pop args))
7308 (if (string-match "%a" a)
7309 (setq a (replace-match address t t a)))
7310 (if (string-match "%s" a)
7311 (setq a (replace-match subject t t a)))
7312 (push a args1))))
7313 (apply cmd (nreverse args1))))
7315 ((member type '("http" "https" "ftp" "news"))
7316 (browse-url (concat type ":" (org-link-escape
7317 path org-link-escape-chars-browser))))
7319 ((member type '("message"))
7320 (browse-url (concat type ":" path)))
7322 ((string= type "tags")
7323 (org-tags-view in-emacs path))
7324 ((string= type "thisfile")
7325 (if in-emacs
7326 (switch-to-buffer-other-window
7327 (org-get-buffer-for-internal-link (current-buffer)))
7328 (org-mark-ring-push))
7329 (let ((cmd `(org-link-search
7330 ,path
7331 ,(cond ((equal in-emacs '(4)) 'occur)
7332 ((equal in-emacs '(16)) 'org-occur)
7333 (t nil))
7334 ,pos)))
7335 (condition-case nil (eval cmd)
7336 (error (progn (widen) (eval cmd))))))
7338 ((string= type "tree-match")
7339 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7341 ((string= type "file")
7342 (if (string-match "::\\([0-9]+\\)\\'" path)
7343 (setq line (string-to-number (match-string 1 path))
7344 path (substring path 0 (match-beginning 0)))
7345 (if (string-match "::\\(.+\\)\\'" path)
7346 (setq search (match-string 1 path)
7347 path (substring path 0 (match-beginning 0)))))
7348 (if (string-match "[*?{]" (file-name-nondirectory path))
7349 (dired path)
7350 (org-open-file path in-emacs line search)))
7352 ((string= type "news")
7353 (require 'org-gnus)
7354 (org-gnus-follow-link path))
7356 ((string= type "shell")
7357 (let ((cmd path))
7358 (if (or (not org-confirm-shell-link-function)
7359 (funcall org-confirm-shell-link-function
7360 (format "Execute \"%s\" in shell? "
7361 (org-add-props cmd nil
7362 'face 'org-warning))))
7363 (progn
7364 (message "Executing %s" cmd)
7365 (shell-command cmd))
7366 (error "Abort"))))
7368 ((string= type "elisp")
7369 (let ((cmd path))
7370 (if (or (not org-confirm-elisp-link-function)
7371 (funcall org-confirm-elisp-link-function
7372 (format "Execute \"%s\" as elisp? "
7373 (org-add-props cmd nil
7374 'face 'org-warning))))
7375 (message "%s => %s" cmd (eval (read cmd)))
7376 (error "Abort"))))
7379 (browse-url-at-point)))))
7380 (move-marker org-open-link-marker nil)
7381 (run-hook-with-args 'org-follow-link-hook))
7383 ;;;; Time estimates
7385 (defun org-get-effort (&optional pom)
7386 "Get the effort estimate for the current entry."
7387 (org-entry-get pom org-effort-property))
7389 ;;; File search
7391 (defvar org-create-file-search-functions nil
7392 "List of functions to construct the right search string for a file link.
7393 These functions are called in turn with point at the location to
7394 which the link should point.
7396 A function in the hook should first test if it would like to
7397 handle this file type, for example by checking the major-mode or
7398 the file extension. If it decides not to handle this file, it
7399 should just return nil to give other functions a chance. If it
7400 does handle the file, it must return the search string to be used
7401 when following the link. The search string will be part of the
7402 file link, given after a double colon, and `org-open-at-point'
7403 will automatically search for it. If special measures must be
7404 taken to make the search successful, another function should be
7405 added to the companion hook `org-execute-file-search-functions',
7406 which see.
7408 A function in this hook may also use `setq' to set the variable
7409 `description' to provide a suggestion for the descriptive text to
7410 be used for this link when it gets inserted into an Org-mode
7411 buffer with \\[org-insert-link].")
7413 (defvar org-execute-file-search-functions nil
7414 "List of functions to execute a file search triggered by a link.
7416 Functions added to this hook must accept a single argument, the
7417 search string that was part of the file link, the part after the
7418 double colon. The function must first check if it would like to
7419 handle this search, for example by checking the major-mode or the
7420 file extension. If it decides not to handle this search, it
7421 should just return nil to give other functions a chance. If it
7422 does handle the search, it must return a non-nil value to keep
7423 other functions from trying.
7425 Each function can access the current prefix argument through the
7426 variable `current-prefix-argument'. Note that a single prefix is
7427 used to force opening a link in Emacs, so it may be good to only
7428 use a numeric or double prefix to guide the search function.
7430 In case this is needed, a function in this hook can also restore
7431 the window configuration before `org-open-at-point' was called using:
7433 (set-window-configuration org-window-config-before-follow-link)")
7435 (defun org-link-search (s &optional type avoid-pos)
7436 "Search for a link search option.
7437 If S is surrounded by forward slashes, it is interpreted as a
7438 regular expression. In org-mode files, this will create an `org-occur'
7439 sparse tree. In ordinary files, `occur' will be used to list matches.
7440 If the current buffer is in `dired-mode', grep will be used to search
7441 in all files. If AVOID-POS is given, ignore matches near that position."
7442 (let ((case-fold-search t)
7443 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7444 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7445 (append '(("") (" ") ("\t") ("\n"))
7446 org-emphasis-alist)
7447 "\\|") "\\)"))
7448 (pos (point))
7449 (pre nil) (post nil)
7450 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7451 (cond
7452 ;; First check if there are any special
7453 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7454 ;; Now try the builtin stuff
7455 ((save-excursion
7456 (goto-char (point-min))
7457 (and
7458 (re-search-forward
7459 (concat "<<" (regexp-quote s0) ">>") nil t)
7460 (setq type 'dedicated
7461 pos (match-beginning 0))))
7462 ;; There is an exact target for this
7463 (goto-char pos))
7464 ((string-match "^/\\(.*\\)/$" s)
7465 ;; A regular expression
7466 (cond
7467 ((org-mode-p)
7468 (org-occur (match-string 1 s)))
7469 ;;((eq major-mode 'dired-mode)
7470 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7471 (t (org-do-occur (match-string 1 s)))))
7473 ;; A normal search strings
7474 (when (equal (string-to-char s) ?*)
7475 ;; Anchor on headlines, post may include tags.
7476 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7477 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7478 s (substring s 1)))
7479 (remove-text-properties
7480 0 (length s)
7481 '(face nil mouse-face nil keymap nil fontified nil) s)
7482 ;; Make a series of regular expressions to find a match
7483 (setq words (org-split-string s "[ \n\r\t]+")
7485 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7486 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7487 "\\)" markers)
7488 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7489 re2a (concat "[ \t\r\n]" re2a_)
7490 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7491 re4 (concat "[^a-zA-Z_]" re4_)
7493 re1 (concat pre re2 post)
7494 re3 (concat pre (if pre re4_ re4) post)
7495 re5 (concat pre ".*" re4)
7496 re2 (concat pre re2)
7497 re2a (concat pre (if pre re2a_ re2a))
7498 re4 (concat pre (if pre re4_ re4))
7499 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7500 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7501 re5 "\\)"
7503 (cond
7504 ((eq type 'org-occur) (org-occur reall))
7505 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7506 (t (goto-char (point-min))
7507 (setq type 'fuzzy)
7508 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7509 (org-search-not-self 1 re1 nil t)
7510 (org-search-not-self 1 re2 nil t)
7511 (org-search-not-self 1 re2a nil t)
7512 (org-search-not-self 1 re3 nil t)
7513 (org-search-not-self 1 re4 nil t)
7514 (org-search-not-self 1 re5 nil t)
7516 (goto-char (match-beginning 1))
7517 (goto-char pos)
7518 (error "No match")))))
7520 ;; Normal string-search
7521 (goto-char (point-min))
7522 (if (search-forward s nil t)
7523 (goto-char (match-beginning 0))
7524 (error "No match"))))
7525 (and (org-mode-p) (org-show-context 'link-search))
7526 type))
7528 (defun org-search-not-self (group &rest args)
7529 "Execute `re-search-forward', but only accept matches that do not
7530 enclose the position of `org-open-link-marker'."
7531 (let ((m org-open-link-marker))
7532 (catch 'exit
7533 (while (apply 're-search-forward args)
7534 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7535 (goto-char (match-end group))
7536 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7537 (> (match-beginning 0) (marker-position m))
7538 (< (match-end 0) (marker-position m)))
7539 (save-match-data
7540 (or (not (org-in-regexp
7541 org-bracket-link-analytic-regexp 1))
7542 (not (match-end 4)) ; no description
7543 (and (<= (match-beginning 4) (point))
7544 (>= (match-end 4) (point))))))
7545 (throw 'exit (point))))))))
7547 (defun org-get-buffer-for-internal-link (buffer)
7548 "Return a buffer to be used for displaying the link target of internal links."
7549 (cond
7550 ((not org-display-internal-link-with-indirect-buffer)
7551 buffer)
7552 ((string-match "(Clone)$" (buffer-name buffer))
7553 (message "Buffer is already a clone, not making another one")
7554 ;; we also do not modify visibility in this case
7555 buffer)
7556 (t ; make a new indirect buffer for displaying the link
7557 (let* ((bn (buffer-name buffer))
7558 (ibn (concat bn "(Clone)"))
7559 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7560 (with-current-buffer ib (org-overview))
7561 ib))))
7563 (defun org-do-occur (regexp &optional cleanup)
7564 "Call the Emacs command `occur'.
7565 If CLEANUP is non-nil, remove the printout of the regular expression
7566 in the *Occur* buffer. This is useful if the regex is long and not useful
7567 to read."
7568 (occur regexp)
7569 (when cleanup
7570 (let ((cwin (selected-window)) win beg end)
7571 (when (setq win (get-buffer-window "*Occur*"))
7572 (select-window win))
7573 (goto-char (point-min))
7574 (when (re-search-forward "match[a-z]+" nil t)
7575 (setq beg (match-end 0))
7576 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7577 (setq end (1- (match-beginning 0)))))
7578 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7579 (goto-char (point-min))
7580 (select-window cwin))))
7582 ;;; The mark ring for links jumps
7584 (defvar org-mark-ring nil
7585 "Mark ring for positions before jumps in Org-mode.")
7586 (defvar org-mark-ring-last-goto nil
7587 "Last position in the mark ring used to go back.")
7588 ;; Fill and close the ring
7589 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7590 (loop for i from 1 to org-mark-ring-length do
7591 (push (make-marker) org-mark-ring))
7592 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7593 org-mark-ring)
7595 (defun org-mark-ring-push (&optional pos buffer)
7596 "Put the current position or POS into the mark ring and rotate it."
7597 (interactive)
7598 (setq pos (or pos (point)))
7599 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7600 (move-marker (car org-mark-ring)
7601 (or pos (point))
7602 (or buffer (current-buffer)))
7603 (message "%s"
7604 (substitute-command-keys
7605 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7607 (defun org-mark-ring-goto (&optional n)
7608 "Jump to the previous position in the mark ring.
7609 With prefix arg N, jump back that many stored positions. When
7610 called several times in succession, walk through the entire ring.
7611 Org-mode commands jumping to a different position in the current file,
7612 or to another Org-mode file, automatically push the old position
7613 onto the ring."
7614 (interactive "p")
7615 (let (p m)
7616 (if (eq last-command this-command)
7617 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7618 (setq p org-mark-ring))
7619 (setq org-mark-ring-last-goto p)
7620 (setq m (car p))
7621 (switch-to-buffer (marker-buffer m))
7622 (goto-char m)
7623 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7625 (defun org-remove-angle-brackets (s)
7626 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7627 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7629 (defun org-add-angle-brackets (s)
7630 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7631 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7633 (defun org-remove-double-quotes (s)
7634 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7635 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7638 ;;; Following specific links
7640 (defun org-follow-timestamp-link ()
7641 (cond
7642 ((org-at-date-range-p t)
7643 (let ((org-agenda-start-on-weekday)
7644 (t1 (match-string 1))
7645 (t2 (match-string 2)))
7646 (setq t1 (time-to-days (org-time-string-to-time t1))
7647 t2 (time-to-days (org-time-string-to-time t2)))
7648 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7649 ((org-at-timestamp-p t)
7650 (org-agenda-list nil (time-to-days (org-time-string-to-time
7651 (substring (match-string 1) 0 10)))
7653 (t (error "This should not happen"))))
7656 ;;; Following file links
7657 (defvar org-wait nil)
7658 (defun org-open-file (path &optional in-emacs line search)
7659 "Open the file at PATH.
7660 First, this expands any special file name abbreviations. Then the
7661 configuration variable `org-file-apps' is checked if it contains an
7662 entry for this file type, and if yes, the corresponding command is launched.
7663 If no application is found, Emacs simply visits the file.
7664 With optional argument IN-EMACS, Emacs will visit the file.
7665 Optional LINE specifies a line to go to, optional SEARCH a string to
7666 search for. If LINE or SEARCH is given, the file will always be
7667 opened in Emacs.
7668 If the file does not exist, an error is thrown."
7669 (setq in-emacs (or in-emacs line search))
7670 (let* ((file (if (equal path "")
7671 buffer-file-name
7672 (substitute-in-file-name (expand-file-name path))))
7673 (apps (append org-file-apps (org-default-apps)))
7674 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7675 (dirp (if remp nil (file-directory-p file)))
7676 (file (if (and dirp org-open-directory-means-index-dot-org)
7677 (concat (file-name-as-directory file) "index.org")
7678 file))
7679 (dfile (downcase file))
7680 (old-buffer (current-buffer))
7681 (old-pos (point))
7682 (old-mode major-mode)
7683 ext cmd)
7684 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7685 (setq ext (match-string 1 dfile))
7686 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7687 (setq ext (match-string 1 dfile))))
7688 (if in-emacs
7689 (setq cmd 'emacs)
7690 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7691 (and dirp (cdr (assoc 'directory apps)))
7692 (cdr (assoc ext apps))
7693 (cdr (assoc t apps)))))
7694 (when (eq cmd 'mailcap)
7695 (require 'mailcap)
7696 (mailcap-parse-mailcaps)
7697 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7698 (command (mailcap-mime-info mime-type)))
7699 (if (stringp command)
7700 (setq cmd command)
7701 (setq cmd 'emacs))))
7702 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7703 (not (file-exists-p file))
7704 (not org-open-non-existing-files))
7705 (error "No such file: %s" file))
7706 (cond
7707 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7708 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7709 (while (string-match "['\"]%s['\"]" cmd)
7710 (setq cmd (replace-match "%s" t t cmd)))
7711 (while (string-match "%s" cmd)
7712 (setq cmd (replace-match
7713 (save-match-data
7714 (shell-quote-argument
7715 (convert-standard-filename file)))
7716 t t cmd)))
7717 (save-window-excursion
7718 (start-process-shell-command cmd nil cmd)
7719 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7721 ((or (stringp cmd)
7722 (eq cmd 'emacs))
7723 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7724 (widen)
7725 (if line (goto-line line)
7726 (if search (org-link-search search))))
7727 ((consp cmd)
7728 (let ((file (convert-standard-filename file)))
7729 (eval cmd)))
7730 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7731 (and (org-mode-p) (eq old-mode 'org-mode)
7732 (or (not (equal old-buffer (current-buffer)))
7733 (not (equal old-pos (point))))
7734 (org-mark-ring-push old-pos old-buffer))))
7736 (defun org-default-apps ()
7737 "Return the default applications for this operating system."
7738 (cond
7739 ((eq system-type 'darwin)
7740 org-file-apps-defaults-macosx)
7741 ((eq system-type 'windows-nt)
7742 org-file-apps-defaults-windowsnt)
7743 (t org-file-apps-defaults-gnu)))
7745 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7746 (defun org-file-remote-p (file)
7747 "Test whether FILE specifies a location on a remote system.
7748 Return non-nil if the location is indeed remote.
7750 For example, the filename \"/user@host:/foo\" specifies a location
7751 on the system \"/user@host:\"."
7752 (cond ((fboundp 'file-remote-p)
7753 (file-remote-p file))
7754 ((fboundp 'tramp-handle-file-remote-p)
7755 (tramp-handle-file-remote-p file))
7756 ((and (boundp 'ange-ftp-name-format)
7757 (string-match (car ange-ftp-name-format) file))
7759 (t nil)))
7762 ;;;; Refiling
7764 (defun org-get-org-file ()
7765 "Read a filename, with default directory `org-directory'."
7766 (let ((default (or org-default-notes-file remember-data-file)))
7767 (read-file-name (format "File name [%s]: " default)
7768 (file-name-as-directory org-directory)
7769 default)))
7771 (defun org-notes-order-reversed-p ()
7772 "Check if the current file should receive notes in reversed order."
7773 (cond
7774 ((not org-reverse-note-order) nil)
7775 ((eq t org-reverse-note-order) t)
7776 ((not (listp org-reverse-note-order)) nil)
7777 (t (catch 'exit
7778 (let ((all org-reverse-note-order)
7779 entry)
7780 (while (setq entry (pop all))
7781 (if (string-match (car entry) buffer-file-name)
7782 (throw 'exit (cdr entry))))
7783 nil)))))
7785 (defvar org-refile-target-table nil
7786 "The list of refile targets, created by `org-refile'.")
7788 (defvar org-agenda-new-buffers nil
7789 "Buffers created to visit agenda files.")
7791 (defun org-get-refile-targets (&optional default-buffer)
7792 "Produce a table with refile targets."
7793 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7794 targets txt re files f desc descre)
7795 (with-current-buffer (or default-buffer (current-buffer))
7796 (while (setq entry (pop entries))
7797 (setq files (car entry) desc (cdr entry))
7798 (cond
7799 ((null files) (setq files (list (current-buffer))))
7800 ((eq files 'org-agenda-files)
7801 (setq files (org-agenda-files 'unrestricted)))
7802 ((and (symbolp files) (fboundp files))
7803 (setq files (funcall files)))
7804 ((and (symbolp files) (boundp files))
7805 (setq files (symbol-value files))))
7806 (if (stringp files) (setq files (list files)))
7807 (cond
7808 ((eq (car desc) :tag)
7809 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7810 ((eq (car desc) :todo)
7811 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7812 ((eq (car desc) :regexp)
7813 (setq descre (cdr desc)))
7814 ((eq (car desc) :level)
7815 (setq descre (concat "^\\*\\{" (number-to-string
7816 (if org-odd-levels-only
7817 (1- (* 2 (cdr desc)))
7818 (cdr desc)))
7819 "\\}[ \t]")))
7820 ((eq (car desc) :maxlevel)
7821 (setq descre (concat "^\\*\\{1," (number-to-string
7822 (if org-odd-levels-only
7823 (1- (* 2 (cdr desc)))
7824 (cdr desc)))
7825 "\\}[ \t]")))
7826 (t (error "Bad refiling target description %s" desc)))
7827 (while (setq f (pop files))
7828 (save-excursion
7829 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7830 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7831 (save-excursion
7832 (save-restriction
7833 (widen)
7834 (goto-char (point-min))
7835 (while (re-search-forward descre nil t)
7836 (goto-char (point-at-bol))
7837 (when (looking-at org-complex-heading-regexp)
7838 (setq txt (match-string 4)
7839 re (concat "^" (regexp-quote
7840 (buffer-substring (match-beginning 1)
7841 (match-end 4)))))
7842 (if (match-end 5) (setq re (concat re "[ \t]+"
7843 (regexp-quote
7844 (match-string 5)))))
7845 (setq re (concat re "[ \t]*$"))
7846 (when org-refile-use-outline-path
7847 (setq txt (mapconcat 'identity
7848 (append
7849 (if (eq org-refile-use-outline-path 'file)
7850 (list (file-name-nondirectory
7851 (buffer-file-name (buffer-base-buffer))))
7852 (if (eq org-refile-use-outline-path 'full-file-path)
7853 (list (buffer-file-name (buffer-base-buffer)))))
7854 (org-get-outline-path)
7855 (list txt))
7856 "/")))
7857 (push (list txt f re (point)) targets))
7858 (goto-char (point-at-eol))))))))
7859 (nreverse targets))))
7861 (defun org-get-outline-path ()
7862 "Return the outline path to the current entry, as a list."
7863 (let (rtn)
7864 (save-excursion
7865 (while (org-up-heading-safe)
7866 (when (looking-at org-complex-heading-regexp)
7867 (push (org-match-string-no-properties 4) rtn)))
7868 rtn)))
7870 (defvar org-refile-history nil
7871 "History for refiling operations.")
7873 (defun org-refile (&optional goto default-buffer)
7874 "Move the entry at point to another heading.
7875 The list of target headings is compiled using the information in
7876 `org-refile-targets', which see. This list is created before each use
7877 and will therefore always be up-to-date.
7879 At the target location, the entry is filed as a subitem of the target heading.
7880 Depending on `org-reverse-note-order', the new subitem will either be the
7881 first of the last subitem.
7883 With prefix arg GOTO, the command will only visit the target location,
7884 not actually move anything.
7885 With a double prefix `C-u C-u', go to the location where the last refiling
7886 operation has put the subtree."
7887 (interactive "P")
7888 (let* ((cbuf (current-buffer))
7889 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7890 pos it nbuf file re level reversed)
7891 (if (equal goto '(16))
7892 (org-refile-goto-last-stored)
7893 (when (setq it (org-refile-get-location
7894 (if goto "Goto: " "Refile to: ") default-buffer))
7895 (setq file (nth 1 it)
7896 re (nth 2 it)
7897 pos (nth 3 it))
7898 (setq nbuf (or (find-buffer-visiting file)
7899 (find-file-noselect file)))
7900 (if goto
7901 (progn
7902 (switch-to-buffer nbuf)
7903 (goto-char pos)
7904 (org-show-context 'org-goto))
7905 (org-copy-subtree 1 nil t)
7906 (save-excursion
7907 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7908 (find-file-noselect file))))
7909 (setq reversed (org-notes-order-reversed-p))
7910 (save-excursion
7911 (save-restriction
7912 (widen)
7913 (goto-char pos)
7914 (looking-at outline-regexp)
7915 (setq level (org-get-valid-level (funcall outline-level) 1))
7916 (goto-char
7917 (if reversed
7918 (outline-next-heading)
7919 (or (save-excursion (outline-get-next-sibling))
7920 (org-end-of-subtree t t)
7921 (point-max))))
7922 (bookmark-set "org-refile-last-stored")
7923 (org-paste-subtree level))))
7924 (org-cut-subtree)
7925 (setq org-markers-to-move nil)
7926 (message "Entry refiled to \"%s\"" (car it)))))))
7928 (defun org-refile-goto-last-stored ()
7929 "Go to the location where the last refile was stored."
7930 (interactive)
7931 (bookmark-jump "org-refile-last-stored")
7932 (message "This is the location of the last refile"))
7934 (defun org-refile-get-location (&optional prompt default-buffer)
7935 "Prompt the user for a refile location, using PROMPT."
7936 (let ((org-refile-targets org-refile-targets)
7937 (org-refile-use-outline-path org-refile-use-outline-path))
7938 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7939 (unless org-refile-target-table
7940 (error "No refile targets"))
7941 (let* ((cbuf (current-buffer))
7942 (cfunc (if org-refile-use-outline-path
7943 'org-olpath-completing-read
7944 'completing-read))
7945 (extra (if org-refile-use-outline-path "/" ""))
7946 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7947 (fname (and filename (file-truename filename)))
7948 (tbl (mapcar
7949 (lambda (x)
7950 (if (not (equal fname (file-truename (nth 1 x))))
7951 (cons (concat (car x) extra " ("
7952 (file-name-nondirectory (nth 1 x)) ")")
7953 (cdr x))
7954 (cons (concat (car x) extra) (cdr x))))
7955 org-refile-target-table))
7956 (completion-ignore-case t))
7957 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7958 tbl)))
7960 (defun org-olpath-completing-read (prompt collection &rest args)
7961 "Read an outline path like a file name."
7962 (let ((thetable collection))
7963 (apply
7964 'completing-read prompt
7965 (lambda (string predicate &optional flag)
7966 (let (rtn r s f (l (length string)))
7967 (cond
7968 ((eq flag nil)
7969 ;; try completion
7970 (try-completion string thetable))
7971 ((eq flag t)
7972 ;; all-completions
7973 (setq rtn (all-completions string thetable predicate))
7974 (mapcar
7975 (lambda (x)
7976 (setq r (substring x l))
7977 (if (string-match " ([^)]*)$" x)
7978 (setq f (match-string 0 x))
7979 (setq f ""))
7980 (if (string-match "/" r)
7981 (concat string (substring r 0 (match-end 0)) f)
7983 rtn))
7984 ((eq flag 'lambda)
7985 ;; exact match?
7986 (assoc string thetable)))
7988 args)))
7990 ;;;; Dynamic blocks
7992 (defun org-find-dblock (name)
7993 "Find the first dynamic block with name NAME in the buffer.
7994 If not found, stay at current position and return nil."
7995 (let (pos)
7996 (save-excursion
7997 (goto-char (point-min))
7998 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7999 nil t)
8000 (match-beginning 0))))
8001 (if pos (goto-char pos))
8002 pos))
8004 (defconst org-dblock-start-re
8005 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8006 "Matches the startline of a dynamic block, with parameters.")
8008 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8009 "Matches the end of a dyhamic block.")
8011 (defun org-create-dblock (plist)
8012 "Create a dynamic block section, with parameters taken from PLIST.
8013 PLIST must containe a :name entry which is used as name of the block."
8014 (unless (bolp) (newline))
8015 (let ((name (plist-get plist :name)))
8016 (insert "#+BEGIN: " name)
8017 (while plist
8018 (if (eq (car plist) :name)
8019 (setq plist (cddr plist))
8020 (insert " " (prin1-to-string (pop plist)))))
8021 (insert "\n\n#+END:\n")
8022 (beginning-of-line -2)))
8024 (defun org-prepare-dblock ()
8025 "Prepare dynamic block for refresh.
8026 This empties the block, puts the cursor at the insert position and returns
8027 the property list including an extra property :name with the block name."
8028 (unless (looking-at org-dblock-start-re)
8029 (error "Not at a dynamic block"))
8030 (let* ((begdel (1+ (match-end 0)))
8031 (name (org-no-properties (match-string 1)))
8032 (params (append (list :name name)
8033 (read (concat "(" (match-string 3) ")")))))
8034 (unless (re-search-forward org-dblock-end-re nil t)
8035 (error "Dynamic block not terminated"))
8036 (setq params
8037 (append params
8038 (list :content (buffer-substring
8039 begdel (match-beginning 0)))))
8040 (delete-region begdel (match-beginning 0))
8041 (goto-char begdel)
8042 (open-line 1)
8043 params))
8045 (defun org-map-dblocks (&optional command)
8046 "Apply COMMAND to all dynamic blocks in the current buffer.
8047 If COMMAND is not given, use `org-update-dblock'."
8048 (let ((cmd (or command 'org-update-dblock))
8049 pos)
8050 (save-excursion
8051 (goto-char (point-min))
8052 (while (re-search-forward org-dblock-start-re nil t)
8053 (goto-char (setq pos (match-beginning 0)))
8054 (condition-case nil
8055 (funcall cmd)
8056 (error (message "Error during update of dynamic block")))
8057 (goto-char pos)
8058 (unless (re-search-forward org-dblock-end-re nil t)
8059 (error "Dynamic block not terminated"))))))
8061 (defun org-dblock-update (&optional arg)
8062 "User command for updating dynamic blocks.
8063 Update the dynamic block at point. With prefix ARG, update all dynamic
8064 blocks in the buffer."
8065 (interactive "P")
8066 (if arg
8067 (org-update-all-dblocks)
8068 (or (looking-at org-dblock-start-re)
8069 (org-beginning-of-dblock))
8070 (org-update-dblock)))
8072 (defun org-update-dblock ()
8073 "Update the dynamic block at point
8074 This means to empty the block, parse for parameters and then call
8075 the correct writing function."
8076 (save-window-excursion
8077 (let* ((pos (point))
8078 (line (org-current-line))
8079 (params (org-prepare-dblock))
8080 (name (plist-get params :name))
8081 (cmd (intern (concat "org-dblock-write:" name))))
8082 (message "Updating dynamic block `%s' at line %d..." name line)
8083 (funcall cmd params)
8084 (message "Updating dynamic block `%s' at line %d...done" name line)
8085 (goto-char pos))))
8087 (defun org-beginning-of-dblock ()
8088 "Find the beginning of the dynamic block at point.
8089 Error if there is no scuh block at point."
8090 (let ((pos (point))
8091 beg)
8092 (end-of-line 1)
8093 (if (and (re-search-backward org-dblock-start-re nil t)
8094 (setq beg (match-beginning 0))
8095 (re-search-forward org-dblock-end-re nil t)
8096 (> (match-end 0) pos))
8097 (goto-char beg)
8098 (goto-char pos)
8099 (error "Not in a dynamic block"))))
8101 (defun org-update-all-dblocks ()
8102 "Update all dynamic blocks in the buffer.
8103 This function can be used in a hook."
8104 (when (org-mode-p)
8105 (org-map-dblocks 'org-update-dblock)))
8108 ;;;; Completion
8110 (defconst org-additional-option-like-keywords
8111 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8112 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8113 "BEGIN_EXAMPLE" "END_EXAMPLE"
8114 "BEGIN_QUOTE" "END_QUOTE"
8115 "BEGIN_VERSE" "END_VERSE"
8116 "BEGIN_SRC" "END_SRC"))
8118 (defcustom org-structure-template-alist
8120 ("s" "#+begin_src ?\n\n#+end_src"
8121 "<src lang=\"?\">\n\n</src>")
8122 ("e" "#+begin_example\n?\n#+end_example"
8123 "<example>\n?\n</example>")
8124 ("q" "#+begin_quote\n?\n#+end_quote"
8125 "<quote>\n?\n</quote>")
8126 ("v" "#+begin_verse\n?\n#+end_verse"
8127 "<verse>\n?\n/verse>")
8128 ("l" "#+begin_latex\n?\n#+end_latex"
8129 "<literal style=\"latex\">\n?\n</literal>")
8130 ("L" "#+latex: "
8131 "<literal style=\"latex\">?</literal>")
8132 ("h" "#+begin_html\n?\n#+end_html"
8133 "<literal style=\"html\">\n?\n</literal>")
8134 ("H" "#+html: "
8135 "<literal style=\"html\">?</literal>")
8136 ("a" "#+begin_ascii\n?\n#+end_ascii")
8137 ("A" "#+ascii: ")
8138 ("i" "#+include %file ?"
8139 "<include file=%file markup=\"?\">")
8141 "Structure completion elements.
8142 This is a list of abbreviation keys and values. The value gets inserted
8143 it you type @samp{.} followed by the key and then the completion key,
8144 usually `M-TAB'. %file will be replaced by a file name after prompting
8145 for the file uning completion.
8146 There are two templates for each key, the first uses the original Org syntax,
8147 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8148 the default when the /org-mtags.el/ module has been loaded. See also the
8149 variable `org-mtags-prefere-muse-templates'.
8150 This is an experimental feature, it is undecided if it is going to stay in."
8151 :group 'org-completion
8152 :type '(repeat
8153 (string :tag "Key")
8154 (string :tag "Template")
8155 (string :tag "Muse Template")))
8157 (defun org-try-structure-completion ()
8158 "Try to complete a structure template before point.
8159 This looks for strings like \"<e\" on an otherwise empty line and
8160 expands them."
8161 (let ((l (buffer-substring (point-at-bol) (point)))
8163 (when (and (looking-at "[ \t]*$")
8164 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8165 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8166 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8167 (match-beginning 1)) a)
8168 t)))
8170 (defun org-complete-expand-structure-template (start cell)
8171 "Expand a structure template."
8172 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8173 (rpl (nth (if musep 2 1) cell)))
8174 (delete-region start (point))
8175 (when (string-match "\\`#\\+" rpl)
8176 (cond
8177 ((bolp))
8178 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8179 (delete-region (point-at-bol) (point)))
8180 (t (newline))))
8181 (setq start (point))
8182 (if (string-match "%file" rpl)
8183 (setq rpl (replace-match
8184 (concat
8185 "\""
8186 (save-match-data
8187 (abbreviate-file-name (read-file-name "Include file: ")))
8188 "\"")
8189 t t rpl)))
8190 (insert rpl)
8191 (if (re-search-backward "\\?" start t) (delete-char 1))))
8194 (defun org-complete (&optional arg)
8195 "Perform completion on word at point.
8196 At the beginning of a headline, this completes TODO keywords as given in
8197 `org-todo-keywords'.
8198 If the current word is preceded by a backslash, completes the TeX symbols
8199 that are supported for HTML support.
8200 If the current word is preceded by \"#+\", completes special words for
8201 setting file options.
8202 In the line after \"#+STARTUP:, complete valid keywords.\"
8203 At all other locations, this simply calls the value of
8204 `org-completion-fallback-command'."
8205 (interactive "P")
8206 (org-without-partial-completion
8207 (catch 'exit
8208 (let* ((a nil)
8209 (end (point))
8210 (beg1 (save-excursion
8211 (skip-chars-backward (org-re "[:alnum:]_@"))
8212 (point)))
8213 (beg (save-excursion
8214 (skip-chars-backward "a-zA-Z0-9_:$")
8215 (point)))
8216 (confirm (lambda (x) (stringp (car x))))
8217 (searchhead (equal (char-before beg) ?*))
8218 (struct
8219 (when (and (member (char-before beg1) '(?. ?<))
8220 (setq a (assoc (buffer-substring beg1 (point))
8221 org-structure-template-alist)))
8222 (org-complete-expand-structure-template (1- beg1) a)
8223 (throw 'exit t)))
8224 (tag (and (equal (char-before beg1) ?:)
8225 (equal (char-after (point-at-bol)) ?*)))
8226 (prop (and (equal (char-before beg1) ?:)
8227 (not (equal (char-after (point-at-bol)) ?*))))
8228 (texp (equal (char-before beg) ?\\))
8229 (link (equal (char-before beg) ?\[))
8230 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8231 beg)
8232 "#+"))
8233 (startup (string-match "^#\\+STARTUP:.*"
8234 (buffer-substring (point-at-bol) (point))))
8235 (completion-ignore-case opt)
8236 (type nil)
8237 (tbl nil)
8238 (table (cond
8239 (opt
8240 (setq type :opt)
8241 (require 'org-exp)
8242 (append
8243 (mapcar
8244 (lambda (x)
8245 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8246 (cons (match-string 2 x) (match-string 1 x)))
8247 (org-split-string (org-get-current-options) "\n"))
8248 (mapcar 'list org-additional-option-like-keywords)))
8249 (startup
8250 (setq type :startup)
8251 org-startup-options)
8252 (link (append org-link-abbrev-alist-local
8253 org-link-abbrev-alist))
8254 (texp
8255 (setq type :tex)
8256 org-html-entities)
8257 ((string-match "\\`\\*+[ \t]+\\'"
8258 (buffer-substring (point-at-bol) beg))
8259 (setq type :todo)
8260 (mapcar 'list org-todo-keywords-1))
8261 (searchhead
8262 (setq type :searchhead)
8263 (save-excursion
8264 (goto-char (point-min))
8265 (while (re-search-forward org-todo-line-regexp nil t)
8266 (push (list
8267 (org-make-org-heading-search-string
8268 (match-string 3) t))
8269 tbl)))
8270 tbl)
8271 (tag (setq type :tag beg beg1)
8272 (or org-tag-alist (org-get-buffer-tags)))
8273 (prop (setq type :prop beg beg1)
8274 (mapcar 'list (org-buffer-property-keys nil t t)))
8275 (t (progn
8276 (call-interactively org-completion-fallback-command)
8277 (throw 'exit nil)))))
8278 (pattern (buffer-substring-no-properties beg end))
8279 (completion (try-completion pattern table confirm)))
8280 (cond ((eq completion t)
8281 (if (not (assoc (upcase pattern) table))
8282 (message "Already complete")
8283 (if (and (equal type :opt)
8284 (not (member (car (assoc (upcase pattern) table))
8285 org-additional-option-like-keywords)))
8286 (insert (substring (cdr (assoc (upcase pattern) table))
8287 (length pattern)))
8288 (if (memq type '(:tag :prop)) (insert ":")))))
8289 ((null completion)
8290 (message "Can't find completion for \"%s\"" pattern)
8291 (ding))
8292 ((not (string= pattern completion))
8293 (delete-region beg end)
8294 (if (string-match " +$" completion)
8295 (setq completion (replace-match "" t t completion)))
8296 (insert completion)
8297 (if (get-buffer-window "*Completions*")
8298 (delete-window (get-buffer-window "*Completions*")))
8299 (if (assoc completion table)
8300 (if (eq type :todo) (insert " ")
8301 (if (memq type '(:tag :prop)) (insert ":"))))
8302 (if (and (equal type :opt) (assoc completion table))
8303 (message "%s" (substitute-command-keys
8304 "Press \\[org-complete] again to insert example settings"))))
8306 (message "Making completion list...")
8307 (let ((list (sort (all-completions pattern table confirm)
8308 'string<)))
8309 (with-output-to-temp-buffer "*Completions*"
8310 (condition-case nil
8311 ;; Protection needed for XEmacs and emacs 21
8312 (display-completion-list list pattern)
8313 (error (display-completion-list list)))))
8314 (message "Making completion list...%s" "done")))))))
8316 ;;;; TODO, DEADLINE, Comments
8318 (defun org-toggle-comment ()
8319 "Change the COMMENT state of an entry."
8320 (interactive)
8321 (save-excursion
8322 (org-back-to-heading)
8323 (let (case-fold-search)
8324 (if (looking-at (concat outline-regexp
8325 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8326 (replace-match "" t t nil 1)
8327 (if (looking-at outline-regexp)
8328 (progn
8329 (goto-char (match-end 0))
8330 (insert org-comment-string " ")))))))
8332 (defvar org-last-todo-state-is-todo nil
8333 "This is non-nil when the last TODO state change led to a TODO state.
8334 If the last change removed the TODO tag or switched to DONE, then
8335 this is nil.")
8337 (defvar org-setting-tags nil) ; dynamically skiped
8339 (defun org-parse-local-options (string var)
8340 "Parse STRING for startup setting relevant for variable VAR."
8341 (let ((rtn (symbol-value var))
8342 e opts)
8343 (save-match-data
8344 (if (or (not string) (not (string-match "\\S-" string)))
8346 (setq opts (delq nil (mapcar (lambda (x)
8347 (setq e (assoc x org-startup-options))
8348 (if (eq (nth 1 e) var) e nil))
8349 (org-split-string string "[ \t]+"))))
8350 (if (not opts)
8352 (setq rtn nil)
8353 (while (setq e (pop opts))
8354 (if (not (nth 3 e))
8355 (setq rtn (nth 2 e))
8356 (if (not (listp rtn)) (setq rtn nil))
8357 (push (nth 2 e) rtn)))
8358 rtn)))))
8360 (defvar org-blocker-hook nil
8361 "Hook for functions that are allowed to block a state change.
8363 Each function gets as its single argument a property list, see
8364 `org-trigger-hook' for more information about this list.
8366 If any of the functions in this hook returns nil, the state change
8367 is blocked.")
8369 (defvar org-trigger-hook nil
8370 "Hook for functions that are triggered by a state change.
8372 Each function gets as its single argument a property list with at least
8373 the following elements:
8375 (:type type-of-change :position pos-at-entry-start
8376 :from old-state :to new-state)
8378 Depending on the type, more properties may be present.
8380 This mechanism is currently implemented for:
8382 TODO state changes
8383 ------------------
8384 :type todo-state-change
8385 :from previous state (keyword as a string), or nil
8386 :to new state (keyword as a string), or nil")
8389 (defun org-todo (&optional arg)
8390 "Change the TODO state of an item.
8391 The state of an item is given by a keyword at the start of the heading,
8392 like
8393 *** TODO Write paper
8394 *** DONE Call mom
8396 The different keywords are specified in the variable `org-todo-keywords'.
8397 By default the available states are \"TODO\" and \"DONE\".
8398 So for this example: when the item starts with TODO, it is changed to DONE.
8399 When it starts with DONE, the DONE is removed. And when neither TODO nor
8400 DONE are present, add TODO at the beginning of the heading.
8402 With C-u prefix arg, use completion to determine the new state.
8403 With numeric prefix arg, switch to that state.
8405 For calling through lisp, arg is also interpreted in the following way:
8406 'none -> empty state
8407 \"\"(empty string) -> switch to empty state
8408 'done -> switch to DONE
8409 'nextset -> switch to the next set of keywords
8410 'previousset -> switch to the previous set of keywords
8411 \"WAITING\" -> switch to the specified keyword, but only if it
8412 really is a member of `org-todo-keywords'."
8413 (interactive "P")
8414 (save-excursion
8415 (catch 'exit
8416 (org-back-to-heading)
8417 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8418 (or (looking-at (concat " +" org-todo-regexp " *"))
8419 (looking-at " *"))
8420 (let* ((match-data (match-data))
8421 (startpos (point-at-bol))
8422 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8423 (org-log-done org-log-done)
8424 (org-log-repeat org-log-repeat)
8425 (org-todo-log-states org-todo-log-states)
8426 (this (match-string 1))
8427 (hl-pos (match-beginning 0))
8428 (head (org-get-todo-sequence-head this))
8429 (ass (assoc head org-todo-kwd-alist))
8430 (interpret (nth 1 ass))
8431 (done-word (nth 3 ass))
8432 (final-done-word (nth 4 ass))
8433 (last-state (or this ""))
8434 (completion-ignore-case t)
8435 (member (member this org-todo-keywords-1))
8436 (tail (cdr member))
8437 (state (cond
8438 ((and org-todo-key-trigger
8439 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8440 (and (not arg) org-use-fast-todo-selection
8441 (not (eq org-use-fast-todo-selection 'prefix)))))
8442 ;; Use fast selection
8443 (org-fast-todo-selection))
8444 ((and (equal arg '(4))
8445 (or (not org-use-fast-todo-selection)
8446 (not org-todo-key-trigger)))
8447 ;; Read a state with completion
8448 (completing-read "State: " (mapcar (lambda(x) (list x))
8449 org-todo-keywords-1)
8450 nil t))
8451 ((eq arg 'right)
8452 (if this
8453 (if tail (car tail) nil)
8454 (car org-todo-keywords-1)))
8455 ((eq arg 'left)
8456 (if (equal member org-todo-keywords-1)
8458 (if this
8459 (nth (- (length org-todo-keywords-1) (length tail) 2)
8460 org-todo-keywords-1)
8461 (org-last org-todo-keywords-1))))
8462 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8463 (setq arg nil))) ; hack to fall back to cycling
8464 (arg
8465 ;; user or caller requests a specific state
8466 (cond
8467 ((equal arg "") nil)
8468 ((eq arg 'none) nil)
8469 ((eq arg 'done) (or done-word (car org-done-keywords)))
8470 ((eq arg 'nextset)
8471 (or (car (cdr (member head org-todo-heads)))
8472 (car org-todo-heads)))
8473 ((eq arg 'previousset)
8474 (let ((org-todo-heads (reverse org-todo-heads)))
8475 (or (car (cdr (member head org-todo-heads)))
8476 (car org-todo-heads))))
8477 ((car (member arg org-todo-keywords-1)))
8478 ((nth (1- (prefix-numeric-value arg))
8479 org-todo-keywords-1))))
8480 ((null member) (or head (car org-todo-keywords-1)))
8481 ((equal this final-done-word) nil) ;; -> make empty
8482 ((null tail) nil) ;; -> first entry
8483 ((eq interpret 'sequence)
8484 (car tail))
8485 ((memq interpret '(type priority))
8486 (if (eq this-command last-command)
8487 (car tail)
8488 (if (> (length tail) 0)
8489 (or done-word (car org-done-keywords))
8490 nil)))
8491 (t nil)))
8492 (next (if state (concat " " state " ") " "))
8493 (change-plist (list :type 'todo-state-change :from this :to state
8494 :position startpos))
8495 dolog now-done-p)
8496 (when org-blocker-hook
8497 (unless (save-excursion
8498 (save-match-data
8499 (run-hook-with-args-until-failure
8500 'org-blocker-hook change-plist)))
8501 (if (interactive-p)
8502 (error "TODO state change from %s to %s blocked" this state)
8503 ;; fail silently
8504 (message "TODO state change from %s to %s blocked" this state)
8505 (throw 'exit nil))))
8506 (store-match-data match-data)
8507 (replace-match next t t)
8508 (unless (pos-visible-in-window-p hl-pos)
8509 (message "TODO state changed to %s" (org-trim next)))
8510 (unless head
8511 (setq head (org-get-todo-sequence-head state)
8512 ass (assoc head org-todo-kwd-alist)
8513 interpret (nth 1 ass)
8514 done-word (nth 3 ass)
8515 final-done-word (nth 4 ass)))
8516 (when (memq arg '(nextset previousset))
8517 (message "Keyword-Set %d/%d: %s"
8518 (- (length org-todo-sets) -1
8519 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8520 (length org-todo-sets)
8521 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8522 (setq org-last-todo-state-is-todo
8523 (not (member state org-done-keywords)))
8524 (setq now-done-p (and (member state org-done-keywords)
8525 (not (member this org-done-keywords))))
8526 (and logging (org-local-logging logging))
8527 (when (and (or org-todo-log-states org-log-done)
8528 (not (memq arg '(nextset previousset))))
8529 ;; we need to look at recording a time and note
8530 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8531 (nth 2 (assoc this org-todo-log-states))))
8532 (when (and state
8533 (member state org-not-done-keywords)
8534 (not (member this org-not-done-keywords)))
8535 ;; This is now a todo state and was not one before
8536 ;; If there was a CLOSED time stamp, get rid of it.
8537 (org-add-planning-info nil nil 'closed))
8538 (when (and now-done-p org-log-done)
8539 ;; It is now done, and it was not done before
8540 (org-add-planning-info 'closed (org-current-time))
8541 (if (and (not dolog) (eq 'note org-log-done))
8542 (org-add-log-setup 'done state 'findpos 'note)))
8543 (when (and state dolog)
8544 ;; This is a non-nil state, and we need to log it
8545 (org-add-log-setup 'state state 'findpos dolog)))
8546 ;; Fixup tag positioning
8547 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8548 (when org-provide-todo-statistics
8549 (org-update-parent-todo-statistics))
8550 (run-hooks 'org-after-todo-state-change-hook)
8551 (if (and arg (not (member state org-done-keywords)))
8552 (setq head (org-get-todo-sequence-head state)))
8553 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8554 ;; Do we need to trigger a repeat?
8555 (when now-done-p (org-auto-repeat-maybe state))
8556 ;; Fixup cursor location if close to the keyword
8557 (if (and (outline-on-heading-p)
8558 (not (bolp))
8559 (save-excursion (beginning-of-line 1)
8560 (looking-at org-todo-line-regexp))
8561 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8562 (progn
8563 (goto-char (or (match-end 2) (match-end 1)))
8564 (just-one-space)))
8565 (when org-trigger-hook
8566 (save-excursion
8567 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8569 (defun org-update-parent-todo-statistics ()
8570 "Update any statistics cookie in the parent of the current headline."
8571 (interactive)
8572 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8573 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8574 (catch 'exit
8575 (save-excursion
8576 (setq level (org-up-heading-safe))
8577 (unless (and level
8578 (re-search-forward box-re (point-at-eol) t))
8579 (throw 'exit nil))
8580 (setq is-percent (match-end 2))
8581 (save-match-data
8582 (unless (outline-next-heading) (throw 'exit nil))
8583 (while (looking-at org-todo-line-regexp)
8584 (setq kwd (match-string 2))
8585 (and kwd (setq cnt-all (1+ cnt-all)))
8586 (and (member kwd org-done-keywords)
8587 (setq cnt-done (1+ cnt-done)))
8588 (condition-case nil
8589 (outline-forward-same-level 1)
8590 (error (end-of-line 1)))))
8591 (replace-match
8592 (if is-percent
8593 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8594 (format "[%d/%d]" cnt-done cnt-all)))
8595 (run-hook-with-args 'org-after-todo-statistics-hook
8596 cnt-done (- cnt-all cnt-done))))))
8598 (defvar org-after-todo-statistics-hook nil
8599 "Hook that is called after a TODO statistics cookie has been updated.
8600 Each function is called with two arguments: the number of not-done entries
8601 and the number of done entries.
8603 For example, the following function, when added to this hook, will switch
8604 an entry to DONE when all children are done, and back to TODO when new
8605 entries are set to a TODO status. Note that this hook is only called
8606 when there is a statistics cookie in the headline!
8608 (defun org-summary-todo (n-done n-not-done)
8609 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8610 (let (org-log-done org-log-states) ; turn off logging
8611 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8614 (defun org-local-logging (value)
8615 "Get logging settings from a property VALUE."
8616 (let* (words w a)
8617 ;; directly set the variables, they are already local.
8618 (setq org-log-done nil
8619 org-log-repeat nil
8620 org-todo-log-states nil)
8621 (setq words (org-split-string value))
8622 (while (setq w (pop words))
8623 (cond
8624 ((setq a (assoc w org-startup-options))
8625 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8626 (set (nth 1 a) (nth 2 a))))
8627 ((setq a (org-extract-log-state-settings w))
8628 (and (member (car a) org-todo-keywords-1)
8629 (push a org-todo-log-states)))))))
8631 (defun org-get-todo-sequence-head (kwd)
8632 "Return the head of the TODO sequence to which KWD belongs.
8633 If KWD is not set, check if there is a text property remembering the
8634 right sequence."
8635 (let (p)
8636 (cond
8637 ((not kwd)
8638 (or (get-text-property (point-at-bol) 'org-todo-head)
8639 (progn
8640 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8641 nil (point-at-eol)))
8642 (get-text-property p 'org-todo-head))))
8643 ((not (member kwd org-todo-keywords-1))
8644 (car org-todo-keywords-1))
8645 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8647 (defun org-fast-todo-selection ()
8648 "Fast TODO keyword selection with single keys.
8649 Returns the new TODO keyword, or nil if no state change should occur."
8650 (let* ((fulltable org-todo-key-alist)
8651 (done-keywords org-done-keywords) ;; needed for the faces.
8652 (maxlen (apply 'max (mapcar
8653 (lambda (x)
8654 (if (stringp (car x)) (string-width (car x)) 0))
8655 fulltable)))
8656 (expert nil)
8657 (fwidth (+ maxlen 3 1 3))
8658 (ncol (/ (- (window-width) 4) fwidth))
8659 tg cnt e c tbl
8660 groups ingroup)
8661 (save-window-excursion
8662 (if expert
8663 (set-buffer (get-buffer-create " *Org todo*"))
8664 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8665 (erase-buffer)
8666 (org-set-local 'org-done-keywords done-keywords)
8667 (setq tbl fulltable cnt 0)
8668 (while (setq e (pop tbl))
8669 (cond
8670 ((equal e '(:startgroup))
8671 (push '() groups) (setq ingroup t)
8672 (when (not (= cnt 0))
8673 (setq cnt 0)
8674 (insert "\n"))
8675 (insert "{ "))
8676 ((equal e '(:endgroup))
8677 (setq ingroup nil cnt 0)
8678 (insert "}\n"))
8680 (setq tg (car e) c (cdr e))
8681 (if ingroup (push tg (car groups)))
8682 (setq tg (org-add-props tg nil 'face
8683 (org-get-todo-face tg)))
8684 (if (and (= cnt 0) (not ingroup)) (insert " "))
8685 (insert "[" c "] " tg (make-string
8686 (- fwidth 4 (length tg)) ?\ ))
8687 (when (= (setq cnt (1+ cnt)) ncol)
8688 (insert "\n")
8689 (if ingroup (insert " "))
8690 (setq cnt 0)))))
8691 (insert "\n")
8692 (goto-char (point-min))
8693 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8694 (fit-window-to-buffer))
8695 (message "[a-z..]:Set [SPC]:clear")
8696 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8697 (cond
8698 ((or (= c ?\C-g)
8699 (and (= c ?q) (not (rassoc c fulltable))))
8700 (setq quit-flag t))
8701 ((= c ?\ ) nil)
8702 ((setq e (rassoc c fulltable) tg (car e))
8704 (t (setq quit-flag t))))))
8706 (defun org-entry-is-todo-p ()
8707 (member (org-get-todo-state) org-not-done-keywords))
8709 (defun org-entry-is-done-p ()
8710 (member (org-get-todo-state) org-done-keywords))
8712 (defun org-get-todo-state ()
8713 (save-excursion
8714 (org-back-to-heading t)
8715 (and (looking-at org-todo-line-regexp)
8716 (match-end 2)
8717 (match-string 2))))
8719 (defun org-at-date-range-p (&optional inactive-ok)
8720 "Is the cursor inside a date range?"
8721 (interactive)
8722 (save-excursion
8723 (catch 'exit
8724 (let ((pos (point)))
8725 (skip-chars-backward "^[<\r\n")
8726 (skip-chars-backward "<[")
8727 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8728 (>= (match-end 0) pos)
8729 (throw 'exit t))
8730 (skip-chars-backward "^<[\r\n")
8731 (skip-chars-backward "<[")
8732 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8733 (>= (match-end 0) pos)
8734 (throw 'exit t)))
8735 nil)))
8737 (defun org-get-repeat ()
8738 "Check if there is a deadline/schedule with repeater in this entry."
8739 (save-match-data
8740 (save-excursion
8741 (org-back-to-heading t)
8742 (if (re-search-forward
8743 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8744 (match-string 1)))))
8746 (defvar org-last-changed-timestamp)
8747 (defvar org-last-inserted-timestamp)
8748 (defvar org-log-post-message)
8749 (defvar org-log-note-purpose)
8750 (defvar org-log-note-how)
8751 (defvar org-log-note-extra)
8752 (defun org-auto-repeat-maybe (done-word)
8753 "Check if the current headline contains a repeated deadline/schedule.
8754 If yes, set TODO state back to what it was and change the base date
8755 of repeating deadline/scheduled time stamps to new date.
8756 This function is run automatically after each state change to a DONE state."
8757 ;; last-state is dynamically scoped into this function
8758 (let* ((repeat (org-get-repeat))
8759 (aa (assoc last-state org-todo-kwd-alist))
8760 (interpret (nth 1 aa))
8761 (head (nth 2 aa))
8762 (whata '(("d" . day) ("m" . month) ("y" . year)))
8763 (msg "Entry repeats: ")
8764 (org-log-done nil)
8765 (org-todo-log-states nil)
8766 (nshiftmax 10) (nshift 0)
8767 re type n what ts mb0 time)
8768 (when repeat
8769 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8770 (org-todo (if (eq interpret 'type) last-state head))
8771 (when org-log-repeat
8772 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8773 (memq 'org-add-log-note post-command-hook))
8774 ;; OK, we are already setup for some record
8775 (if (eq org-log-repeat 'note)
8776 ;; make sure we take a note, not only a time stamp
8777 (setq org-log-note-how 'note))
8778 ;; Set up for taking a record
8779 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8780 'findpos org-log-repeat)))
8781 (org-back-to-heading t)
8782 (org-add-planning-info nil nil 'closed)
8783 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8784 org-deadline-time-regexp "\\)\\|\\("
8785 org-ts-regexp "\\)"))
8786 (while (re-search-forward
8787 re (save-excursion (outline-next-heading) (point)) t)
8788 (setq type (if (match-end 1) org-scheduled-string
8789 (if (match-end 3) org-deadline-string "Plain:"))
8790 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8791 mb0 (match-beginning 0))
8792 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8793 (setq n (string-to-number (match-string 2 ts))
8794 what (match-string 3 ts))
8795 (if (equal what "w") (setq n (* n 7) what "d"))
8796 ;; Preparation, see if we need to modify the start date for the change
8797 (when (match-end 1)
8798 (setq time (save-match-data (org-time-string-to-time ts)))
8799 (cond
8800 ((equal (match-string 1 ts) ".")
8801 ;; Shift starting date to today
8802 (org-timestamp-change
8803 (- (time-to-days (current-time)) (time-to-days time))
8804 'day))
8805 ((equal (match-string 1 ts) "+")
8806 (while (or (= nshift 0)
8807 (<= (time-to-days time) (time-to-days (current-time))))
8808 (when (= (incf nshift) nshiftmax)
8809 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8810 (error "Abort")))
8811 (org-timestamp-change n (cdr (assoc what whata)))
8812 (org-at-timestamp-p t)
8813 (setq ts (match-string 1))
8814 (setq time (save-match-data (org-time-string-to-time ts))))
8815 (org-timestamp-change (- n) (cdr (assoc what whata)))
8816 ;; rematch, so that we have everything in place for the real shift
8817 (org-at-timestamp-p t)
8818 (setq ts (match-string 1))
8819 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8820 (org-timestamp-change n (cdr (assoc what whata)))
8821 (setq msg (concat msg type org-last-changed-timestamp " "))))
8822 (setq org-log-post-message msg)
8823 (message "%s" msg))))
8825 (defun org-show-todo-tree (arg)
8826 "Make a compact tree which shows all headlines marked with TODO.
8827 The tree will show the lines where the regexp matches, and all higher
8828 headlines above the match.
8829 With a \\[universal-argument] prefix, also show the DONE entries.
8830 With a numeric prefix N, construct a sparse tree for the Nth element
8831 of `org-todo-keywords-1'."
8832 (interactive "P")
8833 (let ((case-fold-search nil)
8834 (kwd-re
8835 (cond ((null arg) org-not-done-regexp)
8836 ((equal arg '(4))
8837 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8838 (mapcar 'list org-todo-keywords-1))))
8839 (concat "\\("
8840 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8841 "\\)\\>")))
8842 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8843 (regexp-quote (nth (1- (prefix-numeric-value arg))
8844 org-todo-keywords-1)))
8845 (t (error "Invalid prefix argument: %s" arg)))))
8846 (message "%d TODO entries found"
8847 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8849 (defun org-deadline (&optional remove time)
8850 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8851 With argument REMOVE, remove any deadline from the item.
8852 When TIME is set, it should be an internal time specification, and the
8853 scheduling will use the corresponding date."
8854 (interactive "P")
8855 (if remove
8856 (progn
8857 (org-remove-timestamp-with-keyword org-deadline-string)
8858 (message "Item no longer has a deadline."))
8859 (if (org-get-repeat)
8860 (error "Cannot change deadline on task with repeater, please do that by hand")
8861 (org-add-planning-info 'deadline time 'closed)
8862 (message "Deadline on %s" org-last-inserted-timestamp))))
8864 (defun org-schedule (&optional remove time)
8865 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8866 With argument REMOVE, remove any scheduling date from the item.
8867 When TIME is set, it should be an internal time specification, and the
8868 scheduling will use the corresponding date."
8869 (interactive "P")
8870 (if remove
8871 (progn
8872 (org-remove-timestamp-with-keyword org-scheduled-string)
8873 (message "Item is no longer scheduled."))
8874 (if (org-get-repeat)
8875 (error "Cannot reschedule task with repeater, please do that by hand")
8876 (org-add-planning-info 'scheduled time 'closed)
8877 (message "Scheduled to %s" org-last-inserted-timestamp))))
8879 (defun org-remove-timestamp-with-keyword (keyword)
8880 "Remove all time stamps with KEYWORD in the current entry."
8881 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8882 beg)
8883 (save-excursion
8884 (org-back-to-heading t)
8885 (setq beg (point))
8886 (org-end-of-subtree t t)
8887 (while (re-search-backward re beg t)
8888 (replace-match "")
8889 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8890 (equal (char-before) ?\ ))
8891 (backward-delete-char 1)
8892 (if (string-match "^[ \t]*$" (buffer-substring
8893 (point-at-bol) (point-at-eol)))
8894 (delete-region (point-at-bol)
8895 (min (point-max) (1+ (point-at-eol))))))))))
8897 (defun org-add-planning-info (what &optional time &rest remove)
8898 "Insert new timestamp with keyword in the line directly after the headline.
8899 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8900 If non is given, the user is prompted for a date.
8901 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8902 be removed."
8903 (interactive)
8904 (let (org-time-was-given org-end-time-was-given ts
8905 end default-time default-input)
8907 (when (and (not time) (memq what '(scheduled deadline)))
8908 ;; Try to get a default date/time from existing timestamp
8909 (save-excursion
8910 (org-back-to-heading t)
8911 (setq end (save-excursion (outline-next-heading) (point)))
8912 (when (re-search-forward (if (eq what 'scheduled)
8913 org-scheduled-time-regexp
8914 org-deadline-time-regexp)
8915 end t)
8916 (setq ts (match-string 1)
8917 default-time
8918 (apply 'encode-time (org-parse-time-string ts))
8919 default-input (and ts (org-get-compact-tod ts))))))
8920 (when what
8921 ;; If necessary, get the time from the user
8922 (setq time (or time (org-read-date nil 'to-time nil nil
8923 default-time default-input))))
8925 (when (and org-insert-labeled-timestamps-at-point
8926 (member what '(scheduled deadline)))
8927 (insert
8928 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8929 (org-insert-time-stamp time org-time-was-given
8930 nil nil nil (list org-end-time-was-given))
8931 (setq what nil))
8932 (save-excursion
8933 (save-restriction
8934 (let (col list elt ts buffer-invisibility-spec)
8935 (org-back-to-heading t)
8936 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8937 (goto-char (match-end 1))
8938 (setq col (current-column))
8939 (goto-char (match-end 0))
8940 (if (eobp) (insert "\n") (forward-char 1))
8941 (if (and (not (looking-at outline-regexp))
8942 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8943 "[^\r\n]*"))
8944 (not (equal (match-string 1) org-clock-string)))
8945 (narrow-to-region (match-beginning 0) (match-end 0))
8946 (insert-before-markers "\n")
8947 (backward-char 1)
8948 (narrow-to-region (point) (point))
8949 (and org-adapt-indentation (org-indent-to-column col)))
8950 ;; Check if we have to remove something.
8951 (setq list (cons what remove))
8952 (while list
8953 (setq elt (pop list))
8954 (goto-char (point-min))
8955 (when (or (and (eq elt 'scheduled)
8956 (re-search-forward org-scheduled-time-regexp nil t))
8957 (and (eq elt 'deadline)
8958 (re-search-forward org-deadline-time-regexp nil t))
8959 (and (eq elt 'closed)
8960 (re-search-forward org-closed-time-regexp nil t)))
8961 (replace-match "")
8962 (if (looking-at "--+<[^>]+>") (replace-match ""))
8963 (if (looking-at " +") (replace-match ""))))
8964 (goto-char (point-max))
8965 (when what
8966 (insert
8967 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8968 (cond ((eq what 'scheduled) org-scheduled-string)
8969 ((eq what 'deadline) org-deadline-string)
8970 ((eq what 'closed) org-closed-string))
8971 " ")
8972 (setq ts (org-insert-time-stamp
8973 time
8974 (or org-time-was-given
8975 (and (eq what 'closed) org-log-done-with-time))
8976 (eq what 'closed)
8977 nil nil (list org-end-time-was-given)))
8978 (end-of-line 1))
8979 (goto-char (point-min))
8980 (widen)
8981 (if (and (looking-at "[ \t]+\n")
8982 (equal (char-before) ?\n))
8983 (delete-region (1- (point)) (point-at-eol)))
8984 ts)))))
8986 (defvar org-log-note-marker (make-marker))
8987 (defvar org-log-note-purpose nil)
8988 (defvar org-log-note-state nil)
8989 (defvar org-log-note-how nil)
8990 (defvar org-log-note-extra nil)
8991 (defvar org-log-note-window-configuration nil)
8992 (defvar org-log-note-return-to (make-marker))
8993 (defvar org-log-post-message nil
8994 "Message to be displayed after a log note has been stored.
8995 The auto-repeater uses this.")
8997 (defun org-add-note ()
8998 "Add a note to the current entry.
8999 This is done in the same way as adding a state change note."
9000 (interactive)
9001 (org-add-log-setup 'note nil t nil))
9003 (defun org-add-log-setup (&optional purpose state findpos how extra)
9004 "Set up the post command hook to take a note.
9005 If this is about to TODO state change, the new state is expected in STATE.
9006 When FINDPOS is non-nil, find the correct position for the note in
9007 the current entry. If not, assume that it can be inserted at point.
9008 HOW is an indicator what kind of note should be created.
9009 EXTRA is additional text that will be inserted into the notes buffer."
9010 (save-excursion
9011 (when findpos
9012 (org-back-to-heading t)
9013 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9014 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9015 "[^\r\n]*\\)?"))
9016 (goto-char (match-end 0))
9017 (unless org-log-states-order-reversed
9018 (and (= (char-after) ?\n) (forward-char 1))
9019 (org-skip-over-state-notes)
9020 (skip-chars-backward " \t\n\r")))
9021 (move-marker org-log-note-marker (point))
9022 (setq org-log-note-purpose purpose
9023 org-log-note-state state
9024 org-log-note-how how
9025 org-log-note-extra extra)
9026 (add-hook 'post-command-hook 'org-add-log-note 'append)))
9028 (defun org-skip-over-state-notes ()
9029 "Skip past the list of State notes in an entry."
9030 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9031 (while (looking-at "[ \t]*- State")
9032 (condition-case nil
9033 (org-next-item)
9034 (error (org-end-of-item)))))
9036 (defun org-add-log-note (&optional purpose)
9037 "Pop up a window for taking a note, and add this note later at point."
9038 (remove-hook 'post-command-hook 'org-add-log-note)
9039 (setq org-log-note-window-configuration (current-window-configuration))
9040 (delete-other-windows)
9041 (move-marker org-log-note-return-to (point))
9042 (switch-to-buffer (marker-buffer org-log-note-marker))
9043 (goto-char org-log-note-marker)
9044 (org-switch-to-buffer-other-window "*Org Note*")
9045 (erase-buffer)
9046 (if (memq org-log-note-how '(time state))
9047 (org-store-log-note)
9048 (let ((org-inhibit-startup t)) (org-mode))
9049 (insert (format "# Insert note for %s.
9050 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9051 (cond
9052 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9053 ((eq org-log-note-purpose 'done) "closed todo item")
9054 ((eq org-log-note-purpose 'state)
9055 (format "state change to \"%s\"" org-log-note-state))
9056 ((eq org-log-note-purpose 'note)
9057 "this entry")
9058 (t (error "This should not happen")))))
9059 (if org-log-note-extra (insert org-log-note-extra))
9060 (org-set-local 'org-finish-function 'org-store-log-note)))
9062 (defvar org-note-abort nil) ; dynamically scoped
9063 (defun org-store-log-note ()
9064 "Finish taking a log note, and insert it to where it belongs."
9065 (let ((txt (buffer-string))
9066 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9067 lines ind)
9068 (kill-buffer (current-buffer))
9069 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9070 (setq txt (replace-match "" t t txt)))
9071 (if (string-match "\\s-+\\'" txt)
9072 (setq txt (replace-match "" t t txt)))
9073 (setq lines (org-split-string txt "\n"))
9074 (when (and note (string-match "\\S-" note))
9075 (setq note
9076 (org-replace-escapes
9077 note
9078 (list (cons "%u" (user-login-name))
9079 (cons "%U" user-full-name)
9080 (cons "%t" (format-time-string
9081 (org-time-stamp-format 'long 'inactive)
9082 (current-time)))
9083 (cons "%s" (if org-log-note-state
9084 (concat "\"" org-log-note-state "\"")
9085 "")))))
9086 (if lines (setq note (concat note " \\\\")))
9087 (push note lines))
9088 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9089 (when lines
9090 (save-excursion
9091 (set-buffer (marker-buffer org-log-note-marker))
9092 (save-excursion
9093 (goto-char org-log-note-marker)
9094 (move-marker org-log-note-marker nil)
9095 (end-of-line 1)
9096 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9097 (indent-relative nil)
9098 (insert "- " (pop lines))
9099 (org-indent-line-function)
9100 (beginning-of-line 1)
9101 (looking-at "[ \t]*")
9102 (setq ind (concat (match-string 0) " "))
9103 (end-of-line 1)
9104 (while lines (insert "\n" ind (pop lines)))))))
9105 (set-window-configuration org-log-note-window-configuration)
9106 (with-current-buffer (marker-buffer org-log-note-return-to)
9107 (goto-char org-log-note-return-to))
9108 (move-marker org-log-note-return-to nil)
9109 (and org-log-post-message (message "%s" org-log-post-message)))
9111 (defun org-sparse-tree (&optional arg)
9112 "Create a sparse tree, prompt for the details.
9113 This command can create sparse trees. You first need to select the type
9114 of match used to create the tree:
9116 t Show entries with a specific TODO keyword.
9117 T Show entries selected by a tags match.
9118 p Enter a property name and its value (both with completion on existing
9119 names/values) and show entries with that property.
9120 r Show entries matching a regular expression
9121 d Show deadlines due within `org-deadline-warning-days'."
9122 (interactive "P")
9123 (let (ans kwd value)
9124 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9125 (setq ans (read-char-exclusive))
9126 (cond
9127 ((equal ans ?d)
9128 (call-interactively 'org-check-deadlines))
9129 ((equal ans ?b)
9130 (call-interactively 'org-check-before-date))
9131 ((equal ans ?t)
9132 (org-show-todo-tree '(4)))
9133 ((equal ans ?T)
9134 (call-interactively 'org-tags-sparse-tree))
9135 ((member ans '(?p ?P))
9136 (setq kwd (completing-read "Property: "
9137 (mapcar 'list (org-buffer-property-keys))))
9138 (setq value (completing-read "Value: "
9139 (mapcar 'list (org-property-values kwd))))
9140 (unless (string-match "\\`{.*}\\'" value)
9141 (setq value (concat "\"" value "\"")))
9142 (org-tags-sparse-tree arg (concat kwd "=" value)))
9143 ((member ans '(?r ?R ?/))
9144 (call-interactively 'org-occur))
9145 (t (error "No such sparse tree command \"%c\"" ans)))))
9147 (defvar org-occur-highlights nil
9148 "List of overlays used for occur matches.")
9149 (make-variable-buffer-local 'org-occur-highlights)
9150 (defvar org-occur-parameters nil
9151 "Parameters of the active org-occur calls.
9152 This is a list, each call to org-occur pushes as cons cell,
9153 containing the regular expression and the callback, onto the list.
9154 The list can contain several entries if `org-occur' has been called
9155 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9156 will only contain one set of parameters. When the highlights are
9157 removed (for example with `C-c C-c', or with the next edit (depending
9158 on `org-remove-highlights-with-change'), this variable is emptied
9159 as well.")
9160 (make-variable-buffer-local 'org-occur-parameters)
9162 (defun org-occur (regexp &optional keep-previous callback)
9163 "Make a compact tree which shows all matches of REGEXP.
9164 The tree will show the lines where the regexp matches, and all higher
9165 headlines above the match. It will also show the heading after the match,
9166 to make sure editing the matching entry is easy.
9167 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9168 call to `org-occur' will be kept, to allow stacking of calls to this
9169 command.
9170 If CALLBACK is non-nil, it is a function which is called to confirm
9171 that the match should indeed be shown."
9172 (interactive "sRegexp: \nP")
9173 (unless keep-previous
9174 (org-remove-occur-highlights nil nil t))
9175 (push (cons regexp callback) org-occur-parameters)
9176 (let ((cnt 0))
9177 (save-excursion
9178 (goto-char (point-min))
9179 (if (or (not keep-previous) ; do not want to keep
9180 (not org-occur-highlights)) ; no previous matches
9181 ;; hide everything
9182 (org-overview))
9183 (while (re-search-forward regexp nil t)
9184 (when (or (not callback)
9185 (save-match-data (funcall callback)))
9186 (setq cnt (1+ cnt))
9187 (when org-highlight-sparse-tree-matches
9188 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9189 (org-show-context 'occur-tree))))
9190 (when org-remove-highlights-with-change
9191 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9192 nil 'local))
9193 (unless org-sparse-tree-open-archived-trees
9194 (org-hide-archived-subtrees (point-min) (point-max)))
9195 (run-hooks 'org-occur-hook)
9196 (if (interactive-p)
9197 (message "%d match(es) for regexp %s" cnt regexp))
9198 cnt))
9200 (defun org-show-context (&optional key)
9201 "Make sure point and context and visible.
9202 How much context is shown depends upon the variables
9203 `org-show-hierarchy-above', `org-show-following-heading'. and
9204 `org-show-siblings'."
9205 (let ((heading-p (org-on-heading-p t))
9206 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9207 (following-p (org-get-alist-option org-show-following-heading key))
9208 (entry-p (org-get-alist-option org-show-entry-below key))
9209 (siblings-p (org-get-alist-option org-show-siblings key)))
9210 (catch 'exit
9211 ;; Show heading or entry text
9212 (if (and heading-p (not entry-p))
9213 (org-flag-heading nil) ; only show the heading
9214 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9215 (org-show-hidden-entry))) ; show entire entry
9216 (when following-p
9217 ;; Show next sibling, or heading below text
9218 (save-excursion
9219 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9220 (org-flag-heading nil))))
9221 (when siblings-p (org-show-siblings))
9222 (when hierarchy-p
9223 ;; show all higher headings, possibly with siblings
9224 (save-excursion
9225 (while (and (condition-case nil
9226 (progn (org-up-heading-all 1) t)
9227 (error nil))
9228 (not (bobp)))
9229 (org-flag-heading nil)
9230 (when siblings-p (org-show-siblings))))))))
9232 (defun org-reveal (&optional siblings)
9233 "Show current entry, hierarchy above it, and the following headline.
9234 This can be used to show a consistent set of context around locations
9235 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9236 not t for the search context.
9238 With optional argument SIBLINGS, on each level of the hierarchy all
9239 siblings are shown. This repairs the tree structure to what it would
9240 look like when opened with hierarchical calls to `org-cycle'."
9241 (interactive "P")
9242 (let ((org-show-hierarchy-above t)
9243 (org-show-following-heading t)
9244 (org-show-siblings (if siblings t org-show-siblings)))
9245 (org-show-context nil)))
9247 (defun org-highlight-new-match (beg end)
9248 "Highlight from BEG to END and mark the highlight is an occur headline."
9249 (let ((ov (org-make-overlay beg end)))
9250 (org-overlay-put ov 'face 'secondary-selection)
9251 (push ov org-occur-highlights)))
9253 (defun org-remove-occur-highlights (&optional beg end noremove)
9254 "Remove the occur highlights from the buffer.
9255 BEG and END are ignored. If NOREMOVE is nil, remove this function
9256 from the `before-change-functions' in the current buffer."
9257 (interactive)
9258 (unless org-inhibit-highlight-removal
9259 (mapc 'org-delete-overlay org-occur-highlights)
9260 (setq org-occur-highlights nil)
9261 (setq org-occur-parameters nil)
9262 (unless noremove
9263 (remove-hook 'before-change-functions
9264 'org-remove-occur-highlights 'local))))
9266 ;;;; Priorities
9268 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9269 "Regular expression matching the priority indicator.")
9271 (defvar org-remove-priority-next-time nil)
9273 (defun org-priority-up ()
9274 "Increase the priority of the current item."
9275 (interactive)
9276 (org-priority 'up))
9278 (defun org-priority-down ()
9279 "Decrease the priority of the current item."
9280 (interactive)
9281 (org-priority 'down))
9283 (defun org-priority (&optional action)
9284 "Change the priority of an item by ARG.
9285 ACTION can be `set', `up', `down', or a character."
9286 (interactive)
9287 (setq action (or action 'set))
9288 (let (current new news have remove)
9289 (save-excursion
9290 (org-back-to-heading)
9291 (if (looking-at org-priority-regexp)
9292 (setq current (string-to-char (match-string 2))
9293 have t)
9294 (setq current org-default-priority))
9295 (cond
9296 ((or (eq action 'set)
9297 (if (featurep 'xemacs) (characterp action) (integerp action)))
9298 (if (not (eq action 'set))
9299 (setq new action)
9300 (message "Priority %c-%c, SPC to remove: "
9301 org-highest-priority org-lowest-priority)
9302 (setq new (read-char-exclusive)))
9303 (if (and (= (upcase org-highest-priority) org-highest-priority)
9304 (= (upcase org-lowest-priority) org-lowest-priority))
9305 (setq new (upcase new)))
9306 (cond ((equal new ?\ ) (setq remove t))
9307 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9308 (error "Priority must be between `%c' and `%c'"
9309 org-highest-priority org-lowest-priority))))
9310 ((eq action 'up)
9311 (if (and (not have) (eq last-command this-command))
9312 (setq new org-lowest-priority)
9313 (setq new (if (and org-priority-start-cycle-with-default (not have))
9314 org-default-priority (1- current)))))
9315 ((eq action 'down)
9316 (if (and (not have) (eq last-command this-command))
9317 (setq new org-highest-priority)
9318 (setq new (if (and org-priority-start-cycle-with-default (not have))
9319 org-default-priority (1+ current)))))
9320 (t (error "Invalid action")))
9321 (if (or (< (upcase new) org-highest-priority)
9322 (> (upcase new) org-lowest-priority))
9323 (setq remove t))
9324 (setq news (format "%c" new))
9325 (if have
9326 (if remove
9327 (replace-match "" t t nil 1)
9328 (replace-match news t t nil 2))
9329 (if remove
9330 (error "No priority cookie found in line")
9331 (looking-at org-todo-line-regexp)
9332 (if (match-end 2)
9333 (progn
9334 (goto-char (match-end 2))
9335 (insert " [#" news "]"))
9336 (goto-char (match-beginning 3))
9337 (insert "[#" news "] ")))))
9338 (org-preserve-lc (org-set-tags nil 'align))
9339 (if remove
9340 (message "Priority removed")
9341 (message "Priority of current item set to %s" news))))
9344 (defun org-get-priority (s)
9345 "Find priority cookie and return priority."
9346 (save-match-data
9347 (if (not (string-match org-priority-regexp s))
9348 (* 1000 (- org-lowest-priority org-default-priority))
9349 (* 1000 (- org-lowest-priority
9350 (string-to-char (match-string 2 s)))))))
9352 ;;;; Tags
9354 (defvar org-agenda-archives-mode)
9355 (defun org-scan-tags (action matcher &optional todo-only)
9356 "Scan headline tags with inheritance and produce output ACTION.
9358 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9359 or `agenda' to produce an entry list for an agenda view. It can also be
9360 a Lisp form or a function that should be called at each matched headline, in
9361 this case the return value is a list of all return values from these calls.
9363 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9364 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9365 only lines with a TODO keyword are included in the output."
9366 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9367 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9368 (org-re
9369 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9370 (props (list 'face 'default
9371 'done-face 'org-done
9372 'undone-face 'default
9373 'mouse-face 'highlight
9374 'org-not-done-regexp org-not-done-regexp
9375 'org-todo-regexp org-todo-regexp
9376 'keymap org-agenda-keymap
9377 'help-echo
9378 (format "mouse-2 or RET jump to org file %s"
9379 (abbreviate-file-name
9380 (or (buffer-file-name (buffer-base-buffer))
9381 (buffer-name (buffer-base-buffer)))))))
9382 (case-fold-search nil)
9383 lspos tags tags-list
9384 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9385 (llast 0) rtn rtn1 level category i txt
9386 todo marker entry priority)
9387 (when (not (member action '(agenda sparse-tree)))
9388 (setq action (list 'lambda nil action)))
9389 (save-excursion
9390 (goto-char (point-min))
9391 (when (eq action 'sparse-tree)
9392 (org-overview)
9393 (org-remove-occur-highlights))
9394 (while (re-search-forward re nil t)
9395 (catch :skip
9396 (setq todo (if (match-end 1) (match-string 2))
9397 tags (if (match-end 4) (match-string 4)))
9398 (goto-char (setq lspos (1+ (match-beginning 0))))
9399 (setq level (org-reduced-level (funcall outline-level))
9400 category (org-get-category))
9401 (setq i llast llast level)
9402 ;; remove tag lists from same and sublevels
9403 (while (>= i level)
9404 (when (setq entry (assoc i tags-alist))
9405 (setq tags-alist (delete entry tags-alist)))
9406 (setq i (1- i)))
9407 ;; add the next tags
9408 (when tags
9409 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9410 tags-alist
9411 (cons (cons level tags) tags-alist)))
9412 ;; compile tags for current headline
9413 (setq tags-list
9414 (if org-use-tag-inheritance
9415 (apply 'append (mapcar 'cdr tags-alist))
9416 tags))
9417 (when (and tags org-use-tag-inheritance
9418 (not (eq t org-use-tag-inheritance)))
9419 ;; selective inheritance, remove uninherited ones
9420 (setcdr (car tags-alist)
9421 (org-remove-uniherited-tags (cdar tags-alist))))
9422 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9423 (eval matcher)
9425 (not (member org-archive-tag tags-list))
9426 ;; we have an archive tag, should we use this anyway?
9427 (or (not org-agenda-skip-archived-trees)
9428 (and (eq action 'agenda) org-agenda-archives-mode))))
9429 (unless (eq action 'sparse-tree) (org-agenda-skip))
9431 ;; select this headline
9433 (cond
9434 ((eq action 'sparse-tree)
9435 (and org-highlight-sparse-tree-matches
9436 (org-get-heading) (match-end 0)
9437 (org-highlight-new-match
9438 (match-beginning 0) (match-beginning 1)))
9439 (org-show-context 'tags-tree))
9440 ((eq action 'agenda)
9441 (setq txt (org-format-agenda-item
9443 (concat
9444 (if org-tags-match-list-sublevels
9445 (make-string (1- level) ?.) "")
9446 (org-get-heading))
9447 category tags-list)
9448 priority (org-get-priority txt))
9449 (goto-char lspos)
9450 (setq marker (org-agenda-new-marker))
9451 (org-add-props txt props
9452 'org-marker marker 'org-hd-marker marker 'org-category category
9453 'priority priority 'type "tagsmatch")
9454 (push txt rtn))
9455 ((functionp action)
9456 (save-excursion
9457 (setq rtn1 (funcall action))
9458 (push rtn1 rtn))
9459 (goto-char (point-at-eol)))
9460 (t (error "Invalid action")))
9462 ;; if we are to skip sublevels, jump to end of subtree
9463 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9464 (when (and (eq action 'sparse-tree)
9465 (not org-sparse-tree-open-archived-trees))
9466 (org-hide-archived-subtrees (point-min) (point-max)))
9467 (nreverse rtn)))
9469 (defun org-remove-uniherited-tags (tags)
9470 "Remove all tags that are not inherited from the list TAGS."
9471 (cond
9472 ((eq org-use-tag-inheritance t) tags)
9473 ((not org-use-tag-inheritance) nil)
9474 ((stringp org-use-tag-inheritance)
9475 (delq nil (mapcar
9476 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9477 tags)))
9478 ((listp org-use-tag-inheritance)
9479 (org-delete-all org-use-tag-inheritance tags))))
9481 (defvar todo-only) ;; dynamically scoped
9483 (defun org-tags-sparse-tree (&optional todo-only match)
9484 "Create a sparse tree according to tags string MATCH.
9485 MATCH can contain positive and negative selection of tags, like
9486 \"+WORK+URGENT-WITHBOSS\".
9487 If optional argument TODO_ONLY is non-nil, only select lines that are
9488 also TODO lines."
9489 (interactive "P")
9490 (org-prepare-agenda-buffers (list (current-buffer)))
9491 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9493 (defvar org-cached-props nil)
9494 (defun org-cached-entry-get (pom property)
9495 (if (or (eq t org-use-property-inheritance)
9496 (and (stringp org-use-property-inheritance)
9497 (string-match org-use-property-inheritance property))
9498 (and (listp org-use-property-inheritance)
9499 (member property org-use-property-inheritance)))
9500 ;; Caching is not possible, check it directly
9501 (org-entry-get pom property 'inherit)
9502 ;; Get all properties, so that we can do complicated checks easily
9503 (cdr (assoc property (or org-cached-props
9504 (setq org-cached-props
9505 (org-entry-properties pom)))))))
9507 (defun org-global-tags-completion-table (&optional files)
9508 "Return the list of all tags in all agenda buffer/files."
9509 (save-excursion
9510 (org-uniquify
9511 (delq nil
9512 (apply 'append
9513 (mapcar
9514 (lambda (file)
9515 (set-buffer (find-file-noselect file))
9516 (append (org-get-buffer-tags)
9517 (mapcar (lambda (x) (if (stringp (car-safe x))
9518 (list (car-safe x)) nil))
9519 org-tag-alist)))
9520 (if (and files (car files))
9521 files
9522 (org-agenda-files))))))))
9524 (defun org-make-tags-matcher (match)
9525 "Create the TAGS//TODO matcher form for the selection string MATCH."
9526 ;; todo-only is scoped dynamically into this function, and the function
9527 ;; may change it it the matcher asksk for it.
9528 (unless match
9529 ;; Get a new match request, with completion
9530 (let ((org-last-tags-completion-table
9531 (org-global-tags-completion-table)))
9532 (setq match (completing-read
9533 "Match: " 'org-tags-completion-function nil nil nil
9534 'org-tags-history))))
9536 ;; Parse the string and create a lisp form
9537 (let ((match0 match)
9538 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9539 minus tag mm
9540 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9541 orterms term orlist re-p str-p level-p level-op time-p
9542 prop-p pn pv po cat-p gv)
9543 (if (string-match "/+" match)
9544 ;; match contains also a todo-matching request
9545 (progn
9546 (setq tagsmatch (substring match 0 (match-beginning 0))
9547 todomatch (substring match (match-end 0)))
9548 (if (string-match "^!" todomatch)
9549 (setq todo-only t todomatch (substring todomatch 1)))
9550 (if (string-match "^\\s-*$" todomatch)
9551 (setq todomatch nil)))
9552 ;; only matching tags
9553 (setq tagsmatch match todomatch nil))
9555 ;; Make the tags matcher
9556 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9557 (setq tagsmatcher t)
9558 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9559 (while (setq term (pop orterms))
9560 (while (and (equal (substring term -1) "\\") orterms)
9561 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9562 (while (string-match re term)
9563 (setq minus (and (match-end 1)
9564 (equal (match-string 1 term) "-"))
9565 tag (match-string 2 term)
9566 re-p (equal (string-to-char tag) ?{)
9567 level-p (match-end 4)
9568 prop-p (match-end 5)
9569 mm (cond
9570 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9571 (level-p
9572 (setq level-op (org-op-to-function (match-string 3 term)))
9573 `(,level-op level ,(string-to-number
9574 (match-string 4 term))))
9575 (prop-p
9576 (setq pn (match-string 5 term)
9577 po (match-string 6 term)
9578 pv (match-string 7 term)
9579 cat-p (equal pn "CATEGORY")
9580 re-p (equal (string-to-char pv) ?{)
9581 str-p (equal (string-to-char pv) ?\")
9582 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9583 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9584 (if time-p (setq pv (org-matcher-time pv)))
9585 (setq po (org-op-to-function po (if time-p 'time str-p)))
9586 (if (equal pn "CATEGORY")
9587 (setq gv '(get-text-property (point) 'org-category))
9588 (setq gv `(org-cached-entry-get nil ,pn)))
9589 (if re-p
9590 (if (eq po 'org<>)
9591 `(not (string-match ,pv (or ,gv "")))
9592 `(string-match ,pv (or ,gv "")))
9593 (if str-p
9594 `(,po (or ,gv "") ,pv)
9595 `(,po (string-to-number (or ,gv ""))
9596 ,(string-to-number pv) ))))
9597 (t `(member ,(downcase tag) tags-list)))
9598 mm (if minus (list 'not mm) mm)
9599 term (substring term (match-end 0)))
9600 (push mm tagsmatcher))
9601 (push (if (> (length tagsmatcher) 1)
9602 (cons 'and tagsmatcher)
9603 (car tagsmatcher))
9604 orlist)
9605 (setq tagsmatcher nil))
9606 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9607 (setq tagsmatcher
9608 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9609 ;; Make the todo matcher
9610 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9611 (setq todomatcher t)
9612 (setq orterms (org-split-string todomatch "|") orlist nil)
9613 (while (setq term (pop orterms))
9614 (while (string-match re term)
9615 (setq minus (and (match-end 1)
9616 (equal (match-string 1 term) "-"))
9617 kwd (match-string 2 term)
9618 re-p (equal (string-to-char kwd) ?{)
9619 term (substring term (match-end 0))
9620 mm (if re-p
9621 `(string-match ,(substring kwd 1 -1) todo)
9622 (list 'equal 'todo kwd))
9623 mm (if minus (list 'not mm) mm))
9624 (push mm todomatcher))
9625 (push (if (> (length todomatcher) 1)
9626 (cons 'and todomatcher)
9627 (car todomatcher))
9628 orlist)
9629 (setq todomatcher nil))
9630 (setq todomatcher (if (> (length orlist) 1)
9631 (cons 'or orlist) (car orlist))))
9633 ;; Return the string and lisp forms of the matcher
9634 (setq matcher (if todomatcher
9635 (list 'and tagsmatcher todomatcher)
9636 tagsmatcher))
9637 (cons match0 matcher)))
9639 (defun org-op-to-function (op &optional stringp)
9640 "Turn an operator into the appropriate function."
9641 (setq op
9642 (cond
9643 ((equal op "<" ) '(< string< org-time<))
9644 ((equal op ">" ) '(> org-string> org-time>))
9645 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9646 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9647 ((member op '("=" "==")) '(= string= org-time=))
9648 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9649 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9651 (defun org<> (a b) (not (= a b)))
9652 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9653 (defun org-string>= (a b) (not (string< a b)))
9654 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9655 (defun org-string<> (a b) (not (string= a b)))
9656 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9657 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9658 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9659 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9660 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9661 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9662 (defun org-2ft (s)
9663 "Convert S to a floating point time.
9664 If S is already a number, just return it. If it is a string, parse
9665 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9666 (cond
9667 ((numberp s) s)
9668 ((stringp s)
9669 (condition-case nil
9670 (float-time (apply 'encode-time (org-parse-time-string s)))
9671 (error 0.)))
9672 (t 0.)))
9674 (defun org-matcher-time (s)
9675 (cond
9676 ((equal s "<now>") (float-time))
9677 ((equal s "<today>")
9678 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9679 (t (org-2ft s))))
9681 (defun org-match-any-p (re list)
9682 "Does re match any element of list?"
9683 (setq list (mapcar (lambda (x) (string-match re x)) list))
9684 (delq nil list))
9686 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9687 (defvar org-tags-overlay (org-make-overlay 1 1))
9688 (org-detach-overlay org-tags-overlay)
9690 (defun org-get-tags-at (&optional pos)
9691 "Get a list of all headline tags applicable at POS.
9692 POS defaults to point. If tags are inherited, the list contains
9693 the targets in the same sequence as the headlines appear, i.e.
9694 the tags of the current headline come last."
9695 (interactive)
9696 (let (tags ltags lastpos parent)
9697 (save-excursion
9698 (save-restriction
9699 (widen)
9700 (goto-char (or pos (point)))
9701 (save-match-data
9702 (condition-case nil
9703 (progn
9704 (org-back-to-heading t)
9705 (while (not (equal lastpos (point)))
9706 (setq lastpos (point))
9707 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9708 (setq ltags (org-split-string
9709 (org-match-string-no-properties 1) ":"))
9710 (setq tags (append (org-remove-uniherited-tags ltags)
9711 tags)))
9712 (or org-use-tag-inheritance (error ""))
9713 (org-up-heading-all 1)
9714 (setq parent t)))
9715 (error nil))))
9716 (append (org-remove-uniherited-tags org-file-tags) tags))))
9718 (defun org-toggle-tag (tag &optional onoff)
9719 "Toggle the tag TAG for the current line.
9720 If ONOFF is `on' or `off', don't toggle but set to this state."
9721 (unless (org-on-heading-p t) (error "Not on headling"))
9722 (let (res current)
9723 (save-excursion
9724 (beginning-of-line)
9725 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9726 (point-at-eol) t)
9727 (progn
9728 (setq current (match-string 1))
9729 (replace-match ""))
9730 (setq current ""))
9731 (setq current (nreverse (org-split-string current ":")))
9732 (cond
9733 ((eq onoff 'on)
9734 (setq res t)
9735 (or (member tag current) (push tag current)))
9736 ((eq onoff 'off)
9737 (or (not (member tag current)) (setq current (delete tag current))))
9738 (t (if (member tag current)
9739 (setq current (delete tag current))
9740 (setq res t)
9741 (push tag current))))
9742 (end-of-line 1)
9743 (if current
9744 (progn
9745 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9746 (org-set-tags nil t))
9747 (delete-horizontal-space))
9748 (run-hooks 'org-after-tags-change-hook))
9749 res))
9751 (defun org-align-tags-here (to-col)
9752 ;; Assumes that this is a headline
9753 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9754 (beginning-of-line 1)
9755 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9756 (< pos (match-beginning 2)))
9757 (progn
9758 (setq tags-l (- (match-end 2) (match-beginning 2)))
9759 (goto-char (match-beginning 1))
9760 (insert " ")
9761 (delete-region (point) (1+ (match-beginning 2)))
9762 (setq ncol (max (1+ (current-column))
9763 (1+ col)
9764 (if (> to-col 0)
9765 to-col
9766 (- (abs to-col) tags-l))))
9767 (setq p (point))
9768 (insert (make-string (- ncol (current-column)) ?\ ))
9769 (setq ncol (current-column))
9770 (when indent-tabs-mode (tabify p (point-at-eol)))
9771 (org-move-to-column (min ncol col) t))
9772 (goto-char pos))))
9774 (defun org-set-tags (&optional arg just-align)
9775 "Set the tags for the current headline.
9776 With prefix ARG, realign all tags in headings in the current buffer."
9777 (interactive "P")
9778 (let* ((re (concat "^" outline-regexp))
9779 (current (org-get-tags-string))
9780 (col (current-column))
9781 (org-setting-tags t)
9782 table current-tags inherited-tags ; computed below when needed
9783 tags p0 c0 c1 rpl)
9784 (if arg
9785 (save-excursion
9786 (goto-char (point-min))
9787 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9788 (while (re-search-forward re nil t)
9789 (org-set-tags nil t)
9790 (end-of-line 1)))
9791 (message "All tags realigned to column %d" org-tags-column))
9792 (if just-align
9793 (setq tags current)
9794 ;; Get a new set of tags from the user
9795 (save-excursion
9796 (setq table (or org-tag-alist (org-get-buffer-tags))
9797 org-last-tags-completion-table table
9798 current-tags (org-split-string current ":")
9799 inherited-tags (nreverse
9800 (nthcdr (length current-tags)
9801 (nreverse (org-get-tags-at))))
9802 tags
9803 (if (or (eq t org-use-fast-tag-selection)
9804 (and org-use-fast-tag-selection
9805 (delq nil (mapcar 'cdr table))))
9806 (org-fast-tag-selection
9807 current-tags inherited-tags table
9808 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9809 (let ((org-add-colon-after-tag-completion t))
9810 (org-trim
9811 (org-without-partial-completion
9812 (completing-read "Tags: " 'org-tags-completion-function
9813 nil nil current 'org-tags-history)))))))
9814 (while (string-match "[-+&]+" tags)
9815 ;; No boolean logic, just a list
9816 (setq tags (replace-match ":" t t tags))))
9818 (if (string-match "\\`[\t ]*\\'" tags)
9819 (setq tags "")
9820 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9821 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9823 ;; Insert new tags at the correct column
9824 (beginning-of-line 1)
9825 (cond
9826 ((and (equal current "") (equal tags "")))
9827 ((re-search-forward
9828 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9829 (point-at-eol) t)
9830 (if (equal tags "")
9831 (setq rpl "")
9832 (goto-char (match-beginning 0))
9833 (setq c0 (current-column) p0 (point)
9834 c1 (max (1+ c0) (if (> org-tags-column 0)
9835 org-tags-column
9836 (- (- org-tags-column) (length tags))))
9837 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9838 (replace-match rpl t t)
9839 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9840 tags)
9841 (t (error "Tags alignment failed")))
9842 (org-move-to-column col)
9843 (unless just-align
9844 (run-hooks 'org-after-tags-change-hook)))))
9846 (defun org-change-tag-in-region (beg end tag off)
9847 "Add or remove TAG for each entry in the region.
9848 This works in the agenda, and also in an org-mode buffer."
9849 (interactive
9850 (list (region-beginning) (region-end)
9851 (let ((org-last-tags-completion-table
9852 (if (org-mode-p)
9853 (org-get-buffer-tags)
9854 (org-global-tags-completion-table))))
9855 (completing-read
9856 "Tag: " 'org-tags-completion-function nil nil nil
9857 'org-tags-history))
9858 (progn
9859 (message "[s]et or [r]emove? ")
9860 (equal (read-char-exclusive) ?r))))
9861 (if (fboundp 'deactivate-mark) (deactivate-mark))
9862 (let ((agendap (equal major-mode 'org-agenda-mode))
9863 l1 l2 m buf pos newhead (cnt 0))
9864 (goto-char end)
9865 (setq l2 (1- (org-current-line)))
9866 (goto-char beg)
9867 (setq l1 (org-current-line))
9868 (loop for l from l1 to l2 do
9869 (goto-line l)
9870 (setq m (get-text-property (point) 'org-hd-marker))
9871 (when (or (and (org-mode-p) (org-on-heading-p))
9872 (and agendap m))
9873 (setq buf (if agendap (marker-buffer m) (current-buffer))
9874 pos (if agendap m (point)))
9875 (with-current-buffer buf
9876 (save-excursion
9877 (save-restriction
9878 (goto-char pos)
9879 (setq cnt (1+ cnt))
9880 (org-toggle-tag tag (if off 'off 'on))
9881 (setq newhead (org-get-heading)))))
9882 (and agendap (org-agenda-change-all-lines newhead m))))
9883 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9885 (defun org-tags-completion-function (string predicate &optional flag)
9886 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9887 (confirm (lambda (x) (stringp (car x)))))
9888 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9889 (setq s1 (match-string 1 string)
9890 s2 (match-string 2 string))
9891 (setq s1 "" s2 string))
9892 (cond
9893 ((eq flag nil)
9894 ;; try completion
9895 (setq rtn (try-completion s2 ctable confirm))
9896 (if (stringp rtn)
9897 (setq rtn
9898 (concat s1 s2 (substring rtn (length s2))
9899 (if (and org-add-colon-after-tag-completion
9900 (assoc rtn ctable))
9901 ":" ""))))
9902 rtn)
9903 ((eq flag t)
9904 ;; all-completions
9905 (all-completions s2 ctable confirm)
9907 ((eq flag 'lambda)
9908 ;; exact match?
9909 (assoc s2 ctable)))
9912 (defun org-fast-tag-insert (kwd tags face &optional end)
9913 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9914 (insert (format "%-12s" (concat kwd ":"))
9915 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9916 (or end "")))
9918 (defun org-fast-tag-show-exit (flag)
9919 (save-excursion
9920 (goto-line 3)
9921 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9922 (replace-match ""))
9923 (when flag
9924 (end-of-line 1)
9925 (org-move-to-column (- (window-width) 19) t)
9926 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9928 (defun org-set-current-tags-overlay (current prefix)
9929 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9930 (if (featurep 'xemacs)
9931 (org-overlay-display org-tags-overlay (concat prefix s)
9932 'secondary-selection)
9933 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9934 (org-overlay-display org-tags-overlay (concat prefix s)))))
9936 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9937 "Fast tag selection with single keys.
9938 CURRENT is the current list of tags in the headline, INHERITED is the
9939 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9940 possibly with grouping information. TODO-TABLE is a similar table with
9941 TODO keywords, should these have keys assigned to them.
9942 If the keys are nil, a-z are automatically assigned.
9943 Returns the new tags string, or nil to not change the current settings."
9944 (let* ((fulltable (append table todo-table))
9945 (maxlen (apply 'max (mapcar
9946 (lambda (x)
9947 (if (stringp (car x)) (string-width (car x)) 0))
9948 fulltable)))
9949 (buf (current-buffer))
9950 (expert (eq org-fast-tag-selection-single-key 'expert))
9951 (buffer-tags nil)
9952 (fwidth (+ maxlen 3 1 3))
9953 (ncol (/ (- (window-width) 4) fwidth))
9954 (i-face 'org-done)
9955 (c-face 'org-todo)
9956 tg cnt e c char c1 c2 ntable tbl rtn
9957 ov-start ov-end ov-prefix
9958 (exit-after-next org-fast-tag-selection-single-key)
9959 (done-keywords org-done-keywords)
9960 groups ingroup)
9961 (save-excursion
9962 (beginning-of-line 1)
9963 (if (looking-at
9964 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9965 (setq ov-start (match-beginning 1)
9966 ov-end (match-end 1)
9967 ov-prefix "")
9968 (setq ov-start (1- (point-at-eol))
9969 ov-end (1+ ov-start))
9970 (skip-chars-forward "^\n\r")
9971 (setq ov-prefix
9972 (concat
9973 (buffer-substring (1- (point)) (point))
9974 (if (> (current-column) org-tags-column)
9976 (make-string (- org-tags-column (current-column)) ?\ ))))))
9977 (org-move-overlay org-tags-overlay ov-start ov-end)
9978 (save-window-excursion
9979 (if expert
9980 (set-buffer (get-buffer-create " *Org tags*"))
9981 (delete-other-windows)
9982 (split-window-vertically)
9983 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9984 (erase-buffer)
9985 (org-set-local 'org-done-keywords done-keywords)
9986 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9987 (org-fast-tag-insert "Current" current c-face "\n\n")
9988 (org-fast-tag-show-exit exit-after-next)
9989 (org-set-current-tags-overlay current ov-prefix)
9990 (setq tbl fulltable char ?a cnt 0)
9991 (while (setq e (pop tbl))
9992 (cond
9993 ((equal e '(:startgroup))
9994 (push '() groups) (setq ingroup t)
9995 (when (not (= cnt 0))
9996 (setq cnt 0)
9997 (insert "\n"))
9998 (insert "{ "))
9999 ((equal e '(:endgroup))
10000 (setq ingroup nil cnt 0)
10001 (insert "}\n"))
10003 (setq tg (car e) c2 nil)
10004 (if (cdr e)
10005 (setq c (cdr e))
10006 ;; automatically assign a character.
10007 (setq c1 (string-to-char
10008 (downcase (substring
10009 tg (if (= (string-to-char tg) ?@) 1 0)))))
10010 (if (or (rassoc c1 ntable) (rassoc c1 table))
10011 (while (or (rassoc char ntable) (rassoc char table))
10012 (setq char (1+ char)))
10013 (setq c2 c1))
10014 (setq c (or c2 char)))
10015 (if ingroup (push tg (car groups)))
10016 (setq tg (org-add-props tg nil 'face
10017 (cond
10018 ((not (assoc tg table))
10019 (org-get-todo-face tg))
10020 ((member tg current) c-face)
10021 ((member tg inherited) i-face)
10022 (t nil))))
10023 (if (and (= cnt 0) (not ingroup)) (insert " "))
10024 (insert "[" c "] " tg (make-string
10025 (- fwidth 4 (length tg)) ?\ ))
10026 (push (cons tg c) ntable)
10027 (when (= (setq cnt (1+ cnt)) ncol)
10028 (insert "\n")
10029 (if ingroup (insert " "))
10030 (setq cnt 0)))))
10031 (setq ntable (nreverse ntable))
10032 (insert "\n")
10033 (goto-char (point-min))
10034 (if (and (not expert) (fboundp 'fit-window-to-buffer))
10035 (fit-window-to-buffer))
10036 (setq rtn
10037 (catch 'exit
10038 (while t
10039 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10040 (if groups " [!] no groups" " [!]groups")
10041 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10042 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10043 (cond
10044 ((= c ?\r) (throw 'exit t))
10045 ((= c ?!)
10046 (setq groups (not groups))
10047 (goto-char (point-min))
10048 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10049 ((= c ?\C-c)
10050 (if (not expert)
10051 (org-fast-tag-show-exit
10052 (setq exit-after-next (not exit-after-next)))
10053 (setq expert nil)
10054 (delete-other-windows)
10055 (split-window-vertically)
10056 (org-switch-to-buffer-other-window " *Org tags*")
10057 (and (fboundp 'fit-window-to-buffer)
10058 (fit-window-to-buffer))))
10059 ((or (= c ?\C-g)
10060 (and (= c ?q) (not (rassoc c ntable))))
10061 (org-detach-overlay org-tags-overlay)
10062 (setq quit-flag t))
10063 ((= c ?\ )
10064 (setq current nil)
10065 (if exit-after-next (setq exit-after-next 'now)))
10066 ((= c ?\t)
10067 (condition-case nil
10068 (setq tg (completing-read
10069 "Tag: "
10070 (or buffer-tags
10071 (with-current-buffer buf
10072 (org-get-buffer-tags)))))
10073 (quit (setq tg "")))
10074 (when (string-match "\\S-" tg)
10075 (add-to-list 'buffer-tags (list tg))
10076 (if (member tg current)
10077 (setq current (delete tg current))
10078 (push tg current)))
10079 (if exit-after-next (setq exit-after-next 'now)))
10080 ((setq e (rassoc c todo-table) tg (car e))
10081 (with-current-buffer buf
10082 (save-excursion (org-todo tg)))
10083 (if exit-after-next (setq exit-after-next 'now)))
10084 ((setq e (rassoc c ntable) tg (car e))
10085 (if (member tg current)
10086 (setq current (delete tg current))
10087 (loop for g in groups do
10088 (if (member tg g)
10089 (mapc (lambda (x)
10090 (setq current (delete x current)))
10091 g)))
10092 (push tg current))
10093 (if exit-after-next (setq exit-after-next 'now))))
10095 ;; Create a sorted list
10096 (setq current
10097 (sort current
10098 (lambda (a b)
10099 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10100 (if (eq exit-after-next 'now) (throw 'exit t))
10101 (goto-char (point-min))
10102 (beginning-of-line 2)
10103 (delete-region (point) (point-at-eol))
10104 (org-fast-tag-insert "Current" current c-face)
10105 (org-set-current-tags-overlay current ov-prefix)
10106 (while (re-search-forward
10107 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10108 (setq tg (match-string 1))
10109 (add-text-properties
10110 (match-beginning 1) (match-end 1)
10111 (list 'face
10112 (cond
10113 ((member tg current) c-face)
10114 ((member tg inherited) i-face)
10115 (t (get-text-property (match-beginning 1) 'face))))))
10116 (goto-char (point-min)))))
10117 (org-detach-overlay org-tags-overlay)
10118 (if rtn
10119 (mapconcat 'identity current ":")
10120 nil))))
10122 (defun org-get-tags-string ()
10123 "Get the TAGS string in the current headline."
10124 (unless (org-on-heading-p t)
10125 (error "Not on a heading"))
10126 (save-excursion
10127 (beginning-of-line 1)
10128 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10129 (org-match-string-no-properties 1)
10130 "")))
10132 (defun org-get-tags ()
10133 "Get the list of tags specified in the current headline."
10134 (org-split-string (org-get-tags-string) ":"))
10136 (defun org-get-buffer-tags ()
10137 "Get a table of all tags used in the buffer, for completion."
10138 (let (tags)
10139 (save-excursion
10140 (goto-char (point-min))
10141 (while (re-search-forward
10142 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10143 (when (equal (char-after (point-at-bol 0)) ?*)
10144 (mapc (lambda (x) (add-to-list 'tags x))
10145 (org-split-string (org-match-string-no-properties 1) ":")))))
10146 (mapcar 'list tags)))
10148 ;;;; The mapping API
10150 ;;;###autoload
10151 (defun org-map-entries (func &optional match scope &rest skip)
10152 "Call FUNC at each headline selected by MATCH in SCOPE.
10154 FUNC is a function or a lisp form. The function will be called without
10155 arguments, with the cursor positioned at the beginning of the headline.
10156 The return values of all calls to the function will be collected and
10157 returned as a list.
10159 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10160 Only headlines that are matched by this query will be considered during
10161 the iteration. When MATCH is nil or t, all headlines will be
10162 visited by the iteration.
10164 SCOPE determines the scope of this command. It can be any of:
10166 nil The current buffer, respecting the restriction if any
10167 tree The subtree started with the entry at point
10168 file The current buffer, without restriction
10169 file-with-archives
10170 The current buffer, and any archives associated with it
10171 agenda All agenda files
10172 agenda-with-archives
10173 All agenda files with any archive files associated with them
10174 \(file1 file2 ...)
10175 If this is a list, all files in the list will be scanned
10177 The remaining args are treated as settings for the skipping facilities of
10178 the scanner. The following items can be given here:
10180 archive skip trees with the archive tag.
10181 comment skip trees with the COMMENT keyword
10182 function or Emacs Lisp form:
10183 will be used as value for `org-agenda-skip-function', so whenever
10184 the the function returns t, FUNC will not be called for that
10185 entry and search will continue from the point where the
10186 function leaves it."
10187 (let* ((org-agenda-archives-mode nil) ; just to make sure
10188 (org-agenda-skip-archived-trees (memq 'archive skip))
10189 (org-agenda-skip-comment-trees (memq 'comment skip))
10190 (org-agenda-skip-function
10191 (car (org-delete-all '(comment archive) skip)))
10192 (org-tags-match-list-sublevels t)
10193 matcher pos file)
10195 (cond
10196 ((eq match t) (setq matcher t))
10197 ((eq match nil) (setq matcher t))
10198 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10200 (when (eq scope 'tree)
10201 (org-back-to-heading t)
10202 (org-narrow-to-subtree)
10203 (setq scope nil))
10205 (if (not scope)
10206 (progn
10207 (org-prepare-agenda-buffers
10208 (list (buffer-file-name (current-buffer))))
10209 (org-scan-tags func matcher))
10210 ;; Get the right scope
10211 (setq pos (point))
10212 (cond
10213 ((and scope (listp scope) (symbolp (car scope)))
10214 (setq scope (eval scope)))
10215 ((eq scope 'agenda)
10216 (setq scope (org-agenda-files t)))
10217 ((eq scope 'agenda-with-archives)
10218 (setq scope (org-agenda-files t))
10219 (setq scope (org-add-archive-files scope)))
10220 ((eq scope 'file)
10221 (setq scope (list (buffer-file-name))))
10222 ((eq scope 'file-with-archives)
10223 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10224 (org-prepare-agenda-buffers scope)
10225 (while (setq file (pop scope))
10226 (with-current-buffer (org-find-base-buffer-visiting file)
10227 (save-excursion
10228 (save-restriction
10229 (widen)
10230 (goto-char (point-min))
10231 (org-scan-tags func matcher))))))))
10233 ;;;; Properties
10235 ;;; Setting and retrieving properties
10237 (defconst org-special-properties
10238 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10239 "TIMESTAMP" "TIMESTAMP_IA")
10240 "The special properties valid in Org-mode.
10242 These are properties that are not defined in the property drawer,
10243 but in some other way.")
10245 (defconst org-default-properties
10246 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10247 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10248 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10249 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10250 "Some properties that are used by Org-mode for various purposes.
10251 Being in this list makes sure that they are offered for completion.")
10253 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10254 "Regular expression matching the first line of a property drawer.")
10256 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10257 "Regular expression matching the first line of a property drawer.")
10259 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10260 "Regular expression matching the first line of a property drawer.")
10262 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10263 "Regular expression matching the first line of a property drawer.")
10265 (defconst org-property-drawer-re
10266 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10267 org-property-end-re "\\)\n?")
10268 "Matches an entire property drawer.")
10270 (defconst org-clock-drawer-re
10271 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10272 org-property-end-re "\\)\n?")
10273 "Matches an entire clock drawer.")
10275 (defun org-property-action ()
10276 "Do an action on properties."
10277 (interactive)
10278 (let (c)
10279 (org-at-property-p)
10280 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10281 (setq c (read-char-exclusive))
10282 (cond
10283 ((equal c ?s)
10284 (call-interactively 'org-set-property))
10285 ((equal c ?d)
10286 (call-interactively 'org-delete-property))
10287 ((equal c ?D)
10288 (call-interactively 'org-delete-property-globally))
10289 ((equal c ?c)
10290 (call-interactively 'org-compute-property-at-point))
10291 (t (error "No such property action %c" c)))))
10293 (defun org-at-property-p ()
10294 "Is the cursor in a property line?"
10295 ;; FIXME: Does not check if we are actually in the drawer.
10296 ;; FIXME: also returns true on any drawers.....
10297 ;; This is used by C-c C-c for property action.
10298 (save-excursion
10299 (beginning-of-line 1)
10300 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10302 (defun org-get-property-block (&optional beg end force)
10303 "Return the (beg . end) range of the body of the property drawer.
10304 BEG and END can be beginning and end of subtree, if not given
10305 they will be found.
10306 If the drawer does not exist and FORCE is non-nil, create the drawer."
10307 (catch 'exit
10308 (save-excursion
10309 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10310 (end (or end (progn (outline-next-heading) (point)))))
10311 (goto-char beg)
10312 (if (re-search-forward org-property-start-re end t)
10313 (setq beg (1+ (match-end 0)))
10314 (if force
10315 (save-excursion
10316 (org-insert-property-drawer)
10317 (setq end (progn (outline-next-heading) (point))))
10318 (throw 'exit nil))
10319 (goto-char beg)
10320 (if (re-search-forward org-property-start-re end t)
10321 (setq beg (1+ (match-end 0)))))
10322 (if (re-search-forward org-property-end-re end t)
10323 (setq end (match-beginning 0))
10324 (or force (throw 'exit nil))
10325 (goto-char beg)
10326 (setq end beg)
10327 (org-indent-line-function)
10328 (insert ":END:\n"))
10329 (cons beg end)))))
10331 (defun org-entry-properties (&optional pom which)
10332 "Get all properties of the entry at point-or-marker POM.
10333 This includes the TODO keyword, the tags, time strings for deadline,
10334 scheduled, and clocking, and any additional properties defined in the
10335 entry. The return value is an alist, keys may occur multiple times
10336 if the property key was used several times.
10337 POM may also be nil, in which case the current entry is used.
10338 If WHICH is nil or `all', get all properties. If WHICH is
10339 `special' or `standard', only get that subclass."
10340 (setq which (or which 'all))
10341 (org-with-point-at pom
10342 (let ((clockstr (substring org-clock-string 0 -1))
10343 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10344 beg end range props sum-props key value string clocksum)
10345 (save-excursion
10346 (when (condition-case nil (org-back-to-heading t) (error nil))
10347 (setq beg (point))
10348 (setq sum-props (get-text-property (point) 'org-summaries))
10349 (setq clocksum (get-text-property (point) :org-clock-minutes))
10350 (outline-next-heading)
10351 (setq end (point))
10352 (when (memq which '(all special))
10353 ;; Get the special properties, like TODO and tags
10354 (goto-char beg)
10355 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10356 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10357 (when (looking-at org-priority-regexp)
10358 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10359 (when (and (setq value (org-get-tags-string))
10360 (string-match "\\S-" value))
10361 (push (cons "TAGS" value) props))
10362 (when (setq value (org-get-tags-at))
10363 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10364 props))
10365 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10366 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10367 string (if (equal key clockstr)
10368 (org-no-properties
10369 (org-trim
10370 (buffer-substring
10371 (match-beginning 3) (goto-char (point-at-eol)))))
10372 (substring (org-match-string-no-properties 3) 1 -1)))
10373 (unless key
10374 (if (= (char-after (match-beginning 3)) ?\[)
10375 (setq key "TIMESTAMP_IA")
10376 (setq key "TIMESTAMP")))
10377 (when (or (equal key clockstr) (not (assoc key props)))
10378 (push (cons key string) props)))
10382 (when (memq which '(all standard))
10383 ;; Get the standard properties, like :PORP: ...
10384 (setq range (org-get-property-block beg end))
10385 (when range
10386 (goto-char (car range))
10387 (while (re-search-forward
10388 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10389 (cdr range) t)
10390 (setq key (org-match-string-no-properties 1)
10391 value (org-trim (or (org-match-string-no-properties 2) "")))
10392 (unless (member key excluded)
10393 (push (cons key (or value "")) props)))))
10394 (if clocksum
10395 (push (cons "CLOCKSUM"
10396 (org-columns-number-to-string (/ (float clocksum) 60.)
10397 'add_times))
10398 props))
10399 (append sum-props (nreverse props)))))))
10401 (defun org-entry-get (pom property &optional inherit)
10402 "Get value of PROPERTY for entry at point-or-marker POM.
10403 If INHERIT is non-nil and the entry does not have the property,
10404 then also check higher levels of the hierarchy.
10405 If INHERIT is the symbol `selective', use inheritance only if the setting
10406 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10407 If the property is present but empty, the return value is the empty string.
10408 If the property is not present at all, nil is returned."
10409 (org-with-point-at pom
10410 (if (and inherit (if (eq inherit 'selective)
10411 (org-property-inherit-p property)
10413 (org-entry-get-with-inheritance property)
10414 (if (member property org-special-properties)
10415 ;; We need a special property. Use brute force, get all properties.
10416 (cdr (assoc property (org-entry-properties nil 'special)))
10417 (let ((range (org-get-property-block)))
10418 (if (and range
10419 (goto-char (car range))
10420 (re-search-forward
10421 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10422 (cdr range) t))
10423 ;; Found the property, return it.
10424 (if (match-end 1)
10425 (org-match-string-no-properties 1)
10426 "")))))))
10428 (defun org-property-or-variable-value (var &optional inherit)
10429 "Check if there is a property fixing the value of VAR.
10430 If yes, return this value. If not, return the current value of the variable."
10431 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10432 (if (and prop (stringp prop) (string-match "\\S-" prop))
10433 (read prop)
10434 (symbol-value var))))
10436 (defun org-entry-delete (pom property)
10437 "Delete the property PROPERTY from entry at point-or-marker POM."
10438 (org-with-point-at pom
10439 (if (member property org-special-properties)
10440 nil ; cannot delete these properties.
10441 (let ((range (org-get-property-block)))
10442 (if (and range
10443 (goto-char (car range))
10444 (re-search-forward
10445 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10446 (cdr range) t))
10447 (progn
10448 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10450 nil)))))
10452 ;; Multi-values properties are properties that contain multiple values
10453 ;; These values are assumed to be single words, separated by whitespace.
10454 (defun org-entry-add-to-multivalued-property (pom property value)
10455 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10456 (let* ((old (org-entry-get pom property))
10457 (values (and old (org-split-string old "[ \t]"))))
10458 (unless (member value values)
10459 (setq values (cons value values))
10460 (org-entry-put pom property
10461 (mapconcat 'identity values " ")))))
10463 (defun org-entry-remove-from-multivalued-property (pom property value)
10464 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10465 (let* ((old (org-entry-get pom property))
10466 (values (and old (org-split-string old "[ \t]"))))
10467 (when (member value values)
10468 (setq values (delete value values))
10469 (org-entry-put pom property
10470 (mapconcat 'identity values " ")))))
10472 (defun org-entry-member-in-multivalued-property (pom property value)
10473 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10474 (let* ((old (org-entry-get pom property))
10475 (values (and old (org-split-string old "[ \t]"))))
10476 (member value values)))
10478 (defvar org-entry-property-inherited-from (make-marker))
10480 (defun org-entry-get-with-inheritance (property)
10481 "Get entry property, and search higher levels if not present."
10482 (let (tmp)
10483 (save-excursion
10484 (save-restriction
10485 (widen)
10486 (catch 'ex
10487 (while t
10488 (when (setq tmp (org-entry-get nil property))
10489 (org-back-to-heading t)
10490 (move-marker org-entry-property-inherited-from (point))
10491 (throw 'ex tmp))
10492 (or (org-up-heading-safe) (throw 'ex nil)))))
10493 (or tmp
10494 (cdr (assoc property org-file-properties))
10495 (cdr (assoc property org-global-properties))
10496 (cdr (assoc property org-global-properties-fixed))))))
10498 (defun org-entry-put (pom property value)
10499 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10500 (org-with-point-at pom
10501 (org-back-to-heading t)
10502 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10503 range)
10504 (cond
10505 ((equal property "TODO")
10506 (when (and (stringp value) (string-match "\\S-" value)
10507 (not (member value org-todo-keywords-1)))
10508 (error "\"%s\" is not a valid TODO state" value))
10509 (if (or (not value)
10510 (not (string-match "\\S-" value)))
10511 (setq value 'none))
10512 (org-todo value)
10513 (org-set-tags nil 'align))
10514 ((equal property "PRIORITY")
10515 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10516 (string-to-char value) ?\ ))
10517 (org-set-tags nil 'align))
10518 ((equal property "SCHEDULED")
10519 (if (re-search-forward org-scheduled-time-regexp end t)
10520 (cond
10521 ((eq value 'earlier) (org-timestamp-change -1 'day))
10522 ((eq value 'later) (org-timestamp-change 1 'day))
10523 (t (call-interactively 'org-schedule)))
10524 (call-interactively 'org-schedule)))
10525 ((equal property "DEADLINE")
10526 (if (re-search-forward org-deadline-time-regexp end t)
10527 (cond
10528 ((eq value 'earlier) (org-timestamp-change -1 'day))
10529 ((eq value 'later) (org-timestamp-change 1 'day))
10530 (t (call-interactively 'org-deadline)))
10531 (call-interactively 'org-deadline)))
10532 ((member property org-special-properties)
10533 (error "The %s property can not yet be set with `org-entry-put'"
10534 property))
10535 (t ; a non-special property
10536 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10537 (setq range (org-get-property-block beg end 'force))
10538 (goto-char (car range))
10539 (if (re-search-forward
10540 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10541 (progn
10542 (delete-region (match-beginning 1) (match-end 1))
10543 (goto-char (match-beginning 1)))
10544 (goto-char (cdr range))
10545 (insert "\n")
10546 (backward-char 1)
10547 (org-indent-line-function)
10548 (insert ":" property ":"))
10549 (and value (insert " " value))
10550 (org-indent-line-function)))))))
10552 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10553 "Get all property keys in the current buffer.
10554 With INCLUDE-SPECIALS, also list the special properties that relect things
10555 like tags and TODO state.
10556 With INCLUDE-DEFAULTS, also include properties that has special meaning
10557 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10558 With INCLUDE-COLUMNS, also include property names given in COLUMN
10559 formats in the current buffer."
10560 (let (rtn range cfmt cols s p)
10561 (save-excursion
10562 (save-restriction
10563 (widen)
10564 (goto-char (point-min))
10565 (while (re-search-forward org-property-start-re nil t)
10566 (setq range (org-get-property-block))
10567 (goto-char (car range))
10568 (while (re-search-forward
10569 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10570 (cdr range) t)
10571 (add-to-list 'rtn (org-match-string-no-properties 1)))
10572 (outline-next-heading))))
10574 (when include-specials
10575 (setq rtn (append org-special-properties rtn)))
10577 (when include-defaults
10578 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10580 (when include-columns
10581 (save-excursion
10582 (save-restriction
10583 (widen)
10584 (goto-char (point-min))
10585 (while (re-search-forward
10586 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10587 nil t)
10588 (setq cfmt (match-string 2) s 0)
10589 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10590 cfmt s)
10591 (setq s (match-end 0)
10592 p (match-string 1 cfmt))
10593 (unless (or (equal p "ITEM")
10594 (member p org-special-properties))
10595 (add-to-list 'rtn (match-string 1 cfmt))))))))
10597 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10599 (defun org-property-values (key)
10600 "Return a list of all values of property KEY."
10601 (save-excursion
10602 (save-restriction
10603 (widen)
10604 (goto-char (point-min))
10605 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10606 values)
10607 (while (re-search-forward re nil t)
10608 (add-to-list 'values (org-trim (match-string 1))))
10609 (delete "" values)))))
10611 (defun org-insert-property-drawer ()
10612 "Insert a property drawer into the current entry."
10613 (interactive)
10614 (org-back-to-heading t)
10615 (looking-at outline-regexp)
10616 (let ((indent (- (match-end 0)(match-beginning 0)))
10617 (beg (point))
10618 (re (concat "^[ \t]*" org-keyword-time-regexp))
10619 end hiddenp)
10620 (outline-next-heading)
10621 (setq end (point))
10622 (goto-char beg)
10623 (while (re-search-forward re end t))
10624 (setq hiddenp (org-invisible-p))
10625 (end-of-line 1)
10626 (and (equal (char-after) ?\n) (forward-char 1))
10627 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10628 (beginning-of-line 2))
10629 (org-skip-over-state-notes)
10630 (skip-chars-backward " \t\n\r")
10631 (if (eq (char-before) ?*) (forward-char 1))
10632 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10633 (beginning-of-line 0)
10634 (org-indent-to-column indent)
10635 (beginning-of-line 2)
10636 (org-indent-to-column indent)
10637 (beginning-of-line 0)
10638 (if hiddenp
10639 (save-excursion
10640 (org-back-to-heading t)
10641 (hide-entry))
10642 (org-flag-drawer t))))
10644 (defun org-set-property (property value)
10645 "In the current entry, set PROPERTY to VALUE.
10646 When called interactively, this will prompt for a property name, offering
10647 completion on existing and default properties. And then it will prompt
10648 for a value, offering competion either on allowed values (via an inherited
10649 xxx_ALL property) or on existing values in other instances of this property
10650 in the current file."
10651 (interactive
10652 (let* ((completion-ignore-case t)
10653 (keys (org-buffer-property-keys nil t t))
10654 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10655 (prop (if (member prop0 keys)
10656 prop0
10657 (or (cdr (assoc (downcase prop0)
10658 (mapcar (lambda (x) (cons (downcase x) x))
10659 keys)))
10660 prop0)))
10661 (cur (org-entry-get nil prop))
10662 (allowed (org-property-get-allowed-values nil prop 'table))
10663 (existing (mapcar 'list (org-property-values prop)))
10664 (val (if allowed
10665 (org-completing-read "Value: " allowed nil 'req-match)
10666 (org-completing-read
10667 (concat "Value" (if (and cur (string-match "\\S-" cur))
10668 (concat "[" cur "]") "")
10669 ": ")
10670 existing nil nil "" nil cur))))
10671 (list prop (if (equal val "") cur val))))
10672 (unless (equal (org-entry-get nil property) value)
10673 (org-entry-put nil property value)))
10675 (defun org-delete-property (property)
10676 "In the current entry, delete PROPERTY."
10677 (interactive
10678 (let* ((completion-ignore-case t)
10679 (prop (completing-read
10680 "Property: " (org-entry-properties nil 'standard))))
10681 (list prop)))
10682 (message "Property %s %s" property
10683 (if (org-entry-delete nil property)
10684 "deleted"
10685 "was not present in the entry")))
10687 (defun org-delete-property-globally (property)
10688 "Remove PROPERTY globally, from all entries."
10689 (interactive
10690 (let* ((completion-ignore-case t)
10691 (prop (completing-read
10692 "Globally remove property: "
10693 (mapcar 'list (org-buffer-property-keys)))))
10694 (list prop)))
10695 (save-excursion
10696 (save-restriction
10697 (widen)
10698 (goto-char (point-min))
10699 (let ((cnt 0))
10700 (while (re-search-forward
10701 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10702 nil t)
10703 (setq cnt (1+ cnt))
10704 (replace-match ""))
10705 (message "Property \"%s\" removed from %d entries" property cnt)))))
10707 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10709 (defun org-compute-property-at-point ()
10710 "Compute the property at point.
10711 This looks for an enclosing column format, extracts the operator and
10712 then applies it to the proerty in the column format's scope."
10713 (interactive)
10714 (unless (org-at-property-p)
10715 (error "Not at a property"))
10716 (let ((prop (org-match-string-no-properties 2)))
10717 (org-columns-get-format-and-top-level)
10718 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10719 (error "No operator defined for property %s" prop))
10720 (org-columns-compute prop)))
10722 (defun org-property-get-allowed-values (pom property &optional table)
10723 "Get allowed values for the property PROPERTY.
10724 When TABLE is non-nil, return an alist that can directly be used for
10725 completion."
10726 (let (vals)
10727 (cond
10728 ((equal property "TODO")
10729 (setq vals (org-with-point-at pom
10730 (append org-todo-keywords-1 '("")))))
10731 ((equal property "PRIORITY")
10732 (let ((n org-lowest-priority))
10733 (while (>= n org-highest-priority)
10734 (push (char-to-string n) vals)
10735 (setq n (1- n)))))
10736 ((member property org-special-properties))
10738 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10740 (when (and vals (string-match "\\S-" vals))
10741 (setq vals (car (read-from-string (concat "(" vals ")"))))
10742 (setq vals (mapcar (lambda (x)
10743 (cond ((stringp x) x)
10744 ((numberp x) (number-to-string x))
10745 ((symbolp x) (symbol-name x))
10746 (t "???")))
10747 vals)))))
10748 (if table (mapcar 'list vals) vals)))
10750 (defun org-property-previous-allowed-value (&optional previous)
10751 "Switch to the next allowed value for this property."
10752 (interactive)
10753 (org-property-next-allowed-value t))
10755 (defun org-property-next-allowed-value (&optional previous)
10756 "Switch to the next allowed value for this property."
10757 (interactive)
10758 (unless (org-at-property-p)
10759 (error "Not at a property"))
10760 (let* ((key (match-string 2))
10761 (value (match-string 3))
10762 (allowed (or (org-property-get-allowed-values (point) key)
10763 (and (member value '("[ ]" "[-]" "[X]"))
10764 '("[ ]" "[X]"))))
10765 nval)
10766 (unless allowed
10767 (error "Allowed values for this property have not been defined"))
10768 (if previous (setq allowed (reverse allowed)))
10769 (if (member value allowed)
10770 (setq nval (car (cdr (member value allowed)))))
10771 (setq nval (or nval (car allowed)))
10772 (if (equal nval value)
10773 (error "Only one allowed value for this property"))
10774 (org-at-property-p)
10775 (replace-match (concat " :" key ": " nval) t t)
10776 (org-indent-line-function)
10777 (beginning-of-line 1)
10778 (skip-chars-forward " \t")))
10780 (defun org-find-entry-with-id (ident)
10781 "Locate the entry that contains the ID property with exact value IDENT.
10782 IDENT can be a string, a symbol or a number, this function will search for
10783 the string representation of it.
10784 Return the position where this entry starts, or nil if there is no such entry."
10785 (let ((id (cond
10786 ((stringp ident) ident)
10787 ((symbol-name ident) (symbol-name ident))
10788 ((numberp ident) (number-to-string ident))
10789 (t (error "IDENT %s must be a string, symbol or number" ident))))
10790 (case-fold-search nil))
10791 (save-excursion
10792 (save-restriction
10793 (widen)
10794 (goto-char (point-min))
10795 (when (re-search-forward
10796 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10797 nil t)
10798 (org-back-to-heading)
10799 (point))))))
10801 ;;;; Timestamps
10803 (defvar org-last-changed-timestamp nil)
10804 (defvar org-last-inserted-timestamp nil
10805 "The last time stamp inserted with `org-insert-time-stamp'.")
10806 (defvar org-time-was-given) ; dynamically scoped parameter
10807 (defvar org-end-time-was-given) ; dynamically scoped parameter
10808 (defvar org-ts-what) ; dynamically scoped parameter
10810 (defun org-time-stamp (arg)
10811 "Prompt for a date/time and insert a time stamp.
10812 If the user specifies a time like HH:MM, or if this command is called
10813 with a prefix argument, the time stamp will contain date and time.
10814 Otherwise, only the date will be included. All parts of a date not
10815 specified by the user will be filled in from the current date/time.
10816 So if you press just return without typing anything, the time stamp
10817 will represent the current date/time. If there is already a timestamp
10818 at the cursor, it will be modified."
10819 (interactive "P")
10820 (let* ((ts nil)
10821 (default-time
10822 ;; Default time is either today, or, when entering a range,
10823 ;; the range start.
10824 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10825 (save-excursion
10826 (re-search-backward
10827 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10828 (- (point) 20) t)))
10829 (apply 'encode-time (org-parse-time-string (match-string 1)))
10830 (current-time)))
10831 (default-input (and ts (org-get-compact-tod ts)))
10832 org-time-was-given org-end-time-was-given time)
10833 (cond
10834 ((and (org-at-timestamp-p)
10835 (eq last-command 'org-time-stamp)
10836 (eq this-command 'org-time-stamp))
10837 (insert "--")
10838 (setq time (let ((this-command this-command))
10839 (org-read-date arg 'totime nil nil default-time default-input)))
10840 (org-insert-time-stamp time (or org-time-was-given arg)))
10841 ((org-at-timestamp-p)
10842 (setq time (let ((this-command this-command))
10843 (org-read-date arg 'totime nil nil default-time default-input)))
10844 (when (org-at-timestamp-p) ; just to get the match data
10845 (replace-match "")
10846 (setq org-last-changed-timestamp
10847 (org-insert-time-stamp
10848 time (or org-time-was-given arg)
10849 nil nil nil (list org-end-time-was-given))))
10850 (message "Timestamp updated"))
10852 (setq time (let ((this-command this-command))
10853 (org-read-date arg 'totime nil nil default-time default-input)))
10854 (org-insert-time-stamp time (or org-time-was-given arg)
10855 nil nil nil (list org-end-time-was-given))))))
10857 ;; FIXME: can we use this for something else, like computing time differences?
10858 (defun org-get-compact-tod (s)
10859 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10860 (let* ((t1 (match-string 1 s))
10861 (h1 (string-to-number (match-string 2 s)))
10862 (m1 (string-to-number (match-string 3 s)))
10863 (t2 (and (match-end 4) (match-string 5 s)))
10864 (h2 (and t2 (string-to-number (match-string 6 s))))
10865 (m2 (and t2 (string-to-number (match-string 7 s))))
10866 dh dm)
10867 (if (not t2)
10869 (setq dh (- h2 h1) dm (- m2 m1))
10870 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10871 (concat t1 "+" (number-to-string dh)
10872 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10874 (defun org-time-stamp-inactive (&optional arg)
10875 "Insert an inactive time stamp.
10876 An inactive time stamp is enclosed in square brackets instead of angle
10877 brackets. It is inactive in the sense that it does not trigger agenda entries,
10878 does not link to the calendar and cannot be changed with the S-cursor keys.
10879 So these are more for recording a certain time/date."
10880 (interactive "P")
10881 (let (org-time-was-given org-end-time-was-given time)
10882 (setq time (org-read-date arg 'totime))
10883 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10884 nil nil (list org-end-time-was-given))))
10886 (defvar org-date-ovl (org-make-overlay 1 1))
10887 (org-overlay-put org-date-ovl 'face 'org-warning)
10888 (org-detach-overlay org-date-ovl)
10890 (defvar org-ans1) ; dynamically scoped parameter
10891 (defvar org-ans2) ; dynamically scoped parameter
10893 (defvar org-plain-time-of-day-regexp) ; defined below
10895 (defvar org-overriding-default-time nil) ; dynamically scoped
10896 (defvar org-read-date-overlay nil)
10897 (defvar org-dcst nil) ; dynamically scoped
10899 (defun org-read-date (&optional with-time to-time from-string prompt
10900 default-time default-input)
10901 "Read a date, possibly a time, and make things smooth for the user.
10902 The prompt will suggest to enter an ISO date, but you can also enter anything
10903 which will at least partially be understood by `parse-time-string'.
10904 Unrecognized parts of the date will default to the current day, month, year,
10905 hour and minute. If this command is called to replace a timestamp at point,
10906 of to enter the second timestamp of a range, the default time is taken from the
10907 existing stamp. For example,
10908 3-2-5 --> 2003-02-05
10909 feb 15 --> currentyear-02-15
10910 sep 12 9 --> 2009-09-12
10911 12:45 --> today 12:45
10912 22 sept 0:34 --> currentyear-09-22 0:34
10913 12 --> currentyear-currentmonth-12
10914 Fri --> nearest Friday (today or later)
10915 etc.
10917 Furthermore you can specify a relative date by giving, as the *first* thing
10918 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10919 change in days weeks, months, years.
10920 With a single plus or minus, the date is relative to today. With a double
10921 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10922 +4d --> four days from today
10923 +4 --> same as above
10924 +2w --> two weeks from today
10925 ++5 --> five days from default date
10927 The function understands only English month and weekday abbreviations,
10928 but this can be configured with the variables `parse-time-months' and
10929 `parse-time-weekdays'.
10931 While prompting, a calendar is popped up - you can also select the
10932 date with the mouse (button 1). The calendar shows a period of three
10933 months. To scroll it to other months, use the keys `>' and `<'.
10934 If you don't like the calendar, turn it off with
10935 \(setq org-read-date-popup-calendar nil)
10937 With optional argument TO-TIME, the date will immediately be converted
10938 to an internal time.
10939 With an optional argument WITH-TIME, the prompt will suggest to also
10940 insert a time. Note that when WITH-TIME is not set, you can still
10941 enter a time, and this function will inform the calling routine about
10942 this change. The calling routine may then choose to change the format
10943 used to insert the time stamp into the buffer to include the time.
10944 With optional argument FROM-STRING, read from this string instead from
10945 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10946 the time/date that is used for everything that is not specified by the
10947 user."
10948 (require 'parse-time)
10949 (let* ((org-time-stamp-rounding-minutes
10950 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10951 (org-dcst org-display-custom-times)
10952 (ct (org-current-time))
10953 (def (or org-overriding-default-time default-time ct))
10954 (defdecode (decode-time def))
10955 (dummy (progn
10956 (when (< (nth 2 defdecode) org-extend-today-until)
10957 (setcar (nthcdr 2 defdecode) -1)
10958 (setcar (nthcdr 1 defdecode) 59)
10959 (setq def (apply 'encode-time defdecode)
10960 defdecode (decode-time def)))))
10961 (calendar-move-hook nil)
10962 (calendar-view-diary-initially-flag nil)
10963 (view-diary-entries-initially nil)
10964 (calendar-view-holidays-initially-flag nil)
10965 (view-calendar-holidays-initially nil)
10966 (timestr (format-time-string
10967 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10968 (prompt (concat (if prompt (concat prompt " ") "")
10969 (format "Date+time [%s]: " timestr)))
10970 ans (org-ans0 "") org-ans1 org-ans2 final)
10972 (cond
10973 (from-string (setq ans from-string))
10974 (org-read-date-popup-calendar
10975 (save-excursion
10976 (save-window-excursion
10977 (calendar)
10978 (calendar-forward-day (- (time-to-days def)
10979 (calendar-absolute-from-gregorian
10980 (calendar-current-date))))
10981 (org-eval-in-calendar nil t)
10982 (let* ((old-map (current-local-map))
10983 (map (copy-keymap calendar-mode-map))
10984 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10985 (org-defkey map (kbd "RET") 'org-calendar-select)
10986 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10987 'org-calendar-select-mouse)
10988 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10989 'org-calendar-select-mouse)
10990 (org-defkey minibuffer-local-map [(meta shift left)]
10991 (lambda () (interactive)
10992 (org-eval-in-calendar '(calendar-backward-month 1))))
10993 (org-defkey minibuffer-local-map [(meta shift right)]
10994 (lambda () (interactive)
10995 (org-eval-in-calendar '(calendar-forward-month 1))))
10996 (org-defkey minibuffer-local-map [(meta shift up)]
10997 (lambda () (interactive)
10998 (org-eval-in-calendar '(calendar-backward-year 1))))
10999 (org-defkey minibuffer-local-map [(meta shift down)]
11000 (lambda () (interactive)
11001 (org-eval-in-calendar '(calendar-forward-year 1))))
11002 (org-defkey minibuffer-local-map [(shift up)]
11003 (lambda () (interactive)
11004 (org-eval-in-calendar '(calendar-backward-week 1))))
11005 (org-defkey minibuffer-local-map [(shift down)]
11006 (lambda () (interactive)
11007 (org-eval-in-calendar '(calendar-forward-week 1))))
11008 (org-defkey minibuffer-local-map [(shift left)]
11009 (lambda () (interactive)
11010 (org-eval-in-calendar '(calendar-backward-day 1))))
11011 (org-defkey minibuffer-local-map [(shift right)]
11012 (lambda () (interactive)
11013 (org-eval-in-calendar '(calendar-forward-day 1))))
11014 (org-defkey minibuffer-local-map ">"
11015 (lambda () (interactive)
11016 (org-eval-in-calendar '(scroll-calendar-left 1))))
11017 (org-defkey minibuffer-local-map "<"
11018 (lambda () (interactive)
11019 (org-eval-in-calendar '(scroll-calendar-right 1))))
11020 (unwind-protect
11021 (progn
11022 (use-local-map map)
11023 (add-hook 'post-command-hook 'org-read-date-display)
11024 (setq org-ans0 (read-string prompt default-input nil nil))
11025 ;; org-ans0: from prompt
11026 ;; org-ans1: from mouse click
11027 ;; org-ans2: from calendar motion
11028 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11029 (remove-hook 'post-command-hook 'org-read-date-display)
11030 (use-local-map old-map)
11031 (when org-read-date-overlay
11032 (org-delete-overlay org-read-date-overlay)
11033 (setq org-read-date-overlay nil)))))))
11035 (t ; Naked prompt only
11036 (unwind-protect
11037 (setq ans (read-string prompt default-input nil timestr))
11038 (when org-read-date-overlay
11039 (org-delete-overlay org-read-date-overlay)
11040 (setq org-read-date-overlay nil)))))
11042 (setq final (org-read-date-analyze ans def defdecode))
11044 (if to-time
11045 (apply 'encode-time final)
11046 (if (and (boundp 'org-time-was-given) org-time-was-given)
11047 (format "%04d-%02d-%02d %02d:%02d"
11048 (nth 5 final) (nth 4 final) (nth 3 final)
11049 (nth 2 final) (nth 1 final))
11050 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11051 (defvar def)
11052 (defvar defdecode)
11053 (defvar with-time)
11054 (defun org-read-date-display ()
11055 "Display the currrent date prompt interpretation in the minibuffer."
11056 (when org-read-date-display-live
11057 (when org-read-date-overlay
11058 (org-delete-overlay org-read-date-overlay))
11059 (let ((p (point)))
11060 (end-of-line 1)
11061 (while (not (equal (buffer-substring
11062 (max (point-min) (- (point) 4)) (point))
11063 " "))
11064 (insert " "))
11065 (goto-char p))
11066 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11067 " " (or org-ans1 org-ans2)))
11068 (org-end-time-was-given nil)
11069 (f (org-read-date-analyze ans def defdecode))
11070 (fmts (if org-dcst
11071 org-time-stamp-custom-formats
11072 org-time-stamp-formats))
11073 (fmt (if (or with-time
11074 (and (boundp 'org-time-was-given) org-time-was-given))
11075 (cdr fmts)
11076 (car fmts)))
11077 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11078 (when (and org-end-time-was-given
11079 (string-match org-plain-time-of-day-regexp txt))
11080 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11081 org-end-time-was-given
11082 (substring txt (match-end 0)))))
11083 (setq org-read-date-overlay
11084 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11085 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11087 (defun org-read-date-analyze (ans def defdecode)
11088 "Analyze the combined answer of the date prompt."
11089 ;; FIXME: cleanup and comment
11090 (let (delta deltan deltaw deltadef year month day
11091 hour minute second wday pm h2 m2 tl wday1
11092 iso-year iso-weekday iso-week iso-year iso-date)
11094 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11095 (setq ans "+0"))
11097 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11098 (setq ans (replace-match "" t t ans)
11099 deltan (car delta)
11100 deltaw (nth 1 delta)
11101 deltadef (nth 2 delta)))
11103 ;; Check if there is an iso week date in there
11104 ;; If yes, sore the info and ostpone interpreting it until the rest
11105 ;; of the parsing is done
11106 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11107 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11108 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11109 iso-week (string-to-number (match-string 2 ans)))
11110 (setq ans (replace-match "" t t ans)))
11112 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11113 (when (string-match
11114 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11115 (setq year (if (match-end 2)
11116 (string-to-number (match-string 2 ans))
11117 (string-to-number (format-time-string "%Y")))
11118 month (string-to-number (match-string 3 ans))
11119 day (string-to-number (match-string 4 ans)))
11120 (if (< year 100) (setq year (+ 2000 year)))
11121 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11122 t nil ans)))
11123 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11124 ;; If there is a time with am/pm, and *no* time without it, we convert
11125 ;; so that matching will be successful.
11126 (loop for i from 1 to 2 do ; twice, for end time as well
11127 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11128 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11129 (setq hour (string-to-number (match-string 1 ans))
11130 minute (if (match-end 3)
11131 (string-to-number (match-string 3 ans))
11133 pm (equal ?p
11134 (string-to-char (downcase (match-string 4 ans)))))
11135 (if (and (= hour 12) (not pm))
11136 (setq hour 0)
11137 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11138 (setq ans (replace-match (format "%02d:%02d" hour minute)
11139 t t ans))))
11141 ;; Check if a time range is given as a duration
11142 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11143 (setq hour (string-to-number (match-string 1 ans))
11144 h2 (+ hour (string-to-number (match-string 3 ans)))
11145 minute (string-to-number (match-string 2 ans))
11146 m2 (+ minute (if (match-end 5) (string-to-number
11147 (match-string 5 ans))0)))
11148 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11149 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11150 t t ans)))
11152 ;; Check if there is a time range
11153 (when (boundp 'org-end-time-was-given)
11154 (setq org-time-was-given nil)
11155 (when (and (string-match org-plain-time-of-day-regexp ans)
11156 (match-end 8))
11157 (setq org-end-time-was-given (match-string 8 ans))
11158 (setq ans (concat (substring ans 0 (match-beginning 7))
11159 (substring ans (match-end 7))))))
11161 (setq tl (parse-time-string ans)
11162 day (or (nth 3 tl) (nth 3 defdecode))
11163 month (or (nth 4 tl)
11164 (if (and org-read-date-prefer-future
11165 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11166 (1+ (nth 4 defdecode))
11167 (nth 4 defdecode)))
11168 year (or (nth 5 tl)
11169 (if (and org-read-date-prefer-future
11170 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11171 (1+ (nth 5 defdecode))
11172 (nth 5 defdecode)))
11173 hour (or (nth 2 tl) (nth 2 defdecode))
11174 minute (or (nth 1 tl) (nth 1 defdecode))
11175 second (or (nth 0 tl) 0)
11176 wday (nth 6 tl))
11178 ;; Special date definitions below
11179 (cond
11180 (iso-week
11181 ;; There was an iso week
11182 (setq year (or iso-year year)
11183 day (or iso-weekday wday 1)
11184 wday nil ; to make sure that the trigger below does not match
11185 iso-date (calendar-gregorian-from-absolute
11186 (calendar-absolute-from-iso
11187 (list iso-week day year))))
11188 ; FIXME: Should we also push ISO weeks into the future?
11189 ; (when (and org-read-date-prefer-future
11190 ; (not iso-year)
11191 ; (< (calendar-absolute-from-gregorian iso-date)
11192 ; (time-to-days (current-time))))
11193 ; (setq year (1+ year)
11194 ; iso-date (calendar-gregorian-from-absolute
11195 ; (calendar-absolute-from-iso
11196 ; (list iso-week day year)))))
11197 (setq month (car iso-date)
11198 year (nth 2 iso-date)
11199 day (nth 1 iso-date)))
11200 (deltan
11201 (unless deltadef
11202 (let ((now (decode-time (current-time))))
11203 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11204 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11205 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11206 ((equal deltaw "m") (setq month (+ month deltan)))
11207 ((equal deltaw "y") (setq year (+ year deltan)))))
11208 ((and wday (not (nth 3 tl)))
11209 ;; Weekday was given, but no day, so pick that day in the week
11210 ;; on or after the derived date.
11211 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11212 (unless (equal wday wday1)
11213 (setq day (+ day (% (- wday wday1 -7) 7))))))
11214 (if (and (boundp 'org-time-was-given)
11215 (nth 2 tl))
11216 (setq org-time-was-given t))
11217 (if (< year 100) (setq year (+ 2000 year)))
11218 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11219 (list second minute hour day month year)))
11221 (defvar parse-time-weekdays)
11223 (defun org-read-date-get-relative (s today default)
11224 "Check string S for special relative date string.
11225 TODAY and DEFAULT are internal times, for today and for a default.
11226 Return shift list (N what def-flag)
11227 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11228 N is the number of WHATs to shift.
11229 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11230 the DEFAULT date rather than TODAY."
11231 (when (and
11232 (string-match
11233 (concat
11234 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11235 "\\([0-9]+\\)?"
11236 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11237 "\\([ \t]\\|$\\)") s)
11238 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11239 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11240 (string-to-char (substring (match-string 1 s) -1))
11241 ?+))
11242 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11243 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11244 (what (if (match-end 3) (match-string 3 s) "d"))
11245 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11246 (date (if rel default today))
11247 (wday (nth 6 (decode-time date)))
11248 delta)
11249 (if wday1
11250 (progn
11251 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11252 (if (= dir ?-) (setq delta (- delta 7)))
11253 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11254 (list delta "d" rel))
11255 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11257 (defun org-eval-in-calendar (form &optional keepdate)
11258 "Eval FORM in the calendar window and return to current window.
11259 Also, store the cursor date in variable org-ans2."
11260 (let ((sw (selected-window)))
11261 (select-window (get-buffer-window "*Calendar*"))
11262 (eval form)
11263 (when (and (not keepdate) (calendar-cursor-to-date))
11264 (let* ((date (calendar-cursor-to-date))
11265 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11266 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11267 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11268 (select-window sw)))
11270 ; ;; Update the prompt to show new default date
11271 ; (save-excursion
11272 ; (goto-char (point-min))
11273 ; (when (and org-ans2
11274 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11275 ; (get-text-property (match-end 0) 'field))
11276 ; (let ((inhibit-read-only t))
11277 ; (replace-match (concat "[" org-ans2 "]") t t)
11278 ; (add-text-properties (point-min) (1+ (match-end 0))
11279 ; (text-properties-at (1+ (point-min)))))))))
11281 (defun org-calendar-select ()
11282 "Return to `org-read-date' with the date currently selected.
11283 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11284 (interactive)
11285 (when (calendar-cursor-to-date)
11286 (let* ((date (calendar-cursor-to-date))
11287 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11288 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11289 (if (active-minibuffer-window) (exit-minibuffer))))
11291 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11292 "Insert a date stamp for the date given by the internal TIME.
11293 WITH-HM means, use the stamp format that includes the time of the day.
11294 INACTIVE means use square brackets instead of angular ones, so that the
11295 stamp will not contribute to the agenda.
11296 PRE and POST are optional strings to be inserted before and after the
11297 stamp.
11298 The command returns the inserted time stamp."
11299 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11300 stamp)
11301 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11302 (insert-before-markers (or pre ""))
11303 (insert-before-markers (setq stamp (format-time-string fmt time)))
11304 (when (listp extra)
11305 (setq extra (car extra))
11306 (if (and (stringp extra)
11307 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11308 (setq extra (format "-%02d:%02d"
11309 (string-to-number (match-string 1 extra))
11310 (string-to-number (match-string 2 extra))))
11311 (setq extra nil)))
11312 (when extra
11313 (backward-char 1)
11314 (insert-before-markers extra)
11315 (forward-char 1))
11316 (insert-before-markers (or post ""))
11317 (setq org-last-inserted-timestamp stamp)))
11319 (defun org-toggle-time-stamp-overlays ()
11320 "Toggle the use of custom time stamp formats."
11321 (interactive)
11322 (setq org-display-custom-times (not org-display-custom-times))
11323 (unless org-display-custom-times
11324 (let ((p (point-min)) (bmp (buffer-modified-p)))
11325 (while (setq p (next-single-property-change p 'display))
11326 (if (and (get-text-property p 'display)
11327 (eq (get-text-property p 'face) 'org-date))
11328 (remove-text-properties
11329 p (setq p (next-single-property-change p 'display))
11330 '(display t))))
11331 (set-buffer-modified-p bmp)))
11332 (if (featurep 'xemacs)
11333 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11334 (org-restart-font-lock)
11335 (setq org-table-may-need-update t)
11336 (if org-display-custom-times
11337 (message "Time stamps are overlayed with custom format")
11338 (message "Time stamp overlays removed")))
11340 (defun org-display-custom-time (beg end)
11341 "Overlay modified time stamp format over timestamp between BEG and END."
11342 (let* ((ts (buffer-substring beg end))
11343 t1 w1 with-hm tf time str w2 (off 0))
11344 (save-match-data
11345 (setq t1 (org-parse-time-string ts t))
11346 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11347 (setq off (- (match-end 0) (match-beginning 0)))))
11348 (setq end (- end off))
11349 (setq w1 (- end beg)
11350 with-hm (and (nth 1 t1) (nth 2 t1))
11351 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11352 time (org-fix-decoded-time t1)
11353 str (org-add-props
11354 (format-time-string
11355 (substring tf 1 -1) (apply 'encode-time time))
11356 nil 'mouse-face 'highlight)
11357 w2 (length str))
11358 (if (not (= w2 w1))
11359 (add-text-properties (1+ beg) (+ 2 beg)
11360 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11361 (if (featurep 'xemacs)
11362 (progn
11363 (put-text-property beg end 'invisible t)
11364 (put-text-property beg end 'end-glyph (make-glyph str)))
11365 (put-text-property beg end 'display str))))
11367 (defun org-translate-time (string)
11368 "Translate all timestamps in STRING to custom format.
11369 But do this only if the variable `org-display-custom-times' is set."
11370 (when org-display-custom-times
11371 (save-match-data
11372 (let* ((start 0)
11373 (re org-ts-regexp-both)
11374 t1 with-hm inactive tf time str beg end)
11375 (while (setq start (string-match re string start))
11376 (setq beg (match-beginning 0)
11377 end (match-end 0)
11378 t1 (save-match-data
11379 (org-parse-time-string (substring string beg end) t))
11380 with-hm (and (nth 1 t1) (nth 2 t1))
11381 inactive (equal (substring string beg (1+ beg)) "[")
11382 tf (funcall (if with-hm 'cdr 'car)
11383 org-time-stamp-custom-formats)
11384 time (org-fix-decoded-time t1)
11385 str (format-time-string
11386 (concat
11387 (if inactive "[" "<") (substring tf 1 -1)
11388 (if inactive "]" ">"))
11389 (apply 'encode-time time))
11390 string (replace-match str t t string)
11391 start (+ start (length str)))))))
11392 string)
11394 (defun org-fix-decoded-time (time)
11395 "Set 0 instead of nil for the first 6 elements of time.
11396 Don't touch the rest."
11397 (let ((n 0))
11398 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11400 (defun org-days-to-time (timestamp-string)
11401 "Difference between TIMESTAMP-STRING and now in days."
11402 (- (time-to-days (org-time-string-to-time timestamp-string))
11403 (time-to-days (current-time))))
11405 (defun org-deadline-close (timestamp-string &optional ndays)
11406 "Is the time in TIMESTAMP-STRING close to the current date?"
11407 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11408 (and (< (org-days-to-time timestamp-string) ndays)
11409 (not (org-entry-is-done-p))))
11411 (defun org-get-wdays (ts)
11412 "Get the deadline lead time appropriate for timestring TS."
11413 (cond
11414 ((<= org-deadline-warning-days 0)
11415 ;; 0 or negative, enforce this value no matter what
11416 (- org-deadline-warning-days))
11417 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11418 ;; lead time is specified.
11419 (floor (* (string-to-number (match-string 1 ts))
11420 (cdr (assoc (match-string 2 ts)
11421 '(("d" . 1) ("w" . 7)
11422 ("m" . 30.4) ("y" . 365.25)))))))
11423 ;; go for the default.
11424 (t org-deadline-warning-days)))
11426 (defun org-calendar-select-mouse (ev)
11427 "Return to `org-read-date' with the date currently selected.
11428 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11429 (interactive "e")
11430 (mouse-set-point ev)
11431 (when (calendar-cursor-to-date)
11432 (let* ((date (calendar-cursor-to-date))
11433 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11434 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11435 (if (active-minibuffer-window) (exit-minibuffer))))
11437 (defun org-check-deadlines (ndays)
11438 "Check if there are any deadlines due or past due.
11439 A deadline is considered due if it happens within `org-deadline-warning-days'
11440 days from today's date. If the deadline appears in an entry marked DONE,
11441 it is not shown. The prefix arg NDAYS can be used to test that many
11442 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11443 (interactive "P")
11444 (let* ((org-warn-days
11445 (cond
11446 ((equal ndays '(4)) 100000)
11447 (ndays (prefix-numeric-value ndays))
11448 (t (abs org-deadline-warning-days))))
11449 (case-fold-search nil)
11450 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11451 (callback
11452 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11454 (message "%d deadlines past-due or due within %d days"
11455 (org-occur regexp nil callback)
11456 org-warn-days)))
11458 (defun org-check-before-date (date)
11459 "Check if there are deadlines or scheduled entries before DATE."
11460 (interactive (list (org-read-date)))
11461 (let ((case-fold-search nil)
11462 (regexp (concat "\\<\\(" org-deadline-string
11463 "\\|" org-scheduled-string
11464 "\\) *<\\([^>]+\\)>"))
11465 (callback
11466 (lambda () (time-less-p
11467 (org-time-string-to-time (match-string 2))
11468 (org-time-string-to-time date)))))
11469 (message "%d entries before %s"
11470 (org-occur regexp nil callback) date)))
11472 (defun org-evaluate-time-range (&optional to-buffer)
11473 "Evaluate a time range by computing the difference between start and end.
11474 Normally the result is just printed in the echo area, but with prefix arg
11475 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11476 If the time range is actually in a table, the result is inserted into the
11477 next column.
11478 For time difference computation, a year is assumed to be exactly 365
11479 days in order to avoid rounding problems."
11480 (interactive "P")
11482 (org-clock-update-time-maybe)
11483 (save-excursion
11484 (unless (org-at-date-range-p t)
11485 (goto-char (point-at-bol))
11486 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11487 (if (not (org-at-date-range-p t))
11488 (error "Not at a time-stamp range, and none found in current line")))
11489 (let* ((ts1 (match-string 1))
11490 (ts2 (match-string 2))
11491 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11492 (match-end (match-end 0))
11493 (time1 (org-time-string-to-time ts1))
11494 (time2 (org-time-string-to-time ts2))
11495 (t1 (time-to-seconds time1))
11496 (t2 (time-to-seconds time2))
11497 (diff (abs (- t2 t1)))
11498 (negative (< (- t2 t1) 0))
11499 ;; (ys (floor (* 365 24 60 60)))
11500 (ds (* 24 60 60))
11501 (hs (* 60 60))
11502 (fy "%dy %dd %02d:%02d")
11503 (fy1 "%dy %dd")
11504 (fd "%dd %02d:%02d")
11505 (fd1 "%dd")
11506 (fh "%02d:%02d")
11507 y d h m align)
11508 (if havetime
11509 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11511 d (floor (/ diff ds)) diff (mod diff ds)
11512 h (floor (/ diff hs)) diff (mod diff hs)
11513 m (floor (/ diff 60)))
11514 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11516 d (floor (+ (/ diff ds) 0.5))
11517 h 0 m 0))
11518 (if (not to-buffer)
11519 (message "%s" (org-make-tdiff-string y d h m))
11520 (if (org-at-table-p)
11521 (progn
11522 (goto-char match-end)
11523 (setq align t)
11524 (and (looking-at " *|") (goto-char (match-end 0))))
11525 (goto-char match-end))
11526 (if (looking-at
11527 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11528 (replace-match ""))
11529 (if negative (insert " -"))
11530 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11531 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11532 (insert " " (format fh h m))))
11533 (if align (org-table-align))
11534 (message "Time difference inserted")))))
11536 (defun org-make-tdiff-string (y d h m)
11537 (let ((fmt "")
11538 (l nil))
11539 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11540 l (push y l)))
11541 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11542 l (push d l)))
11543 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11544 l (push h l)))
11545 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11546 l (push m l)))
11547 (apply 'format fmt (nreverse l))))
11549 (defun org-time-string-to-time (s)
11550 (apply 'encode-time (org-parse-time-string s)))
11552 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11553 "Convert a time stamp to an absolute day number.
11554 If there is a specifyer for a cyclic time stamp, get the closest date to
11555 DAYNR.
11556 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11557 (cond
11558 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11559 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11560 daynr
11561 (+ daynr 1000)))
11562 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11563 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11564 (time-to-days (current-time))) (match-string 0 s)
11565 prefer show-all))
11566 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11568 (defun org-days-to-iso-week (days)
11569 "Return the iso week number."
11570 (require 'cal-iso)
11571 (car (calendar-iso-from-absolute days)))
11573 (defun org-small-year-to-year (year)
11574 "Convert 2-digit years into 4-digit years.
11575 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11576 The year 2000 cannot be abbreviated. Any year lager than 99
11577 is retrned unchanged."
11578 (if (< year 38)
11579 (setq year (+ 2000 year))
11580 (if (< year 100)
11581 (setq year (+ 1900 year))))
11582 year)
11584 (defun org-time-from-absolute (d)
11585 "Return the time corresponding to date D.
11586 D may be an absolute day number, or a calendar-type list (month day year)."
11587 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11588 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11590 (defun org-calendar-holiday ()
11591 "List of holidays, for Diary display in Org-mode."
11592 (require 'holidays)
11593 (let ((hl (funcall
11594 (if (fboundp 'calendar-check-holidays)
11595 'calendar-check-holidays 'check-calendar-holidays) date)))
11596 (if hl (mapconcat 'identity hl "; "))))
11598 (defun org-diary-sexp-entry (sexp entry date)
11599 "Process a SEXP diary ENTRY for DATE."
11600 (require 'diary-lib)
11601 (let ((result (if calendar-debug-sexp
11602 (let ((stack-trace-on-error t))
11603 (eval (car (read-from-string sexp))))
11604 (condition-case nil
11605 (eval (car (read-from-string sexp)))
11606 (error
11607 (beep)
11608 (message "Bad sexp at line %d in %s: %s"
11609 (org-current-line)
11610 (buffer-file-name) sexp)
11611 (sleep-for 2))))))
11612 (cond ((stringp result) result)
11613 ((and (consp result)
11614 (stringp (cdr result))) (cdr result))
11615 (result entry)
11616 (t nil))))
11618 (defun org-diary-to-ical-string (frombuf)
11619 "Get iCalendar entries from diary entries in buffer FROMBUF.
11620 This uses the icalendar.el library."
11621 (let* ((tmpdir (if (featurep 'xemacs)
11622 (temp-directory)
11623 temporary-file-directory))
11624 (tmpfile (make-temp-name
11625 (expand-file-name "orgics" tmpdir)))
11626 buf rtn b e)
11627 (save-excursion
11628 (set-buffer frombuf)
11629 (icalendar-export-region (point-min) (point-max) tmpfile)
11630 (setq buf (find-buffer-visiting tmpfile))
11631 (set-buffer buf)
11632 (goto-char (point-min))
11633 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11634 (setq b (match-beginning 0)))
11635 (goto-char (point-max))
11636 (if (re-search-backward "^END:VEVENT" nil t)
11637 (setq e (match-end 0)))
11638 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11639 (kill-buffer buf)
11640 (delete-file tmpfile)
11641 rtn))
11643 (defun org-closest-date (start current change prefer show-all)
11644 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11645 When PREFER is `past' return a date that is either CURRENT or past.
11646 When PREFER is `future', return a date that is either CURRENT or future.
11647 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11648 ;; Make the proper lists from the dates
11649 (catch 'exit
11650 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11651 dn dw sday cday n1 n2
11652 d m y y1 y2 date1 date2 nmonths nm ny m2)
11654 (setq start (org-date-to-gregorian start)
11655 current (org-date-to-gregorian
11656 (if show-all
11657 current
11658 (time-to-days (current-time))))
11659 sday (calendar-absolute-from-gregorian start)
11660 cday (calendar-absolute-from-gregorian current))
11662 (if (<= cday sday) (throw 'exit sday))
11664 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11665 (setq dn (string-to-number (match-string 1 change))
11666 dw (cdr (assoc (match-string 2 change) a1)))
11667 (error "Invalid change specifyer: %s" change))
11668 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11669 (cond
11670 ((eq dw 'day)
11671 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11672 n2 (+ n1 dn)))
11673 ((eq dw 'year)
11674 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11675 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11676 (setq date1 (list m d y1)
11677 n1 (calendar-absolute-from-gregorian date1)
11678 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11679 n2 (calendar-absolute-from-gregorian date2)))
11680 ((eq dw 'month)
11681 ;; approx number of month between the two dates
11682 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11683 ;; How often does dn fit in there?
11684 (setq d (nth 1 start) m (car start) y (nth 2 start)
11685 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11686 m (+ m nm)
11687 ny (floor (/ m 12))
11688 y (+ y ny)
11689 m (- m (* ny 12)))
11690 (while (> m 12) (setq m (- m 12) y (1+ y)))
11691 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11692 (setq m2 (+ m dn) y2 y)
11693 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11694 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11695 (while (<= n2 cday)
11696 (setq n1 n2 m m2 y y2)
11697 (setq m2 (+ m dn) y2 y)
11698 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11699 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11700 (if show-all
11701 (cond
11702 ((eq prefer 'past) n1)
11703 ((eq prefer 'future) (if (= cday n1) n1 n2))
11704 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11705 (cond
11706 ((eq prefer 'past) n1)
11707 ((eq prefer 'future) (if (= cday n1) n1 n2))
11708 (t (if (= cday n1) n1 n2)))))))
11710 (defun org-date-to-gregorian (date)
11711 "Turn any specification of DATE into a gregorian date for the calendar."
11712 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11713 ((and (listp date) (= (length date) 3)) date)
11714 ((stringp date)
11715 (setq date (org-parse-time-string date))
11716 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11717 ((listp date)
11718 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11720 (defun org-parse-time-string (s &optional nodefault)
11721 "Parse the standard Org-mode time string.
11722 This should be a lot faster than the normal `parse-time-string'.
11723 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11724 hour and minute fields will be nil if not given."
11725 (if (string-match org-ts-regexp0 s)
11726 (list 0
11727 (if (or (match-beginning 8) (not nodefault))
11728 (string-to-number (or (match-string 8 s) "0")))
11729 (if (or (match-beginning 7) (not nodefault))
11730 (string-to-number (or (match-string 7 s) "0")))
11731 (string-to-number (match-string 4 s))
11732 (string-to-number (match-string 3 s))
11733 (string-to-number (match-string 2 s))
11734 nil nil nil)
11735 (make-list 9 0)))
11737 (defun org-timestamp-up (&optional arg)
11738 "Increase the date item at the cursor by one.
11739 If the cursor is on the year, change the year. If it is on the month or
11740 the day, change that.
11741 With prefix ARG, change by that many units."
11742 (interactive "p")
11743 (org-timestamp-change (prefix-numeric-value arg)))
11745 (defun org-timestamp-down (&optional arg)
11746 "Decrease the date item at the cursor by one.
11747 If the cursor is on the year, change the year. If it is on the month or
11748 the day, change that.
11749 With prefix ARG, change by that many units."
11750 (interactive "p")
11751 (org-timestamp-change (- (prefix-numeric-value arg))))
11753 (defun org-timestamp-up-day (&optional arg)
11754 "Increase the date in the time stamp by one day.
11755 With prefix ARG, change that many days."
11756 (interactive "p")
11757 (if (and (not (org-at-timestamp-p t))
11758 (org-on-heading-p))
11759 (org-todo 'up)
11760 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11762 (defun org-timestamp-down-day (&optional arg)
11763 "Decrease the date in the time stamp by one day.
11764 With prefix ARG, change that many days."
11765 (interactive "p")
11766 (if (and (not (org-at-timestamp-p t))
11767 (org-on-heading-p))
11768 (org-todo 'down)
11769 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11771 (defun org-at-timestamp-p (&optional inactive-ok)
11772 "Determine if the cursor is in or at a timestamp."
11773 (interactive)
11774 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11775 (pos (point))
11776 (ans (or (looking-at tsr)
11777 (save-excursion
11778 (skip-chars-backward "^[<\n\r\t")
11779 (if (> (point) (point-min)) (backward-char 1))
11780 (and (looking-at tsr)
11781 (> (- (match-end 0) pos) -1))))))
11782 (and ans
11783 (boundp 'org-ts-what)
11784 (setq org-ts-what
11785 (cond
11786 ((= pos (match-beginning 0)) 'bracket)
11787 ((= pos (1- (match-end 0))) 'bracket)
11788 ((org-pos-in-match-range pos 2) 'year)
11789 ((org-pos-in-match-range pos 3) 'month)
11790 ((org-pos-in-match-range pos 7) 'hour)
11791 ((org-pos-in-match-range pos 8) 'minute)
11792 ((or (org-pos-in-match-range pos 4)
11793 (org-pos-in-match-range pos 5)) 'day)
11794 ((and (> pos (or (match-end 8) (match-end 5)))
11795 (< pos (match-end 0)))
11796 (- pos (or (match-end 8) (match-end 5))))
11797 (t 'day))))
11798 ans))
11800 (defun org-toggle-timestamp-type ()
11801 "Toggle the type (<active> or [inactive]) of a time stamp."
11802 (interactive)
11803 (when (org-at-timestamp-p t)
11804 (save-excursion
11805 (goto-char (match-beginning 0))
11806 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11807 (goto-char (1- (match-end 0)))
11808 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11809 (message "Timestamp is now %sactive"
11810 (if (equal (char-before) ?>) "in" ""))))
11812 (defun org-timestamp-change (n &optional what)
11813 "Change the date in the time stamp at point.
11814 The date will be changed by N times WHAT. WHAT can be `day', `month',
11815 `year', `minute', `second'. If WHAT is not given, the cursor position
11816 in the timestamp determines what will be changed."
11817 (let ((pos (point))
11818 with-hm inactive
11819 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11820 org-ts-what
11821 extra rem
11822 ts time time0)
11823 (if (not (org-at-timestamp-p t))
11824 (error "Not at a timestamp"))
11825 (if (and (not what) (eq org-ts-what 'bracket))
11826 (org-toggle-timestamp-type)
11827 (if (and (not what) (not (eq org-ts-what 'day))
11828 org-display-custom-times
11829 (get-text-property (point) 'display)
11830 (not (get-text-property (1- (point)) 'display)))
11831 (setq org-ts-what 'day))
11832 (setq org-ts-what (or what org-ts-what)
11833 inactive (= (char-after (match-beginning 0)) ?\[)
11834 ts (match-string 0))
11835 (replace-match "")
11836 (if (string-match
11837 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11839 (setq extra (match-string 1 ts)))
11840 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11841 (setq with-hm t))
11842 (setq time0 (org-parse-time-string ts))
11843 (when (and (eq org-ts-what 'minute)
11844 (eq current-prefix-arg nil))
11845 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11846 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11847 (setcar (cdr time0) (+ (nth 1 time0)
11848 (if (> n 0) (- rem) (- dm rem))))))
11849 (setq time
11850 (encode-time (or (car time0) 0)
11851 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11852 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11853 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11854 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11855 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11856 (nthcdr 6 time0)))
11857 (when (integerp org-ts-what)
11858 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11859 (if (eq what 'calendar)
11860 (let ((cal-date (org-get-date-from-calendar)))
11861 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11862 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11863 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11864 (setcar time0 (or (car time0) 0))
11865 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11866 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11867 (setq time (apply 'encode-time time0))))
11868 (setq org-last-changed-timestamp
11869 (org-insert-time-stamp time with-hm inactive nil nil extra))
11870 (org-clock-update-time-maybe)
11871 (goto-char pos)
11872 ;; Try to recenter the calendar window, if any
11873 (if (and org-calendar-follow-timestamp-change
11874 (get-buffer-window "*Calendar*" t)
11875 (memq org-ts-what '(day month year)))
11876 (org-recenter-calendar (time-to-days time))))))
11878 (defun org-modify-ts-extra (s pos n dm)
11879 "Change the different parts of the lead-time and repeat fields in timestamp."
11880 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11881 ng h m new rem)
11882 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11883 (cond
11884 ((or (org-pos-in-match-range pos 2)
11885 (org-pos-in-match-range pos 3))
11886 (setq m (string-to-number (match-string 3 s))
11887 h (string-to-number (match-string 2 s)))
11888 (if (org-pos-in-match-range pos 2)
11889 (setq h (+ h n))
11890 (setq n (* dm (org-no-warnings (signum n))))
11891 (when (not (= 0 (setq rem (% m dm))))
11892 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11893 (setq m (+ m n)))
11894 (if (< m 0) (setq m (+ m 60) h (1- h)))
11895 (if (> m 59) (setq m (- m 60) h (1+ h)))
11896 (setq h (min 24 (max 0 h)))
11897 (setq ng 1 new (format "-%02d:%02d" h m)))
11898 ((org-pos-in-match-range pos 6)
11899 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11900 ((org-pos-in-match-range pos 5)
11901 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11903 ((org-pos-in-match-range pos 9)
11904 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11905 ((org-pos-in-match-range pos 8)
11906 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11908 (when ng
11909 (setq s (concat
11910 (substring s 0 (match-beginning ng))
11912 (substring s (match-end ng))))))
11915 (defun org-recenter-calendar (date)
11916 "If the calendar is visible, recenter it to DATE."
11917 (let* ((win (selected-window))
11918 (cwin (get-buffer-window "*Calendar*" t))
11919 (calendar-move-hook nil))
11920 (when cwin
11921 (select-window cwin)
11922 (calendar-goto-date (if (listp date) date
11923 (calendar-gregorian-from-absolute date)))
11924 (select-window win))))
11926 (defun org-goto-calendar (&optional arg)
11927 "Go to the Emacs calendar at the current date.
11928 If there is a time stamp in the current line, go to that date.
11929 A prefix ARG can be used to force the current date."
11930 (interactive "P")
11931 (let ((tsr org-ts-regexp) diff
11932 (calendar-move-hook nil)
11933 (calendar-view-holidays-initially-flag nil)
11934 (view-calendar-holidays-initially nil)
11935 (calendar-view-diary-initially-flag nil)
11936 (view-diary-entries-initially nil))
11937 (if (or (org-at-timestamp-p)
11938 (save-excursion
11939 (beginning-of-line 1)
11940 (looking-at (concat ".*" tsr))))
11941 (let ((d1 (time-to-days (current-time)))
11942 (d2 (time-to-days
11943 (org-time-string-to-time (match-string 1)))))
11944 (setq diff (- d2 d1))))
11945 (calendar)
11946 (calendar-goto-today)
11947 (if (and diff (not arg)) (calendar-forward-day diff))))
11949 (defun org-get-date-from-calendar ()
11950 "Return a list (month day year) of date at point in calendar."
11951 (with-current-buffer "*Calendar*"
11952 (save-match-data
11953 (calendar-cursor-to-date))))
11955 (defun org-date-from-calendar ()
11956 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11957 If there is already a time stamp at the cursor position, update it."
11958 (interactive)
11959 (if (org-at-timestamp-p t)
11960 (org-timestamp-change 0 'calendar)
11961 (let ((cal-date (org-get-date-from-calendar)))
11962 (org-insert-time-stamp
11963 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11965 (defun org-minutes-to-hh:mm-string (m)
11966 "Compute H:MM from a number of minutes."
11967 (let ((h (/ m 60)))
11968 (setq m (- m (* 60 h)))
11969 (format org-time-clocksum-format h m)))
11971 (defun org-hh:mm-string-to-minutes (s)
11972 "Convert a string H:MM to a number of minutes."
11973 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11974 (+ (* (string-to-number (match-string 1 s)) 60)
11975 (string-to-number (match-string 2 s)))
11978 ;;;; Agenda files
11980 ;;;###autoload
11981 (defun org-iswitchb (&optional arg)
11982 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11983 With a prefix argument, restrict available to files.
11984 With two prefix arguments, restrict available buffers to agenda files.
11986 Due to some yet unresolved reason, the global function
11987 `iswitchb-mode' needs to be active for this function to work."
11988 (interactive "P")
11989 (require 'iswitchb)
11990 (let ((enabled iswitchb-mode) blist)
11991 (or enabled (iswitchb-mode 1))
11992 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11993 ((equal arg '(16)) (org-buffer-list 'agenda))
11994 (t (org-buffer-list))))
11995 (unwind-protect
11996 (let ((iswitchb-make-buflist-hook
11997 (lambda ()
11998 (setq iswitchb-temp-buflist
11999 (mapcar 'buffer-name blist)))))
12000 (switch-to-buffer
12001 (iswitchb-read-buffer
12002 "Switch-to: " nil t))
12003 (or enabled (iswitchb-mode -1))))))
12005 (defun org-buffer-list (&optional predicate exclude-tmp)
12006 "Return a list of Org buffers.
12007 PREDICATE can be `export', `files' or `agenda'.
12009 export restrict the list to Export buffers.
12010 files restrict the list to buffers visiting Org files.
12011 agenda restrict the list to buffers visiting agenda files.
12013 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12014 (let* ((bfn nil)
12015 (agenda-files (and (eq predicate 'agenda)
12016 (mapcar 'file-truename (org-agenda-files t))))
12017 (filter
12018 (cond
12019 ((eq predicate 'files)
12020 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12021 ((eq predicate 'export)
12022 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12023 ((eq predicate 'agenda)
12024 (lambda (b)
12025 (with-current-buffer b
12026 (and (eq major-mode 'org-mode)
12027 (setq bfn (buffer-file-name b))
12028 (member (file-truename bfn) agenda-files)))))
12029 (t (lambda (b) (with-current-buffer b
12030 (or (eq major-mode 'org-mode)
12031 (string-match "\*Org .*Export"
12032 (buffer-name b)))))))))
12033 (delq nil
12034 (mapcar
12035 (lambda(b)
12036 (if (and (funcall filter b)
12037 (or (not exclude-tmp)
12038 (not (string-match "tmp" (buffer-name b)))))
12040 nil))
12041 (buffer-list)))))
12043 (defun org-agenda-files (&optional unrestricted archives)
12044 "Get the list of agenda files.
12045 Optional UNRESTRICTED means return the full list even if a restriction
12046 is currently in place.
12047 When ARCHIVES is t, include all archive files hat are really being
12048 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12049 `org-agenda-archives-mode' is t."
12050 (let ((files
12051 (cond
12052 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12053 ((stringp org-agenda-files) (org-read-agenda-file-list))
12054 ((listp org-agenda-files) org-agenda-files)
12055 (t (error "Invalid value of `org-agenda-files'")))))
12056 (setq files (apply 'append
12057 (mapcar (lambda (f)
12058 (if (file-directory-p f)
12059 (directory-files
12060 f t org-agenda-file-regexp)
12061 (list f)))
12062 files)))
12063 (when org-agenda-skip-unavailable-files
12064 (setq files (delq nil
12065 (mapcar (function
12066 (lambda (file)
12067 (and (file-readable-p file) file)))
12068 files))))
12069 (when (or (eq archives t)
12070 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12071 (setq files (org-add-archive-files files)))
12072 files))
12074 (defun org-edit-agenda-file-list ()
12075 "Edit the list of agenda files.
12076 Depending on setup, this either uses customize to edit the variable
12077 `org-agenda-files', or it visits the file that is holding the list. In the
12078 latter case, the buffer is set up in a way that saving it automatically kills
12079 the buffer and restores the previous window configuration."
12080 (interactive)
12081 (if (stringp org-agenda-files)
12082 (let ((cw (current-window-configuration)))
12083 (find-file org-agenda-files)
12084 (org-set-local 'org-window-configuration cw)
12085 (org-add-hook 'after-save-hook
12086 (lambda ()
12087 (set-window-configuration
12088 (prog1 org-window-configuration
12089 (kill-buffer (current-buffer))))
12090 (org-install-agenda-files-menu)
12091 (message "New agenda file list installed"))
12092 nil 'local)
12093 (message "%s" (substitute-command-keys
12094 "Edit list and finish with \\[save-buffer]")))
12095 (customize-variable 'org-agenda-files)))
12097 (defun org-store-new-agenda-file-list (list)
12098 "Set new value for the agenda file list and save it correcly."
12099 (if (stringp org-agenda-files)
12100 (let ((f org-agenda-files) b)
12101 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12102 (with-temp-file f
12103 (insert (mapconcat 'identity list "\n") "\n")))
12104 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12105 (setq org-agenda-files list)
12106 (customize-save-variable 'org-agenda-files org-agenda-files))))
12108 (defun org-read-agenda-file-list ()
12109 "Read the list of agenda files from a file."
12110 (when (file-directory-p org-agenda-files)
12111 (error "`org-agenda-files' cannot be a single directory"))
12112 (when (stringp org-agenda-files)
12113 (with-temp-buffer
12114 (insert-file-contents org-agenda-files)
12115 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12118 ;;;###autoload
12119 (defun org-cycle-agenda-files ()
12120 "Cycle through the files in `org-agenda-files'.
12121 If the current buffer visits an agenda file, find the next one in the list.
12122 If the current buffer does not, find the first agenda file."
12123 (interactive)
12124 (let* ((fs (org-agenda-files t))
12125 (files (append fs (list (car fs))))
12126 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12127 file)
12128 (unless files (error "No agenda files"))
12129 (catch 'exit
12130 (while (setq file (pop files))
12131 (if (equal (file-truename file) tcf)
12132 (when (car files)
12133 (find-file (car files))
12134 (throw 'exit t))))
12135 (find-file (car fs)))
12136 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12138 (defun org-agenda-file-to-front (&optional to-end)
12139 "Move/add the current file to the top of the agenda file list.
12140 If the file is not present in the list, it is added to the front. If it is
12141 present, it is moved there. With optional argument TO-END, add/move to the
12142 end of the list."
12143 (interactive "P")
12144 (let ((org-agenda-skip-unavailable-files nil)
12145 (file-alist (mapcar (lambda (x)
12146 (cons (file-truename x) x))
12147 (org-agenda-files t)))
12148 (ctf (file-truename buffer-file-name))
12149 x had)
12150 (setq x (assoc ctf file-alist) had x)
12152 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12153 (if to-end
12154 (setq file-alist (append (delq x file-alist) (list x)))
12155 (setq file-alist (cons x (delq x file-alist))))
12156 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12157 (org-install-agenda-files-menu)
12158 (message "File %s to %s of agenda file list"
12159 (if had "moved" "added") (if to-end "end" "front"))))
12161 (defun org-remove-file (&optional file)
12162 "Remove current file from the list of files in variable `org-agenda-files'.
12163 These are the files which are being checked for agenda entries.
12164 Optional argument FILE means, use this file instead of the current."
12165 (interactive)
12166 (let* ((org-agenda-skip-unavailable-files nil)
12167 (file (or file buffer-file-name))
12168 (true-file (file-truename file))
12169 (afile (abbreviate-file-name file))
12170 (files (delq nil (mapcar
12171 (lambda (x)
12172 (if (equal true-file
12173 (file-truename x))
12174 nil x))
12175 (org-agenda-files t)))))
12176 (if (not (= (length files) (length (org-agenda-files t))))
12177 (progn
12178 (org-store-new-agenda-file-list files)
12179 (org-install-agenda-files-menu)
12180 (message "Removed file: %s" afile))
12181 (message "File was not in list: %s (not removed)" afile))))
12183 (defun org-file-menu-entry (file)
12184 (vector file (list 'find-file file) t))
12186 (defun org-check-agenda-file (file)
12187 "Make sure FILE exists. If not, ask user what to do."
12188 (when (not (file-exists-p file))
12189 (message "non-existent file %s. [R]emove from list or [A]bort?"
12190 (abbreviate-file-name file))
12191 (let ((r (downcase (read-char-exclusive))))
12192 (cond
12193 ((equal r ?r)
12194 (org-remove-file file)
12195 (throw 'nextfile t))
12196 (t (error "Abort"))))))
12198 (defun org-get-agenda-file-buffer (file)
12199 "Get a buffer visiting FILE. If the buffer needs to be created, add
12200 it to the list of buffers which might be released later."
12201 (let ((buf (org-find-base-buffer-visiting file)))
12202 (if buf
12203 buf ; just return it
12204 ;; Make a new buffer and remember it
12205 (setq buf (find-file-noselect file))
12206 (if buf (push buf org-agenda-new-buffers))
12207 buf)))
12209 (defun org-release-buffers (blist)
12210 "Release all buffers in list, asking the user for confirmation when needed.
12211 When a buffer is unmodified, it is just killed. When modified, it is saved
12212 \(if the user agrees) and then killed."
12213 (let (buf file)
12214 (while (setq buf (pop blist))
12215 (setq file (buffer-file-name buf))
12216 (when (and (buffer-modified-p buf)
12217 file
12218 (y-or-n-p (format "Save file %s? " file)))
12219 (with-current-buffer buf (save-buffer)))
12220 (kill-buffer buf))))
12222 (defun org-prepare-agenda-buffers (files)
12223 "Create buffers for all agenda files, protect archived trees and comments."
12224 (interactive)
12225 (let ((pa '(:org-archived t))
12226 (pc '(:org-comment t))
12227 (pall '(:org-archived t :org-comment t))
12228 (inhibit-read-only t)
12229 (rea (concat ":" org-archive-tag ":"))
12230 bmp file re)
12231 (save-excursion
12232 (save-restriction
12233 (while (setq file (pop files))
12234 (if (bufferp file)
12235 (set-buffer file)
12236 (org-check-agenda-file file)
12237 (set-buffer (org-get-agenda-file-buffer file)))
12238 (widen)
12239 (setq bmp (buffer-modified-p))
12240 (org-refresh-category-properties)
12241 (setq org-todo-keywords-for-agenda
12242 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12243 (setq org-done-keywords-for-agenda
12244 (append org-done-keywords-for-agenda org-done-keywords))
12245 (setq org-todo-keyword-alist-for-agenda
12246 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12247 (setq org-tag-alist-for-agenda
12248 (append org-tag-alist-for-agenda org-tag-alist))
12250 (save-excursion
12251 (remove-text-properties (point-min) (point-max) pall)
12252 (when org-agenda-skip-archived-trees
12253 (goto-char (point-min))
12254 (while (re-search-forward rea nil t)
12255 (if (org-on-heading-p t)
12256 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12257 (goto-char (point-min))
12258 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12259 (while (re-search-forward re nil t)
12260 (add-text-properties
12261 (match-beginning 0) (org-end-of-subtree t) pc)))
12262 (set-buffer-modified-p bmp))))
12263 (setq org-todo-keyword-alist-for-agenda
12264 (org-uniquify org-todo-keyword-alist-for-agenda)
12265 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12267 ;;;; Embedded LaTeX
12269 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12270 "Keymap for the minor `org-cdlatex-mode'.")
12272 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12273 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12274 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12275 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12276 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12278 (defvar org-cdlatex-texmathp-advice-is-done nil
12279 "Flag remembering if we have applied the advice to texmathp already.")
12281 (define-minor-mode org-cdlatex-mode
12282 "Toggle the minor `org-cdlatex-mode'.
12283 This mode supports entering LaTeX environment and math in LaTeX fragments
12284 in Org-mode.
12285 \\{org-cdlatex-mode-map}"
12286 nil " OCDL" nil
12287 (when org-cdlatex-mode (require 'cdlatex))
12288 (unless org-cdlatex-texmathp-advice-is-done
12289 (setq org-cdlatex-texmathp-advice-is-done t)
12290 (defadvice texmathp (around org-math-always-on activate)
12291 "Always return t in org-mode buffers.
12292 This is because we want to insert math symbols without dollars even outside
12293 the LaTeX math segments. If Orgmode thinks that point is actually inside
12294 en embedded LaTeX fragement, let texmathp do its job.
12295 \\[org-cdlatex-mode-map]"
12296 (interactive)
12297 (let (p)
12298 (cond
12299 ((not (org-mode-p)) ad-do-it)
12300 ((eq this-command 'cdlatex-math-symbol)
12301 (setq ad-return-value t
12302 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12304 (let ((p (org-inside-LaTeX-fragment-p)))
12305 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12306 (setq ad-return-value t
12307 texmathp-why '("Org-mode embedded math" . 0))
12308 (if p ad-do-it)))))))))
12310 (defun turn-on-org-cdlatex ()
12311 "Unconditionally turn on `org-cdlatex-mode'."
12312 (org-cdlatex-mode 1))
12314 (defun org-inside-LaTeX-fragment-p ()
12315 "Test if point is inside a LaTeX fragment.
12316 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12317 sequence appearing also before point.
12318 Even though the matchers for math are configurable, this function assumes
12319 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12320 delimiters are skipped when they have been removed by customization.
12321 The return value is nil, or a cons cell with the delimiter and
12322 and the position of this delimiter.
12324 This function does a reasonably good job, but can locally be fooled by
12325 for example currency specifications. For example it will assume being in
12326 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12327 fragments that are properly closed, but during editing, we have to live
12328 with the uncertainty caused by missing closing delimiters. This function
12329 looks only before point, not after."
12330 (catch 'exit
12331 (let ((pos (point))
12332 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12333 (lim (progn
12334 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12335 (point)))
12336 dd-on str (start 0) m re)
12337 (goto-char pos)
12338 (when dodollar
12339 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12340 re (nth 1 (assoc "$" org-latex-regexps)))
12341 (while (string-match re str start)
12342 (cond
12343 ((= (match-end 0) (length str))
12344 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12345 ((= (match-end 0) (- (length str) 5))
12346 (throw 'exit nil))
12347 (t (setq start (match-end 0))))))
12348 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12349 (goto-char pos)
12350 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12351 (and (match-beginning 2) (throw 'exit nil))
12352 ;; count $$
12353 (while (re-search-backward "\\$\\$" lim t)
12354 (setq dd-on (not dd-on)))
12355 (goto-char pos)
12356 (if dd-on (cons "$$" m))))))
12359 (defun org-try-cdlatex-tab ()
12360 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12361 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12362 - inside a LaTeX fragment, or
12363 - after the first word in a line, where an abbreviation expansion could
12364 insert a LaTeX environment."
12365 (when org-cdlatex-mode
12366 (cond
12367 ((save-excursion
12368 (skip-chars-backward "a-zA-Z0-9*")
12369 (skip-chars-backward " \t")
12370 (bolp))
12371 (cdlatex-tab) t)
12372 ((org-inside-LaTeX-fragment-p)
12373 (cdlatex-tab) t)
12374 (t nil))))
12376 (defun org-cdlatex-underscore-caret (&optional arg)
12377 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12378 Revert to the normal definition outside of these fragments."
12379 (interactive "P")
12380 (if (org-inside-LaTeX-fragment-p)
12381 (call-interactively 'cdlatex-sub-superscript)
12382 (let (org-cdlatex-mode)
12383 (call-interactively (key-binding (vector last-input-event))))))
12385 (defun org-cdlatex-math-modify (&optional arg)
12386 "Execute `cdlatex-math-modify' in LaTeX fragments.
12387 Revert to the normal definition outside of these fragments."
12388 (interactive "P")
12389 (if (org-inside-LaTeX-fragment-p)
12390 (call-interactively 'cdlatex-math-modify)
12391 (let (org-cdlatex-mode)
12392 (call-interactively (key-binding (vector last-input-event))))))
12394 (defvar org-latex-fragment-image-overlays nil
12395 "List of overlays carrying the images of latex fragments.")
12396 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12398 (defun org-remove-latex-fragment-image-overlays ()
12399 "Remove all overlays with LaTeX fragment images in current buffer."
12400 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12401 (setq org-latex-fragment-image-overlays nil))
12403 (defun org-preview-latex-fragment (&optional subtree)
12404 "Preview the LaTeX fragment at point, or all locally or globally.
12405 If the cursor is in a LaTeX fragment, create the image and overlay
12406 it over the source code. If there is no fragment at point, display
12407 all fragments in the current text, from one headline to the next. With
12408 prefix SUBTREE, display all fragments in the current subtree. With a
12409 double prefix `C-u C-u', or when the cursor is before the first headline,
12410 display all fragments in the buffer.
12411 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12412 (interactive "P")
12413 (org-remove-latex-fragment-image-overlays)
12414 (save-excursion
12415 (save-restriction
12416 (let (beg end at msg)
12417 (cond
12418 ((or (equal subtree '(16))
12419 (not (save-excursion
12420 (re-search-backward (concat "^" outline-regexp) nil t))))
12421 (setq beg (point-min) end (point-max)
12422 msg "Creating images for buffer...%s"))
12423 ((equal subtree '(4))
12424 (org-back-to-heading)
12425 (setq beg (point) end (org-end-of-subtree t)
12426 msg "Creating images for subtree...%s"))
12428 (if (setq at (org-inside-LaTeX-fragment-p))
12429 (goto-char (max (point-min) (- (cdr at) 2)))
12430 (org-back-to-heading))
12431 (setq beg (point) end (progn (outline-next-heading) (point))
12432 msg (if at "Creating image...%s"
12433 "Creating images for entry...%s"))))
12434 (message msg "")
12435 (narrow-to-region beg end)
12436 (goto-char beg)
12437 (org-format-latex
12438 (concat "ltxpng/" (file-name-sans-extension
12439 (file-name-nondirectory
12440 buffer-file-name)))
12441 default-directory 'overlays msg at 'forbuffer)
12442 (message msg "done. Use `C-c C-c' to remove images.")))))
12444 (defvar org-latex-regexps
12445 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12446 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12447 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12448 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12449 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12450 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12451 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12452 "Regular expressions for matching embedded LaTeX.")
12454 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12455 "Replace LaTeX fragments with links to an image, and produce images."
12456 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12457 (let* ((prefixnodir (file-name-nondirectory prefix))
12458 (absprefix (expand-file-name prefix dir))
12459 (todir (file-name-directory absprefix))
12460 (opt org-format-latex-options)
12461 (matchers (plist-get opt :matchers))
12462 (re-list org-latex-regexps)
12463 (cnt 0) txt link beg end re e checkdir
12464 m n block linkfile movefile ov)
12465 ;; Check if there are old images files with this prefix, and remove them
12466 (when (file-directory-p todir)
12467 (mapc 'delete-file
12468 (directory-files
12469 todir 'full
12470 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12471 ;; Check the different regular expressions
12472 (while (setq e (pop re-list))
12473 (setq m (car e) re (nth 1 e) n (nth 2 e)
12474 block (if (nth 3 e) "\n\n" ""))
12475 (when (member m matchers)
12476 (goto-char (point-min))
12477 (while (re-search-forward re nil t)
12478 (when (or (not at) (equal (cdr at) (match-beginning n)))
12479 (setq txt (match-string n)
12480 beg (match-beginning n) end (match-end n)
12481 cnt (1+ cnt)
12482 linkfile (format "%s_%04d.png" prefix cnt)
12483 movefile (format "%s_%04d.png" absprefix cnt)
12484 link (concat block "[[file:" linkfile "]]" block))
12485 (if msg (message msg cnt))
12486 (goto-char beg)
12487 (unless checkdir ; make sure the directory exists
12488 (setq checkdir t)
12489 (or (file-directory-p todir) (make-directory todir)))
12490 (org-create-formula-image
12491 txt movefile opt forbuffer)
12492 (if overlays
12493 (progn
12494 (setq ov (org-make-overlay beg end))
12495 (if (featurep 'xemacs)
12496 (progn
12497 (org-overlay-put ov 'invisible t)
12498 (org-overlay-put
12499 ov 'end-glyph
12500 (make-glyph (vector 'png :file movefile))))
12501 (org-overlay-put
12502 ov 'display
12503 (list 'image :type 'png :file movefile :ascent 'center)))
12504 (push ov org-latex-fragment-image-overlays)
12505 (goto-char end))
12506 (delete-region beg end)
12507 (insert link))))))))
12509 ;; This function borrows from Ganesh Swami's latex2png.el
12510 (defun org-create-formula-image (string tofile options buffer)
12511 (let* ((tmpdir (if (featurep 'xemacs)
12512 (temp-directory)
12513 temporary-file-directory))
12514 (texfilebase (make-temp-name
12515 (expand-file-name "orgtex" tmpdir)))
12516 (texfile (concat texfilebase ".tex"))
12517 (dvifile (concat texfilebase ".dvi"))
12518 (pngfile (concat texfilebase ".png"))
12519 (fnh (if (featurep 'xemacs)
12520 (font-height (get-face-font 'default))
12521 (face-attribute 'default :height nil)))
12522 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12523 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12524 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12525 "Black"))
12526 (bg (or (plist-get options (if buffer :background :html-background))
12527 "Transparent")))
12528 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12529 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12530 (with-temp-file texfile
12531 (insert org-format-latex-header
12532 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12533 (let ((dir default-directory))
12534 (condition-case nil
12535 (progn
12536 (cd tmpdir)
12537 (call-process "latex" nil nil nil texfile))
12538 (error nil))
12539 (cd dir))
12540 (if (not (file-exists-p dvifile))
12541 (progn (message "Failed to create dvi file from %s" texfile) nil)
12542 (condition-case nil
12543 (call-process "dvipng" nil nil nil
12544 "-E" "-fg" fg "-bg" bg
12545 "-D" dpi
12546 ;;"-x" scale "-y" scale
12547 "-T" "tight"
12548 "-o" pngfile
12549 dvifile)
12550 (error nil))
12551 (if (not (file-exists-p pngfile))
12552 (progn (message "Failed to create png file from %s" texfile) nil)
12553 ;; Use the requested file name and clean up
12554 (copy-file pngfile tofile 'replace)
12555 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12556 (delete-file (concat texfilebase e)))
12557 pngfile))))
12559 (defun org-dvipng-color (attr)
12560 "Return an rgb color specification for dvipng."
12561 (apply 'format "rgb %s %s %s"
12562 (mapcar 'org-normalize-color
12563 (color-values (face-attribute 'default attr nil)))))
12565 (defun org-normalize-color (value)
12566 "Return string to be used as color value for an RGB component."
12567 (format "%g" (/ value 65535.0)))
12570 ;;;; Key bindings
12572 ;; Make `C-c C-x' a prefix key
12573 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12575 ;; TAB key with modifiers
12576 (org-defkey org-mode-map "\C-i" 'org-cycle)
12577 (org-defkey org-mode-map [(tab)] 'org-cycle)
12578 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12579 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12580 (org-defkey org-mode-map "\M-\t" 'org-complete)
12581 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12582 ;; The following line is necessary under Suse GNU/Linux
12583 (unless (featurep 'xemacs)
12584 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12585 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12586 (define-key org-mode-map [backtab] 'org-shifttab)
12588 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12589 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12590 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12592 ;; Cursor keys with modifiers
12593 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12594 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12595 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12596 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12598 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12599 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12600 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12601 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12603 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12604 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12605 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12606 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12608 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12609 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12611 ;;; Extra keys for tty access.
12612 ;; We only set them when really needed because otherwise the
12613 ;; menus don't show the simple keys
12615 (when (or org-use-extra-keys
12616 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12617 (not window-system))
12618 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12619 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12620 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12621 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12622 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12623 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12624 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12625 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12626 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12627 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12628 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12629 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12630 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12631 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12632 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12633 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12634 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12635 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12636 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12637 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12638 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12639 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12641 ;; All the other keys
12643 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12644 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12645 (if (boundp 'narrow-map)
12646 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12647 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12648 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12649 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12650 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12651 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12652 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12653 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12654 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12655 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12656 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12657 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12658 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12659 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12660 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12661 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12662 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12663 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12664 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12665 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12666 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12667 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12668 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12669 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12670 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12671 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12672 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12673 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12674 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12675 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12676 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12677 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12678 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12679 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12680 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12681 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12682 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12683 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12684 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12685 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12686 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12687 (org-defkey org-mode-map "\C-c^" 'org-sort)
12688 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12689 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12690 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12691 (org-defkey org-mode-map "\C-m" 'org-return)
12692 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12693 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12694 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12695 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12696 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12697 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12698 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12699 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12700 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12701 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12702 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12703 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12704 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12705 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12706 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12707 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12709 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12710 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12711 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12712 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12714 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12715 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12716 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12717 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12718 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12719 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12720 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12721 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12722 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12723 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12724 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12725 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12727 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12729 (when (featurep 'xemacs)
12730 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12732 (defvar org-table-auto-blank-field) ; defined in org-table.el
12733 (defun org-self-insert-command (N)
12734 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12735 If the cursor is in a table looking at whitespace, the whitespace is
12736 overwritten, and the table is not marked as requiring realignment."
12737 (interactive "p")
12738 (if (and (org-table-p)
12739 (progn
12740 ;; check if we blank the field, and if that triggers align
12741 (and (featurep 'org-table) org-table-auto-blank-field
12742 (member last-command
12743 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12744 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12745 ;; got extra space, this field does not determine column width
12746 (let (org-table-may-need-update) (org-table-blank-field))
12747 ;; no extra space, this field may determine column width
12748 (org-table-blank-field)))
12750 (eq N 1)
12751 (looking-at "[^|\n]* |"))
12752 (let (org-table-may-need-update)
12753 (goto-char (1- (match-end 0)))
12754 (delete-backward-char 1)
12755 (goto-char (match-beginning 0))
12756 (self-insert-command N))
12757 (setq org-table-may-need-update t)
12758 (self-insert-command N)
12759 (org-fix-tags-on-the-fly)))
12761 (defun org-fix-tags-on-the-fly ()
12762 (when (and (equal (char-after (point-at-bol)) ?*)
12763 (org-on-heading-p))
12764 (org-align-tags-here org-tags-column)))
12766 (defun org-delete-backward-char (N)
12767 "Like `delete-backward-char', insert whitespace at field end in tables.
12768 When deleting backwards, in tables this function will insert whitespace in
12769 front of the next \"|\" separator, to keep the table aligned. The table will
12770 still be marked for re-alignment if the field did fill the entire column,
12771 because, in this case the deletion might narrow the column."
12772 (interactive "p")
12773 (if (and (org-table-p)
12774 (eq N 1)
12775 (string-match "|" (buffer-substring (point-at-bol) (point)))
12776 (looking-at ".*?|"))
12777 (let ((pos (point))
12778 (noalign (looking-at "[^|\n\r]* |"))
12779 (c org-table-may-need-update))
12780 (backward-delete-char N)
12781 (skip-chars-forward "^|")
12782 (insert " ")
12783 (goto-char (1- pos))
12784 ;; noalign: if there were two spaces at the end, this field
12785 ;; does not determine the width of the column.
12786 (if noalign (setq org-table-may-need-update c)))
12787 (backward-delete-char N)
12788 (org-fix-tags-on-the-fly)))
12790 (defun org-delete-char (N)
12791 "Like `delete-char', but insert whitespace at field end in tables.
12792 When deleting characters, in tables this function will insert whitespace in
12793 front of the next \"|\" separator, to keep the table aligned. The table will
12794 still be marked for re-alignment if the field did fill the entire column,
12795 because, in this case the deletion might narrow the column."
12796 (interactive "p")
12797 (if (and (org-table-p)
12798 (not (bolp))
12799 (not (= (char-after) ?|))
12800 (eq N 1))
12801 (if (looking-at ".*?|")
12802 (let ((pos (point))
12803 (noalign (looking-at "[^|\n\r]* |"))
12804 (c org-table-may-need-update))
12805 (replace-match (concat
12806 (substring (match-string 0) 1 -1)
12807 " |"))
12808 (goto-char pos)
12809 ;; noalign: if there were two spaces at the end, this field
12810 ;; does not determine the width of the column.
12811 (if noalign (setq org-table-may-need-update c)))
12812 (delete-char N))
12813 (delete-char N)
12814 (org-fix-tags-on-the-fly)))
12816 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12817 (put 'org-self-insert-command 'delete-selection t)
12818 (put 'orgtbl-self-insert-command 'delete-selection t)
12819 (put 'org-delete-char 'delete-selection 'supersede)
12820 (put 'org-delete-backward-char 'delete-selection 'supersede)
12822 ;; Make `flyspell-mode' delay after some commands
12823 (put 'org-self-insert-command 'flyspell-delayed t)
12824 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12825 (put 'org-delete-char 'flyspell-delayed t)
12826 (put 'org-delete-backward-char 'flyspell-delayed t)
12828 ;; Make pabbrev-mode expand after org-mode commands
12829 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12830 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12832 ;; How to do this: Measure non-white length of current string
12833 ;; If equal to column width, we should realign.
12835 (defun org-remap (map &rest commands)
12836 "In MAP, remap the functions given in COMMANDS.
12837 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12838 (let (new old)
12839 (while commands
12840 (setq old (pop commands) new (pop commands))
12841 (if (fboundp 'command-remapping)
12842 (org-defkey map (vector 'remap old) new)
12843 (substitute-key-definition old new map global-map)))))
12845 (when (eq org-enable-table-editor 'optimized)
12846 ;; If the user wants maximum table support, we need to hijack
12847 ;; some standard editing functions
12848 (org-remap org-mode-map
12849 'self-insert-command 'org-self-insert-command
12850 'delete-char 'org-delete-char
12851 'delete-backward-char 'org-delete-backward-char)
12852 (org-defkey org-mode-map "|" 'org-force-self-insert))
12854 (defun org-shiftcursor-error ()
12855 "Throw an error because Shift-Cursor command was applied in wrong context."
12856 (error "This command is active in special context like tables, headlines or timestamps"))
12858 (defun org-shifttab (&optional arg)
12859 "Global visibility cycling or move to previous table field.
12860 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12861 on context.
12862 See the individual commands for more information."
12863 (interactive "P")
12864 (cond
12865 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12866 ((integerp arg)
12867 (message "Content view to level: %d" arg)
12868 (org-content (prefix-numeric-value arg))
12869 (setq org-cycle-global-status 'overview))
12870 (t (call-interactively 'org-global-cycle))))
12872 (defun org-shiftmetaleft ()
12873 "Promote subtree or delete table column.
12874 Calls `org-promote-subtree', `org-outdent-item',
12875 or `org-table-delete-column', depending on context.
12876 See the individual commands for more information."
12877 (interactive)
12878 (cond
12879 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12880 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12881 ((org-at-item-p) (call-interactively 'org-outdent-item))
12882 (t (org-shiftcursor-error))))
12884 (defun org-shiftmetaright ()
12885 "Demote subtree or insert table column.
12886 Calls `org-demote-subtree', `org-indent-item',
12887 or `org-table-insert-column', depending on context.
12888 See the individual commands for more information."
12889 (interactive)
12890 (cond
12891 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12892 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12893 ((org-at-item-p) (call-interactively 'org-indent-item))
12894 (t (org-shiftcursor-error))))
12896 (defun org-shiftmetaup (&optional arg)
12897 "Move subtree up or kill table row.
12898 Calls `org-move-subtree-up' or `org-table-kill-row' or
12899 `org-move-item-up' depending on context. See the individual commands
12900 for more information."
12901 (interactive "P")
12902 (cond
12903 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12904 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12905 ((org-at-item-p) (call-interactively 'org-move-item-up))
12906 (t (org-shiftcursor-error))))
12907 (defun org-shiftmetadown (&optional arg)
12908 "Move subtree down or insert table row.
12909 Calls `org-move-subtree-down' or `org-table-insert-row' or
12910 `org-move-item-down', depending on context. See the individual
12911 commands for more information."
12912 (interactive "P")
12913 (cond
12914 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12915 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12916 ((org-at-item-p) (call-interactively 'org-move-item-down))
12917 (t (org-shiftcursor-error))))
12919 (defun org-metaleft (&optional arg)
12920 "Promote heading or move table column to left.
12921 Calls `org-do-promote' or `org-table-move-column', depending on context.
12922 With no specific context, calls the Emacs default `backward-word'.
12923 See the individual commands for more information."
12924 (interactive "P")
12925 (cond
12926 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12927 ((or (org-on-heading-p) (org-region-active-p))
12928 (call-interactively 'org-do-promote))
12929 ((org-at-item-p) (call-interactively 'org-outdent-item))
12930 (t (call-interactively 'backward-word))))
12932 (defun org-metaright (&optional arg)
12933 "Demote subtree or move table column to right.
12934 Calls `org-do-demote' or `org-table-move-column', depending on context.
12935 With no specific context, calls the Emacs default `forward-word'.
12936 See the individual commands for more information."
12937 (interactive "P")
12938 (cond
12939 ((org-at-table-p) (call-interactively 'org-table-move-column))
12940 ((or (org-on-heading-p) (org-region-active-p))
12941 (call-interactively 'org-do-demote))
12942 ((org-at-item-p) (call-interactively 'org-indent-item))
12943 (t (call-interactively 'forward-word))))
12945 (defun org-metaup (&optional arg)
12946 "Move subtree up or move table row up.
12947 Calls `org-move-subtree-up' or `org-table-move-row' or
12948 `org-move-item-up', depending on context. See the individual commands
12949 for more information."
12950 (interactive "P")
12951 (cond
12952 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12953 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12954 ((org-at-item-p) (call-interactively 'org-move-item-up))
12955 (t (transpose-lines 1) (beginning-of-line -1))))
12957 (defun org-metadown (&optional arg)
12958 "Move subtree down or move table row down.
12959 Calls `org-move-subtree-down' or `org-table-move-row' or
12960 `org-move-item-down', depending on context. See the individual
12961 commands for more information."
12962 (interactive "P")
12963 (cond
12964 ((org-at-table-p) (call-interactively 'org-table-move-row))
12965 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12966 ((org-at-item-p) (call-interactively 'org-move-item-down))
12967 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12969 (defun org-shiftup (&optional arg)
12970 "Increase item in timestamp or increase priority of current headline.
12971 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12972 depending on context. See the individual commands for more information."
12973 (interactive "P")
12974 (cond
12975 ((org-at-timestamp-p t)
12976 (call-interactively (if org-edit-timestamp-down-means-later
12977 'org-timestamp-down 'org-timestamp-up)))
12978 ((org-on-heading-p) (call-interactively 'org-priority-up))
12979 ((org-at-item-p) (call-interactively 'org-previous-item))
12980 ((org-clocktable-try-shift 'up arg))
12981 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12983 (defun org-shiftdown (&optional arg)
12984 "Decrease item in timestamp or decrease priority of current headline.
12985 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12986 depending on context. See the individual commands for more information."
12987 (interactive "P")
12988 (cond
12989 ((org-at-timestamp-p t)
12990 (call-interactively (if org-edit-timestamp-down-means-later
12991 'org-timestamp-up 'org-timestamp-down)))
12992 ((org-on-heading-p) (call-interactively 'org-priority-down))
12993 ((org-clocktable-try-shift 'down arg))
12994 (t (call-interactively 'org-next-item))))
12996 (defun org-shiftright (&optional arg)
12997 "Next TODO keyword or timestamp one day later, depending on context."
12998 (interactive "P")
12999 (cond
13000 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13001 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13002 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13003 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13004 ((org-clocktable-try-shift 'right arg))
13005 (t (org-shiftcursor-error))))
13007 (defun org-shiftleft (&optional arg)
13008 "Previous TODO keyword or timestamp one day earlier, depending on context."
13009 (interactive "P")
13010 (cond
13011 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13012 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13013 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13014 ((org-at-property-p)
13015 (call-interactively 'org-property-previous-allowed-value))
13016 ((org-clocktable-try-shift 'left arg))
13017 (t (org-shiftcursor-error))))
13019 (defun org-shiftcontrolright ()
13020 "Switch to next TODO set."
13021 (interactive)
13022 (cond
13023 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13024 (t (org-shiftcursor-error))))
13026 (defun org-shiftcontrolleft ()
13027 "Switch to previous TODO set."
13028 (interactive)
13029 (cond
13030 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13031 (t (org-shiftcursor-error))))
13033 (defun org-ctrl-c-ret ()
13034 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13035 (interactive)
13036 (cond
13037 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13038 (t (call-interactively 'org-insert-heading))))
13040 (defun org-copy-special ()
13041 "Copy region in table or copy current subtree.
13042 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13043 See the individual commands for more information."
13044 (interactive)
13045 (call-interactively
13046 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13048 (defun org-cut-special ()
13049 "Cut region in table or cut current subtree.
13050 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13051 See the individual commands for more information."
13052 (interactive)
13053 (call-interactively
13054 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13056 (defun org-paste-special (arg)
13057 "Paste rectangular region into table, or past subtree relative to level.
13058 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13059 See the individual commands for more information."
13060 (interactive "P")
13061 (if (org-at-table-p)
13062 (org-table-paste-rectangle)
13063 (org-paste-subtree arg)))
13065 (defun org-edit-special ()
13066 "Call a special editor for the stuff at point.
13067 When at a table, call the formula editor with `org-table-edit-formulas'.
13068 When at the first line of an src example, call `org-edit-src-code'.
13069 When in an #+include line, visit the include file. Otherwise call
13070 `ffap' to visit the file at point."
13071 (interactive)
13072 (cond
13073 ((org-at-table-p)
13074 (call-interactively 'org-table-edit-formulas))
13075 ((save-excursion
13076 (beginning-of-line 1)
13077 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13078 (find-file (org-trim (match-string 1))))
13079 ((org-edit-src-code))
13080 ((org-edit-fixed-width-region))
13081 (t (call-interactively 'ffap))))
13083 (defun org-ctrl-c-ctrl-c (&optional arg)
13084 "Set tags in headline, or update according to changed information at point.
13086 This command does many different things, depending on context:
13088 - If the cursor is in a headline, prompt for tags and insert them
13089 into the current line, aligned to `org-tags-column'. When called
13090 with prefix arg, realign all tags in the current buffer.
13092 - If the cursor is in one of the special #+KEYWORD lines, this
13093 triggers scanning the buffer for these lines and updating the
13094 information.
13096 - If the cursor is inside a table, realign the table. This command
13097 works even if the automatic table editor has been turned off.
13099 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13100 the entire table.
13102 - If the cursor is a the beginning of a dynamic block, update it.
13104 - If the cursor is inside a table created by the table.el package,
13105 activate that table.
13107 - If the current buffer is a remember buffer, close note and file it.
13108 with a prefix argument, file it without further interaction to the default
13109 location.
13111 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13112 links in this buffer.
13114 - If the cursor is on a numbered item in a plain list, renumber the
13115 ordered list.
13117 - If the cursor is on a checkbox, toggle it."
13118 (interactive "P")
13119 (let ((org-enable-table-editor t))
13120 (cond
13121 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13122 org-occur-highlights
13123 org-latex-fragment-image-overlays)
13124 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13125 (org-remove-occur-highlights)
13126 (org-remove-latex-fragment-image-overlays)
13127 (message "Temporary highlights/overlays removed from current buffer"))
13128 ((and (local-variable-p 'org-finish-function (current-buffer))
13129 (fboundp org-finish-function))
13130 (funcall org-finish-function))
13131 ((org-at-property-p)
13132 (call-interactively 'org-property-action))
13133 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13134 ((org-on-heading-p) (call-interactively 'org-set-tags))
13135 ((org-at-table.el-p)
13136 (require 'table)
13137 (beginning-of-line 1)
13138 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13139 (call-interactively 'table-recognize-table))
13140 ((org-at-table-p)
13141 (org-table-maybe-eval-formula)
13142 (if arg
13143 (call-interactively 'org-table-recalculate)
13144 (org-table-maybe-recalculate-line))
13145 (call-interactively 'org-table-align))
13146 ((org-at-item-checkbox-p)
13147 (call-interactively 'org-toggle-checkbox))
13148 ((org-at-item-p)
13149 (call-interactively 'org-maybe-renumber-ordered-list))
13150 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13151 ;; Dynamic block
13152 (beginning-of-line 1)
13153 (save-excursion (org-update-dblock)))
13154 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13155 (cond
13156 ((equal (match-string 1) "TBLFM")
13157 ;; Recalculate the table before this line
13158 (save-excursion
13159 (beginning-of-line 1)
13160 (skip-chars-backward " \r\n\t")
13161 (if (org-at-table-p)
13162 (org-call-with-arg 'org-table-recalculate t))))
13164 ; (org-set-regexps-and-options)
13165 ; (org-restart-font-lock)
13166 (let ((org-inhibit-startup t)) (org-mode-restart))
13167 (message "Local setup has been refreshed"))))
13168 (t (error "C-c C-c can do nothing useful at this location.")))))
13170 (defun org-mode-restart ()
13171 "Restart Org-mode, to scan again for special lines.
13172 Also updates the keyword regular expressions."
13173 (interactive)
13174 (org-mode)
13175 (message "Org-mode restarted"))
13177 (defun org-kill-note-or-show-branches ()
13178 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13179 (interactive)
13180 (if (not org-finish-function)
13181 (call-interactively 'show-branches)
13182 (let ((org-note-abort t))
13183 (funcall org-finish-function))))
13185 (defun org-return (&optional indent)
13186 "Goto next table row or insert a newline.
13187 Calls `org-table-next-row' or `newline', depending on context.
13188 See the individual commands for more information."
13189 (interactive)
13190 (cond
13191 ((bobp) (if indent (newline-and-indent) (newline)))
13192 ((and (org-at-heading-p)
13193 (looking-at
13194 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13195 (org-show-entry)
13196 (end-of-line 1)
13197 (newline))
13198 ((org-at-table-p)
13199 (org-table-justify-field-maybe)
13200 (call-interactively 'org-table-next-row))
13201 (t (if indent (newline-and-indent) (newline)))))
13203 (defun org-return-indent ()
13204 "Goto next table row or insert a newline and indent.
13205 Calls `org-table-next-row' or `newline-and-indent', depending on
13206 context. See the individual commands for more information."
13207 (interactive)
13208 (org-return t))
13210 (defun org-ctrl-c-star ()
13211 "Compute table, or change heading status of lines.
13212 Calls `org-table-recalculate' or `org-toggle-region-headings',
13213 depending on context. This will also turn a plain list item or a normal
13214 line into a subheading."
13215 (interactive)
13216 (cond
13217 ((org-at-table-p)
13218 (call-interactively 'org-table-recalculate))
13219 ((org-region-active-p)
13220 ;; Convert all lines in region to list items
13221 (call-interactively 'org-toggle-region-headings))
13222 ((org-on-heading-p)
13223 (org-toggle-region-headings (point-at-bol)
13224 (min (1+ (point-at-eol)) (point-max))))
13225 ((org-at-item-p)
13226 ;; Convert to heading
13227 (let ((level (save-match-data
13228 (save-excursion
13229 (condition-case nil
13230 (progn
13231 (org-back-to-heading t)
13232 (funcall outline-level))
13233 (error 0))))))
13234 (replace-match
13235 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13236 (t (org-toggle-region-headings (point-at-bol)
13237 (min (1+ (point-at-eol)) (point-max))))))
13239 (defun org-ctrl-c-minus ()
13240 "Insert separator line in table or modify bullet status of line.
13241 Also turns a plain line or a region of lines into list items.
13242 Calls `org-table-insert-hline', `org-toggle-region-items', or
13243 `org-cycle-list-bullet', depending on context."
13244 (interactive)
13245 (cond
13246 ((org-at-table-p)
13247 (call-interactively 'org-table-insert-hline))
13248 ((org-on-heading-p)
13249 ;; Convert to item
13250 (save-excursion
13251 (beginning-of-line 1)
13252 (if (looking-at "\\*+ ")
13253 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13254 ((org-region-active-p)
13255 ;; Convert all lines in region to list items
13256 (call-interactively 'org-toggle-region-items))
13257 ((org-in-item-p)
13258 (call-interactively 'org-cycle-list-bullet))
13259 (t (org-toggle-region-items (point-at-bol)
13260 (min (1+ (point-at-eol)) (point-max))))))
13262 (defun org-toggle-region-items (beg end)
13263 "Convert all lines in region to list items.
13264 If the first line is already an item, convert all list items in the region
13265 to normal lines."
13266 (interactive "r")
13267 (let (l2 l)
13268 (save-excursion
13269 (goto-char end)
13270 (setq l2 (org-current-line))
13271 (goto-char beg)
13272 (beginning-of-line 1)
13273 (setq l (1- (org-current-line)))
13274 (if (org-at-item-p)
13275 ;; We already have items, de-itemize
13276 (while (< (setq l (1+ l)) l2)
13277 (when (org-at-item-p)
13278 (goto-char (match-beginning 2))
13279 (delete-region (match-beginning 2) (match-end 2))
13280 (and (looking-at "[ \t]+") (replace-match "")))
13281 (beginning-of-line 2))
13282 (while (< (setq l (1+ l)) l2)
13283 (unless (org-at-item-p)
13284 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13285 (replace-match "\\1- \\2")))
13286 (beginning-of-line 2))))))
13288 (defun org-toggle-region-headings (beg end)
13289 "Convert all lines in region to list items.
13290 If the first line is already an item, convert all list items in the region
13291 to normal lines."
13292 (interactive "r")
13293 (let (l2 l)
13294 (save-excursion
13295 (goto-char end)
13296 (setq l2 (org-current-line))
13297 (goto-char beg)
13298 (beginning-of-line 1)
13299 (setq l (1- (org-current-line)))
13300 (if (org-on-heading-p)
13301 ;; We already have headlines, de-star them
13302 (while (< (setq l (1+ l)) l2)
13303 (when (org-on-heading-p t)
13304 (and (looking-at outline-regexp) (replace-match "")))
13305 (beginning-of-line 2))
13306 (let* ((stars (save-excursion
13307 (re-search-backward org-complex-heading-regexp nil t)
13308 (or (match-string 1) "*")))
13309 (add-stars (if org-odd-levels-only "**" "*"))
13310 (rpl (concat stars add-stars " \\2")))
13311 (while (< (setq l (1+ l)) l2)
13312 (unless (org-on-heading-p)
13313 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13314 (replace-match rpl)))
13315 (beginning-of-line 2)))))))
13317 (defun org-meta-return (&optional arg)
13318 "Insert a new heading or wrap a region in a table.
13319 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13320 See the individual commands for more information."
13321 (interactive "P")
13322 (cond
13323 ((org-at-table-p)
13324 (call-interactively 'org-table-wrap-region))
13325 (t (call-interactively 'org-insert-heading))))
13327 ;;; Menu entries
13329 ;; Define the Org-mode menus
13330 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13331 '("Tbl"
13332 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13333 ["Next Field" org-cycle (org-at-table-p)]
13334 ["Previous Field" org-shifttab (org-at-table-p)]
13335 ["Next Row" org-return (org-at-table-p)]
13336 "--"
13337 ["Blank Field" org-table-blank-field (org-at-table-p)]
13338 ["Edit Field" org-table-edit-field (org-at-table-p)]
13339 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13340 "--"
13341 ("Column"
13342 ["Move Column Left" org-metaleft (org-at-table-p)]
13343 ["Move Column Right" org-metaright (org-at-table-p)]
13344 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13345 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13346 ("Row"
13347 ["Move Row Up" org-metaup (org-at-table-p)]
13348 ["Move Row Down" org-metadown (org-at-table-p)]
13349 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13350 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13351 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13352 "--"
13353 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13354 ("Rectangle"
13355 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13356 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13357 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13358 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13359 "--"
13360 ("Calculate"
13361 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13362 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13363 ["Edit Formulas" org-edit-special (org-at-table-p)]
13364 "--"
13365 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13366 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13367 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13368 "--"
13369 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13370 "--"
13371 ["Sum Column/Rectangle" org-table-sum
13372 (or (org-at-table-p) (org-region-active-p))]
13373 ["Which Column?" org-table-current-column (org-at-table-p)])
13374 ["Debug Formulas"
13375 org-table-toggle-formula-debugger
13376 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13377 ["Show Col/Row Numbers"
13378 org-table-toggle-coordinate-overlays
13379 :style toggle
13380 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13381 "--"
13382 ["Create" org-table-create (and (not (org-at-table-p))
13383 org-enable-table-editor)]
13384 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13385 ["Import from File" org-table-import (not (org-at-table-p))]
13386 ["Export to File" org-table-export (org-at-table-p)]
13387 "--"
13388 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13390 (easy-menu-define org-org-menu org-mode-map "Org menu"
13391 '("Org"
13392 ("Show/Hide"
13393 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13394 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13395 ["Sparse Tree..." org-sparse-tree t]
13396 ["Reveal Context" org-reveal t]
13397 ["Show All" show-all t]
13398 "--"
13399 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13400 "--"
13401 ["New Heading" org-insert-heading t]
13402 ("Navigate Headings"
13403 ["Up" outline-up-heading t]
13404 ["Next" outline-next-visible-heading t]
13405 ["Previous" outline-previous-visible-heading t]
13406 ["Next Same Level" outline-forward-same-level t]
13407 ["Previous Same Level" outline-backward-same-level t]
13408 "--"
13409 ["Jump" org-goto t])
13410 ("Edit Structure"
13411 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13412 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13413 "--"
13414 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13415 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13416 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13417 "--"
13418 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13419 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13420 ["Demote Heading" org-metaright (not (org-at-table-p))]
13421 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13422 "--"
13423 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13424 "--"
13425 ["Convert to odd levels" org-convert-to-odd-levels t]
13426 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13427 ("Editing"
13428 ["Emphasis..." org-emphasize t]
13429 ["Edit Source Example" org-edit-special t])
13430 ("Archive"
13431 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13432 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13433 ; :active t :keys "C-u C-c C-x C-a"]
13434 ["Sparse trees open ARCHIVE trees"
13435 (setq org-sparse-tree-open-archived-trees
13436 (not org-sparse-tree-open-archived-trees))
13437 :style toggle :selected org-sparse-tree-open-archived-trees]
13438 ["Cycling opens ARCHIVE trees"
13439 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13440 :style toggle :selected org-cycle-open-archived-trees]
13441 "--"
13442 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13443 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13444 ; ["Check and Move Children" (org-archive-subtree '(4))
13445 ; :active t :keys "C-u C-c C-x C-s"]
13447 "--"
13448 ("TODO Lists"
13449 ["TODO/DONE/-" org-todo t]
13450 ("Select keyword"
13451 ["Next keyword" org-shiftright (org-on-heading-p)]
13452 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13453 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13454 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13455 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13456 ["Show TODO Tree" org-show-todo-tree t]
13457 ["Global TODO list" org-todo-list t]
13458 "--"
13459 ["Set Priority" org-priority t]
13460 ["Priority Up" org-shiftup t]
13461 ["Priority Down" org-shiftdown t])
13462 ("TAGS and Properties"
13463 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13464 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13465 "--"
13466 ["Set property" 'org-set-property t]
13467 ["Column view of properties" org-columns t]
13468 ["Insert Column View DBlock" org-insert-columns-dblock t])
13469 ("Dates and Scheduling"
13470 ["Timestamp" org-time-stamp t]
13471 ["Timestamp (inactive)" org-time-stamp-inactive t]
13472 ("Change Date"
13473 ["1 Day Later" org-shiftright t]
13474 ["1 Day Earlier" org-shiftleft t]
13475 ["1 ... Later" org-shiftup t]
13476 ["1 ... Earlier" org-shiftdown t])
13477 ["Compute Time Range" org-evaluate-time-range t]
13478 ["Schedule Item" org-schedule t]
13479 ["Deadline" org-deadline t]
13480 "--"
13481 ["Custom time format" org-toggle-time-stamp-overlays
13482 :style radio :selected org-display-custom-times]
13483 "--"
13484 ["Goto Calendar" org-goto-calendar t]
13485 ["Date from Calendar" org-date-from-calendar t])
13486 ("Logging work"
13487 ["Clock in" org-clock-in t]
13488 ["Clock out" org-clock-out t]
13489 ["Clock cancel" org-clock-cancel t]
13490 ["Goto running clock" org-clock-goto t]
13491 ["Display times" org-clock-display t]
13492 ["Create clock table" org-clock-report t]
13493 "--"
13494 ["Record DONE time"
13495 (progn (setq org-log-done (not org-log-done))
13496 (message "Switching to %s will %s record a timestamp"
13497 (car org-done-keywords)
13498 (if org-log-done "automatically" "not")))
13499 :style toggle :selected org-log-done])
13500 "--"
13501 ["Agenda Command..." org-agenda t]
13502 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13503 ("File List for Agenda")
13504 ("Special views current file"
13505 ["TODO Tree" org-show-todo-tree t]
13506 ["Check Deadlines" org-check-deadlines t]
13507 ["Timeline" org-timeline t]
13508 ["Tags Tree" org-tags-sparse-tree t])
13509 "--"
13510 ("Hyperlinks"
13511 ["Store Link (Global)" org-store-link t]
13512 ["Insert Link" org-insert-link t]
13513 ["Follow Link" org-open-at-point t]
13514 "--"
13515 ["Next link" org-next-link t]
13516 ["Previous link" org-previous-link t]
13517 "--"
13518 ["Descriptive Links"
13519 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13520 :style radio
13521 :selected (member '(org-link) buffer-invisibility-spec)]
13522 ["Literal Links"
13523 (progn
13524 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13525 :style radio
13526 :selected (not (member '(org-link) buffer-invisibility-spec))])
13527 "--"
13528 ["Export/Publish..." org-export t]
13529 ("LaTeX"
13530 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13531 :selected org-cdlatex-mode]
13532 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13533 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13534 ["Modify math symbol" org-cdlatex-math-modify
13535 (org-inside-LaTeX-fragment-p)]
13536 ["Export LaTeX fragments as images"
13537 (if (featurep 'org-exp)
13538 (setq org-export-with-LaTeX-fragments
13539 (not org-export-with-LaTeX-fragments))
13540 (require 'org-exp))
13541 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13542 org-export-with-LaTeX-fragments)])
13543 "--"
13544 ("Documentation"
13545 ["Show Version" org-version t]
13546 ["Info Documentation" org-info t])
13547 ("Customize"
13548 ["Browse Org Group" org-customize t]
13549 "--"
13550 ["Expand This Menu" org-create-customize-menu
13551 (fboundp 'customize-menu-create)])
13552 "--"
13553 ["Refresh setup" org-mode-restart t]
13556 (defun org-info (&optional node)
13557 "Read documentation for Org-mode in the info system.
13558 With optional NODE, go directly to that node."
13559 (interactive)
13560 (info (format "(org)%s" (or node ""))))
13562 (defun org-install-agenda-files-menu ()
13563 (let ((bl (buffer-list)))
13564 (save-excursion
13565 (while bl
13566 (set-buffer (pop bl))
13567 (if (org-mode-p) (setq bl nil)))
13568 (when (org-mode-p)
13569 (easy-menu-change
13570 '("Org") "File List for Agenda"
13571 (append
13572 (list
13573 ["Edit File List" (org-edit-agenda-file-list) t]
13574 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13575 ["Remove Current File from List" org-remove-file t]
13576 ["Cycle through agenda files" org-cycle-agenda-files t]
13577 ["Occur in all agenda files" org-occur-in-agenda-files t]
13578 "--")
13579 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13581 ;;;; Documentation
13583 ;;;###autoload
13584 (defun org-require-autoloaded-modules ()
13585 (interactive)
13586 (mapc 'require
13587 '(org-agenda org-archive org-clock org-colview
13588 org-exp org-id org-export-latex org-publish
13589 org-remember org-table)))
13591 ;;;###autoload
13592 (defun org-customize ()
13593 "Call the customize function with org as argument."
13594 (interactive)
13595 (org-load-modules-maybe)
13596 (org-require-autoloaded-modules)
13597 (customize-browse 'org))
13599 (defun org-create-customize-menu ()
13600 "Create a full customization menu for Org-mode, insert it into the menu."
13601 (interactive)
13602 (org-load-modules-maybe)
13603 (org-require-autoloaded-modules)
13604 (if (fboundp 'customize-menu-create)
13605 (progn
13606 (easy-menu-change
13607 '("Org") "Customize"
13608 `(["Browse Org group" org-customize t]
13609 "--"
13610 ,(customize-menu-create 'org)
13611 ["Set" Custom-set t]
13612 ["Save" Custom-save t]
13613 ["Reset to Current" Custom-reset-current t]
13614 ["Reset to Saved" Custom-reset-saved t]
13615 ["Reset to Standard Settings" Custom-reset-standard t]))
13616 (message "\"Org\"-menu now contains full customization menu"))
13617 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13619 ;;;; Miscellaneous stuff
13621 ;;; Generally useful functions
13623 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13624 "Display the given MESSAGE as a warning."
13625 (if (fboundp 'display-warning)
13626 (display-warning 'org message
13627 (if (featurep 'xemacs)
13628 'warning
13629 :warning))
13630 (let ((buf (get-buffer-create "*Org warnings*")))
13631 (with-current-buffer buf
13632 (goto-char (point-max))
13633 (insert "Warning (Org): " message)
13634 (unless (bolp)
13635 (newline)))
13636 (display-buffer buf)
13637 (sit-for 0))))
13639 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13640 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13641 (if (and marker (marker-buffer marker)
13642 (buffer-live-p (marker-buffer marker)))
13643 (progn
13644 (switch-to-buffer (marker-buffer marker))
13645 (if (or (> marker (point-max)) (< marker (point-min)))
13646 (widen))
13647 (goto-char marker))
13648 (if bookmark
13649 (bookmark-jump bookmark)
13650 (error "Cannot find location"))))
13652 (defun org-quote-csv-field (s)
13653 "Quote field for inclusion in CSV material."
13654 (if (string-match "[\",]" s)
13655 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13658 (defun org-plist-delete (plist property)
13659 "Delete PROPERTY from PLIST.
13660 This is in contrast to merely setting it to 0."
13661 (let (p)
13662 (while plist
13663 (if (not (eq property (car plist)))
13664 (setq p (plist-put p (car plist) (nth 1 plist))))
13665 (setq plist (cddr plist)))
13668 (defun org-force-self-insert (N)
13669 "Needed to enforce self-insert under remapping."
13670 (interactive "p")
13671 (self-insert-command N))
13673 (defun org-string-width (s)
13674 "Compute width of string, ignoring invisible characters.
13675 This ignores character with invisibility property `org-link', and also
13676 characters with property `org-cwidth', because these will become invisible
13677 upon the next fontification round."
13678 (let (b l)
13679 (when (or (eq t buffer-invisibility-spec)
13680 (assq 'org-link buffer-invisibility-spec))
13681 (while (setq b (text-property-any 0 (length s)
13682 'invisible 'org-link s))
13683 (setq s (concat (substring s 0 b)
13684 (substring s (or (next-single-property-change
13685 b 'invisible s) (length s)))))))
13686 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13687 (setq s (concat (substring s 0 b)
13688 (substring s (or (next-single-property-change
13689 b 'org-cwidth s) (length s))))))
13690 (setq l (string-width s) b -1)
13691 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13692 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13695 (defun org-base-buffer (buffer)
13696 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13697 (if (not buffer)
13698 buffer
13699 (or (buffer-base-buffer buffer)
13700 buffer)))
13702 (defun org-trim (s)
13703 "Remove whitespace at beginning and end of string."
13704 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13705 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13708 (defun org-wrap (string &optional width lines)
13709 "Wrap string to either a number of lines, or a width in characters.
13710 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13711 that costs. If there is a word longer than WIDTH, the text is actually
13712 wrapped to the length of that word.
13713 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13714 many lines, whatever width that takes.
13715 The return value is a list of lines, without newlines at the end."
13716 (let* ((words (org-split-string string "[ \t\n]+"))
13717 (maxword (apply 'max (mapcar 'org-string-width words)))
13718 w ll)
13719 (cond (width
13720 (org-do-wrap words (max maxword width)))
13721 (lines
13722 (setq w maxword)
13723 (setq ll (org-do-wrap words maxword))
13724 (if (<= (length ll) lines)
13726 (setq ll words)
13727 (while (> (length ll) lines)
13728 (setq w (1+ w))
13729 (setq ll (org-do-wrap words w)))
13730 ll))
13731 (t (error "Cannot wrap this")))))
13733 (defun org-do-wrap (words width)
13734 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13735 (let (lines line)
13736 (while words
13737 (setq line (pop words))
13738 (while (and words (< (+ (length line) (length (car words))) width))
13739 (setq line (concat line " " (pop words))))
13740 (setq lines (push line lines)))
13741 (nreverse lines)))
13743 (defun org-split-string (string &optional separators)
13744 "Splits STRING into substrings at SEPARATORS.
13745 No empty strings are returned if there are matches at the beginning
13746 and end of string."
13747 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13748 (start 0)
13749 notfirst
13750 (list nil))
13751 (while (and (string-match rexp string
13752 (if (and notfirst
13753 (= start (match-beginning 0))
13754 (< start (length string)))
13755 (1+ start) start))
13756 (< (match-beginning 0) (length string)))
13757 (setq notfirst t)
13758 (or (eq (match-beginning 0) 0)
13759 (and (eq (match-beginning 0) (match-end 0))
13760 (eq (match-beginning 0) start))
13761 (setq list
13762 (cons (substring string start (match-beginning 0))
13763 list)))
13764 (setq start (match-end 0)))
13765 (or (eq start (length string))
13766 (setq list
13767 (cons (substring string start)
13768 list)))
13769 (nreverse list)))
13771 (defun org-context ()
13772 "Return a list of contexts of the current cursor position.
13773 If several contexts apply, all are returned.
13774 Each context entry is a list with a symbol naming the context, and
13775 two positions indicating start and end of the context. Possible
13776 contexts are:
13778 :headline anywhere in a headline
13779 :headline-stars on the leading stars in a headline
13780 :todo-keyword on a TODO keyword (including DONE) in a headline
13781 :tags on the TAGS in a headline
13782 :priority on the priority cookie in a headline
13783 :item on the first line of a plain list item
13784 :item-bullet on the bullet/number of a plain list item
13785 :checkbox on the checkbox in a plain list item
13786 :table in an org-mode table
13787 :table-special on a special filed in a table
13788 :table-table in a table.el table
13789 :link on a hyperlink
13790 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13791 :target on a <<target>>
13792 :radio-target on a <<<radio-target>>>
13793 :latex-fragment on a LaTeX fragment
13794 :latex-preview on a LaTeX fragment with overlayed preview image
13796 This function expects the position to be visible because it uses font-lock
13797 faces as a help to recognize the following contexts: :table-special, :link,
13798 and :keyword."
13799 (let* ((f (get-text-property (point) 'face))
13800 (faces (if (listp f) f (list f)))
13801 (p (point)) clist o)
13802 ;; First the large context
13803 (cond
13804 ((org-on-heading-p t)
13805 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13806 (when (progn
13807 (beginning-of-line 1)
13808 (looking-at org-todo-line-tags-regexp))
13809 (push (org-point-in-group p 1 :headline-stars) clist)
13810 (push (org-point-in-group p 2 :todo-keyword) clist)
13811 (push (org-point-in-group p 4 :tags) clist))
13812 (goto-char p)
13813 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13814 (if (looking-at "\\[#[A-Z0-9]\\]")
13815 (push (org-point-in-group p 0 :priority) clist)))
13817 ((org-at-item-p)
13818 (push (org-point-in-group p 2 :item-bullet) clist)
13819 (push (list :item (point-at-bol)
13820 (save-excursion (org-end-of-item) (point)))
13821 clist)
13822 (and (org-at-item-checkbox-p)
13823 (push (org-point-in-group p 0 :checkbox) clist)))
13825 ((org-at-table-p)
13826 (push (list :table (org-table-begin) (org-table-end)) clist)
13827 (if (memq 'org-formula faces)
13828 (push (list :table-special
13829 (previous-single-property-change p 'face)
13830 (next-single-property-change p 'face)) clist)))
13831 ((org-at-table-p 'any)
13832 (push (list :table-table) clist)))
13833 (goto-char p)
13835 ;; Now the small context
13836 (cond
13837 ((org-at-timestamp-p)
13838 (push (org-point-in-group p 0 :timestamp) clist))
13839 ((memq 'org-link faces)
13840 (push (list :link
13841 (previous-single-property-change p 'face)
13842 (next-single-property-change p 'face)) clist))
13843 ((memq 'org-special-keyword faces)
13844 (push (list :keyword
13845 (previous-single-property-change p 'face)
13846 (next-single-property-change p 'face)) clist))
13847 ((org-on-target-p)
13848 (push (org-point-in-group p 0 :target) clist)
13849 (goto-char (1- (match-beginning 0)))
13850 (if (looking-at org-radio-target-regexp)
13851 (push (org-point-in-group p 0 :radio-target) clist))
13852 (goto-char p))
13853 ((setq o (car (delq nil
13854 (mapcar
13855 (lambda (x)
13856 (if (memq x org-latex-fragment-image-overlays) x))
13857 (org-overlays-at (point))))))
13858 (push (list :latex-fragment
13859 (org-overlay-start o) (org-overlay-end o)) clist)
13860 (push (list :latex-preview
13861 (org-overlay-start o) (org-overlay-end o)) clist))
13862 ((org-inside-LaTeX-fragment-p)
13863 ;; FIXME: positions wrong.
13864 (push (list :latex-fragment (point) (point)) clist)))
13866 (setq clist (nreverse (delq nil clist)))
13867 clist))
13869 ;; FIXME: Compare with at-regexp-p Do we need both?
13870 (defun org-in-regexp (re &optional nlines visually)
13871 "Check if point is inside a match of regexp.
13872 Normally only the current line is checked, but you can include NLINES extra
13873 lines both before and after point into the search.
13874 If VISUALLY is set, require that the cursor is not after the match but
13875 really on, so that the block visually is on the match."
13876 (catch 'exit
13877 (let ((pos (point))
13878 (eol (point-at-eol (+ 1 (or nlines 0))))
13879 (inc (if visually 1 0)))
13880 (save-excursion
13881 (beginning-of-line (- 1 (or nlines 0)))
13882 (while (re-search-forward re eol t)
13883 (if (and (<= (match-beginning 0) pos)
13884 (>= (+ inc (match-end 0)) pos))
13885 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13887 (defun org-at-regexp-p (regexp)
13888 "Is point inside a match of REGEXP in the current line?"
13889 (catch 'exit
13890 (save-excursion
13891 (let ((pos (point)) (end (point-at-eol)))
13892 (beginning-of-line 1)
13893 (while (re-search-forward regexp end t)
13894 (if (and (<= (match-beginning 0) pos)
13895 (>= (match-end 0) pos))
13896 (throw 'exit t)))
13897 nil))))
13899 (defun org-occur-in-agenda-files (regexp &optional nlines)
13900 "Call `multi-occur' with buffers for all agenda files."
13901 (interactive "sOrg-files matching: \np")
13902 (let* ((files (org-agenda-files))
13903 (tnames (mapcar 'file-truename files))
13904 (extra org-agenda-text-search-extra-files)
13906 (when (eq (car extra) 'agenda-archives)
13907 (setq extra (cdr extra))
13908 (setq files (org-add-archive-files files)))
13909 (while (setq f (pop extra))
13910 (unless (member (file-truename f) tnames)
13911 (add-to-list 'files f 'append)
13912 (add-to-list 'tnames (file-truename f) 'append)))
13913 (multi-occur
13914 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13915 regexp)))
13917 (if (boundp 'occur-mode-find-occurrence-hook)
13918 ;; Emacs 23
13919 (add-hook 'occur-mode-find-occurrence-hook
13920 (lambda ()
13921 (when (org-mode-p)
13922 (org-reveal))))
13923 ;; Emacs 22
13924 (defadvice occur-mode-goto-occurrence
13925 (after org-occur-reveal activate)
13926 (and (org-mode-p) (org-reveal)))
13927 (defadvice occur-mode-goto-occurrence-other-window
13928 (after org-occur-reveal activate)
13929 (and (org-mode-p) (org-reveal)))
13930 (defadvice occur-mode-display-occurrence
13931 (after org-occur-reveal activate)
13932 (when (org-mode-p)
13933 (let ((pos (occur-mode-find-occurrence)))
13934 (with-current-buffer (marker-buffer pos)
13935 (save-excursion
13936 (goto-char pos)
13937 (org-reveal)))))))
13939 (defun org-uniquify (list)
13940 "Remove duplicate elements from LIST."
13941 (let (res)
13942 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13943 res))
13945 (defun org-delete-all (elts list)
13946 "Remove all elements in ELTS from LIST."
13947 (while elts
13948 (setq list (delete (pop elts) list)))
13949 list)
13951 (defun org-back-over-empty-lines ()
13952 "Move backwards over witespace, to the beginning of the first empty line.
13953 Returns the number of empty lines passed."
13954 (let ((pos (point)))
13955 (skip-chars-backward " \t\n\r")
13956 (beginning-of-line 2)
13957 (goto-char (min (point) pos))
13958 (count-lines (point) pos)))
13960 (defun org-skip-whitespace ()
13961 (skip-chars-forward " \t\n\r"))
13963 (defun org-point-in-group (point group &optional context)
13964 "Check if POINT is in match-group GROUP.
13965 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13966 match. If the match group does ot exist or point is not inside it,
13967 return nil."
13968 (and (match-beginning group)
13969 (>= point (match-beginning group))
13970 (<= point (match-end group))
13971 (if context
13972 (list context (match-beginning group) (match-end group))
13973 t)))
13975 (defun org-switch-to-buffer-other-window (&rest args)
13976 "Switch to buffer in a second window on the current frame.
13977 In particular, do not allow pop-up frames."
13978 (let (pop-up-frames special-display-buffer-names special-display-regexps
13979 special-display-function)
13980 (apply 'switch-to-buffer-other-window args)))
13982 (defun org-combine-plists (&rest plists)
13983 "Create a single property list from all plists in PLISTS.
13984 The process starts by copying the first list, and then setting properties
13985 from the other lists. Settings in the last list are the most significant
13986 ones and overrule settings in the other lists."
13987 (let ((rtn (copy-sequence (pop plists)))
13988 p v ls)
13989 (while plists
13990 (setq ls (pop plists))
13991 (while ls
13992 (setq p (pop ls) v (pop ls))
13993 (setq rtn (plist-put rtn p v))))
13994 rtn))
13996 (defun org-move-line-down (arg)
13997 "Move the current line down. With prefix argument, move it past ARG lines."
13998 (interactive "p")
13999 (let ((col (current-column))
14000 beg end pos)
14001 (beginning-of-line 1) (setq beg (point))
14002 (beginning-of-line 2) (setq end (point))
14003 (beginning-of-line (+ 1 arg))
14004 (setq pos (move-marker (make-marker) (point)))
14005 (insert (delete-and-extract-region beg end))
14006 (goto-char pos)
14007 (org-move-to-column col)))
14009 (defun org-move-line-up (arg)
14010 "Move the current line up. With prefix argument, move it past ARG lines."
14011 (interactive "p")
14012 (let ((col (current-column))
14013 beg end pos)
14014 (beginning-of-line 1) (setq beg (point))
14015 (beginning-of-line 2) (setq end (point))
14016 (beginning-of-line (- arg))
14017 (setq pos (move-marker (make-marker) (point)))
14018 (insert (delete-and-extract-region beg end))
14019 (goto-char pos)
14020 (org-move-to-column col)))
14022 (defun org-replace-escapes (string table)
14023 "Replace %-escapes in STRING with values in TABLE.
14024 TABLE is an association list with keys like \"%a\" and string values.
14025 The sequences in STRING may contain normal field width and padding information,
14026 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14027 so values can contain further %-escapes if they are define later in TABLE."
14028 (let ((case-fold-search nil)
14029 e re rpl)
14030 (while (setq e (pop table))
14031 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14032 (while (string-match re string)
14033 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14034 (cdr e)))
14035 (setq string (replace-match rpl t t string))))
14036 string))
14039 (defun org-sublist (list start end)
14040 "Return a section of LIST, from START to END.
14041 Counting starts at 1."
14042 (let (rtn (c start))
14043 (setq list (nthcdr (1- start) list))
14044 (while (and list (<= c end))
14045 (push (pop list) rtn)
14046 (setq c (1+ c)))
14047 (nreverse rtn)))
14049 (defun org-find-base-buffer-visiting (file)
14050 "Like `find-buffer-visiting' but alway return the base buffer and
14051 not an indirect buffer."
14052 (let ((buf (find-buffer-visiting file)))
14053 (if buf
14054 (or (buffer-base-buffer buf) buf)
14055 nil)))
14057 (defun org-image-file-name-regexp ()
14058 "Return regexp matching the file names of images."
14059 (if (fboundp 'image-file-name-regexp)
14060 (image-file-name-regexp)
14061 (let ((image-file-name-extensions
14062 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14063 "xbm" "xpm" "pbm" "pgm" "ppm")))
14064 (concat "\\."
14065 (regexp-opt (nconc (mapcar 'upcase
14066 image-file-name-extensions)
14067 image-file-name-extensions)
14069 "\\'"))))
14071 (defun org-file-image-p (file)
14072 "Return non-nil if FILE is an image."
14073 (save-match-data
14074 (string-match (org-image-file-name-regexp) file)))
14076 (defun org-get-cursor-date ()
14077 "Return the date at cursor in as a time.
14078 This works in the calendar and in the agenda, anywhere else it just
14079 returns the current time."
14080 (let (date day defd)
14081 (cond
14082 ((eq major-mode 'calendar-mode)
14083 (setq date (calendar-cursor-to-date)
14084 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14085 ((eq major-mode 'org-agenda-mode)
14086 (setq day (get-text-property (point) 'day))
14087 (if day
14088 (setq date (calendar-gregorian-from-absolute day)
14089 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14090 (nth 2 date))))))
14091 (or defd (current-time))))
14093 (defvar org-agenda-action-marker (make-marker)
14094 "Marker pointing to the entry for the next agenda action.")
14096 (defun org-mark-entry-for-agenda-action ()
14097 "Mark the current entry as target of an agenda action.
14098 Agenda actions are actions executed from the agenda with the key `k',
14099 which make use of the date at the cursor."
14100 (interactive)
14101 (move-marker org-agenda-action-marker
14102 (save-excursion (org-back-to-heading t) (point))
14103 (current-buffer))
14104 (message
14105 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14107 ;;; Paragraph filling stuff.
14108 ;; We want this to be just right, so use the full arsenal.
14110 (defun org-indent-line-function ()
14111 "Indent line like previous, but further if previous was headline or item."
14112 (interactive)
14113 (let* ((pos (point))
14114 (itemp (org-at-item-p))
14115 column bpos bcol tpos tcol bullet btype bullet-type)
14116 ;; Find the previous relevant line
14117 (beginning-of-line 1)
14118 (cond
14119 ((looking-at "#") (setq column 0))
14120 ((looking-at "\\*+ ") (setq column 0))
14122 (beginning-of-line 0)
14123 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14124 (beginning-of-line 0))
14125 (cond
14126 ((looking-at "\\*+[ \t]+")
14127 (if (not org-adapt-indentation)
14128 (setq column 0)
14129 (goto-char (match-end 0))
14130 (setq column (current-column))))
14131 ((org-in-item-p)
14132 (org-beginning-of-item)
14133 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14134 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14135 (setq bpos (match-beginning 1) tpos (match-end 0)
14136 bcol (progn (goto-char bpos) (current-column))
14137 tcol (progn (goto-char tpos) (current-column))
14138 bullet (match-string 1)
14139 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14140 (if (> tcol (+ bcol org-description-max-indent))
14141 (setq tcol (+ bcol 5)))
14142 (if (not itemp)
14143 (setq column tcol)
14144 (goto-char pos)
14145 (beginning-of-line 1)
14146 (if (looking-at "\\S-")
14147 (progn
14148 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14149 (setq bullet (match-string 1)
14150 btype (if (string-match "[0-9]" bullet) "n" bullet))
14151 (setq column (if (equal btype bullet-type) bcol tcol)))
14152 (setq column (org-get-indentation)))))
14153 (t (setq column (org-get-indentation))))))
14154 (goto-char pos)
14155 (if (<= (current-column) (current-indentation))
14156 (org-indent-line-to column)
14157 (save-excursion (org-indent-line-to column)))
14158 (setq column (current-column))
14159 (beginning-of-line 1)
14160 (if (looking-at
14161 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14162 (replace-match (concat "\\1" (format org-property-format
14163 (match-string 2) (match-string 3)))
14164 t nil))
14165 (org-move-to-column column)))
14167 (defun org-set-autofill-regexps ()
14168 (interactive)
14169 ;; In the paragraph separator we include headlines, because filling
14170 ;; text in a line directly attached to a headline would otherwise
14171 ;; fill the headline as well.
14172 (org-set-local 'comment-start-skip "^#+[ \t]*")
14173 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14174 ;; The paragraph starter includes hand-formatted lists.
14175 (org-set-local 'paragraph-start
14176 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14177 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14178 ;; But only if the user has not turned off tables or fixed-width regions
14179 (org-set-local
14180 'auto-fill-inhibit-regexp
14181 (concat "\\*+ \\|#\\+"
14182 "\\|[ \t]*" org-keyword-time-regexp
14183 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14184 (concat
14185 "\\|[ \t]*["
14186 (if org-enable-table-editor "|" "")
14187 (if org-enable-fixed-width-editor ":" "")
14188 "]"))))
14189 ;; We use our own fill-paragraph function, to make sure that tables
14190 ;; and fixed-width regions are not wrapped. That function will pass
14191 ;; through to `fill-paragraph' when appropriate.
14192 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14193 ; Adaptive filling: To get full control, first make sure that
14194 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14195 (org-set-local 'adaptive-fill-regexp "\000")
14196 (org-set-local 'adaptive-fill-function
14197 'org-adaptive-fill-function)
14198 (org-set-local
14199 'align-mode-rules-list
14200 '((org-in-buffer-settings
14201 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14202 (modes . '(org-mode))))))
14204 (defun org-fill-paragraph (&optional justify)
14205 "Re-align a table, pass through to fill-paragraph if no table."
14206 (let ((table-p (org-at-table-p))
14207 (table.el-p (org-at-table.el-p)))
14208 (cond ((and (equal (char-after (point-at-bol)) ?*)
14209 (save-excursion (goto-char (point-at-bol))
14210 (looking-at outline-regexp)))
14211 t) ; skip headlines
14212 (table.el-p t) ; skip table.el tables
14213 (table-p (org-table-align) t) ; align org-mode tables
14214 (t nil)))) ; call paragraph-fill
14216 ;; For reference, this is the default value of adaptive-fill-regexp
14217 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14219 (defun org-adaptive-fill-function ()
14220 "Return a fill prefix for org-mode files.
14221 In particular, this makes sure hanging paragraphs for hand-formatted lists
14222 work correctly."
14223 (cond ((looking-at "#[ \t]+")
14224 (match-string 0))
14225 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14226 (save-excursion
14227 (if (> (match-end 1) (+ (match-beginning 1)
14228 org-description-max-indent))
14229 (goto-char (+ (match-beginning 1) 5))
14230 (goto-char (match-end 0)))
14231 (make-string (current-column) ?\ )))
14232 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14233 (save-excursion
14234 (goto-char (match-end 0))
14235 (make-string (current-column) ?\ )))
14236 (t nil)))
14238 ;;; Other stuff.
14240 (defun org-toggle-fixed-width-section (arg)
14241 "Toggle the fixed-width export.
14242 If there is no active region, the QUOTE keyword at the current headline is
14243 inserted or removed. When present, it causes the text between this headline
14244 and the next to be exported as fixed-width text, and unmodified.
14245 If there is an active region, this command adds or removes a colon as the
14246 first character of this line. If the first character of a line is a colon,
14247 this line is also exported in fixed-width font."
14248 (interactive "P")
14249 (let* ((cc 0)
14250 (regionp (org-region-active-p))
14251 (beg (if regionp (region-beginning) (point)))
14252 (end (if regionp (region-end)))
14253 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14254 (case-fold-search nil)
14255 (re "[ \t]*\\(:\\)")
14256 off)
14257 (if regionp
14258 (save-excursion
14259 (goto-char beg)
14260 (setq cc (current-column))
14261 (beginning-of-line 1)
14262 (setq off (looking-at re))
14263 (while (> nlines 0)
14264 (setq nlines (1- nlines))
14265 (beginning-of-line 1)
14266 (cond
14267 (arg
14268 (org-move-to-column cc t)
14269 (insert ":\n")
14270 (forward-line -1))
14271 ((and off (looking-at re))
14272 (replace-match "" t t nil 1))
14273 ((not off) (org-move-to-column cc t) (insert ":")))
14274 (forward-line 1)))
14275 (save-excursion
14276 (org-back-to-heading)
14277 (if (looking-at (concat outline-regexp
14278 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14279 (replace-match "" t t nil 1)
14280 (if (looking-at outline-regexp)
14281 (progn
14282 (goto-char (match-end 0))
14283 (insert org-quote-string " "))))))))
14285 ;;;; Functions extending outline functionality
14287 (defun org-beginning-of-line (&optional arg)
14288 "Go to the beginning of the current line. If that is invisible, continue
14289 to a visible line beginning. This makes the function of C-a more intuitive.
14290 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14291 first attempt, and only move to after the tags when the cursor is already
14292 beyond the end of the headline."
14293 (interactive "P")
14294 (let ((pos (point)) refpos)
14295 (beginning-of-line 1)
14296 (if (bobp)
14298 (backward-char 1)
14299 (if (org-invisible-p)
14300 (while (and (not (bobp)) (org-invisible-p))
14301 (backward-char 1)
14302 (beginning-of-line 1))
14303 (forward-char 1)))
14304 (when org-special-ctrl-a/e
14305 (cond
14306 ((and (looking-at org-complex-heading-regexp)
14307 (= (char-after (match-end 1)) ?\ ))
14308 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14309 (point-at-eol)))
14310 (goto-char
14311 (if (eq org-special-ctrl-a/e t)
14312 (cond ((> pos refpos) refpos)
14313 ((= pos (point)) refpos)
14314 (t (point)))
14315 (cond ((> pos (point)) (point))
14316 ((not (eq last-command this-command)) (point))
14317 (t refpos)))))
14318 ((org-at-item-p)
14319 (goto-char
14320 (if (eq org-special-ctrl-a/e t)
14321 (cond ((> pos (match-end 4)) (match-end 4))
14322 ((= pos (point)) (match-end 4))
14323 (t (point)))
14324 (cond ((> pos (point)) (point))
14325 ((not (eq last-command this-command)) (point))
14326 (t (match-end 4))))))))
14327 (org-no-warnings
14328 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14330 (defun org-end-of-line (&optional arg)
14331 "Go to the end of the line.
14332 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14333 first attempt, and only move to after the tags when the cursor is already
14334 beyond the end of the headline."
14335 (interactive "P")
14336 (if (or (not org-special-ctrl-a/e)
14337 (not (org-on-heading-p)))
14338 (end-of-line arg)
14339 (let ((pos (point)))
14340 (beginning-of-line 1)
14341 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14342 (if (eq org-special-ctrl-a/e t)
14343 (if (or (< pos (match-beginning 1))
14344 (= pos (match-end 0)))
14345 (goto-char (match-beginning 1))
14346 (goto-char (match-end 0)))
14347 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14348 (goto-char (match-end 0))
14349 (goto-char (match-beginning 1))))
14350 (end-of-line arg))))
14351 (org-no-warnings
14352 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14355 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14356 (define-key org-mode-map "\C-e" 'org-end-of-line)
14358 (defun org-kill-line (&optional arg)
14359 "Kill line, to tags or end of line."
14360 (interactive "P")
14361 (cond
14362 ((or (not org-special-ctrl-k)
14363 (bolp)
14364 (not (org-on-heading-p)))
14365 (call-interactively 'kill-line))
14366 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14367 (kill-region (point) (match-beginning 1))
14368 (org-set-tags nil t))
14369 (t (kill-region (point) (point-at-eol)))))
14371 (define-key org-mode-map "\C-k" 'org-kill-line)
14373 (defun org-yank (&optional arg)
14374 (interactive "*P")
14375 (let ((fold (get-text-property 0 :org-folded-kill
14376 (current-kill (cond ((listp arg) 0)
14377 ((eq arg '-) -2)
14378 (t (1- arg))))))
14379 (fold t)
14380 (yank-excluded-properties
14381 (cons :org-folded-kill yank-excluded-properties))
14382 (pos (point)) p1)
14383 (call-interactively 'yank)
14384 (setq p1 (point))
14385 (goto-char pos)
14386 (when (and (bolp) (looking-at outline-regexp) fold)
14387 (save-restriction
14388 (narrow-to-region pos p1)
14389 (hide-subtree)
14390 (org-cycle-show-empty-lines 'folded))
14391 (goto-char p1))))
14393 (defun org-invisible-p ()
14394 "Check if point is at a character currently not visible."
14395 ;; Early versions of noutline don't have `outline-invisible-p'.
14396 (if (fboundp 'outline-invisible-p)
14397 (outline-invisible-p)
14398 (get-char-property (point) 'invisible)))
14400 (defun org-invisible-p2 ()
14401 "Check if point is at a character currently not visible."
14402 (save-excursion
14403 (if (and (eolp) (not (bobp))) (backward-char 1))
14404 ;; Early versions of noutline don't have `outline-invisible-p'.
14405 (if (fboundp 'outline-invisible-p)
14406 (outline-invisible-p)
14407 (get-char-property (point) 'invisible))))
14409 (defalias 'org-back-to-heading 'outline-back-to-heading)
14410 (defalias 'org-on-heading-p 'outline-on-heading-p)
14411 (defalias 'org-at-heading-p 'outline-on-heading-p)
14412 (defun org-at-heading-or-item-p ()
14413 (or (org-on-heading-p) (org-at-item-p)))
14415 (defun org-on-target-p ()
14416 (or (org-in-regexp org-radio-target-regexp)
14417 (org-in-regexp org-target-regexp)))
14419 (defun org-up-heading-all (arg)
14420 "Move to the heading line of which the present line is a subheading.
14421 This function considers both visible and invisible heading lines.
14422 With argument, move up ARG levels."
14423 (if (fboundp 'outline-up-heading-all)
14424 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14425 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14427 (defun org-up-heading-safe ()
14428 "Move to the heading line of which the present line is a subheading.
14429 This version will not throw an error. It will return the level of the
14430 headline found, or nil if no higher level is found."
14431 (let ((pos (point)) start-level level
14432 (re (concat "^" outline-regexp)))
14433 (catch 'exit
14434 (outline-back-to-heading t)
14435 (setq start-level (funcall outline-level))
14436 (if (equal start-level 1) (throw 'exit nil))
14437 (while (re-search-backward re nil t)
14438 (setq level (funcall outline-level))
14439 (if (< level start-level) (throw 'exit level)))
14440 nil)))
14442 (defun org-first-sibling-p ()
14443 "Is this heading the first child of its parents?"
14444 (interactive)
14445 (let ((re (concat "^" outline-regexp))
14446 level l)
14447 (unless (org-at-heading-p t)
14448 (error "Not at a heading"))
14449 (setq level (funcall outline-level))
14450 (save-excursion
14451 (if (not (re-search-backward re nil t))
14453 (setq l (funcall outline-level))
14454 (< l level)))))
14456 (defun org-goto-sibling (&optional previous)
14457 "Goto the next sibling, even if it is invisible.
14458 When PREVIOUS is set, go to the previous sibling instead. Returns t
14459 when a sibling was found. When none is found, return nil and don't
14460 move point."
14461 (let ((fun (if previous 're-search-backward 're-search-forward))
14462 (pos (point))
14463 (re (concat "^" outline-regexp))
14464 level l)
14465 (when (condition-case nil (org-back-to-heading t) (error nil))
14466 (setq level (funcall outline-level))
14467 (catch 'exit
14468 (or previous (forward-char 1))
14469 (while (funcall fun re nil t)
14470 (setq l (funcall outline-level))
14471 (when (< l level) (goto-char pos) (throw 'exit nil))
14472 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14473 (goto-char pos)
14474 nil))))
14476 (defun org-show-siblings ()
14477 "Show all siblings of the current headline."
14478 (save-excursion
14479 (while (org-goto-sibling) (org-flag-heading nil)))
14480 (save-excursion
14481 (while (org-goto-sibling 'previous)
14482 (org-flag-heading nil))))
14484 (defun org-show-hidden-entry ()
14485 "Show an entry where even the heading is hidden."
14486 (save-excursion
14487 (org-show-entry)))
14489 (defun org-flag-heading (flag &optional entry)
14490 "Flag the current heading. FLAG non-nil means make invisible.
14491 When ENTRY is non-nil, show the entire entry."
14492 (save-excursion
14493 (org-back-to-heading t)
14494 ;; Check if we should show the entire entry
14495 (if entry
14496 (progn
14497 (org-show-entry)
14498 (save-excursion
14499 (and (outline-next-heading)
14500 (org-flag-heading nil))))
14501 (outline-flag-region (max (point-min) (1- (point)))
14502 (save-excursion (outline-end-of-heading) (point))
14503 flag))))
14505 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14506 ;; This is an exact copy of the original function, but it uses
14507 ;; `org-back-to-heading', to make it work also in invisible
14508 ;; trees. And is uses an invisible-OK argument.
14509 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14510 (org-back-to-heading invisible-OK)
14511 (let ((first t)
14512 (level (funcall outline-level)))
14513 (while (and (not (eobp))
14514 (or first (> (funcall outline-level) level)))
14515 (setq first nil)
14516 (outline-next-heading))
14517 (unless to-heading
14518 (if (memq (preceding-char) '(?\n ?\^M))
14519 (progn
14520 ;; Go to end of line before heading
14521 (forward-char -1)
14522 (if (memq (preceding-char) '(?\n ?\^M))
14523 ;; leave blank line before heading
14524 (forward-char -1))))))
14525 (point))
14527 (defun org-show-subtree ()
14528 "Show everything after this heading at deeper levels."
14529 (outline-flag-region
14530 (point)
14531 (save-excursion
14532 (outline-end-of-subtree) (outline-next-heading) (point))
14533 nil))
14535 (defun org-show-entry ()
14536 "Show the body directly following this heading.
14537 Show the heading too, if it is currently invisible."
14538 (interactive)
14539 (save-excursion
14540 (condition-case nil
14541 (progn
14542 (org-back-to-heading t)
14543 (outline-flag-region
14544 (max (point-min) (1- (point)))
14545 (save-excursion
14546 (re-search-forward
14547 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14548 (or (match-beginning 1) (point-max)))
14549 nil))
14550 (error nil))))
14552 (defun org-make-options-regexp (kwds)
14553 "Make a regular expression for keyword lines."
14554 (concat
14556 "#?[ \t]*\\+\\("
14557 (mapconcat 'regexp-quote kwds "\\|")
14558 "\\):[ \t]*"
14559 "\\(.+\\)"))
14561 ;; Make isearch reveal the necessary context
14562 (defun org-isearch-end ()
14563 "Reveal context after isearch exits."
14564 (when isearch-success ; only if search was successful
14565 (if (featurep 'xemacs)
14566 ;; Under XEmacs, the hook is run in the correct place,
14567 ;; we directly show the context.
14568 (org-show-context 'isearch)
14569 ;; In Emacs the hook runs *before* restoring the overlays.
14570 ;; So we have to use a one-time post-command-hook to do this.
14571 ;; (Emacs 22 has a special variable, see function `org-mode')
14572 (unless (and (boundp 'isearch-mode-end-hook-quit)
14573 isearch-mode-end-hook-quit)
14574 ;; Only when the isearch was not quitted.
14575 (org-add-hook 'post-command-hook 'org-isearch-post-command
14576 'append 'local)))))
14578 (defun org-isearch-post-command ()
14579 "Remove self from hook, and show context."
14580 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14581 (org-show-context 'isearch))
14584 ;;;; Integration with and fixes for other packages
14586 ;;; Imenu support
14588 (defvar org-imenu-markers nil
14589 "All markers currently used by Imenu.")
14590 (make-variable-buffer-local 'org-imenu-markers)
14592 (defun org-imenu-new-marker (&optional pos)
14593 "Return a new marker for use by Imenu, and remember the marker."
14594 (let ((m (make-marker)))
14595 (move-marker m (or pos (point)))
14596 (push m org-imenu-markers)
14599 (defun org-imenu-get-tree ()
14600 "Produce the index for Imenu."
14601 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14602 (setq org-imenu-markers nil)
14603 (let* ((n org-imenu-depth)
14604 (re (concat "^" outline-regexp))
14605 (subs (make-vector (1+ n) nil))
14606 (last-level 0)
14607 m tree level head)
14608 (save-excursion
14609 (save-restriction
14610 (widen)
14611 (goto-char (point-max))
14612 (while (re-search-backward re nil t)
14613 (setq level (org-reduced-level (funcall outline-level)))
14614 (when (<= level n)
14615 (looking-at org-complex-heading-regexp)
14616 (setq head (org-match-string-no-properties 4)
14617 m (org-imenu-new-marker))
14618 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14619 (if (>= level last-level)
14620 (push (cons head m) (aref subs level))
14621 (push (cons head (aref subs (1+ level))) (aref subs level))
14622 (loop for i from (1+ level) to n do (aset subs i nil)))
14623 (setq last-level level)))))
14624 (aref subs 1)))
14626 (eval-after-load "imenu"
14627 '(progn
14628 (add-hook 'imenu-after-jump-hook
14629 (lambda ()
14630 (if (eq major-mode 'org-mode)
14631 (org-show-context 'org-goto))))))
14633 ;; Speedbar support
14635 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14636 "Overlay marking the agenda restriction line in speedbar.")
14637 (org-overlay-put org-speedbar-restriction-lock-overlay
14638 'face 'org-agenda-restriction-lock)
14639 (org-overlay-put org-speedbar-restriction-lock-overlay
14640 'help-echo "Agendas are currently limited to this item.")
14641 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14643 (defun org-speedbar-set-agenda-restriction ()
14644 "Restrict future agenda commands to the location at point in speedbar.
14645 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14646 (interactive)
14647 (require 'org-agenda)
14648 (let (p m tp np dir txt w)
14649 (cond
14650 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14651 'org-imenu t))
14652 (setq m (get-text-property p 'org-imenu-marker))
14653 (save-excursion
14654 (save-restriction
14655 (set-buffer (marker-buffer m))
14656 (goto-char m)
14657 (org-agenda-set-restriction-lock 'subtree))))
14658 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14659 'speedbar-function 'speedbar-find-file))
14660 (setq tp (previous-single-property-change
14661 (1+ p) 'speedbar-function)
14662 np (next-single-property-change
14663 tp 'speedbar-function)
14664 dir (speedbar-line-directory)
14665 txt (buffer-substring-no-properties (or tp (point-min))
14666 (or np (point-max))))
14667 (save-excursion
14668 (save-restriction
14669 (set-buffer (find-file-noselect
14670 (let ((default-directory dir))
14671 (expand-file-name txt))))
14672 (unless (org-mode-p)
14673 (error "Cannot restrict to non-Org-mode file"))
14674 (org-agenda-set-restriction-lock 'file))))
14675 (t (error "Don't know how to restrict Org-mode's agenda")))
14676 (org-move-overlay org-speedbar-restriction-lock-overlay
14677 (point-at-bol) (point-at-eol))
14678 (setq current-prefix-arg nil)
14679 (org-agenda-maybe-redo)))
14681 (eval-after-load "speedbar"
14682 '(progn
14683 (speedbar-add-supported-extension ".org")
14684 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14685 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14686 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14687 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14688 (add-hook 'speedbar-visiting-tag-hook
14689 (lambda () (org-show-context 'org-goto)))))
14692 ;;; Fixes and Hacks for problems with other packages
14694 ;; Make flyspell not check words in links, to not mess up our keymap
14695 (defun org-mode-flyspell-verify ()
14696 "Don't let flyspell put overlays at active buttons."
14697 (not (get-text-property (point) 'keymap)))
14699 ;; Make `bookmark-jump' show the jump location if it was hidden.
14700 (eval-after-load "bookmark"
14701 '(if (boundp 'bookmark-after-jump-hook)
14702 ;; We can use the hook
14703 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14704 ;; Hook not available, use advice
14705 (defadvice bookmark-jump (after org-make-visible activate)
14706 "Make the position visible."
14707 (org-bookmark-jump-unhide))))
14709 (defun org-bookmark-jump-unhide ()
14710 "Unhide the current position, to show the bookmark location."
14711 (and (org-mode-p)
14712 (or (org-invisible-p)
14713 (save-excursion (goto-char (max (point-min) (1- (point))))
14714 (org-invisible-p)))
14715 (org-show-context 'bookmark-jump)))
14717 ;; Make session.el ignore our circular variable
14718 (eval-after-load "session"
14719 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14721 ;;;; Experimental code
14723 (defun org-closed-in-range ()
14724 "Sparse tree of items closed in a certain time range.
14725 Still experimental, may disappear in the future."
14726 (interactive)
14727 ;; Get the time interval from the user.
14728 (let* ((time1 (time-to-seconds
14729 (org-read-date nil 'to-time nil "Starting date: ")))
14730 (time2 (time-to-seconds
14731 (org-read-date nil 'to-time nil "End date:")))
14732 ;; callback function
14733 (callback (lambda ()
14734 (let ((time
14735 (time-to-seconds
14736 (apply 'encode-time
14737 (org-parse-time-string
14738 (match-string 1))))))
14739 ;; check if time in interval
14740 (and (>= time time1) (<= time time2))))))
14741 ;; make tree, check each match with the callback
14742 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14745 ;;;; Finish up
14747 (provide 'org)
14749 (run-hooks 'org-load-hook)
14751 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14753 ;;; org.el ends here