Fix typo in documentation.
[org-mode.git] / lisp / org.el
blobd2e999911809d86f01104a402eeb386b929d218a
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-insert-heading-respect-content nil
663 "Non-nil means, insert new headings after the current subtree.
664 When nil, the new heading is created directly after the current line.
665 The commands \\[org-insert-heading-respect-content] and
666 \\[org-insert-todo-heading-respect-content] turn this variable on
667 for the duration of the command."
668 :group 'org-structure
669 :type 'boolean)
671 (defcustom org-blank-before-new-entry '((heading . nil)
672 (plain-list-item . nil))
673 "Should `org-insert-heading' leave a blank line before new heading/item?
674 The value is an alist, with `heading' and `plain-list-item' as car,
675 and a boolean flag as cdr."
676 :group 'org-edit-structure
677 :type '(list
678 (cons (const heading) (boolean))
679 (cons (const plain-list-item) (boolean))))
681 (defcustom org-insert-heading-hook nil
682 "Hook being run after inserting a new heading."
683 :group 'org-edit-structure
684 :type 'hook)
686 (defcustom org-enable-fixed-width-editor t
687 "Non-nil means, lines starting with \":\" are treated as fixed-width.
688 This currently only means, they are never auto-wrapped.
689 When nil, such lines will be treated like ordinary lines.
690 See also the QUOTE keyword."
691 :group 'org-edit-structure
692 :type 'boolean)
694 (defcustom org-edit-fixed-width-region-mode 'artist-mode
695 "The mode that should be used to edit fixed-width regions.
696 These are the regions where each line starts with a colon."
697 :group 'org-edit-structure
698 :type '(choice
699 (const artist-mode)
700 (const picture-mode)
701 (const fundamental-mode)
702 (function :tag "Other (specify)")))
704 (defcustom org-goto-auto-isearch t
705 "Non-nil means, typing characters in org-goto starts incremental search."
706 :group 'org-edit-structure
707 :type 'boolean)
709 (defgroup org-sparse-trees nil
710 "Options concerning sparse trees in Org-mode."
711 :tag "Org Sparse Trees"
712 :group 'org-structure)
714 (defcustom org-highlight-sparse-tree-matches t
715 "Non-nil means, highlight all matches that define a sparse tree.
716 The highlights will automatically disappear the next time the buffer is
717 changed by an edit command."
718 :group 'org-sparse-trees
719 :type 'boolean)
721 (defcustom org-remove-highlights-with-change t
722 "Non-nil means, any change to the buffer will remove temporary highlights.
723 Such highlights are created by `org-occur' and `org-clock-display'.
724 When nil, `C-c C-c needs to be used to get rid of the highlights.
725 The highlights created by `org-preview-latex-fragment' always need
726 `C-c C-c' to be removed."
727 :group 'org-sparse-trees
728 :group 'org-time
729 :type 'boolean)
732 (defcustom org-occur-hook '(org-first-headline-recenter)
733 "Hook that is run after `org-occur' has constructed a sparse tree.
734 This can be used to recenter the window to show as much of the structure
735 as possible."
736 :group 'org-sparse-trees
737 :type 'hook)
739 (defgroup org-plain-lists nil
740 "Options concerning plain lists in Org-mode."
741 :tag "Org Plain lists"
742 :group 'org-structure)
744 (defcustom org-cycle-include-plain-lists nil
745 "Non-nil means, include plain lists into visibility cycling.
746 This means that during cycling, plain list items will *temporarily* be
747 interpreted as outline headlines with a level given by 1000+i where i is the
748 indentation of the bullet. In all other operations, plain list items are
749 not seen as headlines. For example, you cannot assign a TODO keyword to
750 such an item."
751 :group 'org-plain-lists
752 :type 'boolean)
754 (defcustom org-plain-list-ordered-item-terminator t
755 "The character that makes a line with leading number an ordered list item.
756 Valid values are ?. and ?\). To get both terminators, use t. While
757 ?. may look nicer, it creates the danger that a line with leading
758 number may be incorrectly interpreted as an item. ?\) therefore is
759 the safe choice."
760 :group 'org-plain-lists
761 :type '(choice (const :tag "dot like in \"2.\"" ?.)
762 (const :tag "paren like in \"2)\"" ?\))
763 (const :tab "both" t)))
765 (defcustom org-empty-line-terminates-plain-lists nil
766 "Non-nil means, an empty line ends all plain list levels.
767 When nil, empty lines are part of the preceeding item."
768 :group 'org-plain-lists
769 :type 'boolean)
771 (defcustom org-auto-renumber-ordered-lists t
772 "Non-nil means, automatically renumber ordered plain lists.
773 Renumbering happens when the sequence have been changed with
774 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
775 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
776 :group 'org-plain-lists
777 :type 'boolean)
779 (defcustom org-provide-checkbox-statistics t
780 "Non-nil means, update checkbox statistics after insert and toggle.
781 When this is set, checkbox statistics is updated each time you either insert
782 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
783 with \\[org-ctrl-c-ctrl-c\\]."
784 :group 'org-plain-lists
785 :type 'boolean)
787 (defcustom org-description-max-indent 20
788 "Maximum indentation for the second line of a description list.
789 When the indentation would be larger than this, it will become
790 5 characters instead."
791 :group 'org-plain-lists
792 :type 'integer)
794 (defgroup org-imenu-and-speedbar nil
795 "Options concerning imenu and speedbar in Org-mode."
796 :tag "Org Imenu and Speedbar"
797 :group 'org-structure)
799 (defcustom org-imenu-depth 2
800 "The maximum level for Imenu access to Org-mode headlines.
801 This also applied for speedbar access."
802 :group 'org-imenu-and-speedbar
803 :type 'number)
805 (defgroup org-table nil
806 "Options concerning tables in Org-mode."
807 :tag "Org Table"
808 :group 'org)
810 (defcustom org-enable-table-editor 'optimized
811 "Non-nil means, lines starting with \"|\" are handled by the table editor.
812 When nil, such lines will be treated like ordinary lines.
814 When equal to the symbol `optimized', the table editor will be optimized to
815 do the following:
816 - Automatic overwrite mode in front of whitespace in table fields.
817 This makes the structure of the table stay in tact as long as the edited
818 field does not exceed the column width.
819 - Minimize the number of realigns. Normally, the table is aligned each time
820 TAB or RET are pressed to move to another field. With optimization this
821 happens only if changes to a field might have changed the column width.
822 Optimization requires replacing the functions `self-insert-command',
823 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
824 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
825 very good at guessing when a re-align will be necessary, but you can always
826 force one with \\[org-ctrl-c-ctrl-c].
828 If you would like to use the optimized version in Org-mode, but the
829 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
831 This variable can be used to turn on and off the table editor during a session,
832 but in order to toggle optimization, a restart is required.
834 See also the variable `org-table-auto-blank-field'."
835 :group 'org-table
836 :type '(choice
837 (const :tag "off" nil)
838 (const :tag "on" t)
839 (const :tag "on, optimized" optimized)))
841 (defcustom org-table-tab-recognizes-table.el t
842 "Non-nil means, TAB will automatically notice a table.el table.
843 When it sees such a table, it moves point into it and - if necessary -
844 calls `table-recognize-table'."
845 :group 'org-table-editing
846 :type 'boolean)
848 (defgroup org-link nil
849 "Options concerning links in Org-mode."
850 :tag "Org Link"
851 :group 'org)
853 (defvar org-link-abbrev-alist-local nil
854 "Buffer-local version of `org-link-abbrev-alist', which see.
855 The value of this is taken from the #+LINK lines.")
856 (make-variable-buffer-local 'org-link-abbrev-alist-local)
858 (defcustom org-link-abbrev-alist nil
859 "Alist of link abbreviations.
860 The car of each element is a string, to be replaced at the start of a link.
861 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
862 links in Org-mode buffers can have an optional tag after a double colon, e.g.
864 [[linkkey:tag][description]]
866 If REPLACE is a string, the tag will simply be appended to create the link.
867 If the string contains \"%s\", the tag will be inserted there.
869 REPLACE may also be a function that will be called with the tag as the
870 only argument to create the link, which should be returned as a string.
872 See the manual for examples."
873 :group 'org-link
874 :type 'alist)
876 (defcustom org-descriptive-links t
877 "Non-nil means, hide link part and only show description of bracket links.
878 Bracket links are like [[link][descritpion]]. This variable sets the initial
879 state in new org-mode buffers. The setting can then be toggled on a
880 per-buffer basis from the Org->Hyperlinks menu."
881 :group 'org-link
882 :type 'boolean)
884 (defcustom org-link-file-path-type 'adaptive
885 "How the path name in file links should be stored.
886 Valid values are:
888 relative Relative to the current directory, i.e. the directory of the file
889 into which the link is being inserted.
890 absolute Absolute path, if possible with ~ for home directory.
891 noabbrev Absolute path, no abbreviation of home directory.
892 adaptive Use relative path for files in the current directory and sub-
893 directories of it. For other files, use an absolute path."
894 :group 'org-link
895 :type '(choice
896 (const relative)
897 (const absolute)
898 (const noabbrev)
899 (const adaptive)))
901 (defcustom org-activate-links '(bracket angle plain radio tag date)
902 "Types of links that should be activated in Org-mode files.
903 This is a list of symbols, each leading to the activation of a certain link
904 type. In principle, it does not hurt to turn on most link types - there may
905 be a small gain when turning off unused link types. The types are:
907 bracket The recommended [[link][description]] or [[link]] links with hiding.
908 angular Links in angular brackes that may contain whitespace like
909 <bbdb:Carsten Dominik>.
910 plain Plain links in normal text, no whitespace, like http://google.com.
911 radio Text that is matched by a radio target, see manual for details.
912 tag Tag settings in a headline (link to tag search).
913 date Time stamps (link to calendar).
915 Changing this variable requires a restart of Emacs to become effective."
916 :group 'org-link
917 :type '(set (const :tag "Double bracket links (new style)" bracket)
918 (const :tag "Angular bracket links (old style)" angular)
919 (const :tag "Plain text links" plain)
920 (const :tag "Radio target matches" radio)
921 (const :tag "Tags" tag)
922 (const :tag "Timestamps" date)))
924 (defcustom org-make-link-description-function nil
925 "Function to use to generate link descriptions from links. If
926 nil the link location will be used. This function must take two
927 parameters; the first is the link and the second the description
928 org-insert-link has generated, and should return the description
929 to use."
930 :group 'org-link
931 :type 'function)
933 (defgroup org-link-store nil
934 "Options concerning storing links in Org-mode."
935 :tag "Org Store Link"
936 :group 'org-link)
938 (defcustom org-email-link-description-format "Email %c: %.30s"
939 "Format of the description part of a link to an email or usenet message.
940 The following %-excapes will be replaced by corresponding information:
942 %F full \"From\" field
943 %f name, taken from \"From\" field, address if no name
944 %T full \"To\" field
945 %t first name in \"To\" field, address if no name
946 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
947 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
948 %s subject
949 %m message-id.
951 You may use normal field width specification between the % and the letter.
952 This is for example useful to limit the length of the subject.
954 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
955 :group 'org-link-store
956 :type 'string)
958 (defcustom org-from-is-user-regexp
959 (let (r1 r2)
960 (when (and user-mail-address (not (string= user-mail-address "")))
961 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
962 (when (and user-full-name (not (string= user-full-name "")))
963 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
964 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
965 "Regexp mached against the \"From:\" header of an email or usenet message.
966 It should match if the message is from the user him/herself."
967 :group 'org-link-store
968 :type 'regexp)
970 (defcustom org-context-in-file-links t
971 "Non-nil means, file links from `org-store-link' contain context.
972 A search string will be added to the file name with :: as separator and
973 used to find the context when the link is activated by the command
974 `org-open-at-point'.
975 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
976 negates this setting for the duration of the command."
977 :group 'org-link-store
978 :type 'boolean)
980 (defcustom org-keep-stored-link-after-insertion nil
981 "Non-nil means, keep link in list for entire session.
983 The command `org-store-link' adds a link pointing to the current
984 location to an internal list. These links accumulate during a session.
985 The command `org-insert-link' can be used to insert links into any
986 Org-mode file (offering completion for all stored links). When this
987 option is nil, every link which has been inserted once using \\[org-insert-link]
988 will be removed from the list, to make completing the unused links
989 more efficient."
990 :group 'org-link-store
991 :type 'boolean)
993 (defgroup org-link-follow nil
994 "Options concerning following links in Org-mode."
995 :tag "Org Follow Link"
996 :group 'org-link)
998 (defcustom org-follow-link-hook nil
999 "Hook that is run after a link has been followed."
1000 :group 'org-link-follow
1001 :type 'hook)
1003 (defcustom org-tab-follows-link nil
1004 "Non-nil means, on links TAB will follow the link.
1005 Needs to be set before org.el is loaded."
1006 :group 'org-link-follow
1007 :type 'boolean)
1009 (defcustom org-return-follows-link nil
1010 "Non-nil means, on links RET will follow the link.
1011 Needs to be set before org.el is loaded."
1012 :group 'org-link-follow
1013 :type 'boolean)
1015 (defcustom org-mouse-1-follows-link
1016 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1017 "Non-nil means, mouse-1 on a link will follow the link.
1018 A longer mouse click will still set point. Does not work on XEmacs.
1019 Needs to be set before org.el is loaded."
1020 :group 'org-link-follow
1021 :type 'boolean)
1023 (defcustom org-mark-ring-length 4
1024 "Number of different positions to be recorded in the ring
1025 Changing this requires a restart of Emacs to work correctly."
1026 :group 'org-link-follow
1027 :type 'interger)
1029 (defcustom org-link-frame-setup
1030 '((vm . vm-visit-folder-other-frame)
1031 (gnus . gnus-other-frame)
1032 (file . find-file-other-window))
1033 "Setup the frame configuration for following links.
1034 When following a link with Emacs, it may often be useful to display
1035 this link in another window or frame. This variable can be used to
1036 set this up for the different types of links.
1037 For VM, use any of
1038 `vm-visit-folder'
1039 `vm-visit-folder-other-frame'
1040 For Gnus, use any of
1041 `gnus'
1042 `gnus-other-frame'
1043 For FILE, use any of
1044 `find-file'
1045 `find-file-other-window'
1046 `find-file-other-frame'
1047 For the calendar, use the variable `calendar-setup'.
1048 For BBDB, it is currently only possible to display the matches in
1049 another window."
1050 :group 'org-link-follow
1051 :type '(list
1052 (cons (const vm)
1053 (choice
1054 (const vm-visit-folder)
1055 (const vm-visit-folder-other-window)
1056 (const vm-visit-folder-other-frame)))
1057 (cons (const gnus)
1058 (choice
1059 (const gnus)
1060 (const gnus-other-frame)))
1061 (cons (const file)
1062 (choice
1063 (const find-file)
1064 (const find-file-other-window)
1065 (const find-file-other-frame)))))
1067 (defcustom org-display-internal-link-with-indirect-buffer nil
1068 "Non-nil means, use indirect buffer to display infile links.
1069 Activating internal links (from one location in a file to another location
1070 in the same file) normally just jumps to the location. When the link is
1071 activated with a C-u prefix (or with mouse-3), the link is displayed in
1072 another window. When this option is set, the other window actually displays
1073 an indirect buffer clone of the current buffer, to avoid any visibility
1074 changes to the current buffer."
1075 :group 'org-link-follow
1076 :type 'boolean)
1078 (defcustom org-open-non-existing-files nil
1079 "Non-nil means, `org-open-file' will open non-existing files.
1080 When nil, an error will be generated."
1081 :group 'org-link-follow
1082 :type 'boolean)
1084 (defcustom org-open-directory-means-index-dot-org nil
1085 "Non-nil means, a link to a directory really means to index.org.
1086 When nil, following a directory link will run dired or open a finder/explorer
1087 window on that directory."
1088 :group 'org-link-follow
1089 :type 'boolean)
1091 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1092 "Function and arguments to call for following mailto links.
1093 This is a list with the first element being a lisp function, and the
1094 remaining elements being arguments to the function. In string arguments,
1095 %a will be replaced by the address, and %s will be replaced by the subject
1096 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1097 :group 'org-link-follow
1098 :type '(choice
1099 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1100 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1101 (const :tag "message-mail" (message-mail "%a" "%s"))
1102 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1104 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1105 "Non-nil means, ask for confirmation before executing shell links.
1106 Shell links can be dangerous: just think about a link
1108 [[shell:rm -rf ~/*][Google Search]]
1110 This link would show up in your Org-mode document as \"Google Search\",
1111 but really it would remove your entire home directory.
1112 Therefore we advise against setting this variable to nil.
1113 Just change it to `y-or-n-p' of you want to confirm with a
1114 single keystroke rather than having to type \"yes\"."
1115 :group 'org-link-follow
1116 :type '(choice
1117 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1118 (const :tag "with y-or-n (faster)" y-or-n-p)
1119 (const :tag "no confirmation (dangerous)" nil)))
1121 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1122 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1123 Elisp links can be dangerous: just think about a link
1125 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1127 This link would show up in your Org-mode document as \"Google Search\",
1128 but really it would remove your entire home directory.
1129 Therefore we advise against setting this variable to nil.
1130 Just change it to `y-or-n-p' of you want to confirm with a
1131 single keystroke rather than having to type \"yes\"."
1132 :group 'org-link-follow
1133 :type '(choice
1134 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1135 (const :tag "with y-or-n (faster)" y-or-n-p)
1136 (const :tag "no confirmation (dangerous)" nil)))
1138 (defconst org-file-apps-defaults-gnu
1139 '((remote . emacs)
1140 (t . mailcap))
1141 "Default file applications on a UNIX or GNU/Linux system.
1142 See `org-file-apps'.")
1144 (defconst org-file-apps-defaults-macosx
1145 '((remote . emacs)
1146 (t . "open %s")
1147 ("ps" . "gv %s")
1148 ("ps.gz" . "gv %s")
1149 ("eps" . "gv %s")
1150 ("eps.gz" . "gv %s")
1151 ("dvi" . "xdvi %s")
1152 ("fig" . "xfig %s"))
1153 "Default file applications on a MacOS X system.
1154 The system \"open\" is known as a default, but we use X11 applications
1155 for some files for which the OS does not have a good default.
1156 See `org-file-apps'.")
1158 (defconst org-file-apps-defaults-windowsnt
1159 (list
1160 '(remote . emacs)
1161 (cons t
1162 (list (if (featurep 'xemacs)
1163 'mswindows-shell-execute
1164 'w32-shell-execute)
1165 "open" 'file)))
1166 "Default file applications on a Windows NT system.
1167 The system \"open\" is used for most files.
1168 See `org-file-apps'.")
1170 (defcustom org-file-apps
1172 ("txt" . emacs)
1173 ("tex" . emacs)
1174 ("ltx" . emacs)
1175 ("org" . emacs)
1176 ("el" . emacs)
1177 ("bib" . emacs)
1179 "External applications for opening `file:path' items in a document.
1180 Org-mode uses system defaults for different file types, but
1181 you can use this variable to set the application for a given file
1182 extension. The entries in this list are cons cells where the car identifies
1183 files and the cdr the corresponding command. Possible values for the
1184 file identifier are
1185 \"ext\" A string identifying an extension
1186 `directory' Matches a directory
1187 `remote' Matches a remote file, accessible through tramp or efs.
1188 Remote files most likely should be visited through Emacs
1189 because external applications cannot handle such paths.
1190 t Default for all remaining files
1192 Possible values for the command are:
1193 `emacs' The file will be visited by the current Emacs process.
1194 `default' Use the default application for this file type.
1195 string A command to be executed by a shell; %s will be replaced
1196 by the path to the file.
1197 sexp A Lisp form which will be evaluated. The file path will
1198 be available in the Lisp variable `file'.
1199 For more examples, see the system specific constants
1200 `org-file-apps-defaults-macosx'
1201 `org-file-apps-defaults-windowsnt'
1202 `org-file-apps-defaults-gnu'."
1203 :group 'org-link-follow
1204 :type '(repeat
1205 (cons (choice :value ""
1206 (string :tag "Extension")
1207 (const :tag "Default for unrecognized files" t)
1208 (const :tag "Remote file" remote)
1209 (const :tag "Links to a directory" directory))
1210 (choice :value ""
1211 (const :tag "Visit with Emacs" emacs)
1212 (const :tag "Use system default" default)
1213 (string :tag "Command")
1214 (sexp :tag "Lisp form")))))
1216 (defgroup org-refile nil
1217 "Options concerning refiling entries in Org-mode."
1218 :tag "Org Remember"
1219 :group 'org)
1221 (defcustom org-directory "~/org"
1222 "Directory with org files.
1223 This directory will be used as default to prompt for org files.
1224 Used by the hooks for remember.el."
1225 :group 'org-refile
1226 :group 'org-remember
1227 :type 'directory)
1229 (defcustom org-default-notes-file "~/.notes"
1230 "Default target for storing notes.
1231 Used by the hooks for remember.el. This can be a string, or nil to mean
1232 the value of `remember-data-file'.
1233 You can set this on a per-template basis with the variable
1234 `org-remember-templates'."
1235 :group 'org-refile
1236 :group 'org-remember
1237 :type '(choice
1238 (const :tag "Default from remember-data-file" nil)
1239 file))
1241 (defcustom org-goto-interface 'outline
1242 "The default interface to be used for `org-goto'.
1243 Allowed vaues are:
1244 outline The interface shows an outline of the relevant file
1245 and the correct heading is found by moving through
1246 the outline or by searching with incremental search.
1247 outline-path-completion Headlines in the current buffer are offered via
1248 completion."
1249 :group 'org-refile
1250 :type '(choice
1251 (const :tag "Outline" outline)
1252 (const :tag "Outline-path-completion" outline-path-completion)))
1254 (defcustom org-reverse-note-order nil
1255 "Non-nil means, store new notes at the beginning of a file or entry.
1256 When nil, new notes will be filed to the end of a file or entry.
1257 This can also be a list with cons cells of regular expressions that
1258 are matched against file names, and values."
1259 :group 'org-remember
1260 :type '(choice
1261 (const :tag "Reverse always" t)
1262 (const :tag "Reverse never" nil)
1263 (repeat :tag "By file name regexp"
1264 (cons regexp boolean))))
1266 (defcustom org-refile-targets nil
1267 "Targets for refiling entries with \\[org-refile].
1268 This is list of cons cells. Each cell contains:
1269 - a specification of the files to be considered, either a list of files,
1270 or a symbol whose function or variable value will be used to retrieve
1271 a file name or a list of file names. Nil means, refile to a different
1272 heading in the current buffer.
1273 - A specification of how to find candidate refile targets. This may be
1274 any of
1275 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1276 This tag has to be present in all target headlines, inheritance will
1277 not be considered.
1278 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1279 todo keyword.
1280 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1281 headlines that are refiling targets.
1282 - a cons cell (:level . N). Any headline of level N is considered a target.
1283 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1285 When this variable is nil, all top-level headlines in the current buffer
1286 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1287 :group 'org-remember
1288 :type '(repeat
1289 (cons
1290 (choice :value org-agenda-files
1291 (const :tag "All agenda files" org-agenda-files)
1292 (const :tag "Current buffer" nil)
1293 (function) (variable) (file))
1294 (choice :tag "Identify target headline by"
1295 (cons :tag "Specific tag" (const :tag) (string))
1296 (cons :tag "TODO keyword" (const :todo) (string))
1297 (cons :tag "Regular expression" (const :regexp) (regexp))
1298 (cons :tag "Level number" (const :level) (integer))
1299 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1301 (defcustom org-refile-use-outline-path nil
1302 "Non-nil means, provide refile targets as paths.
1303 So a level 3 headline will be available as level1/level2/level3.
1304 When the value is `file', also include the file name (without directory)
1305 into the path. When `full-file-path', include the full file path."
1306 :group 'org-remember
1307 :type '(choice
1308 (const :tag "Not" nil)
1309 (const :tag "Yes" t)
1310 (const :tag "Start with file name" file)
1311 (const :tag "Start with full file path" full-file-path)))
1313 (defgroup org-todo nil
1314 "Options concerning TODO items in Org-mode."
1315 :tag "Org TODO"
1316 :group 'org)
1318 (defgroup org-progress nil
1319 "Options concerning Progress logging in Org-mode."
1320 :tag "Org Progress"
1321 :group 'org-time)
1323 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1324 "List of TODO entry keyword sequences and their interpretation.
1325 \\<org-mode-map>This is a list of sequences.
1327 Each sequence starts with a symbol, either `sequence' or `type',
1328 indicating if the keywords should be interpreted as a sequence of
1329 action steps, or as different types of TODO items. The first
1330 keywords are states requiring action - these states will select a headline
1331 for inclusion into the global TODO list Org-mode produces. If one of
1332 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1333 signify that no further action is necessary. If \"|\" is not found,
1334 the last keyword is treated as the only DONE state of the sequence.
1336 The command \\[org-todo] cycles an entry through these states, and one
1337 additional state where no keyword is present. For details about this
1338 cycling, see the manual.
1340 TODO keywords and interpretation can also be set on a per-file basis with
1341 the special #+SEQ_TODO and #+TYP_TODO lines.
1343 Each keyword can optionally specify a character for fast state selection
1344 \(in combination with the variable `org-use-fast-todo-selection')
1345 and specifiers for state change logging, using the same syntax
1346 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1347 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1348 indicates to record a time stamp each time this state is selected.
1350 Each keyword may also specify if a timestamp or a note should be
1351 recorded when entering or leaving the state, by adding additional
1352 characters in the parenthesis after the keyword. This looks like this:
1353 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1354 record only the time of the state change. With X and Y being either
1355 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1356 Y when leaving the state if and only if the *target* state does not
1357 define X. You may omit any of the fast-selection key or X or /Y,
1358 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1360 For backward compatibility, this variable may also be just a list
1361 of keywords - in this case the interptetation (sequence or type) will be
1362 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1363 :group 'org-todo
1364 :group 'org-keywords
1365 :type '(choice
1366 (repeat :tag "Old syntax, just keywords"
1367 (string :tag "Keyword"))
1368 (repeat :tag "New syntax"
1369 (cons
1370 (choice
1371 :tag "Interpretation"
1372 (const :tag "Sequence (cycling hits every state)" sequence)
1373 (const :tag "Type (cycling directly to DONE)" type))
1374 (repeat
1375 (string :tag "Keyword"))))))
1377 (defvar org-todo-keywords-1 nil
1378 "All TODO and DONE keywords active in a buffer.")
1379 (make-variable-buffer-local 'org-todo-keywords-1)
1380 (defvar org-todo-keywords-for-agenda nil)
1381 (defvar org-done-keywords-for-agenda nil)
1382 (defvar org-todo-keyword-alist-for-agenda nil)
1383 (defvar org-tag-alist-for-agenda nil)
1384 (defvar org-agenda-contributing-files nil)
1385 (defvar org-not-done-keywords nil)
1386 (make-variable-buffer-local 'org-not-done-keywords)
1387 (defvar org-done-keywords nil)
1388 (make-variable-buffer-local 'org-done-keywords)
1389 (defvar org-todo-heads nil)
1390 (make-variable-buffer-local 'org-todo-heads)
1391 (defvar org-todo-sets nil)
1392 (make-variable-buffer-local 'org-todo-sets)
1393 (defvar org-todo-log-states nil)
1394 (make-variable-buffer-local 'org-todo-log-states)
1395 (defvar org-todo-kwd-alist nil)
1396 (make-variable-buffer-local 'org-todo-kwd-alist)
1397 (defvar org-todo-key-alist nil)
1398 (make-variable-buffer-local 'org-todo-key-alist)
1399 (defvar org-todo-key-trigger nil)
1400 (make-variable-buffer-local 'org-todo-key-trigger)
1402 (defcustom org-todo-interpretation 'sequence
1403 "Controls how TODO keywords are interpreted.
1404 This variable is in principle obsolete and is only used for
1405 backward compatibility, if the interpretation of todo keywords is
1406 not given already in `org-todo-keywords'. See that variable for
1407 more information."
1408 :group 'org-todo
1409 :group 'org-keywords
1410 :type '(choice (const sequence)
1411 (const type)))
1413 (defcustom org-use-fast-todo-selection 'prefix
1414 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1415 This variable describes if and under what circumstances the cycling
1416 mechanism for TODO keywords will be replaced by a single-key, direct
1417 selection scheme.
1419 When nil, fast selection is never used.
1421 When the symbol `prefix', it will be used when `org-todo' is called with
1422 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1423 in an agenda buffer.
1425 When t, fast selection is used by default. In this case, the prefix
1426 argument forces cycling instead.
1428 In all cases, the special interface is only used if access keys have actually
1429 been assigned by the user, i.e. if keywords in the configuration are followed
1430 by a letter in parenthesis, like TODO(t)."
1431 :group 'org-todo
1432 :type '(choice
1433 (const :tag "Never" nil)
1434 (const :tag "By default" t)
1435 (const :tag "Only with C-u C-c C-t" prefix)))
1437 (defcustom org-provide-todo-statistics t
1438 "Non-nil means, update todo statistics after insert and toggle.
1439 When this is set, todo statistics is updated in the parent of the current
1440 entry each time a todo state is changed."
1441 :group 'org-todo
1442 :type 'boolean)
1444 (defcustom org-after-todo-state-change-hook nil
1445 "Hook which is run after the state of a TODO item was changed.
1446 The new state (a string with a TODO keyword, or nil) is available in the
1447 Lisp variable `state'."
1448 :group 'org-todo
1449 :type 'hook)
1451 (defcustom org-log-done nil
1452 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1453 When equal to the list (done), also prompt for a closing note.
1454 This can also be configured on a per-file basis by adding one of
1455 the following lines anywhere in the buffer:
1457 #+STARTUP: logdone
1458 #+STARTUP: lognotedone
1459 #+STARTUP: nologdone"
1460 :group 'org-todo
1461 :group 'org-progress
1462 :type '(choice
1463 (const :tag "No logging" nil)
1464 (const :tag "Record CLOSED timestamp" time)
1465 (const :tag "Record CLOSED timestamp with closing note." note)))
1467 ;; Normalize old uses of org-log-done.
1468 (cond
1469 ((eq org-log-done t) (setq org-log-done 'time))
1470 ((and (listp org-log-done) (memq 'done org-log-done))
1471 (setq org-log-done 'note)))
1473 (defcustom org-log-note-clock-out nil
1474 "Non-nil means, record a note when clocking out of an item.
1475 This can also be configured on a per-file basis by adding one of
1476 the following lines anywhere in the buffer:
1478 #+STARTUP: lognoteclock-out
1479 #+STARTUP: nolognoteclock-out"
1480 :group 'org-todo
1481 :group 'org-progress
1482 :type 'boolean)
1484 (defcustom org-log-done-with-time t
1485 "Non-nil means, the CLOSED time stamp will contain date and time.
1486 When nil, only the date will be recorded."
1487 :group 'org-progress
1488 :type 'boolean)
1490 (defcustom org-log-note-headings
1491 '((done . "CLOSING NOTE %t")
1492 (state . "State %-12s %t")
1493 (note . "Note taken on %t")
1494 (clock-out . ""))
1495 "Headings for notes added to entries.
1496 The value is an alist, with the car being a symbol indicating the note
1497 context, and the cdr is the heading to be used. The heading may also be the
1498 empty string.
1499 %t in the heading will be replaced by a time stamp.
1500 %s will be replaced by the new TODO state, in double quotes.
1501 %u will be replaced by the user name.
1502 %U will be replaced by the full user name."
1503 :group 'org-todo
1504 :group 'org-progress
1505 :type '(list :greedy t
1506 (cons (const :tag "Heading when closing an item" done) string)
1507 (cons (const :tag
1508 "Heading when changing todo state (todo sequence only)"
1509 state) string)
1510 (cons (const :tag "Heading when just taking a note" note) string)
1511 (cons (const :tag "Heading when clocking out" clock-out) string)))
1513 (unless (assq 'note org-log-note-headings)
1514 (push '(note . "%t") org-log-note-headings))
1516 (defcustom org-log-states-order-reversed t
1517 "Non-nil means, the latest state change note will be directly after heading.
1518 When nil, the notes will be orderer according to time."
1519 :group 'org-todo
1520 :group 'org-progress
1521 :type 'boolean)
1523 (defcustom org-log-repeat 'time
1524 "Non-nil means, record moving through the DONE state when triggering repeat.
1525 An auto-repeating tasks is immediately switched back to TODO when marked
1526 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1527 the TODO keyword definition, or recording a closing note by setting
1528 `org-log-done', there will be no record of the task moving through DONE.
1529 This variable forces taking a note anyway. Possible values are:
1531 nil Don't force a record
1532 time Record a time stamp
1533 note Record a note
1535 This option can also be set with on a per-file-basis with
1537 #+STARTUP: logrepeat
1538 #+STARTUP: lognoterepeat
1539 #+STARTUP: nologrepeat
1541 You can have local logging settings for a subtree by setting the LOGGING
1542 property to one or more of these keywords."
1543 :group 'org-todo
1544 :group 'org-progress
1545 :type '(choice
1546 (const :tag "Don't force a record" nil)
1547 (const :tag "Force recording the DONE state" time)
1548 (const :tag "Force recording a note with the DONE state" note)))
1551 (defgroup org-priorities nil
1552 "Priorities in Org-mode."
1553 :tag "Org Priorities"
1554 :group 'org-todo)
1556 (defcustom org-highest-priority ?A
1557 "The highest priority of TODO items. A character like ?A, ?B etc.
1558 Must have a smaller ASCII number than `org-lowest-priority'."
1559 :group 'org-priorities
1560 :type 'character)
1562 (defcustom org-lowest-priority ?C
1563 "The lowest priority of TODO items. A character like ?A, ?B etc.
1564 Must have a larger ASCII number than `org-highest-priority'."
1565 :group 'org-priorities
1566 :type 'character)
1568 (defcustom org-default-priority ?B
1569 "The default priority of TODO items.
1570 This is the priority an item get if no explicit priority is given."
1571 :group 'org-priorities
1572 :type 'character)
1574 (defcustom org-priority-start-cycle-with-default t
1575 "Non-nil means, start with default priority when starting to cycle.
1576 When this is nil, the first step in the cycle will be (depending on the
1577 command used) one higher or lower that the default priority."
1578 :group 'org-priorities
1579 :type 'boolean)
1581 (defgroup org-time nil
1582 "Options concerning time stamps and deadlines in Org-mode."
1583 :tag "Org Time"
1584 :group 'org)
1586 (defcustom org-insert-labeled-timestamps-at-point nil
1587 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1588 When nil, these labeled time stamps are forces into the second line of an
1589 entry, just after the headline. When scheduling from the global TODO list,
1590 the time stamp will always be forced into the second line."
1591 :group 'org-time
1592 :type 'boolean)
1594 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1595 "Formats for `format-time-string' which are used for time stamps.
1596 It is not recommended to change this constant.")
1598 (defcustom org-time-stamp-rounding-minutes '(0 5)
1599 "Number of minutes to round time stamps to.
1600 These are two values, the first applies when first creating a time stamp.
1601 The second applies when changing it with the commands `S-up' and `S-down'.
1602 When changing the time stamp, this means that it will change in steps
1603 of N minutes, as given by the second value.
1605 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1606 numbers should be factors of 60, so for example 5, 10, 15.
1608 When this is larger than 1, you can still force an exact time-stamp by using
1609 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1610 and by using a prefix arg to `S-up/down' to specify the exact number
1611 of minutes to shift."
1612 :group 'org-time
1613 :get '(lambda (var) ; Make sure all entries have 5 elements
1614 (if (integerp (default-value var))
1615 (list (default-value var) 5)
1616 (default-value var)))
1617 :type '(list
1618 (integer :tag "when inserting times")
1619 (integer :tag "when modifying times")))
1621 ;; Normalize old customizations of this variable.
1622 (when (integerp org-time-stamp-rounding-minutes)
1623 (setq org-time-stamp-rounding-minutes
1624 (list org-time-stamp-rounding-minutes
1625 org-time-stamp-rounding-minutes)))
1627 (defcustom org-display-custom-times nil
1628 "Non-nil means, overlay custom formats over all time stamps.
1629 The formats are defined through the variable `org-time-stamp-custom-formats'.
1630 To turn this on on a per-file basis, insert anywhere in the file:
1631 #+STARTUP: customtime"
1632 :group 'org-time
1633 :set 'set-default
1634 :type 'sexp)
1635 (make-variable-buffer-local 'org-display-custom-times)
1637 (defcustom org-time-stamp-custom-formats
1638 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1639 "Custom formats for time stamps. See `format-time-string' for the syntax.
1640 These are overlayed over the default ISO format if the variable
1641 `org-display-custom-times' is set. Time like %H:%M should be at the
1642 end of the second format."
1643 :group 'org-time
1644 :type 'sexp)
1646 (defun org-time-stamp-format (&optional long inactive)
1647 "Get the right format for a time string."
1648 (let ((f (if long (cdr org-time-stamp-formats)
1649 (car org-time-stamp-formats))))
1650 (if inactive
1651 (concat "[" (substring f 1 -1) "]")
1652 f)))
1654 (defcustom org-time-clocksum-format "%d:%02d"
1655 "The format string used when creating CLOCKSUM lines, or when
1656 org-mode generates a time duration."
1657 :group 'org-time
1658 :type 'string)
1660 (defcustom org-deadline-warning-days 14
1661 "No. of days before expiration during which a deadline becomes active.
1662 This variable governs the display in sparse trees and in the agenda.
1663 When 0 or negative, it means use this number (the absolute value of it)
1664 even if a deadline has a different individual lead time specified."
1665 :group 'org-time
1666 :group 'org-agenda-daily/weekly
1667 :type 'number)
1669 (defcustom org-read-date-prefer-future t
1670 "Non-nil means, assume future for incomplete date input from user.
1671 This affects the following situations:
1672 1. The user gives a day, but no month.
1673 For example, if today is the 15th, and you enter \"3\", Org-mode will
1674 read this as the third of *next* month. However, if you enter \"17\",
1675 it will be considered as *this* month.
1676 2. The user gives a month but not a year.
1677 For example, if it is april and you enter \"feb 2\", this will be read
1678 as feb 2, *next* year. \"May 5\", however, will be this year.
1680 Currently this does not work for ISO week specifications.
1682 When this option is nil, the current month and year will always be used
1683 as defaults."
1684 :group 'org-time
1685 :type 'boolean)
1687 (defcustom org-read-date-display-live t
1688 "Non-nil means, display current interpretation of date prompt live.
1689 This display will be in an overlay, in the minibuffer."
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-read-date-popup-calendar t
1694 "Non-nil means, pop up a calendar when prompting for a date.
1695 In the calendar, the date can be selected with mouse-1. However, the
1696 minibuffer will also be active, and you can simply enter the date as well.
1697 When nil, only the minibuffer will be available."
1698 :group 'org-time
1699 :type 'boolean)
1700 (if (fboundp 'defvaralias)
1701 (defvaralias 'org-popup-calendar-for-date-prompt
1702 'org-read-date-popup-calendar))
1704 (defcustom org-extend-today-until 0
1705 "The hour when your day really ends. Must be an integer.
1706 This has influence for the following applications:
1707 - When switching the agenda to \"today\". It it is still earlier than
1708 the time given here, the day recognized as TODAY is actually yesterday.
1709 - When a date is read from the user and it is still before the time given
1710 here, the current date and time will be assumed to be yesterday, 23:59.
1711 Also, timestamps inserted in remember templates follow this rule.
1713 IMPORTANT: This is a feature whose implementation is and likely will
1714 remain incomplete. Really, it is only here because past midnight seems to
1715 ne the favorite working time of John Wiegley :-)"
1716 :group 'org-time
1717 :type 'number)
1719 (defcustom org-edit-timestamp-down-means-later nil
1720 "Non-nil means, S-down will increase the time in a time stamp.
1721 When nil, S-up will increase."
1722 :group 'org-time
1723 :type 'boolean)
1725 (defcustom org-calendar-follow-timestamp-change t
1726 "Non-nil means, make the calendar window follow timestamp changes.
1727 When a timestamp is modified and the calendar window is visible, it will be
1728 moved to the new date."
1729 :group 'org-time
1730 :type 'boolean)
1732 (defgroup org-tags nil
1733 "Options concerning tags in Org-mode."
1734 :tag "Org Tags"
1735 :group 'org)
1737 (defcustom org-tag-alist nil
1738 "List of tags allowed in Org-mode files.
1739 When this list is nil, Org-mode will base TAG input on what is already in the
1740 buffer.
1741 The value of this variable is an alist, the car of each entry must be a
1742 keyword as a string, the cdr may be a character that is used to select
1743 that tag through the fast-tag-selection interface.
1744 See the manual for details."
1745 :group 'org-tags
1746 :type '(repeat
1747 (choice
1748 (cons (string :tag "Tag name")
1749 (character :tag "Access char"))
1750 (const :tag "Start radio group" (:startgroup))
1751 (const :tag "End radio group" (:endgroup)))))
1753 (defvar org-file-tags nil
1754 "List of tags that can be inherited by all entries in the file.
1755 The tags will be inherited if the variable `org-use-tag-inheritance'
1756 says they should be.
1757 This variable is populated from #+TAG lines.")
1759 (defcustom org-use-fast-tag-selection 'auto
1760 "Non-nil means, use fast tag selection scheme.
1761 This is a special interface to select and deselect tags with single keys.
1762 When nil, fast selection is never used.
1763 When the symbol `auto', fast selection is used if and only if selection
1764 characters for tags have been configured, either through the variable
1765 `org-tag-alist' or through a #+TAGS line in the buffer.
1766 When t, fast selection is always used and selection keys are assigned
1767 automatically if necessary."
1768 :group 'org-tags
1769 :type '(choice
1770 (const :tag "Always" t)
1771 (const :tag "Never" nil)
1772 (const :tag "When selection characters are configured" 'auto)))
1774 (defcustom org-fast-tag-selection-single-key nil
1775 "Non-nil means, fast tag selection exits after first change.
1776 When nil, you have to press RET to exit it.
1777 During fast tag selection, you can toggle this flag with `C-c'.
1778 This variable can also have the value `expert'. In this case, the window
1779 displaying the tags menu is not even shown, until you press C-c again."
1780 :group 'org-tags
1781 :type '(choice
1782 (const :tag "No" nil)
1783 (const :tag "Yes" t)
1784 (const :tag "Expert" expert)))
1786 (defvar org-fast-tag-selection-include-todo nil
1787 "Non-nil means, fast tags selection interface will also offer TODO states.
1788 This is an undocumented feature, you should not rely on it.")
1790 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1791 "The column to which tags should be indented in a headline.
1792 If this number is positive, it specifies the column. If it is negative,
1793 it means that the tags should be flushright to that column. For example,
1794 -80 works well for a normal 80 character screen."
1795 :group 'org-tags
1796 :type 'integer)
1798 (defcustom org-auto-align-tags t
1799 "Non-nil means, realign tags after pro/demotion of TODO state change.
1800 These operations change the length of a headline and therefore shift
1801 the tags around. With this options turned on, after each such operation
1802 the tags are again aligned to `org-tags-column'."
1803 :group 'org-tags
1804 :type 'boolean)
1806 (defcustom org-use-tag-inheritance t
1807 "Non-nil means, tags in levels apply also for sublevels.
1808 When nil, only the tags directly given in a specific line apply there.
1809 If this option is t, a match early-on in a tree can lead to a large
1810 number of matches in the subtree. If you only want to see the first
1811 match in a tree during a search, check out the variable
1812 `org-tags-match-list-sublevels'.
1814 This may also be a list of tags that should be inherited, or a regexp that
1815 matches tags that should be inherited."
1816 :group 'org-tags
1817 :type '(choice
1818 (const :tag "Not" nil)
1819 (const :tag "Always" t)
1820 (repeat :tag "Specific tags" (string :tag "Tag"))
1821 (regexp :tag "Tags matched by regexp")))
1823 (defun org-tag-inherit-p (tag)
1824 "Check if TAG is one that should be inherited."
1825 (cond
1826 ((eq org-use-tag-inheritance t) t)
1827 ((not org-use-tag-inheritance) nil)
1828 ((stringp org-use-tag-inheritance)
1829 (string-match org-use-tag-inheritance tag))
1830 ((listp org-use-tag-inheritance)
1831 (member tag org-use-tag-inheritance))
1832 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1834 (defcustom org-tags-match-list-sublevels t
1835 "Non-nil means list also sublevels of headlines matching tag search.
1836 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1837 the sublevels of a headline matching a tag search often also match
1838 the same search. Listing all of them can create very long lists.
1839 Setting this variable to nil causes subtrees of a match to be skipped.
1840 This option is off by default, because inheritance in on. If you turn
1841 inheritance off, you very likely want to turn this option on.
1843 As a special case, if the tag search is restricted to TODO items, the
1844 value of this variable is ignored and sublevels are always checked, to
1845 make sure all corresponding TODO items find their way into the list."
1846 :group 'org-tags
1847 :type 'boolean)
1849 (defvar org-tags-history nil
1850 "History of minibuffer reads for tags.")
1851 (defvar org-last-tags-completion-table nil
1852 "The last used completion table for tags.")
1853 (defvar org-after-tags-change-hook nil
1854 "Hook that is run after the tags in a line have changed.")
1856 (defgroup org-properties nil
1857 "Options concerning properties in Org-mode."
1858 :tag "Org Properties"
1859 :group 'org)
1861 (defcustom org-property-format "%-10s %s"
1862 "How property key/value pairs should be formatted by `indent-line'.
1863 When `indent-line' hits a property definition, it will format the line
1864 according to this format, mainly to make sure that the values are
1865 lined-up with respect to each other."
1866 :group 'org-properties
1867 :type 'string)
1869 (defcustom org-use-property-inheritance nil
1870 "Non-nil means, properties apply also for sublevels.
1872 This setting is chiefly used during property searches. Turning it on can
1873 cause significant overhead when doing a search, which is why it is not
1874 on by default.
1876 When nil, only the properties directly given in the current entry count.
1877 When t, every property is inherited. The value may also be a list of
1878 properties that should have inheritance, or a regular expression matching
1879 properties that should be inherited.
1881 However, note that some special properties use inheritance under special
1882 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1883 and the properties ending in \"_ALL\" when they are used as descriptor
1884 for valid values of a property.
1886 Note for programmers:
1887 When querying an entry with `org-entry-get', you can control if inheritance
1888 should be used. By default, `org-entry-get' looks only at the local
1889 properties. You can request inheritance by setting the inherit argument
1890 to t (to force inheritance) or to `selective' (to respect the setting
1891 in this variable)."
1892 :group 'org-properties
1893 :type '(choice
1894 (const :tag "Not" nil)
1895 (const :tag "Always" t)
1896 (repeat :tag "Specific properties" (string :tag "Property"))
1897 (regexp :tag "Properties matched by regexp")))
1899 (defun org-property-inherit-p (property)
1900 "Check if PROPERTY is one that should be inherited."
1901 (cond
1902 ((eq org-use-property-inheritance t) t)
1903 ((not org-use-property-inheritance) nil)
1904 ((stringp org-use-property-inheritance)
1905 (string-match org-use-property-inheritance property))
1906 ((listp org-use-property-inheritance)
1907 (member property org-use-property-inheritance))
1908 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1910 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1911 "The default column format, if no other format has been defined.
1912 This variable can be set on the per-file basis by inserting a line
1914 #+COLUMNS: %25ITEM ....."
1915 :group 'org-properties
1916 :type 'string)
1918 (defcustom org-columns-ellipses ".."
1919 "The ellipses to be used when a field in column view is truncated.
1920 When this is the empty string, as many characters as possible are shown,
1921 but then there will be no visual indication that the field has been truncated.
1922 When this is a string of length N, the last N characters of a truncated
1923 field are replaced by this string. If the column is narrower than the
1924 ellipses string, only part of the ellipses string will be shown."
1925 :group 'org-properties
1926 :type 'string)
1928 (defcustom org-columns-modify-value-for-display-function nil
1929 "Function that modifies values for display in column view.
1930 For example, it can be used to cut out a certain part from a time stamp.
1931 The function must take 2 argments:
1933 column-title The tite of the column (*not* the property name)
1934 value The value that should be modified.
1936 The function should return the value that should be displayed,
1937 or nil if the normal value should be used."
1938 :group 'org-properties
1939 :type 'function)
1941 (defcustom org-effort-property "Effort"
1942 "The property that is being used to keep track of effort estimates.
1943 Effort estimates given in this property need to have the format H:MM."
1944 :group 'org-properties
1945 :group 'org-progress
1946 :type '(string :tag "Property"))
1948 (defconst org-global-properties-fixed
1949 '(("VISIBILITY_ALL" . "folded children content all"))
1950 "List of property/value pairs that can be inherited by any entry.
1951 These are fixed values, for the preset properties.")
1954 (defcustom org-global-properties nil
1955 "List of property/value pairs that can be inherited by any entry.
1956 You can set buffer-local values for this by adding lines like
1958 #+PROPERTY: NAME VALUE"
1959 :group 'org-properties
1960 :type '(repeat
1961 (cons (string :tag "Property")
1962 (string :tag "Value"))))
1964 (defvar org-file-properties nil
1965 "List of property/value pairs that can be inherited by any entry.
1966 Valid for the current buffer.
1967 This variable is populated from #+PROPERTY lines.")
1968 (make-variable-buffer-local 'org-file-properties)
1970 (defgroup org-agenda nil
1971 "Options concerning agenda views in Org-mode."
1972 :tag "Org Agenda"
1973 :group 'org)
1975 (defvar org-category nil
1976 "Variable used by org files to set a category for agenda display.
1977 Such files should use a file variable to set it, for example
1979 # -*- mode: org; org-category: \"ELisp\"
1981 or contain a special line
1983 #+CATEGORY: ELisp
1985 If the file does not specify a category, then file's base name
1986 is used instead.")
1987 (make-variable-buffer-local 'org-category)
1988 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1990 (defcustom org-agenda-files nil
1991 "The files to be used for agenda display.
1992 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1993 \\[org-remove-file]. You can also use customize to edit the list.
1995 If an entry is a directory, all files in that directory that are matched by
1996 `org-agenda-file-regexp' will be part of the file list.
1998 If the value of the variable is not a list but a single file name, then
1999 the list of agenda files is actually stored and maintained in that file, one
2000 agenda file per line."
2001 :group 'org-agenda
2002 :type '(choice
2003 (repeat :tag "List of files and directories" file)
2004 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2006 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2007 "Regular expression to match files for `org-agenda-files'.
2008 If any element in the list in that variable contains a directory instead
2009 of a normal file, all files in that directory that are matched by this
2010 regular expression will be included."
2011 :group 'org-agenda
2012 :type 'regexp)
2014 (defcustom org-agenda-text-search-extra-files nil
2015 "List of extra files to be searched by text search commands.
2016 These files will be search in addition to the agenda files by the
2017 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2018 Note that these files will only be searched for text search commands,
2019 not for the other agenda views like todo lists, tag searches or the weekly
2020 agenda. This variable is intended to list notes and possibly archive files
2021 that should also be searched by these two commands.
2022 In fact, if the first element in the list is the symbol `agenda-archives',
2023 than all archive files of all agenda files will be added to the search
2024 scope."
2025 :group 'org-agenda
2026 :type '(set :greedy t
2027 (const :tag "Agenda Archives" agenda-archives)
2028 (repeat :inline t (file))))
2030 (if (fboundp 'defvaralias)
2031 (defvaralias 'org-agenda-multi-occur-extra-files
2032 'org-agenda-text-search-extra-files))
2034 (defcustom org-agenda-skip-unavailable-files nil
2035 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2036 A nil value means to remove them, after a query, from the list."
2037 :group 'org-agenda
2038 :type 'boolean)
2040 (defcustom org-calendar-to-agenda-key [?c]
2041 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2042 The command `org-calendar-goto-agenda' will be bound to this key. The
2043 default is the character `c' because then `c' can be used to switch back and
2044 forth between agenda and calendar."
2045 :group 'org-agenda
2046 :type 'sexp)
2048 (defcustom org-calendar-agenda-action-key [?k]
2049 "The key to be installed in `calendar-mode-map' for agenda-action.
2050 The command `org-agenda-action' will be bound to this key. The
2051 default is the character `k' because we use the same key in the agenda."
2052 :group 'org-agenda
2053 :type 'sexp)
2055 (eval-after-load "calendar"
2056 '(progn
2057 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2058 'org-calendar-goto-agenda)
2059 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2060 'org-agenda-action)))
2062 (defgroup org-latex nil
2063 "Options for embedding LaTeX code into Org-mode."
2064 :tag "Org LaTeX"
2065 :group 'org)
2067 (defcustom org-format-latex-options
2068 '(:foreground default :background default :scale 1.0
2069 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2070 :matchers ("begin" "$" "$$" "\\(" "\\["))
2071 "Options for creating images from LaTeX fragments.
2072 This is a property list with the following properties:
2073 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2074 `default' means use the foreground of the default face.
2075 :background the background color, or \"Transparent\".
2076 `default' means use the background of the default face.
2077 :scale a scaling factor for the size of the images.
2078 :html-foreground, :html-background, :html-scale
2079 the same numbers for HTML export.
2080 :matchers a list indicating which matchers should be used to
2081 find LaTeX fragments. Valid members of this list are:
2082 \"begin\" find environments
2083 \"$\" find math expressions surrounded by $...$
2084 \"$$\" find math expressions surrounded by $$....$$
2085 \"\\(\" find math expressions surrounded by \\(...\\)
2086 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2087 :group 'org-latex
2088 :type 'plist)
2090 (defcustom org-format-latex-header "\\documentclass{article}
2091 \\usepackage{fullpage} % do not remove
2092 \\usepackage{amssymb}
2093 \\usepackage[usenames]{color}
2094 \\usepackage{amsmath}
2095 \\usepackage{latexsym}
2096 \\usepackage[mathscr]{eucal}
2097 \\pagestyle{empty} % do not remove"
2098 "The document header used for processing LaTeX fragments."
2099 :group 'org-latex
2100 :type 'string)
2103 (defgroup org-font-lock nil
2104 "Font-lock settings for highlighting in Org-mode."
2105 :tag "Org Font Lock"
2106 :group 'org)
2108 (defcustom org-level-color-stars-only nil
2109 "Non-nil means fontify only the stars in each headline.
2110 When nil, the entire headline is fontified.
2111 Changing it requires restart of `font-lock-mode' to become effective
2112 also in regions already fontified."
2113 :group 'org-font-lock
2114 :type 'boolean)
2116 (defcustom org-hide-leading-stars nil
2117 "Non-nil means, hide the first N-1 stars in a headline.
2118 This works by using the face `org-hide' for these stars. This
2119 face is white for a light background, and black for a dark
2120 background. You may have to customize the face `org-hide' to
2121 make this work.
2122 Changing it requires restart of `font-lock-mode' to become effective
2123 also in regions already fontified.
2124 You may also set this on a per-file basis by adding one of the following
2125 lines to the buffer:
2127 #+STARTUP: hidestars
2128 #+STARTUP: showstars"
2129 :group 'org-font-lock
2130 :type 'boolean)
2132 (defcustom org-fontify-done-headline nil
2133 "Non-nil means, change the face of a headline if it is marked DONE.
2134 Normally, only the TODO/DONE keyword indicates the state of a headline.
2135 When this is non-nil, the headline after the keyword is set to the
2136 `org-headline-done' as an additional indication."
2137 :group 'org-font-lock
2138 :type 'boolean)
2140 (defcustom org-fontify-emphasized-text t
2141 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2142 Changing this variable requires a restart of Emacs to take effect."
2143 :group 'org-font-lock
2144 :type 'boolean)
2146 (defcustom org-highlight-latex-fragments-and-specials nil
2147 "Non-nil means, fontify what is treated specially by the exporters."
2148 :group 'org-font-lock
2149 :type 'boolean)
2151 (defcustom org-hide-emphasis-markers nil
2152 "Non-nil mean font-lock should hide the emphasis marker characters."
2153 :group 'org-font-lock
2154 :type 'boolean)
2156 (defvar org-emph-re nil
2157 "Regular expression for matching emphasis.")
2158 (defvar org-verbatim-re nil
2159 "Regular expression for matching verbatim text.")
2160 (defvar org-emphasis-regexp-components) ; defined just below
2161 (defvar org-emphasis-alist) ; defined just below
2162 (defun org-set-emph-re (var val)
2163 "Set variable and compute the emphasis regular expression."
2164 (set var val)
2165 (when (and (boundp 'org-emphasis-alist)
2166 (boundp 'org-emphasis-regexp-components)
2167 org-emphasis-alist org-emphasis-regexp-components)
2168 (let* ((e org-emphasis-regexp-components)
2169 (pre (car e))
2170 (post (nth 1 e))
2171 (border (nth 2 e))
2172 (body (nth 3 e))
2173 (nl (nth 4 e))
2174 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2175 (body1 (concat body "*?"))
2176 (markers (mapconcat 'car org-emphasis-alist ""))
2177 (vmarkers (mapconcat
2178 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2179 org-emphasis-alist "")))
2180 ;; make sure special characters appear at the right position in the class
2181 (if (string-match "\\^" markers)
2182 (setq markers (concat (replace-match "" t t markers) "^")))
2183 (if (string-match "-" markers)
2184 (setq markers (concat (replace-match "" t t markers) "-")))
2185 (if (string-match "\\^" vmarkers)
2186 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2187 (if (string-match "-" vmarkers)
2188 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2189 (if (> nl 0)
2190 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2191 (int-to-string nl) "\\}")))
2192 ;; Make the regexp
2193 (setq org-emph-re
2194 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2195 "\\("
2196 "\\([" markers "]\\)"
2197 "\\("
2198 "[^" border "]\\|"
2199 "[^" border (if (and nil stacked) markers) "]"
2200 body1
2201 "[^" border (if (and nil stacked) markers) "]"
2202 "\\)"
2203 "\\3\\)"
2204 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2205 (setq org-verbatim-re
2206 (concat "\\([" pre "]\\|^\\)"
2207 "\\("
2208 "\\([" vmarkers "]\\)"
2209 "\\("
2210 "[^" border "]\\|"
2211 "[^" border "]"
2212 body1
2213 "[^" border "]"
2214 "\\)"
2215 "\\3\\)"
2216 "\\([" post "]\\|$\\)")))))
2218 (defcustom org-emphasis-regexp-components
2219 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2220 "Components used to build the regular expression for emphasis.
2221 This is a list with 6 entries. Terminology: In an emphasis string
2222 like \" *strong word* \", we call the initial space PREMATCH, the final
2223 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2224 and \"trong wor\" is the body. The different components in this variable
2225 specify what is allowed/forbidden in each part:
2227 pre Chars allowed as prematch. Beginning of line will be allowed too.
2228 post Chars allowed as postmatch. End of line will be allowed too.
2229 border The chars *forbidden* as border characters.
2230 body-regexp A regexp like \".\" to match a body character. Don't use
2231 non-shy groups here, and don't allow newline here.
2232 newline The maximum number of newlines allowed in an emphasis exp.
2234 Use customize to modify this, or restart Emacs after changing it."
2235 :group 'org-font-lock
2236 :set 'org-set-emph-re
2237 :type '(list
2238 (sexp :tag "Allowed chars in pre ")
2239 (sexp :tag "Allowed chars in post ")
2240 (sexp :tag "Forbidden chars in border ")
2241 (sexp :tag "Regexp for body ")
2242 (integer :tag "number of newlines allowed")
2243 (option (boolean :tag "Please ignore this button"))))
2245 (defcustom org-emphasis-alist
2246 `(("*" bold "<b>" "</b>")
2247 ("/" italic "<i>" "</i>")
2248 ("_" underline "<u>" "</u>")
2249 ("=" org-code "<code>" "</code>" verbatim)
2250 ("~" org-verbatim "" "" verbatim)
2251 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2252 "<del>" "</del>")
2254 "Special syntax for emphasized text.
2255 Text starting and ending with a special character will be emphasized, for
2256 example *bold*, _underlined_ and /italic/. This variable sets the marker
2257 characters, the face to be used by font-lock for highlighting in Org-mode
2258 Emacs buffers, and the HTML tags to be used for this.
2259 Use customize to modify this, or restart Emacs after changing it."
2260 :group 'org-font-lock
2261 :set 'org-set-emph-re
2262 :type '(repeat
2263 (list
2264 (string :tag "Marker character")
2265 (choice
2266 (face :tag "Font-lock-face")
2267 (plist :tag "Face property list"))
2268 (string :tag "HTML start tag")
2269 (string :tag "HTML end tag")
2270 (option (const verbatim)))))
2272 ;;; Miscellaneous options
2274 (defgroup org-completion nil
2275 "Completion in Org-mode."
2276 :tag "Org Completion"
2277 :group 'org)
2279 (defcustom org-completion-fallback-command 'hippie-expand
2280 "The expansion command called by \\[org-complete] in normal context.
2281 Normal means, no org-mode-specific context."
2282 :group 'org-completion
2283 :type 'function)
2285 ;;; Functions and variables from ther packages
2286 ;; Declared here to avoid compiler warnings
2288 ;; XEmacs only
2289 (defvar outline-mode-menu-heading)
2290 (defvar outline-mode-menu-show)
2291 (defvar outline-mode-menu-hide)
2292 (defvar zmacs-regions) ; XEmacs regions
2294 ;; Emacs only
2295 (defvar mark-active)
2297 ;; Various packages
2298 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2299 (declare-function calendar-forward-day "cal-move" (arg))
2300 (declare-function calendar-goto-date "cal-move" (date))
2301 (declare-function calendar-goto-today "cal-move" ())
2302 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2303 (defvar calc-embedded-close-formula)
2304 (defvar calc-embedded-open-formula)
2305 (declare-function cdlatex-tab "ext:cdlatex" ())
2306 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2307 (defvar font-lock-unfontify-region-function)
2308 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2309 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2310 (defvar iswitchb-temp-buflist)
2311 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2312 (declare-function org-agenda-skip "org-agenda" ())
2313 (declare-function org-format-agenda-item "org-agenda"
2314 (extra txt &optional category tags dotime noprefix remove-re))
2315 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2316 (declare-function org-agenda-change-all-lines "org-agenda"
2317 (newhead hdmarker &optional fixface))
2318 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2319 (declare-function org-agenda-maybe-redo "org-agenda" ())
2320 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2321 (beg end))
2322 (declare-function parse-time-string "parse-time" (string))
2323 (declare-function remember "remember" (&optional initial))
2324 (declare-function remember-buffer-desc "remember" ())
2325 (declare-function remember-finalize "remember" ())
2326 (defvar remember-save-after-remembering)
2327 (defvar remember-data-file)
2328 (defvar remember-register)
2329 (defvar remember-buffer)
2330 (defvar remember-handler-functions)
2331 (defvar remember-annotation-functions)
2332 (defvar texmathp-why)
2333 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2334 (declare-function table--at-cell-p "table" (position &optional object at-column))
2336 (defvar w3m-current-url)
2337 (defvar w3m-current-title)
2339 (defvar org-latex-regexps)
2341 ;;; Autoload and prepare some org modules
2343 ;; Some table stuff that needs to be defined here, because it is used
2344 ;; by the functions setting up org-mode or checking for table context.
2346 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2347 "Detects an org-type or table-type table.")
2348 (defconst org-table-line-regexp "^[ \t]*|"
2349 "Detects an org-type table line.")
2350 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2351 "Detects an org-type table line.")
2352 (defconst org-table-hline-regexp "^[ \t]*|-"
2353 "Detects an org-type table hline.")
2354 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2355 "Detects a table-type table hline.")
2356 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2357 "Searching from within a table (any type) this finds the first line
2358 outside the table.")
2360 ;; Autoload the functions in org-table.el that are needed by functions here.
2362 (eval-and-compile
2363 (org-autoload "org-table"
2364 '(org-table-align org-table-begin org-table-blank-field
2365 org-table-convert org-table-convert-region org-table-copy-down
2366 org-table-copy-region org-table-create
2367 org-table-create-or-convert-from-region
2368 org-table-create-with-table.el org-table-current-dline
2369 org-table-cut-region org-table-delete-column org-table-edit-field
2370 org-table-edit-formulas org-table-end org-table-eval-formula
2371 org-table-export org-table-field-info
2372 org-table-get-stored-formulas org-table-goto-column
2373 org-table-hline-and-move org-table-import org-table-insert-column
2374 org-table-insert-hline org-table-insert-row org-table-iterate
2375 org-table-justify-field-maybe org-table-kill-row
2376 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2377 org-table-move-column org-table-move-column-left
2378 org-table-move-column-right org-table-move-row
2379 org-table-move-row-down org-table-move-row-up
2380 org-table-next-field org-table-next-row org-table-paste-rectangle
2381 org-table-previous-field org-table-recalculate
2382 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2383 org-table-toggle-coordinate-overlays
2384 org-table-toggle-formula-debugger org-table-wrap-region
2385 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2387 (defun org-at-table-p (&optional table-type)
2388 "Return t if the cursor is inside an org-type table.
2389 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2390 (if org-enable-table-editor
2391 (save-excursion
2392 (beginning-of-line 1)
2393 (looking-at (if table-type org-table-any-line-regexp
2394 org-table-line-regexp)))
2395 nil))
2396 (defsubst org-table-p () (org-at-table-p))
2398 (defun org-at-table.el-p ()
2399 "Return t if and only if we are at a table.el table."
2400 (and (org-at-table-p 'any)
2401 (save-excursion
2402 (goto-char (org-table-begin 'any))
2403 (looking-at org-table1-hline-regexp))))
2404 (defun org-table-recognize-table.el ()
2405 "If there is a table.el table nearby, recognize it and move into it."
2406 (if org-table-tab-recognizes-table.el
2407 (if (org-at-table.el-p)
2408 (progn
2409 (beginning-of-line 1)
2410 (if (looking-at org-table-dataline-regexp)
2412 (if (looking-at org-table1-hline-regexp)
2413 (progn
2414 (beginning-of-line 2)
2415 (if (looking-at org-table-any-border-regexp)
2416 (beginning-of-line -1)))))
2417 (if (re-search-forward "|" (org-table-end t) t)
2418 (progn
2419 (require 'table)
2420 (if (table--at-cell-p (point))
2422 (message "recognizing table.el table...")
2423 (table-recognize-table)
2424 (message "recognizing table.el table...done")))
2425 (error "This should not happen..."))
2427 nil)
2428 nil))
2430 (defun org-at-table-hline-p ()
2431 "Return t if the cursor is inside a hline in a table."
2432 (if org-enable-table-editor
2433 (save-excursion
2434 (beginning-of-line 1)
2435 (looking-at org-table-hline-regexp))
2436 nil))
2438 (defvar org-table-clean-did-remove-column nil)
2440 (defun org-table-map-tables (function)
2441 "Apply FUNCTION to the start of all tables in the buffer."
2442 (save-excursion
2443 (save-restriction
2444 (widen)
2445 (goto-char (point-min))
2446 (while (re-search-forward org-table-any-line-regexp nil t)
2447 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2448 (beginning-of-line 1)
2449 (if (looking-at org-table-line-regexp)
2450 (save-excursion (funcall function)))
2451 (re-search-forward org-table-any-border-regexp nil 1))))
2452 (message "Mapping tables: done"))
2454 ;; Declare and autoload functions from org-exp.el
2456 (declare-function org-default-export-plist "org-exp")
2457 (declare-function org-infile-export-plist "org-exp")
2458 (declare-function org-get-current-options "org-exp")
2459 (eval-and-compile
2460 (org-autoload "org-exp"
2461 '(org-export org-export-as-ascii org-export-visible
2462 org-insert-export-options-template org-export-as-html-and-open
2463 org-export-as-html-batch org-export-as-html-to-buffer
2464 org-replace-region-by-html org-export-region-as-html
2465 org-export-as-html org-export-icalendar-this-file
2466 org-export-icalendar-all-agenda-files
2467 org-table-clean-before-export
2468 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2470 ;; Declare and autoload functions from org-exp.el
2472 (eval-and-compile
2473 (org-autoload "org-exp"
2474 '(org-agenda org-agenda-list org-search-view
2475 org-todo-list org-tags-view org-agenda-list-stuck-projects
2476 org-diary org-agenda-to-appt)))
2478 ;; Autoload org-remember
2480 (eval-and-compile
2481 (org-autoload "org-remember"
2482 '(org-remember-insinuate org-remember-annotation
2483 org-remember-apply-template org-remember org-remember-handler)))
2485 ;; Autoload org-clock.el
2488 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2489 (beg end))
2490 (declare-function org-update-mode-line "org-clock" ())
2491 (defvar org-clock-start-time)
2492 (defvar org-clock-marker (make-marker)
2493 "Marker recording the last clock-in.")
2495 (eval-and-compile
2496 (org-autoload
2497 "org-clock"
2498 '(org-clock-in org-clock-out org-clock-cancel
2499 org-clock-goto org-clock-sum org-clock-display
2500 org-remove-clock-overlays org-clock-report
2501 org-clocktable-shift org-dblock-write:clocktable
2502 org-get-clocktable)))
2504 (defun org-clock-update-time-maybe ()
2505 "If this is a CLOCK line, update it and return t.
2506 Otherwise, return nil."
2507 (interactive)
2508 (save-excursion
2509 (beginning-of-line 1)
2510 (skip-chars-forward " \t")
2511 (when (looking-at org-clock-string)
2512 (let ((re (concat "[ \t]*" org-clock-string
2513 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2514 "\\([ \t]*=>.*\\)?\\)?"))
2515 ts te h m s)
2516 (cond
2517 ((not (looking-at re))
2518 nil)
2519 ((not (match-end 2))
2520 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2521 (> org-clock-marker (point))
2522 (<= org-clock-marker (point-at-eol)))
2523 ;; The clock is running here
2524 (setq org-clock-start-time
2525 (apply 'encode-time
2526 (org-parse-time-string (match-string 1))))
2527 (org-update-mode-line)))
2529 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2530 (end-of-line 1)
2531 (setq ts (match-string 1)
2532 te (match-string 3))
2533 (setq s (- (time-to-seconds
2534 (apply 'encode-time (org-parse-time-string te)))
2535 (time-to-seconds
2536 (apply 'encode-time (org-parse-time-string ts))))
2537 h (floor (/ s 3600))
2538 s (- s (* 3600 h))
2539 m (floor (/ s 60))
2540 s (- s (* 60 s)))
2541 (insert " => " (format "%2d:%02d" h m))
2542 t))))))
2544 (defun org-check-running-clock ()
2545 "Check if the current buffer contains the running clock.
2546 If yes, offer to stop it and to save the buffer with the changes."
2547 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2548 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2549 (buffer-name))))
2550 (org-clock-out)
2551 (when (y-or-n-p "Save changed buffer?")
2552 (save-buffer))))
2554 (defun org-clocktable-try-shift (dir n)
2555 "Check if this line starts a clock table, if yes, shift the time block."
2556 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2557 (org-clocktable-shift dir n)))
2559 ;; Autoload archiving code
2560 ;; The stuff that is needed for cycling and tags has to be defined here.
2562 (defgroup org-archive nil
2563 "Options concerning archiving in Org-mode."
2564 :tag "Org Archive"
2565 :group 'org-structure)
2567 (defcustom org-archive-location "%s_archive::"
2568 "The location where subtrees should be archived.
2570 Otherwise, the value of this variable is a string, consisting of two
2571 parts, separated by a double-colon.
2573 The first part is a file name - when omitted, archiving happens in the same
2574 file. %s will be replaced by the current file name (without directory part).
2575 Archiving to a different file is useful to keep archived entries from
2576 contributing to the Org-mode Agenda.
2578 The part after the double colon is a headline. The archived entries will be
2579 filed under that headline. When omitted, the subtrees are simply filed away
2580 at the end of the file, as top-level entries.
2582 Here are a few examples:
2583 \"%s_archive::\"
2584 If the current file is Projects.org, archive in file
2585 Projects.org_archive, as top-level trees. This is the default.
2587 \"::* Archived Tasks\"
2588 Archive in the current file, under the top-level headline
2589 \"* Archived Tasks\".
2591 \"~/org/archive.org::\"
2592 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2594 \"basement::** Finished Tasks\"
2595 Archive in file ./basement (relative path), as level 3 trees
2596 below the level 2 heading \"** Finished Tasks\".
2598 You may set this option on a per-file basis by adding to the buffer a
2599 line like
2601 #+ARCHIVE: basement::** Finished Tasks
2603 You may also define it locally for a subtree by setting an ARCHIVE property
2604 in the entry. If such a property is found in an entry, or anywhere up
2605 the hierarchy, it will be used."
2606 :group 'org-archive
2607 :type 'string)
2609 (defcustom org-archive-tag "ARCHIVE"
2610 "The tag that marks a subtree as archived.
2611 An archived subtree does not open during visibility cycling, and does
2612 not contribute to the agenda listings.
2613 After changing this, font-lock must be restarted in the relevant buffers to
2614 get the proper fontification."
2615 :group 'org-archive
2616 :group 'org-keywords
2617 :type 'string)
2619 (defcustom org-agenda-skip-archived-trees t
2620 "Non-nil means, the agenda will skip any items located in archived trees.
2621 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2622 variable is no longer recommended, you should leave it at the value t.
2623 Instead, use the key `v' to cycle the archives-mode in the agenda."
2624 :group 'org-archive
2625 :group 'org-agenda-skip
2626 :type 'boolean)
2628 (defcustom org-cycle-open-archived-trees nil
2629 "Non-nil means, `org-cycle' will open archived trees.
2630 An archived tree is a tree marked with the tag ARCHIVE.
2631 When nil, archived trees will stay folded. You can still open them with
2632 normal outline commands like `show-all', but not with the cycling commands."
2633 :group 'org-archive
2634 :group 'org-cycle
2635 :type 'boolean)
2637 (defcustom org-sparse-tree-open-archived-trees nil
2638 "Non-nil means sparse tree construction shows matches in archived trees.
2639 When nil, matches in these trees are highlighted, but the trees are kept in
2640 collapsed state."
2641 :group 'org-archive
2642 :group 'org-sparse-trees
2643 :type 'boolean)
2645 (defun org-cycle-hide-archived-subtrees (state)
2646 "Re-hide all archived subtrees after a visibility state change."
2647 (when (and (not org-cycle-open-archived-trees)
2648 (not (memq state '(overview folded))))
2649 (save-excursion
2650 (let* ((globalp (memq state '(contents all)))
2651 (beg (if globalp (point-min) (point)))
2652 (end (if globalp (point-max) (org-end-of-subtree t))))
2653 (org-hide-archived-subtrees beg end)
2654 (goto-char beg)
2655 (if (looking-at (concat ".*:" org-archive-tag ":"))
2656 (message "%s" (substitute-command-keys
2657 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2659 (defun org-force-cycle-archived ()
2660 "Cycle subtree even if it is archived."
2661 (interactive)
2662 (setq this-command 'org-cycle)
2663 (let ((org-cycle-open-archived-trees t))
2664 (call-interactively 'org-cycle)))
2666 (defun org-hide-archived-subtrees (beg end)
2667 "Re-hide all archived subtrees after a visibility state change."
2668 (save-excursion
2669 (let* ((re (concat ":" org-archive-tag ":")))
2670 (goto-char beg)
2671 (while (re-search-forward re end t)
2672 (and (org-on-heading-p) (hide-subtree))
2673 (org-end-of-subtree t)))))
2675 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2677 (eval-and-compile
2678 (org-autoload "org-archive"
2679 '(org-add-archive-files org-archive-subtree
2680 org-archive-to-archive-sibling org-toggle-archive-tag)))
2682 ;; Autoload Column View Code
2684 (declare-function org-columns-number-to-string "org-colview")
2685 (declare-function org-columns-get-format-and-top-level "org-colview")
2686 (declare-function org-columns-compute "org-colview")
2688 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2689 '(org-columns-number-to-string org-columns-get-format-and-top-level
2690 org-columns-compute org-agenda-columns org-columns-remove-overlays
2691 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2693 ;; Autoload ID code
2695 (org-autoload "org-id"
2696 '(org-id-get-create org-id-new org-id-copy org-id-get
2697 org-id-get-with-outline-path-completion
2698 org-id-get-with-outline-drilling
2699 org-id-goto org-id-find))
2701 ;;; Variables for pre-computed regular expressions, all buffer local
2703 (defvar org-drawer-regexp nil
2704 "Matches first line of a hidden block.")
2705 (make-variable-buffer-local 'org-drawer-regexp)
2706 (defvar org-todo-regexp nil
2707 "Matches any of the TODO state keywords.")
2708 (make-variable-buffer-local 'org-todo-regexp)
2709 (defvar org-not-done-regexp nil
2710 "Matches any of the TODO state keywords except the last one.")
2711 (make-variable-buffer-local 'org-not-done-regexp)
2712 (defvar org-todo-line-regexp nil
2713 "Matches a headline and puts TODO state into group 2 if present.")
2714 (make-variable-buffer-local 'org-todo-line-regexp)
2715 (defvar org-complex-heading-regexp nil
2716 "Matches a headline and puts everything into groups:
2717 group 1: the stars
2718 group 2: The todo keyword, maybe
2719 group 3: Priority cookie
2720 group 4: True headline
2721 group 5: Tags")
2722 (make-variable-buffer-local 'org-complex-heading-regexp)
2723 (defvar org-todo-line-tags-regexp nil
2724 "Matches a headline and puts TODO state into group 2 if present.
2725 Also put tags into group 4 if tags are present.")
2726 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2727 (defvar org-nl-done-regexp nil
2728 "Matches newline followed by a headline with the DONE keyword.")
2729 (make-variable-buffer-local 'org-nl-done-regexp)
2730 (defvar org-looking-at-done-regexp nil
2731 "Matches the DONE keyword a point.")
2732 (make-variable-buffer-local 'org-looking-at-done-regexp)
2733 (defvar org-ds-keyword-length 12
2734 "Maximum length of the Deadline and SCHEDULED keywords.")
2735 (make-variable-buffer-local 'org-ds-keyword-length)
2736 (defvar org-deadline-regexp nil
2737 "Matches the DEADLINE keyword.")
2738 (make-variable-buffer-local 'org-deadline-regexp)
2739 (defvar org-deadline-time-regexp nil
2740 "Matches the DEADLINE keyword together with a time stamp.")
2741 (make-variable-buffer-local 'org-deadline-time-regexp)
2742 (defvar org-deadline-line-regexp nil
2743 "Matches the DEADLINE keyword and the rest of the line.")
2744 (make-variable-buffer-local 'org-deadline-line-regexp)
2745 (defvar org-scheduled-regexp nil
2746 "Matches the SCHEDULED keyword.")
2747 (make-variable-buffer-local 'org-scheduled-regexp)
2748 (defvar org-scheduled-time-regexp nil
2749 "Matches the SCHEDULED keyword together with a time stamp.")
2750 (make-variable-buffer-local 'org-scheduled-time-regexp)
2751 (defvar org-closed-time-regexp nil
2752 "Matches the CLOSED keyword together with a time stamp.")
2753 (make-variable-buffer-local 'org-closed-time-regexp)
2755 (defvar org-keyword-time-regexp nil
2756 "Matches any of the 4 keywords, together with the time stamp.")
2757 (make-variable-buffer-local 'org-keyword-time-regexp)
2758 (defvar org-keyword-time-not-clock-regexp nil
2759 "Matches any of the 3 keywords, together with the time stamp.")
2760 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2761 (defvar org-maybe-keyword-time-regexp nil
2762 "Matches a timestamp, possibly preceeded by a keyword.")
2763 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2764 (defvar org-planning-or-clock-line-re nil
2765 "Matches a line with planning or clock info.")
2766 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2768 (defconst org-plain-time-of-day-regexp
2769 (concat
2770 "\\(\\<[012]?[0-9]"
2771 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2772 "\\(--?"
2773 "\\(\\<[012]?[0-9]"
2774 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2775 "\\)?")
2776 "Regular expression to match a plain time or time range.
2777 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2778 groups carry important information:
2779 0 the full match
2780 1 the first time, range or not
2781 8 the second time, if it is a range.")
2783 (defconst org-plain-time-extension-regexp
2784 (concat
2785 "\\(\\<[012]?[0-9]"
2786 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2787 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2788 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2789 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2790 groups carry important information:
2791 0 the full match
2792 7 hours of duration
2793 9 minutes of duration")
2795 (defconst org-stamp-time-of-day-regexp
2796 (concat
2797 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2798 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2799 "\\(--?"
2800 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2801 "Regular expression to match a timestamp time or time range.
2802 After a match, the following groups carry important information:
2803 0 the full match
2804 1 date plus weekday, for backreferencing to make sure both times on same day
2805 2 the first time, range or not
2806 4 the second time, if it is a range.")
2808 (defconst org-startup-options
2809 '(("fold" org-startup-folded t)
2810 ("overview" org-startup-folded t)
2811 ("nofold" org-startup-folded nil)
2812 ("showall" org-startup-folded nil)
2813 ("content" org-startup-folded content)
2814 ("hidestars" org-hide-leading-stars t)
2815 ("showstars" org-hide-leading-stars nil)
2816 ("odd" org-odd-levels-only t)
2817 ("oddeven" org-odd-levels-only nil)
2818 ("align" org-startup-align-all-tables t)
2819 ("noalign" org-startup-align-all-tables nil)
2820 ("customtime" org-display-custom-times t)
2821 ("logdone" org-log-done time)
2822 ("lognotedone" org-log-done note)
2823 ("nologdone" org-log-done nil)
2824 ("lognoteclock-out" org-log-note-clock-out t)
2825 ("nolognoteclock-out" org-log-note-clock-out nil)
2826 ("logrepeat" org-log-repeat state)
2827 ("lognoterepeat" org-log-repeat note)
2828 ("nologrepeat" org-log-repeat nil)
2829 ("constcgs" constants-unit-system cgs)
2830 ("constSI" constants-unit-system SI))
2831 "Variable associated with STARTUP options for org-mode.
2832 Each element is a list of three items: The startup options as written
2833 in the #+STARTUP line, the corresponding variable, and the value to
2834 set this variable to if the option is found. An optional forth element PUSH
2835 means to push this value onto the list in the variable.")
2837 (defun org-set-regexps-and-options ()
2838 "Precompute regular expressions for current buffer."
2839 (when (org-mode-p)
2840 (org-set-local 'org-todo-kwd-alist nil)
2841 (org-set-local 'org-todo-key-alist nil)
2842 (org-set-local 'org-todo-key-trigger nil)
2843 (org-set-local 'org-todo-keywords-1 nil)
2844 (org-set-local 'org-done-keywords nil)
2845 (org-set-local 'org-todo-heads nil)
2846 (org-set-local 'org-todo-sets nil)
2847 (org-set-local 'org-todo-log-states nil)
2848 (org-set-local 'org-file-properties nil)
2849 (org-set-local 'org-file-tags nil)
2850 (let ((re (org-make-options-regexp
2851 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2852 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2853 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2854 (splitre "[ \t]+")
2855 kwds kws0 kwsa key log value cat arch tags const links hw dws
2856 tail sep kws1 prio props ftags drawers
2857 ext-setup-or-nil setup-contents (start 0))
2858 (save-excursion
2859 (save-restriction
2860 (widen)
2861 (goto-char (point-min))
2862 (while (or (and ext-setup-or-nil
2863 (string-match re ext-setup-or-nil start)
2864 (setq start (match-end 0)))
2865 (and (setq ext-setup-or-nil nil start 0)
2866 (re-search-forward re nil t)))
2867 (setq key (upcase (match-string 1 ext-setup-or-nil))
2868 value (org-match-string-no-properties 2 ext-setup-or-nil))
2869 (cond
2870 ((equal key "CATEGORY")
2871 (if (string-match "[ \t]+$" value)
2872 (setq value (replace-match "" t t value)))
2873 (setq cat value))
2874 ((member key '("SEQ_TODO" "TODO"))
2875 (push (cons 'sequence (org-split-string value splitre)) kwds))
2876 ((equal key "TYP_TODO")
2877 (push (cons 'type (org-split-string value splitre)) kwds))
2878 ((equal key "TAGS")
2879 (setq tags (append tags (org-split-string value splitre))))
2880 ((equal key "COLUMNS")
2881 (org-set-local 'org-columns-default-format value))
2882 ((equal key "LINK")
2883 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2884 (push (cons (match-string 1 value)
2885 (org-trim (match-string 2 value)))
2886 links)))
2887 ((equal key "PRIORITIES")
2888 (setq prio (org-split-string value " +")))
2889 ((equal key "PROPERTY")
2890 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2891 (push (cons (match-string 1 value) (match-string 2 value))
2892 props)))
2893 ((equal key "FILETAGS")
2894 (when (string-match "\\S-" value)
2895 (setq ftags
2896 (append
2897 ftags
2898 (apply 'append
2899 (mapcar (lambda (x) (org-split-string x ":"))
2900 (org-split-string value)))))))
2901 ((equal key "DRAWERS")
2902 (setq drawers (org-split-string value splitre)))
2903 ((equal key "CONSTANTS")
2904 (setq const (append const (org-split-string value splitre))))
2905 ((equal key "STARTUP")
2906 (let ((opts (org-split-string value splitre))
2907 l var val)
2908 (while (setq l (pop opts))
2909 (when (setq l (assoc l org-startup-options))
2910 (setq var (nth 1 l) val (nth 2 l))
2911 (if (not (nth 3 l))
2912 (set (make-local-variable var) val)
2913 (if (not (listp (symbol-value var)))
2914 (set (make-local-variable var) nil))
2915 (set (make-local-variable var) (symbol-value var))
2916 (add-to-list var val))))))
2917 ((equal key "ARCHIVE")
2918 (string-match " *$" value)
2919 (setq arch (replace-match "" t t value))
2920 (remove-text-properties 0 (length arch)
2921 '(face t fontified t) arch))
2922 ((equal key "SETUPFILE")
2923 (setq setup-contents (org-file-contents
2924 (expand-file-name
2925 (org-remove-double-quotes value))
2926 'noerror))
2927 (if (not ext-setup-or-nil)
2928 (setq ext-setup-or-nil setup-contents start 0)
2929 (setq ext-setup-or-nil
2930 (concat (substring ext-setup-or-nil 0 start)
2931 "\n" setup-contents "\n"
2932 (substring ext-setup-or-nil start)))))
2933 ))))
2934 (when cat
2935 (org-set-local 'org-category (intern cat))
2936 (push (cons "CATEGORY" cat) props))
2937 (when prio
2938 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2939 (setq prio (mapcar 'string-to-char prio))
2940 (org-set-local 'org-highest-priority (nth 0 prio))
2941 (org-set-local 'org-lowest-priority (nth 1 prio))
2942 (org-set-local 'org-default-priority (nth 2 prio)))
2943 (and props (org-set-local 'org-file-properties (nreverse props)))
2944 (and ftags (org-set-local 'org-file-tags ftags))
2945 (and drawers (org-set-local 'org-drawers drawers))
2946 (and arch (org-set-local 'org-archive-location arch))
2947 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2948 ;; Process the TODO keywords
2949 (unless kwds
2950 ;; Use the global values as if they had been given locally.
2951 (setq kwds (default-value 'org-todo-keywords))
2952 (if (stringp (car kwds))
2953 (setq kwds (list (cons org-todo-interpretation
2954 (default-value 'org-todo-keywords)))))
2955 (setq kwds (reverse kwds)))
2956 (setq kwds (nreverse kwds))
2957 (let (inter kws kw)
2958 (while (setq kws (pop kwds))
2959 (setq inter (pop kws) sep (member "|" kws)
2960 kws0 (delete "|" (copy-sequence kws))
2961 kwsa nil
2962 kws1 (mapcar
2963 (lambda (x)
2964 ;; 1 2
2965 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2966 (progn
2967 (setq kw (match-string 1 x)
2968 key (and (match-end 2) (match-string 2 x))
2969 log (org-extract-log-state-settings x))
2970 (push (cons kw (and key (string-to-char key))) kwsa)
2971 (and log (push log org-todo-log-states))
2973 (error "Invalid TODO keyword %s" x)))
2974 kws0)
2975 kwsa (if kwsa (append '((:startgroup))
2976 (nreverse kwsa)
2977 '((:endgroup))))
2978 hw (car kws1)
2979 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2980 tail (list inter hw (car dws) (org-last dws)))
2981 (add-to-list 'org-todo-heads hw 'append)
2982 (push kws1 org-todo-sets)
2983 (setq org-done-keywords (append org-done-keywords dws nil))
2984 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2985 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2986 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2987 (setq org-todo-sets (nreverse org-todo-sets)
2988 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2989 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2990 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2991 ;; Process the constants
2992 (when const
2993 (let (e cst)
2994 (while (setq e (pop const))
2995 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2996 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2997 (setq org-table-formula-constants-local cst)))
2999 ;; Process the tags.
3000 (when tags
3001 (let (e tgs)
3002 (while (setq e (pop tags))
3003 (cond
3004 ((equal e "{") (push '(:startgroup) tgs))
3005 ((equal e "}") (push '(:endgroup) tgs))
3006 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3007 (push (cons (match-string 1 e)
3008 (string-to-char (match-string 2 e)))
3009 tgs))
3010 (t (push (list e) tgs))))
3011 (org-set-local 'org-tag-alist nil)
3012 (while (setq e (pop tgs))
3013 (or (and (stringp (car e))
3014 (assoc (car e) org-tag-alist))
3015 (push e org-tag-alist)))))
3017 ;; Compute the regular expressions and other local variables
3018 (if (not org-done-keywords)
3019 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3020 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3021 (length org-scheduled-string)
3022 (length org-clock-string)
3023 (length org-closed-string)))
3024 org-drawer-regexp
3025 (concat "^[ \t]*:\\("
3026 (mapconcat 'regexp-quote org-drawers "\\|")
3027 "\\):[ \t]*$")
3028 org-not-done-keywords
3029 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3030 org-todo-regexp
3031 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3032 "\\|") "\\)\\>")
3033 org-not-done-regexp
3034 (concat "\\<\\("
3035 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3036 "\\)\\>")
3037 org-todo-line-regexp
3038 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3039 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3040 "\\)\\>\\)?[ \t]*\\(.*\\)")
3041 org-complex-heading-regexp
3042 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3043 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3044 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3045 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3046 org-nl-done-regexp
3047 (concat "\n\\*+[ \t]+"
3048 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3049 "\\)" "\\>")
3050 org-todo-line-tags-regexp
3051 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3052 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3053 (org-re
3054 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3055 org-looking-at-done-regexp
3056 (concat "^" "\\(?:"
3057 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3058 "\\>")
3059 org-deadline-regexp (concat "\\<" org-deadline-string)
3060 org-deadline-time-regexp
3061 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3062 org-deadline-line-regexp
3063 (concat "\\<\\(" org-deadline-string "\\).*")
3064 org-scheduled-regexp
3065 (concat "\\<" org-scheduled-string)
3066 org-scheduled-time-regexp
3067 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3068 org-closed-time-regexp
3069 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3070 org-keyword-time-regexp
3071 (concat "\\<\\(" org-scheduled-string
3072 "\\|" org-deadline-string
3073 "\\|" org-closed-string
3074 "\\|" org-clock-string "\\)"
3075 " *[[<]\\([^]>]+\\)[]>]")
3076 org-keyword-time-not-clock-regexp
3077 (concat "\\<\\(" org-scheduled-string
3078 "\\|" org-deadline-string
3079 "\\|" org-closed-string
3080 "\\)"
3081 " *[[<]\\([^]>]+\\)[]>]")
3082 org-maybe-keyword-time-regexp
3083 (concat "\\(\\<\\(" org-scheduled-string
3084 "\\|" org-deadline-string
3085 "\\|" org-closed-string
3086 "\\|" org-clock-string "\\)\\)?"
3087 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3088 org-planning-or-clock-line-re
3089 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3090 "\\|" org-deadline-string
3091 "\\|" org-closed-string "\\|" org-clock-string
3092 "\\)\\>\\)")
3094 (org-compute-latex-and-specials-regexp)
3095 (org-set-font-lock-defaults))))
3097 (defun org-file-contents (file &optional noerror)
3098 "Return the contents of FILE, as a string."
3099 (if (or (not file)
3100 (not (file-readable-p file)))
3101 (if noerror
3102 (progn
3103 (message "Cannot read file %s" file)
3104 (ding) (sit-for 2)
3106 (error "Cannot read file %s" file))
3107 (with-temp-buffer
3108 (insert-file-contents file)
3109 (buffer-string))))
3111 (defun org-extract-log-state-settings (x)
3112 "Extract the log state setting from a TODO keyword string.
3113 This will extract info from a string like \"WAIT(w@/!)\"."
3114 (let (kw key log1 log2)
3115 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3116 (setq kw (match-string 1 x)
3117 key (and (match-end 2) (match-string 2 x))
3118 log1 (and (match-end 3) (match-string 3 x))
3119 log2 (and (match-end 4) (match-string 4 x)))
3120 (and (or log1 log2)
3121 (list kw
3122 (and log1 (if (equal log1 "!") 'time 'note))
3123 (and log2 (if (equal log2 "!") 'time 'note)))))))
3125 (defun org-remove-keyword-keys (list)
3126 "Remove a pair of parenthesis at the end of each string in LIST."
3127 (mapcar (lambda (x)
3128 (if (string-match "(.*)$" x)
3129 (substring x 0 (match-beginning 0))
3131 list))
3133 ;; FIXME: this could be done much better, using second characters etc.
3134 (defun org-assign-fast-keys (alist)
3135 "Assign fast keys to a keyword-key alist.
3136 Respect keys that are already there."
3137 (let (new e k c c1 c2 (char ?a))
3138 (while (setq e (pop alist))
3139 (cond
3140 ((equal e '(:startgroup)) (push e new))
3141 ((equal e '(:endgroup)) (push e new))
3143 (setq k (car e) c2 nil)
3144 (if (cdr e)
3145 (setq c (cdr e))
3146 ;; automatically assign a character.
3147 (setq c1 (string-to-char
3148 (downcase (substring
3149 k (if (= (string-to-char k) ?@) 1 0)))))
3150 (if (or (rassoc c1 new) (rassoc c1 alist))
3151 (while (or (rassoc char new) (rassoc char alist))
3152 (setq char (1+ char)))
3153 (setq c2 c1))
3154 (setq c (or c2 char)))
3155 (push (cons k c) new))))
3156 (nreverse new)))
3158 ;;; Some variables used in various places
3160 (defvar org-window-configuration nil
3161 "Used in various places to store a window configuration.")
3162 (defvar org-finish-function nil
3163 "Function to be called when `C-c C-c' is used.
3164 This is for getting out of special buffers like remember.")
3167 ;; FIXME: Occasionally check by commenting these, to make sure
3168 ;; no other functions uses these, forgetting to let-bind them.
3169 (defvar entry)
3170 (defvar state)
3171 (defvar last-state)
3172 (defvar date)
3173 (defvar description)
3175 ;; Defined somewhere in this file, but used before definition.
3176 (defvar org-html-entities)
3177 (defvar org-struct-menu)
3178 (defvar org-org-menu)
3179 (defvar org-tbl-menu)
3180 (defvar org-agenda-keymap)
3182 ;;;; Define the Org-mode
3184 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3185 (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."))
3188 ;; We use a before-change function to check if a table might need
3189 ;; an update.
3190 (defvar org-table-may-need-update t
3191 "Indicates that a table might need an update.
3192 This variable is set by `org-before-change-function'.
3193 `org-table-align' sets it back to nil.")
3194 (defun org-before-change-function (beg end)
3195 "Every change indicates that a table might need an update."
3196 (setq org-table-may-need-update t))
3197 (defvar org-mode-map)
3198 (defvar org-mode-hook nil)
3199 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3200 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3201 (defvar org-table-buffer-is-an nil)
3202 (defconst org-outline-regexp "\\*+ ")
3204 ;;;###autoload
3205 (define-derived-mode org-mode outline-mode "Org"
3206 "Outline-based notes management and organizer, alias
3207 \"Carsten's outline-mode for keeping track of everything.\"
3209 Org-mode develops organizational tasks around a NOTES file which
3210 contains information about projects as plain text. Org-mode is
3211 implemented on top of outline-mode, which is ideal to keep the content
3212 of large files well structured. It supports ToDo items, deadlines and
3213 time stamps, which magically appear in the diary listing of the Emacs
3214 calendar. Tables are easily created with a built-in table editor.
3215 Plain text URL-like links connect to websites, emails (VM), Usenet
3216 messages (Gnus), BBDB entries, and any files related to the project.
3217 For printing and sharing of notes, an Org-mode file (or a part of it)
3218 can be exported as a structured ASCII or HTML file.
3220 The following commands are available:
3222 \\{org-mode-map}"
3224 ;; Get rid of Outline menus, they are not needed
3225 ;; Need to do this here because define-derived-mode sets up
3226 ;; the keymap so late. Still, it is a waste to call this each time
3227 ;; we switch another buffer into org-mode.
3228 (if (featurep 'xemacs)
3229 (when (boundp 'outline-mode-menu-heading)
3230 ;; Assume this is Greg's port, it used easymenu
3231 (easy-menu-remove outline-mode-menu-heading)
3232 (easy-menu-remove outline-mode-menu-show)
3233 (easy-menu-remove outline-mode-menu-hide))
3234 (define-key org-mode-map [menu-bar headings] 'undefined)
3235 (define-key org-mode-map [menu-bar hide] 'undefined)
3236 (define-key org-mode-map [menu-bar show] 'undefined))
3238 (org-load-modules-maybe)
3239 (easy-menu-add org-org-menu)
3240 (easy-menu-add org-tbl-menu)
3241 (org-install-agenda-files-menu)
3242 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3243 (org-add-to-invisibility-spec '(org-cwidth))
3244 (when (featurep 'xemacs)
3245 (org-set-local 'line-move-ignore-invisible t))
3246 (org-set-local 'outline-regexp org-outline-regexp)
3247 (org-set-local 'outline-level 'org-outline-level)
3248 (when (and org-ellipsis
3249 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3250 (fboundp 'make-glyph-code))
3251 (unless org-display-table
3252 (setq org-display-table (make-display-table)))
3253 (set-display-table-slot
3254 org-display-table 4
3255 (vconcat (mapcar
3256 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3257 org-ellipsis)))
3258 (if (stringp org-ellipsis) org-ellipsis "..."))))
3259 (setq buffer-display-table org-display-table))
3260 (org-set-regexps-and-options)
3261 ;; Calc embedded
3262 (org-set-local 'calc-embedded-open-mode "# ")
3263 (modify-syntax-entry ?# "<")
3264 (modify-syntax-entry ?@ "w")
3265 (if org-startup-truncated (setq truncate-lines t))
3266 (org-set-local 'font-lock-unfontify-region-function
3267 'org-unfontify-region)
3268 ;; Activate before-change-function
3269 (org-set-local 'org-table-may-need-update t)
3270 (org-add-hook 'before-change-functions 'org-before-change-function nil
3271 'local)
3272 ;; Check for running clock before killing a buffer
3273 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3274 ;; Paragraphs and auto-filling
3275 (org-set-autofill-regexps)
3276 (setq indent-line-function 'org-indent-line-function)
3277 (org-update-radio-target-regexp)
3279 ;; Comment characters
3280 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3281 (org-set-local 'comment-padding " ")
3283 ;; Align options lines
3284 (org-set-local
3285 'align-mode-rules-list
3286 '((org-in-buffer-settings
3287 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3288 (modes . '(org-mode)))))
3290 ;; Imenu
3291 (org-set-local 'imenu-create-index-function
3292 'org-imenu-get-tree)
3294 ;; Make isearch reveal context
3295 (if (or (featurep 'xemacs)
3296 (not (boundp 'outline-isearch-open-invisible-function)))
3297 ;; Emacs 21 and XEmacs make use of the hook
3298 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3299 ;; Emacs 22 deals with this through a special variable
3300 (org-set-local 'outline-isearch-open-invisible-function
3301 (lambda (&rest ignore) (org-show-context 'isearch))))
3303 ;; If empty file that did not turn on org-mode automatically, make it to.
3304 (if (and org-insert-mode-line-in-empty-file
3305 (interactive-p)
3306 (= (point-min) (point-max)))
3307 (insert "# -*- mode: org -*-\n\n"))
3309 (unless org-inhibit-startup
3310 (when org-startup-align-all-tables
3311 (let ((bmp (buffer-modified-p)))
3312 (org-table-map-tables 'org-table-align)
3313 (set-buffer-modified-p bmp)))
3314 (org-set-startup-visibility)))
3316 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3318 (defun org-current-time ()
3319 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3320 (if (> (car org-time-stamp-rounding-minutes) 1)
3321 (let ((r (car org-time-stamp-rounding-minutes))
3322 (time (decode-time)))
3323 (apply 'encode-time
3324 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3325 (nthcdr 2 time))))
3326 (current-time)))
3328 ;;;; Font-Lock stuff, including the activators
3330 (defvar org-mouse-map (make-sparse-keymap))
3331 (org-defkey org-mouse-map
3332 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3333 (org-defkey org-mouse-map
3334 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3335 (when org-mouse-1-follows-link
3336 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3337 (when org-tab-follows-link
3338 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3339 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3340 (when org-return-follows-link
3341 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3342 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3344 (require 'font-lock)
3346 (defconst org-non-link-chars "]\t\n\r<>")
3347 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3348 "shell" "elisp"))
3349 (defvar org-link-types-re nil
3350 "Matches a link that has a url-like prefix like \"http:\"")
3351 (defvar org-link-re-with-space nil
3352 "Matches a link with spaces, optional angular brackets around it.")
3353 (defvar org-link-re-with-space2 nil
3354 "Matches a link with spaces, optional angular brackets around it.")
3355 (defvar org-angle-link-re nil
3356 "Matches link with angular brackets, spaces are allowed.")
3357 (defvar org-plain-link-re nil
3358 "Matches plain link, without spaces.")
3359 (defvar org-bracket-link-regexp nil
3360 "Matches a link in double brackets.")
3361 (defvar org-bracket-link-analytic-regexp nil
3362 "Regular expression used to analyze links.
3363 Here is what the match groups contain after a match:
3364 1: http:
3365 2: http
3366 3: path
3367 4: [desc]
3368 5: desc")
3369 (defvar org-any-link-re nil
3370 "Regular expression matching any link.")
3372 (defun org-make-link-regexps ()
3373 "Update the link regular expressions.
3374 This should be called after the variable `org-link-types' has changed."
3375 (setq org-link-types-re
3376 (concat
3377 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3378 org-link-re-with-space
3379 (concat
3380 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3381 "\\([^" org-non-link-chars " ]"
3382 "[^" org-non-link-chars "]*"
3383 "[^" org-non-link-chars " ]\\)>?")
3384 org-link-re-with-space2
3385 (concat
3386 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3387 "\\([^" org-non-link-chars " ]"
3388 "[^]\t\n\r]*"
3389 "[^" org-non-link-chars " ]\\)>?")
3390 org-angle-link-re
3391 (concat
3392 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3393 "\\([^" org-non-link-chars " ]"
3394 "[^" org-non-link-chars "]*"
3395 "\\)>")
3396 org-plain-link-re
3397 (concat
3398 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3399 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3400 org-bracket-link-regexp
3401 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3402 org-bracket-link-analytic-regexp
3403 (concat
3404 "\\[\\["
3405 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3406 "\\([^]]+\\)"
3407 "\\]"
3408 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3409 "\\]")
3410 org-any-link-re
3411 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3412 org-angle-link-re "\\)\\|\\("
3413 org-plain-link-re "\\)")))
3415 (org-make-link-regexps)
3417 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3418 "Regular expression for fast time stamp matching.")
3419 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3420 "Regular expression for fast time stamp matching.")
3421 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3422 "Regular expression matching time strings for analysis.
3423 This one does not require the space after the date, so it can be used
3424 on a string that terminates immediately after the date.")
3425 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3426 "Regular expression matching time strings for analysis.")
3427 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3428 "Regular expression matching time stamps, with groups.")
3429 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3430 "Regular expression matching time stamps (also [..]), with groups.")
3431 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3432 "Regular expression matching a time stamp range.")
3433 (defconst org-tr-regexp-both
3434 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3435 "Regular expression matching a time stamp range.")
3436 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3437 org-ts-regexp "\\)?")
3438 "Regular expression matching a time stamp or time stamp range.")
3439 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3440 org-ts-regexp-both "\\)?")
3441 "Regular expression matching a time stamp or time stamp range.
3442 The time stamps may be either active or inactive.")
3444 (defvar org-emph-face nil)
3446 (defun org-do-emphasis-faces (limit)
3447 "Run through the buffer and add overlays to links."
3448 (let (rtn)
3449 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3450 (if (not (= (char-after (match-beginning 3))
3451 (char-after (match-beginning 4))))
3452 (progn
3453 (setq rtn t)
3454 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3455 'face
3456 (nth 1 (assoc (match-string 3)
3457 org-emphasis-alist)))
3458 (add-text-properties (match-beginning 2) (match-end 2)
3459 '(font-lock-multiline t))
3460 (when org-hide-emphasis-markers
3461 (add-text-properties (match-end 4) (match-beginning 5)
3462 '(invisible org-link))
3463 (add-text-properties (match-beginning 3) (match-end 3)
3464 '(invisible org-link)))))
3465 (backward-char 1))
3466 rtn))
3468 (defun org-emphasize (&optional char)
3469 "Insert or change an emphasis, i.e. a font like bold or italic.
3470 If there is an active region, change that region to a new emphasis.
3471 If there is no region, just insert the marker characters and position
3472 the cursor between them.
3473 CHAR should be either the marker character, or the first character of the
3474 HTML tag associated with that emphasis. If CHAR is a space, the means
3475 to remove the emphasis of the selected region.
3476 If char is not given (for example in an interactive call) it
3477 will be prompted for."
3478 (interactive)
3479 (let ((eal org-emphasis-alist) e det
3480 (erc org-emphasis-regexp-components)
3481 (prompt "")
3482 (string "") beg end move tag c s)
3483 (if (org-region-active-p)
3484 (setq beg (region-beginning) end (region-end)
3485 string (buffer-substring beg end))
3486 (setq move t))
3488 (while (setq e (pop eal))
3489 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3490 c (aref tag 0))
3491 (push (cons c (string-to-char (car e))) det)
3492 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3493 (substring tag 1)))))
3494 (unless char
3495 (message "%s" (concat "Emphasis marker or tag:" prompt))
3496 (setq char (read-char-exclusive)))
3497 (setq char (or (cdr (assoc char det)) char))
3498 (if (equal char ?\ )
3499 (setq s "" move nil)
3500 (unless (assoc (char-to-string char) org-emphasis-alist)
3501 (error "No such emphasis marker: \"%c\"" char))
3502 (setq s (char-to-string char)))
3503 (while (and (> (length string) 1)
3504 (equal (substring string 0 1) (substring string -1))
3505 (assoc (substring string 0 1) org-emphasis-alist))
3506 (setq string (substring string 1 -1)))
3507 (setq string (concat s string s))
3508 (if beg (delete-region beg end))
3509 (unless (or (bolp)
3510 (string-match (concat "[" (nth 0 erc) "\n]")
3511 (char-to-string (char-before (point)))))
3512 (insert " "))
3513 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3514 (char-to-string (char-after (point))))
3515 (insert " ") (backward-char 1))
3516 (insert string)
3517 (and move (backward-char 1))))
3519 (defconst org-nonsticky-props
3520 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3523 (defun org-activate-plain-links (limit)
3524 "Run through the buffer and add overlays to links."
3525 (catch 'exit
3526 (let (f)
3527 (while (re-search-forward org-plain-link-re limit t)
3528 (setq f (get-text-property (match-beginning 0) 'face))
3529 (if (or (eq f 'org-tag)
3530 (and (listp f) (memq 'org-tag f)))
3532 (add-text-properties (match-beginning 0) (match-end 0)
3533 (list 'mouse-face 'highlight
3534 'rear-nonsticky org-nonsticky-props
3535 'keymap org-mouse-map
3537 (throw 'exit t))))))
3539 (defun org-activate-code (limit)
3540 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3541 (progn
3542 (remove-text-properties (match-beginning 0) (match-end 0)
3543 '(display t invisible t intangible t))
3544 t)))
3546 (defun org-activate-angle-links (limit)
3547 "Run through the buffer and add overlays to links."
3548 (if (re-search-forward org-angle-link-re limit t)
3549 (progn
3550 (add-text-properties (match-beginning 0) (match-end 0)
3551 (list 'mouse-face 'highlight
3552 'rear-nonsticky org-nonsticky-props
3553 'keymap org-mouse-map
3555 t)))
3557 (defun org-activate-bracket-links (limit)
3558 "Run through the buffer and add overlays to bracketed links."
3559 (if (re-search-forward org-bracket-link-regexp limit t)
3560 (let* ((help (concat "LINK: "
3561 (org-match-string-no-properties 1)))
3562 ;; FIXME: above we should remove the escapes.
3563 ;; but that requires another match, protecting match data,
3564 ;; a lot of overhead for font-lock.
3565 (ip (org-maybe-intangible
3566 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3567 'keymap org-mouse-map 'mouse-face 'highlight
3568 'font-lock-multiline t 'help-echo help)))
3569 (vp (list 'rear-nonsticky org-nonsticky-props
3570 'keymap org-mouse-map 'mouse-face 'highlight
3571 ' font-lock-multiline t 'help-echo help)))
3572 ;; We need to remove the invisible property here. Table narrowing
3573 ;; may have made some of this invisible.
3574 (remove-text-properties (match-beginning 0) (match-end 0)
3575 '(invisible nil))
3576 (if (match-end 3)
3577 (progn
3578 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3579 (add-text-properties (match-beginning 3) (match-end 3) vp)
3580 (add-text-properties (match-end 3) (match-end 0) ip))
3581 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3582 (add-text-properties (match-beginning 1) (match-end 1) vp)
3583 (add-text-properties (match-end 1) (match-end 0) ip))
3584 t)))
3586 (defun org-activate-dates (limit)
3587 "Run through the buffer and add overlays to dates."
3588 (if (re-search-forward org-tsr-regexp-both limit t)
3589 (progn
3590 (add-text-properties (match-beginning 0) (match-end 0)
3591 (list 'mouse-face 'highlight
3592 'rear-nonsticky org-nonsticky-props
3593 'keymap org-mouse-map))
3594 (when org-display-custom-times
3595 (if (match-end 3)
3596 (org-display-custom-time (match-beginning 3) (match-end 3)))
3597 (org-display-custom-time (match-beginning 1) (match-end 1)))
3598 t)))
3600 (defvar org-target-link-regexp nil
3601 "Regular expression matching radio targets in plain text.")
3602 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3603 "Regular expression matching a link target.")
3604 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3605 "Regular expression matching a radio target.")
3606 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3607 "Regular expression matching any target.")
3609 (defun org-activate-target-links (limit)
3610 "Run through the buffer and add overlays to target matches."
3611 (when org-target-link-regexp
3612 (let ((case-fold-search t))
3613 (if (re-search-forward org-target-link-regexp limit t)
3614 (progn
3615 (add-text-properties (match-beginning 0) (match-end 0)
3616 (list 'mouse-face 'highlight
3617 'rear-nonsticky org-nonsticky-props
3618 'keymap org-mouse-map
3619 'help-echo "Radio target link"
3620 'org-linked-text t))
3621 t)))))
3623 (defun org-update-radio-target-regexp ()
3624 "Find all radio targets in this file and update the regular expression."
3625 (interactive)
3626 (when (memq 'radio org-activate-links)
3627 (setq org-target-link-regexp
3628 (org-make-target-link-regexp (org-all-targets 'radio)))
3629 (org-restart-font-lock)))
3631 (defun org-hide-wide-columns (limit)
3632 (let (s e)
3633 (setq s (text-property-any (point) (or limit (point-max))
3634 'org-cwidth t))
3635 (when s
3636 (setq e (next-single-property-change s 'org-cwidth))
3637 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3638 (goto-char e)
3639 t)))
3641 (defvar org-latex-and-specials-regexp nil
3642 "Regular expression for highlighting export special stuff.")
3643 (defvar org-match-substring-regexp)
3644 (defvar org-match-substring-with-braces-regexp)
3645 (defvar org-export-html-special-string-regexps)
3647 (defun org-compute-latex-and-specials-regexp ()
3648 "Compute regular expression for stuff treated specially by exporters."
3649 (if (not org-highlight-latex-fragments-and-specials)
3650 (org-set-local 'org-latex-and-specials-regexp nil)
3651 (require 'org-exp)
3652 (let*
3653 ((matchers (plist-get org-format-latex-options :matchers))
3654 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3655 org-latex-regexps)))
3656 (options (org-combine-plists (org-default-export-plist)
3657 (org-infile-export-plist)))
3658 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3659 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3660 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3661 (org-export-html-expand (plist-get options :expand-quoted-html))
3662 (org-export-with-special-strings (plist-get options :special-strings))
3663 (re-sub
3664 (cond
3665 ((equal org-export-with-sub-superscripts '{})
3666 (list org-match-substring-with-braces-regexp))
3667 (org-export-with-sub-superscripts
3668 (list org-match-substring-regexp))
3669 (t nil)))
3670 (re-latex
3671 (if org-export-with-LaTeX-fragments
3672 (mapcar (lambda (x) (nth 1 x)) latexs)))
3673 (re-macros
3674 (if org-export-with-TeX-macros
3675 (list (concat "\\\\"
3676 (regexp-opt
3677 (append (mapcar 'car org-html-entities)
3678 (if (boundp 'org-latex-entities)
3679 org-latex-entities nil))
3680 'words))) ; FIXME
3682 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3683 (re-special (if org-export-with-special-strings
3684 (mapcar (lambda (x) (car x))
3685 org-export-html-special-string-regexps)))
3686 (re-rest
3687 (delq nil
3688 (list
3689 (if org-export-html-expand "@<[^>\n]+>")
3690 ))))
3691 (org-set-local
3692 'org-latex-and-specials-regexp
3693 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3694 re-rest) "\\|")))))
3696 (defun org-do-latex-and-special-faces (limit)
3697 "Run through the buffer and add overlays to links."
3698 (when org-latex-and-specials-regexp
3699 (let (rtn d)
3700 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3701 limit t))
3702 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3703 'face))
3704 '(org-code org-verbatim underline)))
3705 (progn
3706 (setq rtn t
3707 d (cond ((member (char-after (1+ (match-beginning 0)))
3708 '(?_ ?^)) 1)
3709 (t 0)))
3710 (font-lock-prepend-text-property
3711 (+ d (match-beginning 0)) (match-end 0)
3712 'face 'org-latex-and-export-specials)
3713 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3714 '(font-lock-multiline t)))))
3715 rtn)))
3717 (defun org-restart-font-lock ()
3718 "Restart font-lock-mode, to force refontification."
3719 (when (and (boundp 'font-lock-mode) font-lock-mode)
3720 (font-lock-mode -1)
3721 (font-lock-mode 1)))
3723 (defun org-all-targets (&optional radio)
3724 "Return a list of all targets in this file.
3725 With optional argument RADIO, only find radio targets."
3726 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3727 rtn)
3728 (save-excursion
3729 (goto-char (point-min))
3730 (while (re-search-forward re nil t)
3731 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3732 rtn)))
3734 (defun org-make-target-link-regexp (targets)
3735 "Make regular expression matching all strings in TARGETS.
3736 The regular expression finds the targets also if there is a line break
3737 between words."
3738 (and targets
3739 (concat
3740 "\\<\\("
3741 (mapconcat
3742 (lambda (x)
3743 (while (string-match " +" x)
3744 (setq x (replace-match "\\s-+" t t x)))
3746 targets
3747 "\\|")
3748 "\\)\\>")))
3750 (defun org-activate-tags (limit)
3751 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3752 (progn
3753 (add-text-properties (match-beginning 1) (match-end 1)
3754 (list 'mouse-face 'highlight
3755 'rear-nonsticky org-nonsticky-props
3756 'keymap org-mouse-map))
3757 t)))
3759 (defun org-outline-level ()
3760 (save-excursion
3761 (looking-at outline-regexp)
3762 (if (match-beginning 1)
3763 (+ (org-get-string-indentation (match-string 1)) 1000)
3764 (1- (- (match-end 0) (match-beginning 0))))))
3766 (defvar org-font-lock-keywords nil)
3768 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3769 "Regular expression matching a property line.")
3771 (defvar org-font-lock-hook nil
3772 "Functions to be called for special font lock stuff.")
3774 (defun org-font-lock-hook (limit)
3775 (run-hook-with-args 'org-font-lock-hook limit))
3777 (defun org-set-font-lock-defaults ()
3778 (let* ((em org-fontify-emphasized-text)
3779 (lk org-activate-links)
3780 (org-font-lock-extra-keywords
3781 (list
3782 ;; Call the hook
3783 '(org-font-lock-hook)
3784 ;; Headlines
3785 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3786 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3787 ;; Table lines
3788 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3789 (1 'org-table t))
3790 ;; Table internals
3791 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3792 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3793 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3794 ;; Drawers
3795 (list org-drawer-regexp '(0 'org-special-keyword t))
3796 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3797 ;; Properties
3798 (list org-property-re
3799 '(1 'org-special-keyword t)
3800 '(3 'org-property-value t))
3801 (if org-format-transports-properties-p
3802 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3803 ;; Links
3804 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3805 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3806 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3807 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3808 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3809 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3810 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3811 '(org-hide-wide-columns (0 nil append))
3812 ;; TODO lines
3813 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3814 '(1 (org-get-todo-face 1) t))
3815 ;; DONE
3816 (if org-fontify-done-headline
3817 (list (concat "^[*]+ +\\<\\("
3818 (mapconcat 'regexp-quote org-done-keywords "\\|")
3819 "\\)\\(.*\\)")
3820 '(2 'org-headline-done t))
3821 nil)
3822 ;; Priorities
3823 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3824 ;; Special keywords
3825 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3826 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3827 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3828 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3829 ;; Emphasis
3830 (if em
3831 (if (featurep 'xemacs)
3832 '(org-do-emphasis-faces (0 nil append))
3833 '(org-do-emphasis-faces)))
3834 ;; Checkboxes
3835 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3836 2 'bold prepend)
3837 (if org-provide-checkbox-statistics
3838 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3839 (0 (org-get-checkbox-statistics-face) t)))
3840 ;; Description list items
3841 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3842 2 'bold prepend)
3843 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3844 '(1 'org-archived prepend))
3845 ;; Specials
3846 '(org-do-latex-and-special-faces)
3847 ;; Code
3848 '(org-activate-code (1 'org-code t))
3849 ;; COMMENT
3850 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3851 "\\|" org-quote-string "\\)\\>")
3852 '(1 'org-special-keyword t))
3853 '("^#.*" (0 'font-lock-comment-face t))
3855 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3856 ;; Now set the full font-lock-keywords
3857 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3858 (org-set-local 'font-lock-defaults
3859 '(org-font-lock-keywords t nil nil backward-paragraph))
3860 (kill-local-variable 'font-lock-keywords) nil))
3862 (defvar org-m nil)
3863 (defvar org-l nil)
3864 (defvar org-f nil)
3865 (defun org-get-level-face (n)
3866 "Get the right face for match N in font-lock matching of healdines."
3867 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3868 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3869 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3870 (cond
3871 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3872 ((eq n 2) org-f)
3873 (t (if org-level-color-stars-only nil org-f))))
3875 (defun org-get-todo-face (kwd)
3876 "Get the right face for a TODO keyword KWD.
3877 If KWD is a number, get the corresponding match group."
3878 (if (numberp kwd) (setq kwd (match-string kwd)))
3879 (or (cdr (assoc kwd org-todo-keyword-faces))
3880 (and (member kwd org-done-keywords) 'org-done)
3881 'org-todo))
3883 (defun org-unfontify-region (beg end &optional maybe_loudly)
3884 "Remove fontification and activation overlays from links."
3885 (font-lock-default-unfontify-region beg end)
3886 (let* ((buffer-undo-list t)
3887 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3888 (inhibit-modification-hooks t)
3889 deactivate-mark buffer-file-name buffer-file-truename)
3890 (remove-text-properties beg end
3891 '(mouse-face t keymap t org-linked-text t
3892 invisible t intangible t))))
3894 ;;;; Visibility cycling, including org-goto and indirect buffer
3896 ;;; Cycling
3898 (defvar org-cycle-global-status nil)
3899 (make-variable-buffer-local 'org-cycle-global-status)
3900 (defvar org-cycle-subtree-status nil)
3901 (make-variable-buffer-local 'org-cycle-subtree-status)
3903 ;;;###autoload
3904 (defun org-cycle (&optional arg)
3905 "Visibility cycling for Org-mode.
3907 - When this function is called with a prefix argument, rotate the entire
3908 buffer through 3 states (global cycling)
3909 1. OVERVIEW: Show only top-level headlines.
3910 2. CONTENTS: Show all headlines of all levels, but no body text.
3911 3. SHOW ALL: Show everything.
3912 When called with two C-c C-u prefixes, switch to the startup visibility,
3913 determined by the variable `org-startup-folded', and by any VISIBILITY
3914 properties in the buffer.
3916 - When point is at the beginning of a headline, rotate the subtree started
3917 by this line through 3 different states (local cycling)
3918 1. FOLDED: Only the main headline is shown.
3919 2. CHILDREN: The main headline and the direct children are shown.
3920 From this state, you can move to one of the children
3921 and zoom in further.
3922 3. SUBTREE: Show the entire subtree, including body text.
3924 - When there is a numeric prefix, go up to a heading with level ARG, do
3925 a `show-subtree' and return to the previous cursor position. If ARG
3926 is negative, go up that many levels.
3928 - When point is not at the beginning of a headline, execute the global
3929 binding for TAB, which is re-indenting the line. See the option
3930 `org-cycle-emulate-tab' for details.
3932 - Special case: if point is at the beginning of the buffer and there is
3933 no headline in line 1, this function will act as if called with prefix arg.
3934 But only if also the variable `org-cycle-global-at-bob' is t."
3935 (interactive "P")
3936 (org-load-modules-maybe)
3937 (let* ((outline-regexp
3938 (if (and (org-mode-p) org-cycle-include-plain-lists)
3939 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3940 outline-regexp))
3941 (bob-special (and org-cycle-global-at-bob (bobp)
3942 (not (looking-at outline-regexp))))
3943 (org-cycle-hook
3944 (if bob-special
3945 (delq 'org-optimize-window-after-visibility-change
3946 (copy-sequence org-cycle-hook))
3947 org-cycle-hook))
3948 (pos (point)))
3950 (if (or bob-special (equal arg '(4)))
3951 ;; special case: use global cycling
3952 (setq arg t))
3954 (cond
3956 ((equal arg '(16))
3957 (org-set-startup-visibility)
3958 (message "Startup visibility, plus VISIBILITY properties."))
3960 ((org-at-table-p 'any)
3961 ;; Enter the table or move to the next field in the table
3962 (or (org-table-recognize-table.el)
3963 (progn
3964 (if arg (org-table-edit-field t)
3965 (org-table-justify-field-maybe)
3966 (call-interactively 'org-table-next-field)))))
3968 ((eq arg t) ;; Global cycling
3970 (cond
3971 ((and (eq last-command this-command)
3972 (eq org-cycle-global-status 'overview))
3973 ;; We just created the overview - now do table of contents
3974 ;; This can be slow in very large buffers, so indicate action
3975 (message "CONTENTS...")
3976 (org-content)
3977 (message "CONTENTS...done")
3978 (setq org-cycle-global-status 'contents)
3979 (run-hook-with-args 'org-cycle-hook 'contents))
3981 ((and (eq last-command this-command)
3982 (eq org-cycle-global-status 'contents))
3983 ;; We just showed the table of contents - now show everything
3984 (show-all)
3985 (message "SHOW ALL")
3986 (setq org-cycle-global-status 'all)
3987 (run-hook-with-args 'org-cycle-hook 'all))
3990 ;; Default action: go to overview
3991 (org-overview)
3992 (message "OVERVIEW")
3993 (setq org-cycle-global-status 'overview)
3994 (run-hook-with-args 'org-cycle-hook 'overview))))
3996 ((and org-drawers org-drawer-regexp
3997 (save-excursion
3998 (beginning-of-line 1)
3999 (looking-at org-drawer-regexp)))
4000 ;; Toggle block visibility
4001 (org-flag-drawer
4002 (not (get-char-property (match-end 0) 'invisible))))
4004 ((integerp arg)
4005 ;; Show-subtree, ARG levels up from here.
4006 (save-excursion
4007 (org-back-to-heading)
4008 (outline-up-heading (if (< arg 0) (- arg)
4009 (- (funcall outline-level) arg)))
4010 (org-show-subtree)))
4012 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4013 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4014 ;; At a heading: rotate between three different views
4015 (org-back-to-heading)
4016 (let ((goal-column 0) eoh eol eos)
4017 ;; First, some boundaries
4018 (save-excursion
4019 (org-back-to-heading)
4020 (save-excursion
4021 (beginning-of-line 2)
4022 (while (and (not (eobp)) ;; this is like `next-line'
4023 (get-char-property (1- (point)) 'invisible))
4024 (beginning-of-line 2)) (setq eol (point)))
4025 (outline-end-of-heading) (setq eoh (point))
4026 (org-end-of-subtree t)
4027 (unless (eobp)
4028 (skip-chars-forward " \t\n")
4029 (beginning-of-line 1) ; in case this is an item
4031 (setq eos (1- (point))))
4032 ;; Find out what to do next and set `this-command'
4033 (cond
4034 ((= eos eoh)
4035 ;; Nothing is hidden behind this heading
4036 (message "EMPTY ENTRY")
4037 (setq org-cycle-subtree-status nil)
4038 (save-excursion
4039 (goto-char eos)
4040 (outline-next-heading)
4041 (if (org-invisible-p) (org-flag-heading nil))))
4042 ((or (>= eol eos)
4043 (not (string-match "\\S-" (buffer-substring eol eos))))
4044 ;; Entire subtree is hidden in one line: open it
4045 (org-show-entry)
4046 (show-children)
4047 (message "CHILDREN")
4048 (save-excursion
4049 (goto-char eos)
4050 (outline-next-heading)
4051 (if (org-invisible-p) (org-flag-heading nil)))
4052 (setq org-cycle-subtree-status 'children)
4053 (run-hook-with-args 'org-cycle-hook 'children))
4054 ((and (eq last-command this-command)
4055 (eq org-cycle-subtree-status 'children))
4056 ;; We just showed the children, now show everything.
4057 (org-show-subtree)
4058 (message "SUBTREE")
4059 (setq org-cycle-subtree-status 'subtree)
4060 (run-hook-with-args 'org-cycle-hook 'subtree))
4062 ;; Default action: hide the subtree.
4063 (hide-subtree)
4064 (message "FOLDED")
4065 (setq org-cycle-subtree-status 'folded)
4066 (run-hook-with-args 'org-cycle-hook 'folded)))))
4068 ;; TAB emulation and template completion
4069 (buffer-read-only (org-back-to-heading))
4071 ((org-try-structure-completion))
4073 ((org-try-cdlatex-tab))
4075 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4076 (or (not (bolp))
4077 (not (looking-at outline-regexp))))
4078 (call-interactively (global-key-binding "\t")))
4080 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4081 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4082 (or (and (eq org-cycle-emulate-tab 'white)
4083 (= (match-end 0) (point-at-eol)))
4084 (and (eq org-cycle-emulate-tab 'whitestart)
4085 (>= (match-end 0) pos))))
4087 (eq org-cycle-emulate-tab t))
4088 (call-interactively (global-key-binding "\t")))
4090 (t (save-excursion
4091 (org-back-to-heading)
4092 (org-cycle))))))
4094 ;;;###autoload
4095 (defun org-global-cycle (&optional arg)
4096 "Cycle the global visibility. For details see `org-cycle'.
4097 With C-u prefix arg, switch to startup visibility.
4098 With a numeric prefix, show all headlines up to that level."
4099 (interactive "P")
4100 (let ((org-cycle-include-plain-lists
4101 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4102 (cond
4103 ((integerp arg)
4104 (show-all)
4105 (hide-sublevels arg)
4106 (setq org-cycle-global-status 'contents))
4107 ((equal arg '(4))
4108 (org-set-startup-visibility)
4109 (message "Startup visibility, plus VISIBILITY properties."))
4111 (org-cycle '(4))))))
4113 (defun org-set-startup-visibility ()
4114 "Set the visibility required by startup options and properties."
4115 (cond
4116 ((eq org-startup-folded t)
4117 (org-cycle '(4)))
4118 ((eq org-startup-folded 'content)
4119 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4120 (org-cycle '(4)) (org-cycle '(4)))))
4121 (org-set-visibility-according-to-property 'no-cleanup)
4122 (org-cycle-hide-archived-subtrees 'all)
4123 (org-cycle-hide-drawers 'all)
4124 (org-cycle-show-empty-lines 'all))
4126 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4127 "Switch subtree visibilities according to :VISIBILITY: property."
4128 (interactive)
4129 (let (state)
4130 (save-excursion
4131 (goto-char (point-min))
4132 (while (re-search-forward
4133 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4134 nil t)
4135 (setq state (match-string 1))
4136 (save-excursion
4137 (org-back-to-heading t)
4138 (hide-subtree)
4139 (org-reveal)
4140 (cond
4141 ((equal state '("fold" "folded"))
4142 (hide-subtree))
4143 ((equal state "children")
4144 (org-show-hidden-entry)
4145 (show-children))
4146 ((equal state "content")
4147 (save-excursion
4148 (save-restriction
4149 (org-narrow-to-subtree)
4150 (org-content))))
4151 ((member state '("all" "showall"))
4152 (show-subtree)))))
4153 (unless no-cleanup
4154 (org-cycle-hide-archived-subtrees 'all)
4155 (org-cycle-hide-drawers 'all)
4156 (org-cycle-show-empty-lines 'all)))))
4158 (defun org-overview ()
4159 "Switch to overview mode, shoing only top-level headlines.
4160 Really, this shows all headlines with level equal or greater than the level
4161 of the first headline in the buffer. This is important, because if the
4162 first headline is not level one, then (hide-sublevels 1) gives confusing
4163 results."
4164 (interactive)
4165 (let ((level (save-excursion
4166 (goto-char (point-min))
4167 (if (re-search-forward (concat "^" outline-regexp) nil t)
4168 (progn
4169 (goto-char (match-beginning 0))
4170 (funcall outline-level))))))
4171 (and level (hide-sublevels level))))
4173 (defun org-content (&optional arg)
4174 "Show all headlines in the buffer, like a table of contents.
4175 With numerical argument N, show content up to level N."
4176 (interactive "P")
4177 (save-excursion
4178 ;; Visit all headings and show their offspring
4179 (and (integerp arg) (org-overview))
4180 (goto-char (point-max))
4181 (catch 'exit
4182 (while (and (progn (condition-case nil
4183 (outline-previous-visible-heading 1)
4184 (error (goto-char (point-min))))
4186 (looking-at outline-regexp))
4187 (if (integerp arg)
4188 (show-children (1- arg))
4189 (show-branches))
4190 (if (bobp) (throw 'exit nil))))))
4193 (defun org-optimize-window-after-visibility-change (state)
4194 "Adjust the window after a change in outline visibility.
4195 This function is the default value of the hook `org-cycle-hook'."
4196 (when (get-buffer-window (current-buffer))
4197 (cond
4198 ; ((eq state 'overview) (org-first-headline-recenter 1))
4199 ; ((eq state 'overview) (org-beginning-of-line))
4200 ((eq state 'content) nil)
4201 ((eq state 'all) nil)
4202 ((eq state 'folded) nil)
4203 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4204 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4206 (defun org-compact-display-after-subtree-move ()
4207 (let (beg end)
4208 (save-excursion
4209 (if (org-up-heading-safe)
4210 (progn
4211 (hide-subtree)
4212 (show-entry)
4213 (show-children)
4214 (org-cycle-show-empty-lines 'children)
4215 (org-cycle-hide-drawers 'children))
4216 (org-overview)))))
4218 (defun org-cycle-show-empty-lines (state)
4219 "Show empty lines above all visible headlines.
4220 The region to be covered depends on STATE when called through
4221 `org-cycle-hook'. Lisp program can use t for STATE to get the
4222 entire buffer covered. Note that an empty line is only shown if there
4223 are at least `org-cycle-separator-lines' empty lines before the headeline."
4224 (when (> org-cycle-separator-lines 0)
4225 (save-excursion
4226 (let* ((n org-cycle-separator-lines)
4227 (re (cond
4228 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4229 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4230 (t (let ((ns (number-to-string (- n 2))))
4231 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4232 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4233 beg end)
4234 (cond
4235 ((memq state '(overview contents t))
4236 (setq beg (point-min) end (point-max)))
4237 ((memq state '(children folded))
4238 (setq beg (point) end (progn (org-end-of-subtree t t)
4239 (beginning-of-line 2)
4240 (point)))))
4241 (when beg
4242 (goto-char beg)
4243 (while (re-search-forward re end t)
4244 (if (not (get-char-property (match-end 1) 'invisible))
4245 (outline-flag-region
4246 (match-beginning 1) (match-end 1) nil)))))))
4247 ;; Never hide empty lines at the end of the file.
4248 (save-excursion
4249 (goto-char (point-max))
4250 (outline-previous-heading)
4251 (outline-end-of-heading)
4252 (if (and (looking-at "[ \t\n]+")
4253 (= (match-end 0) (point-max)))
4254 (outline-flag-region (point) (match-end 0) nil))))
4256 (defun org-show-empty-lines-in-parent ()
4257 "Move to the parent and re-show empty lines before visible headlines."
4258 (save-excursion
4259 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4260 (org-cycle-show-empty-lines context))))
4262 (defun org-cycle-hide-drawers (state)
4263 "Re-hide all drawers after a visibility state change."
4264 (when (and (org-mode-p)
4265 (not (memq state '(overview folded))))
4266 (save-excursion
4267 (let* ((globalp (memq state '(contents all)))
4268 (beg (if globalp (point-min) (point)))
4269 (end (if globalp (point-max) (org-end-of-subtree t))))
4270 (goto-char beg)
4271 (while (re-search-forward org-drawer-regexp end t)
4272 (org-flag-drawer t))))))
4274 (defun org-flag-drawer (flag)
4275 (save-excursion
4276 (beginning-of-line 1)
4277 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4278 (let ((b (match-end 0))
4279 (outline-regexp org-outline-regexp))
4280 (if (re-search-forward
4281 "^[ \t]*:END:"
4282 (save-excursion (outline-next-heading) (point)) t)
4283 (outline-flag-region b (point-at-eol) flag)
4284 (error ":END: line missing"))))))
4286 (defun org-subtree-end-visible-p ()
4287 "Is the end of the current subtree visible?"
4288 (pos-visible-in-window-p
4289 (save-excursion (org-end-of-subtree t) (point))))
4291 (defun org-first-headline-recenter (&optional N)
4292 "Move cursor to the first headline and recenter the headline.
4293 Optional argument N means, put the headline into the Nth line of the window."
4294 (goto-char (point-min))
4295 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4296 (beginning-of-line)
4297 (recenter (prefix-numeric-value N))))
4299 ;;; Org-goto
4301 (defvar org-goto-window-configuration nil)
4302 (defvar org-goto-marker nil)
4303 (defvar org-goto-map
4304 (let ((map (make-sparse-keymap)))
4305 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4306 (while (setq cmd (pop cmds))
4307 (substitute-key-definition cmd cmd map global-map)))
4308 (suppress-keymap map)
4309 (org-defkey map "\C-m" 'org-goto-ret)
4310 (org-defkey map [(return)] 'org-goto-ret)
4311 (org-defkey map [(left)] 'org-goto-left)
4312 (org-defkey map [(right)] 'org-goto-right)
4313 (org-defkey map [(control ?g)] 'org-goto-quit)
4314 (org-defkey map "\C-i" 'org-cycle)
4315 (org-defkey map [(tab)] 'org-cycle)
4316 (org-defkey map [(down)] 'outline-next-visible-heading)
4317 (org-defkey map [(up)] 'outline-previous-visible-heading)
4318 (if org-goto-auto-isearch
4319 (if (fboundp 'define-key-after)
4320 (define-key-after map [t] 'org-goto-local-auto-isearch)
4321 nil)
4322 (org-defkey map "q" 'org-goto-quit)
4323 (org-defkey map "n" 'outline-next-visible-heading)
4324 (org-defkey map "p" 'outline-previous-visible-heading)
4325 (org-defkey map "f" 'outline-forward-same-level)
4326 (org-defkey map "b" 'outline-backward-same-level)
4327 (org-defkey map "u" 'outline-up-heading))
4328 (org-defkey map "/" 'org-occur)
4329 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4330 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4331 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4332 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4333 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4334 map))
4336 (defconst org-goto-help
4337 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4338 RET=jump to location [Q]uit and return to previous location
4339 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4341 (defvar org-goto-start-pos) ; dynamically scoped parameter
4343 ;; FIXME: Docstring doe not mention both interfaces
4344 (defun org-goto (&optional alternative-interface)
4345 "Look up a different location in the current file, keeping current visibility.
4347 When you want look-up or go to a different location in a document, the
4348 fastest way is often to fold the entire buffer and then dive into the tree.
4349 This method has the disadvantage, that the previous location will be folded,
4350 which may not be what you want.
4352 This command works around this by showing a copy of the current buffer
4353 in an indirect buffer, in overview mode. You can dive into the tree in
4354 that copy, use org-occur and incremental search to find a location.
4355 When pressing RET or `Q', the command returns to the original buffer in
4356 which the visibility is still unchanged. After RET is will also jump to
4357 the location selected in the indirect buffer and expose the
4358 the headline hierarchy above."
4359 (interactive "P")
4360 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4361 (org-refile-use-outline-path t)
4362 (interface
4363 (if (not alternative-interface)
4364 org-goto-interface
4365 (if (eq org-goto-interface 'outline)
4366 'outline-path-completion
4367 'outline)))
4368 (org-goto-start-pos (point))
4369 (selected-point
4370 (if (eq interface 'outline)
4371 (car (org-get-location (current-buffer) org-goto-help))
4372 (nth 3 (org-refile-get-location "Goto: ")))))
4373 (if selected-point
4374 (progn
4375 (org-mark-ring-push org-goto-start-pos)
4376 (goto-char selected-point)
4377 (if (or (org-invisible-p) (org-invisible-p2))
4378 (org-show-context 'org-goto)))
4379 (message "Quit"))))
4381 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4382 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4383 (defvar org-goto-local-auto-isearch-map) ; defined below
4385 (defun org-get-location (buf help)
4386 "Let the user select a location in the Org-mode buffer BUF.
4387 This function uses a recursive edit. It returns the selected position
4388 or nil."
4389 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4390 (isearch-hide-immediately nil)
4391 (isearch-search-fun-function
4392 (lambda () 'org-goto-local-search-headings))
4393 (org-goto-selected-point org-goto-exit-command))
4394 (save-excursion
4395 (save-window-excursion
4396 (delete-other-windows)
4397 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4398 (switch-to-buffer
4399 (condition-case nil
4400 (make-indirect-buffer (current-buffer) "*org-goto*")
4401 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4402 (with-output-to-temp-buffer "*Help*"
4403 (princ help))
4404 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4405 (setq buffer-read-only nil)
4406 (let ((org-startup-truncated t)
4407 (org-startup-folded nil)
4408 (org-startup-align-all-tables nil))
4409 (org-mode)
4410 (org-overview))
4411 (setq buffer-read-only t)
4412 (if (and (boundp 'org-goto-start-pos)
4413 (integer-or-marker-p org-goto-start-pos))
4414 (let ((org-show-hierarchy-above t)
4415 (org-show-siblings t)
4416 (org-show-following-heading t))
4417 (goto-char org-goto-start-pos)
4418 (and (org-invisible-p) (org-show-context)))
4419 (goto-char (point-min)))
4420 (org-beginning-of-line)
4421 (message "Select location and press RET")
4422 (use-local-map org-goto-map)
4423 (recursive-edit)
4425 (kill-buffer "*org-goto*")
4426 (cons org-goto-selected-point org-goto-exit-command)))
4428 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4429 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4430 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4431 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4433 (defun org-goto-local-search-headings (string bound noerror)
4434 "Search and make sure that any matches are in headlines."
4435 (catch 'return
4436 (while (if isearch-forward
4437 (search-forward string bound noerror)
4438 (search-backward string bound noerror))
4439 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4440 (and (member :headline context)
4441 (not (member :tags context))))
4442 (throw 'return (point))))))
4444 (defun org-goto-local-auto-isearch ()
4445 "Start isearch."
4446 (interactive)
4447 (goto-char (point-min))
4448 (let ((keys (this-command-keys)))
4449 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4450 (isearch-mode t)
4451 (isearch-process-search-char (string-to-char keys)))))
4453 (defun org-goto-ret (&optional arg)
4454 "Finish `org-goto' by going to the new location."
4455 (interactive "P")
4456 (setq org-goto-selected-point (point)
4457 org-goto-exit-command 'return)
4458 (throw 'exit nil))
4460 (defun org-goto-left ()
4461 "Finish `org-goto' by going to the new location."
4462 (interactive)
4463 (if (org-on-heading-p)
4464 (progn
4465 (beginning-of-line 1)
4466 (setq org-goto-selected-point (point)
4467 org-goto-exit-command 'left)
4468 (throw 'exit nil))
4469 (error "Not on a heading")))
4471 (defun org-goto-right ()
4472 "Finish `org-goto' by going to the new location."
4473 (interactive)
4474 (if (org-on-heading-p)
4475 (progn
4476 (setq org-goto-selected-point (point)
4477 org-goto-exit-command 'right)
4478 (throw 'exit nil))
4479 (error "Not on a heading")))
4481 (defun org-goto-quit ()
4482 "Finish `org-goto' without cursor motion."
4483 (interactive)
4484 (setq org-goto-selected-point nil)
4485 (setq org-goto-exit-command 'quit)
4486 (throw 'exit nil))
4488 ;;; Indirect buffer display of subtrees
4490 (defvar org-indirect-dedicated-frame nil
4491 "This is the frame being used for indirect tree display.")
4492 (defvar org-last-indirect-buffer nil)
4494 (defun org-tree-to-indirect-buffer (&optional arg)
4495 "Create indirect buffer and narrow it to current subtree.
4496 With numerical prefix ARG, go up to this level and then take that tree.
4497 If ARG is negative, go up that many levels.
4498 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4499 indirect buffer previously made with this command, to avoid proliferation of
4500 indirect buffers. However, when you call the command with a `C-u' prefix, or
4501 when `org-indirect-buffer-display' is `new-frame', the last buffer
4502 is kept so that you can work with several indirect buffers at the same time.
4503 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4504 requests that a new frame be made for the new buffer, so that the dedicated
4505 frame is not changed."
4506 (interactive "P")
4507 (let ((cbuf (current-buffer))
4508 (cwin (selected-window))
4509 (pos (point))
4510 beg end level heading ibuf)
4511 (save-excursion
4512 (org-back-to-heading t)
4513 (when (numberp arg)
4514 (setq level (org-outline-level))
4515 (if (< arg 0) (setq arg (+ level arg)))
4516 (while (> (setq level (org-outline-level)) arg)
4517 (outline-up-heading 1 t)))
4518 (setq beg (point)
4519 heading (org-get-heading))
4520 (org-end-of-subtree t) (setq end (point)))
4521 (if (and (buffer-live-p org-last-indirect-buffer)
4522 (not (eq org-indirect-buffer-display 'new-frame))
4523 (not arg))
4524 (kill-buffer org-last-indirect-buffer))
4525 (setq ibuf (org-get-indirect-buffer cbuf)
4526 org-last-indirect-buffer ibuf)
4527 (cond
4528 ((or (eq org-indirect-buffer-display 'new-frame)
4529 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4530 (select-frame (make-frame))
4531 (delete-other-windows)
4532 (switch-to-buffer ibuf)
4533 (org-set-frame-title heading))
4534 ((eq org-indirect-buffer-display 'dedicated-frame)
4535 (raise-frame
4536 (select-frame (or (and org-indirect-dedicated-frame
4537 (frame-live-p org-indirect-dedicated-frame)
4538 org-indirect-dedicated-frame)
4539 (setq org-indirect-dedicated-frame (make-frame)))))
4540 (delete-other-windows)
4541 (switch-to-buffer ibuf)
4542 (org-set-frame-title (concat "Indirect: " heading)))
4543 ((eq org-indirect-buffer-display 'current-window)
4544 (switch-to-buffer ibuf))
4545 ((eq org-indirect-buffer-display 'other-window)
4546 (pop-to-buffer ibuf))
4547 (t (error "Invalid value.")))
4548 (if (featurep 'xemacs)
4549 (save-excursion (org-mode) (turn-on-font-lock)))
4550 (narrow-to-region beg end)
4551 (show-all)
4552 (goto-char pos)
4553 (and (window-live-p cwin) (select-window cwin))))
4555 (defun org-get-indirect-buffer (&optional buffer)
4556 (setq buffer (or buffer (current-buffer)))
4557 (let ((n 1) (base (buffer-name buffer)) bname)
4558 (while (buffer-live-p
4559 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4560 (setq n (1+ n)))
4561 (condition-case nil
4562 (make-indirect-buffer buffer bname 'clone)
4563 (error (make-indirect-buffer buffer bname)))))
4565 (defun org-set-frame-title (title)
4566 "Set the title of the current frame to the string TITLE."
4567 ;; FIXME: how to name a single frame in XEmacs???
4568 (unless (featurep 'xemacs)
4569 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4571 ;;;; Structure editing
4573 ;;; Inserting headlines
4575 (defun org-insert-heading (&optional force-heading)
4576 "Insert a new heading or item with same depth at point.
4577 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4578 If point is at the beginning of a headline, insert a sibling before the
4579 current headline. If point is not at the beginning, do not split the line,
4580 but create the new hedline after the current line."
4581 (interactive "P")
4582 (if (= (buffer-size) 0)
4583 (insert "\n* ")
4584 (when (or force-heading (not (org-insert-item)))
4585 (let* ((head (save-excursion
4586 (condition-case nil
4587 (progn
4588 (org-back-to-heading)
4589 (match-string 0))
4590 (error "*"))))
4591 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4592 pos)
4593 (cond
4594 ((and (org-on-heading-p) (bolp)
4595 (or (bobp)
4596 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4597 ;; insert before the current line
4598 (open-line (if blank 2 1)))
4599 ((and (bolp)
4600 (or (bobp)
4601 (save-excursion
4602 (backward-char 1) (not (org-invisible-p)))))
4603 ;; insert right here
4604 nil)
4606 ;; in the middle of the line
4607 (org-show-entry)
4608 (let ((split
4609 (org-get-alist-option org-M-RET-may-split-line 'headline))
4610 tags pos)
4611 (cond
4612 (org-insert-heading-respect-content
4613 (org-end-of-subtree nil t)
4614 (open-line 1))
4615 ((org-on-heading-p)
4616 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4617 (setq tags (and (match-end 2) (match-string 2)))
4618 (and (match-end 1)
4619 (delete-region (match-beginning 1) (match-end 1)))
4620 (setq pos (point-at-bol))
4621 (or split (end-of-line 1))
4622 (delete-horizontal-space)
4623 (newline (if blank 2 1))
4624 (when tags
4625 (save-excursion
4626 (goto-char pos)
4627 (end-of-line 1)
4628 (insert " " tags)
4629 (org-set-tags nil 'align))))
4631 (or split (end-of-line 1))
4632 (newline (if blank 2 1)))))))
4633 (insert head) (just-one-space)
4634 (setq pos (point))
4635 (end-of-line 1)
4636 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4637 (run-hooks 'org-insert-heading-hook)))))
4639 (defun org-get-heading (&optional no-tags)
4640 "Return the heading of the current entry, without the stars."
4641 (save-excursion
4642 (org-back-to-heading t)
4643 (if (looking-at
4644 (if no-tags
4645 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4646 "\\*+[ \t]+\\([^\r\n]*\\)"))
4647 (match-string 1) "")))
4649 (defun org-insert-heading-after-current ()
4650 "Insert a new heading with same level as current, after current subtree."
4651 (interactive)
4652 (org-back-to-heading)
4653 (org-insert-heading)
4654 (org-move-subtree-down)
4655 (end-of-line 1))
4657 (defun org-insert-heading-respect-content ()
4658 (interactive)
4659 (let ((org-insert-heading-respect-content t))
4660 (call-interactively 'org-insert-heading)))
4662 (defun org-insert-todo-heading-respect-content ()
4663 (interactive)
4664 (let ((org-insert-heading-respect-content t))
4665 (call-interactively 'org-insert-todo-todo-heading)))
4667 (defun org-insert-todo-heading (arg)
4668 "Insert a new heading with the same level and TODO state as current heading.
4669 If the heading has no TODO state, or if the state is DONE, use the first
4670 state (TODO by default). Also with prefix arg, force first state."
4671 (interactive "P")
4672 (when (not (org-insert-item 'checkbox))
4673 (org-insert-heading)
4674 (save-excursion
4675 (org-back-to-heading)
4676 (outline-previous-heading)
4677 (looking-at org-todo-line-regexp))
4678 (if (or arg
4679 (not (match-beginning 2))
4680 (member (match-string 2) org-done-keywords))
4681 (insert (car org-todo-keywords-1) " ")
4682 (insert (match-string 2) " "))
4683 (when org-provide-todo-statistics
4684 (org-update-parent-todo-statistics))))
4686 (defun org-insert-subheading (arg)
4687 "Insert a new subheading and demote it.
4688 Works for outline headings and for plain lists alike."
4689 (interactive "P")
4690 (org-insert-heading arg)
4691 (cond
4692 ((org-on-heading-p) (org-do-demote))
4693 ((org-at-item-p) (org-indent-item 1))))
4695 (defun org-insert-todo-subheading (arg)
4696 "Insert a new subheading with TODO keyword or checkbox and demote it.
4697 Works for outline headings and for plain lists alike."
4698 (interactive "P")
4699 (org-insert-todo-heading arg)
4700 (cond
4701 ((org-on-heading-p) (org-do-demote))
4702 ((org-at-item-p) (org-indent-item 1))))
4704 ;;; Promotion and Demotion
4706 (defun org-promote-subtree ()
4707 "Promote the entire subtree.
4708 See also `org-promote'."
4709 (interactive)
4710 (save-excursion
4711 (org-map-tree 'org-promote))
4712 (org-fix-position-after-promote))
4714 (defun org-demote-subtree ()
4715 "Demote the entire subtree. See `org-demote'.
4716 See also `org-promote'."
4717 (interactive)
4718 (save-excursion
4719 (org-map-tree 'org-demote))
4720 (org-fix-position-after-promote))
4723 (defun org-do-promote ()
4724 "Promote the current heading higher up the tree.
4725 If the region is active in `transient-mark-mode', promote all headings
4726 in the region."
4727 (interactive)
4728 (save-excursion
4729 (if (org-region-active-p)
4730 (org-map-region 'org-promote (region-beginning) (region-end))
4731 (org-promote)))
4732 (org-fix-position-after-promote))
4734 (defun org-do-demote ()
4735 "Demote the current heading lower down the tree.
4736 If the region is active in `transient-mark-mode', demote all headings
4737 in the region."
4738 (interactive)
4739 (save-excursion
4740 (if (org-region-active-p)
4741 (org-map-region 'org-demote (region-beginning) (region-end))
4742 (org-demote)))
4743 (org-fix-position-after-promote))
4745 (defun org-fix-position-after-promote ()
4746 "Make sure that after pro/demotion cursor position is right."
4747 (let ((pos (point)))
4748 (when (save-excursion
4749 (beginning-of-line 1)
4750 (looking-at org-todo-line-regexp)
4751 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4752 (cond ((eobp) (insert " "))
4753 ((eolp) (insert " "))
4754 ((equal (char-after) ?\ ) (forward-char 1))))))
4756 (defun org-reduced-level (l)
4757 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4759 (defun org-get-valid-level (level &optional change)
4760 "Rectify a level change under the influence of `org-odd-levels-only'
4761 LEVEL is a current level, CHANGE is by how much the level should be
4762 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4763 even level numbers will become the next higher odd number."
4764 (if org-odd-levels-only
4765 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4766 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4767 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4768 (max 1 (+ level change))))
4770 (if (boundp 'define-obsolete-function-alias)
4771 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4772 (define-obsolete-function-alias 'org-get-legal-level
4773 'org-get-valid-level)
4774 (define-obsolete-function-alias 'org-get-legal-level
4775 'org-get-valid-level "23.1")))
4777 (defun org-promote ()
4778 "Promote the current heading higher up the tree.
4779 If the region is active in `transient-mark-mode', promote all headings
4780 in the region."
4781 (org-back-to-heading t)
4782 (let* ((level (save-match-data (funcall outline-level)))
4783 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4784 (diff (abs (- level (length up-head) -1))))
4785 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4786 (replace-match up-head nil t)
4787 ;; Fixup tag positioning
4788 (and org-auto-align-tags (org-set-tags nil t))
4789 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4791 (defun org-demote ()
4792 "Demote the current heading lower down the tree.
4793 If the region is active in `transient-mark-mode', demote all headings
4794 in the region."
4795 (org-back-to-heading t)
4796 (let* ((level (save-match-data (funcall outline-level)))
4797 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4798 (diff (abs (- level (length down-head) -1))))
4799 (replace-match down-head nil t)
4800 ;; Fixup tag positioning
4801 (and org-auto-align-tags (org-set-tags nil t))
4802 (if org-adapt-indentation (org-fixup-indentation diff))))
4804 (defun org-map-tree (fun)
4805 "Call FUN for every heading underneath the current one."
4806 (org-back-to-heading)
4807 (let ((level (funcall outline-level)))
4808 (save-excursion
4809 (funcall fun)
4810 (while (and (progn
4811 (outline-next-heading)
4812 (> (funcall outline-level) level))
4813 (not (eobp)))
4814 (funcall fun)))))
4816 (defun org-map-region (fun beg end)
4817 "Call FUN for every heading between BEG and END."
4818 (let ((org-ignore-region t))
4819 (save-excursion
4820 (setq end (copy-marker end))
4821 (goto-char beg)
4822 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4823 (< (point) end))
4824 (funcall fun))
4825 (while (and (progn
4826 (outline-next-heading)
4827 (< (point) end))
4828 (not (eobp)))
4829 (funcall fun)))))
4831 (defun org-fixup-indentation (diff)
4832 "Change the indentation in the current entry by DIFF
4833 However, if any line in the current entry has no indentation, or if it
4834 would end up with no indentation after the change, nothing at all is done."
4835 (save-excursion
4836 (let ((end (save-excursion (outline-next-heading)
4837 (point-marker)))
4838 (prohibit (if (> diff 0)
4839 "^\\S-"
4840 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4841 col)
4842 (unless (save-excursion (end-of-line 1)
4843 (re-search-forward prohibit end t))
4844 (while (and (< (point) end)
4845 (re-search-forward "^[ \t]+" end t))
4846 (goto-char (match-end 0))
4847 (setq col (current-column))
4848 (if (< diff 0) (replace-match ""))
4849 (indent-to (+ diff col))))
4850 (move-marker end nil))))
4852 (defun org-convert-to-odd-levels ()
4853 "Convert an org-mode file with all levels allowed to one with odd levels.
4854 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4855 level 5 etc."
4856 (interactive)
4857 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4858 (let ((org-odd-levels-only nil) n)
4859 (save-excursion
4860 (goto-char (point-min))
4861 (while (re-search-forward "^\\*\\*+ " nil t)
4862 (setq n (- (length (match-string 0)) 2))
4863 (while (>= (setq n (1- n)) 0)
4864 (org-demote))
4865 (end-of-line 1))))))
4868 (defun org-convert-to-oddeven-levels ()
4869 "Convert an org-mode file with only odd levels to one with odd and even levels.
4870 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4871 section with an even level, conversion would destroy the structure of the file. An error
4872 is signaled in this case."
4873 (interactive)
4874 (goto-char (point-min))
4875 ;; First check if there are no even levels
4876 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4877 (org-show-context t)
4878 (error "Not all levels are odd in this file. Conversion not possible."))
4879 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4880 (let ((org-odd-levels-only nil) n)
4881 (save-excursion
4882 (goto-char (point-min))
4883 (while (re-search-forward "^\\*\\*+ " nil t)
4884 (setq n (/ (1- (length (match-string 0))) 2))
4885 (while (>= (setq n (1- n)) 0)
4886 (org-promote))
4887 (end-of-line 1))))))
4889 (defun org-tr-level (n)
4890 "Make N odd if required."
4891 (if org-odd-levels-only (1+ (/ n 2)) n))
4893 ;;; Vertical tree motion, cutting and pasting of subtrees
4895 (defun org-move-subtree-up (&optional arg)
4896 "Move the current subtree up past ARG headlines of the same level."
4897 (interactive "p")
4898 (org-move-subtree-down (- (prefix-numeric-value arg))))
4900 (defun org-move-subtree-down (&optional arg)
4901 "Move the current subtree down past ARG headlines of the same level."
4902 (interactive "p")
4903 (setq arg (prefix-numeric-value arg))
4904 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4905 'outline-get-last-sibling))
4906 (ins-point (make-marker))
4907 (cnt (abs arg))
4908 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4909 ;; Select the tree
4910 (org-back-to-heading)
4911 (setq beg0 (point))
4912 (save-excursion
4913 (setq ne-beg (org-back-over-empty-lines))
4914 (setq beg (point)))
4915 (save-match-data
4916 (save-excursion (outline-end-of-heading)
4917 (setq folded (org-invisible-p)))
4918 (outline-end-of-subtree))
4919 (outline-next-heading)
4920 (setq ne-end (org-back-over-empty-lines))
4921 (setq end (point))
4922 (goto-char beg0)
4923 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4924 ;; include less whitespace
4925 (save-excursion
4926 (goto-char beg)
4927 (forward-line (- ne-beg ne-end))
4928 (setq beg (point))))
4929 ;; Find insertion point, with error handling
4930 (while (> cnt 0)
4931 (or (and (funcall movfunc) (looking-at outline-regexp))
4932 (progn (goto-char beg0)
4933 (error "Cannot move past superior level or buffer limit")))
4934 (setq cnt (1- cnt)))
4935 (if (> arg 0)
4936 ;; Moving forward - still need to move over subtree
4937 (progn (org-end-of-subtree t t)
4938 (save-excursion
4939 (org-back-over-empty-lines)
4940 (or (bolp) (newline)))))
4941 (setq ne-ins (org-back-over-empty-lines))
4942 (move-marker ins-point (point))
4943 (setq txt (buffer-substring beg end))
4944 (org-save-markers-in-region beg end)
4945 (delete-region beg end)
4946 (outline-flag-region (1- beg) beg nil)
4947 (outline-flag-region (1- (point)) (point) nil)
4948 (let ((bbb (point)))
4949 (insert-before-markers txt)
4950 (org-reinstall-markers-in-region bbb)
4951 (move-marker ins-point bbb))
4952 (or (bolp) (insert "\n"))
4953 (setq ins-end (point))
4954 (goto-char ins-point)
4955 (org-skip-whitespace)
4956 (when (and (< arg 0)
4957 (org-first-sibling-p)
4958 (> ne-ins ne-beg))
4959 ;; Move whitespace back to beginning
4960 (save-excursion
4961 (goto-char ins-end)
4962 (let ((kill-whole-line t))
4963 (kill-line (- ne-ins ne-beg)) (point)))
4964 (insert (make-string (- ne-ins ne-beg) ?\n)))
4965 (move-marker ins-point nil)
4966 (org-compact-display-after-subtree-move)
4967 (org-show-empty-lines-in-parent)
4968 (unless folded
4969 (org-show-entry)
4970 (show-children)
4971 (org-cycle-hide-drawers 'children))))
4973 (defvar org-subtree-clip ""
4974 "Clipboard for cut and paste of subtrees.
4975 This is actually only a copy of the kill, because we use the normal kill
4976 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4978 (defvar org-subtree-clip-folded nil
4979 "Was the last copied subtree folded?
4980 This is used to fold the tree back after pasting.")
4982 (defun org-cut-subtree (&optional n)
4983 "Cut the current subtree into the clipboard.
4984 With prefix arg N, cut this many sequential subtrees.
4985 This is a short-hand for marking the subtree and then cutting it."
4986 (interactive "p")
4987 (org-copy-subtree n 'cut))
4989 (defun org-copy-subtree (&optional n cut force-store-markers)
4990 "Cut the current subtree into the clipboard.
4991 With prefix arg N, cut this many sequential subtrees.
4992 This is a short-hand for marking the subtree and then copying it.
4993 If CUT is non-nil, actually cut the subtree.
4994 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4995 of some markers in the region, even if CUT is non-nil. This is
4996 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4997 (interactive "p")
4998 (let (beg end folded (beg0 (point)))
4999 (if (interactive-p)
5000 (org-back-to-heading nil) ; take what looks like a subtree
5001 (org-back-to-heading t)) ; take what is really there
5002 (org-back-over-empty-lines)
5003 (setq beg (point))
5004 (skip-chars-forward " \t\r\n")
5005 (save-match-data
5006 (save-excursion (outline-end-of-heading)
5007 (setq folded (org-invisible-p)))
5008 (condition-case nil
5009 (outline-forward-same-level (1- n))
5010 (error nil))
5011 (org-end-of-subtree t t))
5012 (org-back-over-empty-lines)
5013 (setq end (point))
5014 (goto-char beg0)
5015 (when (> end beg)
5016 (setq org-subtree-clip-folded folded)
5017 (when (or cut force-store-markers)
5018 (org-save-markers-in-region beg end))
5019 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5020 (setq org-subtree-clip (current-kill 0))
5021 (message "%s: Subtree(s) with %d characters"
5022 (if cut "Cut" "Copied")
5023 (length org-subtree-clip)))))
5025 (defun org-paste-subtree (&optional level tree)
5026 "Paste the clipboard as a subtree, with modification of headline level.
5027 The entire subtree is promoted or demoted in order to match a new headline
5028 level. By default, the new level is derived from the visible headings
5029 before and after the insertion point, and taken to be the inferior headline
5030 level of the two. So if the previous visible heading is level 3 and the
5031 next is level 4 (or vice versa), level 4 will be used for insertion.
5032 This makes sure that the subtree remains an independent subtree and does
5033 not swallow low level entries.
5035 You can also force a different level, either by using a numeric prefix
5036 argument, or by inserting the heading marker by hand. For example, if the
5037 cursor is after \"*****\", then the tree will be shifted to level 5.
5039 If you want to insert the tree as is, just use \\[yank].
5041 If optional TREE is given, use this text instead of the kill ring."
5042 (interactive "P")
5043 (unless (org-kill-is-subtree-p tree)
5044 (error "%s"
5045 (substitute-command-keys
5046 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5047 (let* ((visp (not (org-invisible-p)))
5048 (txt (or tree (and kill-ring (current-kill 0))))
5049 (^re (concat "^\\(" outline-regexp "\\)"))
5050 (re (concat "\\(" outline-regexp "\\)"))
5051 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5053 (old-level (if (string-match ^re txt)
5054 (- (match-end 0) (match-beginning 0) 1)
5055 -1))
5056 (force-level (cond (level (prefix-numeric-value level))
5057 ((string-match
5058 ^re_ (buffer-substring (point-at-bol) (point)))
5059 (- (match-end 1) (match-beginning 1)))
5060 (t nil)))
5061 (previous-level (save-excursion
5062 (condition-case nil
5063 (progn
5064 (outline-previous-visible-heading 1)
5065 (if (looking-at re)
5066 (- (match-end 0) (match-beginning 0) 1)
5068 (error 1))))
5069 (next-level (save-excursion
5070 (condition-case nil
5071 (progn
5072 (or (looking-at outline-regexp)
5073 (outline-next-visible-heading 1))
5074 (if (looking-at re)
5075 (- (match-end 0) (match-beginning 0) 1)
5077 (error 1))))
5078 (new-level (or force-level (max previous-level next-level)))
5079 (shift (if (or (= old-level -1)
5080 (= new-level -1)
5081 (= old-level new-level))
5083 (- new-level old-level)))
5084 (delta (if (> shift 0) -1 1))
5085 (func (if (> shift 0) 'org-demote 'org-promote))
5086 (org-odd-levels-only nil)
5087 beg end)
5088 ;; Remove the forced level indicator
5089 (if force-level
5090 (delete-region (point-at-bol) (point)))
5091 ;; Paste
5092 (beginning-of-line 1)
5093 (org-back-over-empty-lines)
5094 (setq beg (point))
5095 (insert-before-markers txt)
5096 (unless (string-match "\n\\'" txt) (insert "\n"))
5097 (org-reinstall-markers-in-region beg)
5098 (setq end (point))
5099 (goto-char beg)
5100 (skip-chars-forward " \t\n\r")
5101 (setq beg (point))
5102 (if (and (org-invisible-p) visp)
5103 (save-excursion (outline-show-heading)))
5104 ;; Shift if necessary
5105 (unless (= shift 0)
5106 (save-restriction
5107 (narrow-to-region beg end)
5108 (while (not (= shift 0))
5109 (org-map-region func (point-min) (point-max))
5110 (setq shift (+ delta shift)))
5111 (goto-char (point-min))))
5112 (when (interactive-p)
5113 (message "Clipboard pasted as level %d subtree" new-level))
5114 (if (and kill-ring
5115 (eq org-subtree-clip (current-kill 0))
5116 org-subtree-clip-folded)
5117 ;; The tree was folded before it was killed/copied
5118 (hide-subtree))))
5120 (defun org-kill-is-subtree-p (&optional txt)
5121 "Check if the current kill is an outline subtree, or a set of trees.
5122 Returns nil if kill does not start with a headline, or if the first
5123 headline level is not the largest headline level in the tree.
5124 So this will actually accept several entries of equal levels as well,
5125 which is OK for `org-paste-subtree'.
5126 If optional TXT is given, check this string instead of the current kill."
5127 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5128 (start-level (and kill
5129 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5130 org-outline-regexp "\\)")
5131 kill)
5132 (- (match-end 2) (match-beginning 2) 1)))
5133 (re (concat "^" org-outline-regexp))
5134 (start (1+ (match-beginning 2))))
5135 (if (not start-level)
5136 (progn
5137 nil) ;; does not even start with a heading
5138 (catch 'exit
5139 (while (setq start (string-match re kill (1+ start)))
5140 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5141 (throw 'exit nil)))
5142 t))))
5144 (defvar org-markers-to-move nil
5145 "Markers that should be moved with a cut-and-paste operation.
5146 Those markers are stored together with their positions relative to
5147 the start of the region.")
5149 (defun org-save-markers-in-region (beg end)
5150 "Check markers in region.
5151 If these markers are between BEG and END, record their position relative
5152 to BEG, so that after moving the block of text, we can put the markers back
5153 into place.
5154 This function gets called just before an entry or tree gets cut from the
5155 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5156 called immediately, to move the markers with the entries."
5157 (setq org-markers-to-move nil)
5158 (when (featurep 'org-clock)
5159 (org-clock-save-markers-for-cut-and-paste beg end))
5160 (when (featurep 'org-agenda)
5161 (org-agenda-save-markers-for-cut-and-paste beg end)))
5163 (defun org-check-and-save-marker (marker beg end)
5164 "Check if MARKER is between BEG and END.
5165 If yes, remember the marker and the distance to BEG."
5166 (when (and (marker-buffer marker)
5167 (equal (marker-buffer marker) (current-buffer)))
5168 (if (and (>= marker beg) (< marker end))
5169 (push (cons marker (- marker beg)) org-markers-to-move))))
5171 (defun org-reinstall-markers-in-region (beg)
5172 "Move all remembered markers to their position relative to BEG."
5173 (mapc (lambda (x)
5174 (move-marker (car x) (+ beg (cdr x))))
5175 org-markers-to-move)
5176 (setq org-markers-to-move nil))
5178 (defun org-narrow-to-subtree ()
5179 "Narrow buffer to the current subtree."
5180 (interactive)
5181 (save-excursion
5182 (save-match-data
5183 (narrow-to-region
5184 (progn (org-back-to-heading) (point))
5185 (progn (org-end-of-subtree t) (point))))))
5188 ;;; Outline Sorting
5190 (defun org-sort (with-case)
5191 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5192 Optional argument WITH-CASE means sort case-sensitively."
5193 (interactive "P")
5194 (if (org-at-table-p)
5195 (org-call-with-arg 'org-table-sort-lines with-case)
5196 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5198 (defun org-sort-remove-invisible (s)
5199 (remove-text-properties 0 (length s) org-rm-props s)
5200 (while (string-match org-bracket-link-regexp s)
5201 (setq s (replace-match (if (match-end 2)
5202 (match-string 3 s)
5203 (match-string 1 s)) t t s)))
5206 (defvar org-priority-regexp) ; defined later in the file
5208 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5209 "Sort entries on a certain level of an outline tree.
5210 If there is an active region, the entries in the region are sorted.
5211 Else, if the cursor is before the first entry, sort the top-level items.
5212 Else, the children of the entry at point are sorted.
5214 Sorting can be alphabetically, numerically, and by date/time as given by
5215 the first time stamp in the entry. The command prompts for the sorting
5216 type unless it has been given to the function through the SORTING-TYPE
5217 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5218 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5219 called with point at the beginning of the record. It must return either
5220 a string or a number that should serve as the sorting key for that record.
5222 Comparing entries ignores case by default. However, with an optional argument
5223 WITH-CASE, the sorting considers case as well."
5224 (interactive "P")
5225 (let ((case-func (if with-case 'identity 'downcase))
5226 start beg end stars re re2
5227 txt what tmp plain-list-p)
5228 ;; Find beginning and end of region to sort
5229 (cond
5230 ((org-region-active-p)
5231 ;; we will sort the region
5232 (setq end (region-end)
5233 what "region")
5234 (goto-char (region-beginning))
5235 (if (not (org-on-heading-p)) (outline-next-heading))
5236 (setq start (point)))
5237 ((org-at-item-p)
5238 ;; we will sort this plain list
5239 (org-beginning-of-item-list) (setq start (point))
5240 (org-end-of-item-list) (setq end (point))
5241 (goto-char start)
5242 (setq plain-list-p t
5243 what "plain list"))
5244 ((or (org-on-heading-p)
5245 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5246 ;; we will sort the children of the current headline
5247 (org-back-to-heading)
5248 (setq start (point)
5249 end (progn (org-end-of-subtree t t)
5250 (org-back-over-empty-lines)
5251 (point))
5252 what "children")
5253 (goto-char start)
5254 (show-subtree)
5255 (outline-next-heading))
5257 ;; we will sort the top-level entries in this file
5258 (goto-char (point-min))
5259 (or (org-on-heading-p) (outline-next-heading))
5260 (setq start (point) end (point-max) what "top-level")
5261 (goto-char start)
5262 (show-all)))
5264 (setq beg (point))
5265 (if (>= beg end) (error "Nothing to sort"))
5267 (unless plain-list-p
5268 (looking-at "\\(\\*+\\)")
5269 (setq stars (match-string 1)
5270 re (concat "^" (regexp-quote stars) " +")
5271 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5272 txt (buffer-substring beg end))
5273 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5274 (if (and (not (equal stars "*")) (string-match re2 txt))
5275 (error "Region to sort contains a level above the first entry")))
5277 (unless sorting-type
5278 (message
5279 (if plain-list-p
5280 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5281 "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:")
5282 what)
5283 (setq sorting-type (read-char-exclusive))
5285 (and (= (downcase sorting-type) ?f)
5286 (setq getkey-func
5287 (completing-read "Sort using function: "
5288 obarray 'fboundp t nil nil))
5289 (setq getkey-func (intern getkey-func)))
5291 (and (= (downcase sorting-type) ?r)
5292 (setq property
5293 (completing-read "Property: "
5294 (mapcar 'list (org-buffer-property-keys t))
5295 nil t))))
5297 (message "Sorting entries...")
5299 (save-restriction
5300 (narrow-to-region start end)
5302 (let ((dcst (downcase sorting-type))
5303 (now (current-time)))
5304 (sort-subr
5305 (/= dcst sorting-type)
5306 ;; This function moves to the beginning character of the "record" to
5307 ;; be sorted.
5308 (if plain-list-p
5309 (lambda nil
5310 (if (org-at-item-p) t (goto-char (point-max))))
5311 (lambda nil
5312 (if (re-search-forward re nil t)
5313 (goto-char (match-beginning 0))
5314 (goto-char (point-max)))))
5315 ;; This function moves to the last character of the "record" being
5316 ;; sorted.
5317 (if plain-list-p
5318 'org-end-of-item
5319 (lambda nil
5320 (save-match-data
5321 (condition-case nil
5322 (outline-forward-same-level 1)
5323 (error
5324 (goto-char (point-max)))))))
5326 ;; This function returns the value that gets sorted against.
5327 (if plain-list-p
5328 (lambda nil
5329 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5330 (cond
5331 ((= dcst ?n)
5332 (string-to-number (buffer-substring (match-end 0)
5333 (point-at-eol))))
5334 ((= dcst ?a)
5335 (buffer-substring (match-end 0) (point-at-eol)))
5336 ((= dcst ?t)
5337 (if (re-search-forward org-ts-regexp
5338 (point-at-eol) t)
5339 (org-time-string-to-time (match-string 0))
5340 now))
5341 ((= dcst ?f)
5342 (if getkey-func
5343 (progn
5344 (setq tmp (funcall getkey-func))
5345 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5346 tmp)
5347 (error "Invalid key function `%s'" getkey-func)))
5348 (t (error "Invalid sorting type `%c'" sorting-type)))))
5349 (lambda nil
5350 (cond
5351 ((= dcst ?n)
5352 (if (looking-at org-complex-heading-regexp)
5353 (string-to-number (match-string 4))
5354 nil))
5355 ((= dcst ?a)
5356 (if (looking-at org-complex-heading-regexp)
5357 (funcall case-func (match-string 4))
5358 nil))
5359 ((= dcst ?t)
5360 (if (re-search-forward org-ts-regexp
5361 (save-excursion
5362 (forward-line 2)
5363 (point)) t)
5364 (org-time-string-to-time (match-string 0))
5365 now))
5366 ((= dcst ?p)
5367 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5368 (string-to-char (match-string 2))
5369 org-default-priority))
5370 ((= dcst ?r)
5371 (or (org-entry-get nil property) ""))
5372 ((= dcst ?o)
5373 (if (looking-at org-complex-heading-regexp)
5374 (- 9999 (length (member (match-string 2)
5375 org-todo-keywords-1)))))
5376 ((= dcst ?f)
5377 (if getkey-func
5378 (progn
5379 (setq tmp (funcall getkey-func))
5380 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5381 tmp)
5382 (error "Invalid key function `%s'" getkey-func)))
5383 (t (error "Invalid sorting type `%c'" sorting-type)))))
5385 (cond
5386 ((= dcst ?a) 'string<)
5387 ((= dcst ?t) 'time-less-p)
5388 (t nil)))))
5389 (message "Sorting entries...done")))
5391 (defun org-do-sort (table what &optional with-case sorting-type)
5392 "Sort TABLE of WHAT according to SORTING-TYPE.
5393 The user will be prompted for the SORTING-TYPE if the call to this
5394 function does not specify it. WHAT is only for the prompt, to indicate
5395 what is being sorted. The sorting key will be extracted from
5396 the car of the elements of the table.
5397 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5398 (unless sorting-type
5399 (message
5400 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5401 what)
5402 (setq sorting-type (read-char-exclusive)))
5403 (let ((dcst (downcase sorting-type))
5404 extractfun comparefun)
5405 ;; Define the appropriate functions
5406 (cond
5407 ((= dcst ?n)
5408 (setq extractfun 'string-to-number
5409 comparefun (if (= dcst sorting-type) '< '>)))
5410 ((= dcst ?a)
5411 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5412 (lambda(x) (downcase (org-sort-remove-invisible x))))
5413 comparefun (if (= dcst sorting-type)
5414 'string<
5415 (lambda (a b) (and (not (string< a b))
5416 (not (string= a b)))))))
5417 ((= dcst ?t)
5418 (setq extractfun
5419 (lambda (x)
5420 (if (string-match org-ts-regexp x)
5421 (time-to-seconds
5422 (org-time-string-to-time (match-string 0 x)))
5424 comparefun (if (= dcst sorting-type) '< '>)))
5425 (t (error "Invalid sorting type `%c'" sorting-type)))
5427 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5428 table)
5429 (lambda (a b) (funcall comparefun (car a) (car b))))))
5431 ;;; Editing source examples
5433 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5434 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5435 (defvar org-edit-src-force-single-line nil)
5436 (defvar org-edit-src-from-org-mode nil)
5437 (defvar org-edit-src-picture nil)
5439 (define-minor-mode org-exit-edit-mode
5440 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5442 (defun org-edit-src-code ()
5443 "Edit the source code example at point.
5444 An indirect buffer is created, and that buffer is then narrowed to the
5445 example at point and switched to the correct language mode. When done,
5446 exit by killing the buffer with \\[org-edit-src-exit]."
5447 (interactive)
5448 (let ((line (org-current-line))
5449 (case-fold-search t)
5450 (msg (substitute-command-keys
5451 "Edit, then exit with C-c ' (C-c and single quote)"))
5452 (info (org-edit-src-find-region-and-lang))
5453 (org-mode-p (eq major-mode 'org-mode))
5454 beg end lang lang-f single)
5455 (if (not info)
5457 (setq beg (nth 0 info)
5458 end (nth 1 info)
5459 lang (nth 2 info)
5460 single (nth 3 info)
5461 lang-f (intern (concat lang "-mode")))
5462 (unless (functionp lang-f)
5463 (error "No such language mode: %s" lang-f))
5464 (goto-line line)
5465 (if (get-buffer "*Org Edit Src Example*")
5466 (kill-buffer "*Org Edit Src Example*"))
5467 (switch-to-buffer (make-indirect-buffer (current-buffer)
5468 "*Org Edit Src Example*"))
5469 (narrow-to-region beg end)
5470 (remove-text-properties beg end '(display nil invisible nil
5471 intangible nil))
5472 (let ((org-inhibit-startup t))
5473 (funcall lang-f))
5474 (set (make-local-variable 'org-edit-src-force-single-line) single)
5475 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5476 (when org-mode-p
5477 (goto-char (point-min))
5478 (while (re-search-forward "^," nil t)
5479 (replace-match "")))
5480 (goto-line line)
5481 (org-exit-edit-mode)
5482 (org-set-local 'header-line-format msg)
5483 (message "%s" msg)
5484 t)))
5486 (defun org-edit-fixed-width-region ()
5487 "Edit the fixed-width ascii drawing at point.
5488 This must be a region where each line starts with ca colon followed by
5489 a space character.
5490 An indirect buffer is created, and that buffer is then narrowed to the
5491 example at point and switched to artist-mode. When done,
5492 exit by killing the buffer with \\[org-edit-src-exit]."
5493 (interactive)
5494 (let ((line (org-current-line))
5495 (case-fold-search t)
5496 (msg (substitute-command-keys
5497 "Edit, then exit with C-c ' (C-c and single quote)"))
5498 (org-mode-p (eq major-mode 'org-mode))
5499 beg end lang lang-f)
5500 (beginning-of-line 1)
5501 (if (looking-at "[ \t]*[^:\n \t]")
5503 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5504 (setq beg (point) end (match-end 0))
5505 (save-excursion
5506 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5507 (setq beg (point-at-bol 2))
5508 (setq beg (point))))
5509 (save-excursion
5510 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5511 (setq end (match-beginning 0))
5512 (setq end (point))))
5513 (goto-line line)
5514 (if (get-buffer "*Org Edit Picture*")
5515 (kill-buffer "*Org Edit Picture*"))
5516 (switch-to-buffer (make-indirect-buffer (current-buffer)
5517 "*Org Edit Picture*"))
5518 (narrow-to-region beg end)
5519 (remove-text-properties beg end '(display nil invisible nil
5520 intangible nil))
5521 (when (fboundp 'font-lock-unfontify-region)
5522 (font-lock-unfontify-region (point-min) (point-max)))
5523 (cond
5524 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5525 (fundamental-mode)
5526 (artist-mode 1))
5527 (t (funcall org-edit-fixed-width-region-mode)))
5528 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5529 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5530 (set (make-local-variable 'org-edit-src-picture) t)
5531 (goto-char (point-min))
5532 (while (re-search-forward "^[ \t]*: " nil t)
5533 (replace-match ""))
5534 (goto-line line)
5535 (org-exit-edit-mode)
5536 (org-set-local 'header-line-format msg)
5537 (message "%s" msg)
5538 t))))
5540 (defun org-edit-src-find-region-and-lang ()
5541 "Find the region and language for a local edit.
5542 Return a list with beginning and end of the region, a string representing
5543 the language, a switch telling of the content should be in a single line."
5544 (let ((re-list
5546 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5547 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5548 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5549 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5550 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5551 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5552 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5553 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5554 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5555 ("^#\\+html:" "\n" "html" single-line)
5556 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5557 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5558 ("^#\\+latex:" "\n" "latex" single-line)
5559 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5560 ("^#\\+ascii:" "\n" "ascii" single-line)
5562 (pos (point))
5563 re re1 re2 single beg end lang)
5564 (catch 'exit
5565 (while (setq entry (pop re-list))
5566 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5567 single (nth 3 entry))
5568 (save-excursion
5569 (if (or (looking-at re1)
5570 (re-search-backward re1 nil t))
5571 (progn
5572 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5573 (if (and (re-search-forward re2 nil t)
5574 (>= (match-end 0) pos))
5575 (throw 'exit (list beg (match-beginning 0) lang single))))
5576 (if (or (looking-at re2)
5577 (re-search-forward re2 nil t))
5578 (progn
5579 (setq end (match-beginning 0))
5580 (if (and (re-search-backward re1 nil t)
5581 (<= (match-beginning 0) pos))
5582 (throw 'exit
5583 (list (match-end 0) end
5584 (org-edit-src-get-lang lang) single)))))))))))
5586 (defun org-edit-src-get-lang (lang)
5587 "Extract the src language."
5588 (let ((m (match-string 0)))
5589 (cond
5590 ((stringp lang) lang)
5591 ((integerp lang) (match-string lang))
5592 ((and (eq lang lang)
5593 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5594 (match-string 1 m))
5595 ((and (eq lang lang)
5596 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5597 (match-string 1 m))
5598 (t "fundamental"))))
5600 (defun org-edit-src-exit ()
5601 "Exit special edit and protect problematic lines."
5602 (interactive)
5603 (unless (buffer-base-buffer (current-buffer))
5604 (error "This is not an indirect buffer, something is wrong..."))
5605 (unless (> (point-min) 1)
5606 (error "This buffer is not narrowed, something is wrong..."))
5607 (goto-char (point-min))
5608 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5609 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5610 (when (org-bound-and-true-p org-edit-src-force-single-line)
5611 (goto-char (point-min))
5612 (while (re-search-forward "\n" nil t)
5613 (replace-match " "))
5614 (goto-char (point-min))
5615 (if (looking-at "\\s-*") (replace-match " "))
5616 (if (re-search-forward "\\s-+\\'" nil t)
5617 (replace-match "")))
5618 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5619 (goto-char (point-min))
5620 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5621 (replace-match ",\\1"))
5622 (when font-lock-mode
5623 (font-lock-unfontify-region (point-min) (point-max)))
5624 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5625 (when (org-bound-and-true-p org-edit-src-picture)
5626 (goto-char (point-min))
5627 (while (re-search-forward "^" nil t)
5628 (replace-match ": "))
5629 (when font-lock-mode
5630 (font-lock-unfontify-region (point-min) (point-max)))
5631 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5632 (kill-buffer (current-buffer))
5633 (and (org-mode-p) (org-restart-font-lock)))
5635 ;;;; Plain list items, including checkboxes
5637 ;;; Plain list items
5639 (defun org-at-item-p ()
5640 "Is point in a line starting a hand-formatted item?"
5641 (let ((llt org-plain-list-ordered-item-terminator))
5642 (save-excursion
5643 (goto-char (point-at-bol))
5644 (looking-at
5645 (cond
5646 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5647 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5648 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5649 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5651 (defun org-in-item-p ()
5652 "It the cursor inside a plain list item.
5653 Does not have to be the first line."
5654 (save-excursion
5655 (condition-case nil
5656 (progn
5657 (org-beginning-of-item)
5658 (org-at-item-p)
5660 (error nil))))
5662 (defun org-insert-item (&optional checkbox)
5663 "Insert a new item at the current level.
5664 Return t when things worked, nil when we are not in an item."
5665 (when (save-excursion
5666 (condition-case nil
5667 (progn
5668 (org-beginning-of-item)
5669 (org-at-item-p)
5670 (if (org-invisible-p) (error "Invisible item"))
5672 (error nil)))
5673 (let* ((bul (match-string 0))
5674 (descp (save-excursion (goto-char (match-beginning 0))
5675 (beginning-of-line 1)
5676 (save-match-data
5677 (looking-at "[ \t]*.*? ::"))))
5678 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5679 (match-end 0)))
5680 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5681 pos)
5682 (if descp (setq checkbox nil))
5683 (cond
5684 ((and (org-at-item-p) (<= (point) eow))
5685 ;; before the bullet
5686 (beginning-of-line 1)
5687 (open-line (if blank 2 1)))
5688 ((<= (point) eow)
5689 (beginning-of-line 1))
5691 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5692 (end-of-line 1)
5693 (delete-horizontal-space))
5694 (newline (if blank 2 1))))
5695 (insert bul
5696 (if checkbox "[ ]" "")
5697 (if descp (concat (if checkbox " " "")
5698 (read-string "Term: ") " :: ") ""))
5699 (just-one-space)
5700 (setq pos (point))
5701 (end-of-line 1)
5702 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5703 (org-maybe-renumber-ordered-list)
5704 (and checkbox (org-update-checkbox-count-maybe))
5707 ;;; Checkboxes
5709 (defun org-at-item-checkbox-p ()
5710 "Is point at a line starting a plain-list item with a checklet?"
5711 (and (org-at-item-p)
5712 (save-excursion
5713 (goto-char (match-end 0))
5714 (skip-chars-forward " \t")
5715 (looking-at "\\[[- X]\\]"))))
5717 (defun org-toggle-checkbox (&optional arg)
5718 "Toggle the checkbox in the current line."
5719 (interactive "P")
5720 (catch 'exit
5721 (let (beg end status (firstnew 'unknown))
5722 (cond
5723 ((org-region-active-p)
5724 (setq beg (region-beginning) end (region-end)))
5725 ((org-on-heading-p)
5726 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5727 ((org-at-item-checkbox-p)
5728 (let ((pos (point)))
5729 (replace-match
5730 (cond (arg "[-]")
5731 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5732 (t "[ ]"))
5733 t t)
5734 (goto-char pos))
5735 (throw 'exit t))
5736 (t (error "Not at a checkbox or heading, and no active region")))
5737 (save-excursion
5738 (goto-char beg)
5739 (while (< (point) end)
5740 (when (org-at-item-checkbox-p)
5741 (setq status (equal (match-string 0) "[X]"))
5742 (when (eq firstnew 'unknown)
5743 (setq firstnew (not status)))
5744 (replace-match
5745 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5746 (beginning-of-line 2)))))
5747 (org-update-checkbox-count-maybe))
5749 (defun org-update-checkbox-count-maybe ()
5750 "Update checkbox statistics unless turned off by user."
5751 (when org-provide-checkbox-statistics
5752 (org-update-checkbox-count)))
5754 (defun org-update-checkbox-count (&optional all)
5755 "Update the checkbox statistics in the current section.
5756 This will find all statistic cookies like [57%] and [6/12] and update them
5757 with the current numbers. With optional prefix argument ALL, do this for
5758 the whole buffer."
5759 (interactive "P")
5760 (save-excursion
5761 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5762 (beg (condition-case nil
5763 (progn (outline-back-to-heading) (point))
5764 (error (point-min))))
5765 (end (move-marker (make-marker)
5766 (progn (outline-next-heading) (point))))
5767 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5768 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5769 (re-find (concat re "\\|" re-box))
5770 beg-cookie end-cookie is-percent c-on c-off lim
5771 eline curr-ind next-ind continue-from startsearch
5772 (cstat 0)
5774 (when all
5775 (goto-char (point-min))
5776 (outline-next-heading)
5777 (setq beg (point) end (point-max)))
5778 (goto-char end)
5779 ;; find each statistic cookie
5780 (while (re-search-backward re-find beg t)
5781 (setq beg-cookie (match-beginning 1)
5782 end-cookie (match-end 1)
5783 cstat (+ cstat (if end-cookie 1 0))
5784 startsearch (point-at-eol)
5785 continue-from (point-at-bol)
5786 is-percent (match-beginning 2)
5787 lim (cond
5788 ((org-on-heading-p) (outline-next-heading) (point))
5789 ((org-at-item-p) (org-end-of-item) (point))
5790 (t nil))
5791 c-on 0
5792 c-off 0)
5793 (when lim
5794 ;; find first checkbox for this cookie and gather
5795 ;; statistics from all that are at this indentation level
5796 (goto-char startsearch)
5797 (if (re-search-forward re-box lim t)
5798 (progn
5799 (org-beginning-of-item)
5800 (setq curr-ind (org-get-indentation))
5801 (setq next-ind curr-ind)
5802 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5803 (save-excursion (end-of-line) (setq eline (point)))
5804 (if (re-search-forward re-box eline t)
5805 (if (member (match-string 2) '("[ ]" "[-]"))
5806 (setq c-off (1+ c-off))
5807 (setq c-on (1+ c-on))
5810 (org-end-of-item)
5811 (setq next-ind (org-get-indentation))
5813 (goto-char continue-from)
5814 ;; update cookie
5815 (when end-cookie
5816 (delete-region beg-cookie end-cookie)
5817 (goto-char beg-cookie)
5818 (insert
5819 (if is-percent
5820 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5821 (format "[%d/%d]" c-on (+ c-on c-off)))))
5822 ;; update items checkbox if it has one
5823 (when (org-at-item-p)
5824 (org-beginning-of-item)
5825 (when (and (> (+ c-on c-off) 0)
5826 (re-search-forward re-box (point-at-eol) t))
5827 (setq beg-cookie (match-beginning 2)
5828 end-cookie (match-end 2))
5829 (delete-region beg-cookie end-cookie)
5830 (goto-char beg-cookie)
5831 (cond ((= c-off 0) (insert "[X]"))
5832 ((= c-on 0) (insert "[ ]"))
5833 (t (insert "[-]")))
5835 (goto-char continue-from))
5836 (when (interactive-p)
5837 (message "Checkbox satistics updated %s (%d places)"
5838 (if all "in entire file" "in current outline entry") cstat)))))
5840 (defun org-get-checkbox-statistics-face ()
5841 "Select the face for checkbox statistics.
5842 The face will be `org-done' when all relevant boxes are checked. Otherwise
5843 it will be `org-todo'."
5844 (if (match-end 1)
5845 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5846 (if (and (> (match-end 2) (match-beginning 2))
5847 (equal (match-string 2) (match-string 3)))
5848 'org-done
5849 'org-todo)))
5851 (defun org-get-indentation (&optional line)
5852 "Get the indentation of the current line, interpreting tabs.
5853 When LINE is given, assume it represents a line and compute its indentation."
5854 (if line
5855 (if (string-match "^ *" (org-remove-tabs line))
5856 (match-end 0))
5857 (save-excursion
5858 (beginning-of-line 1)
5859 (skip-chars-forward " \t")
5860 (current-column))))
5862 (defun org-remove-tabs (s &optional width)
5863 "Replace tabulators in S with spaces.
5864 Assumes that s is a single line, starting in column 0."
5865 (setq width (or width tab-width))
5866 (while (string-match "\t" s)
5867 (setq s (replace-match
5868 (make-string
5869 (- (* width (/ (+ (match-beginning 0) width) width))
5870 (match-beginning 0)) ?\ )
5871 t t s)))
5874 (defun org-fix-indentation (line ind)
5875 "Fix indentation in LINE.
5876 IND is a cons cell with target and minimum indentation.
5877 If the current indenation in LINE is smaller than the minimum,
5878 leave it alone. If it is larger than ind, set it to the target."
5879 (let* ((l (org-remove-tabs line))
5880 (i (org-get-indentation l))
5881 (i1 (car ind)) (i2 (cdr ind)))
5882 (if (>= i i2) (setq l (substring line i2)))
5883 (if (> i1 0)
5884 (concat (make-string i1 ?\ ) l)
5885 l)))
5887 (defun org-beginning-of-item ()
5888 "Go to the beginning of the current hand-formatted item.
5889 If the cursor is not in an item, throw an error."
5890 (interactive)
5891 (let ((pos (point))
5892 (limit (save-excursion
5893 (condition-case nil
5894 (progn
5895 (org-back-to-heading)
5896 (beginning-of-line 2) (point))
5897 (error (point-min)))))
5898 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5899 ind ind1)
5900 (if (org-at-item-p)
5901 (beginning-of-line 1)
5902 (beginning-of-line 1)
5903 (skip-chars-forward " \t")
5904 (setq ind (current-column))
5905 (if (catch 'exit
5906 (while t
5907 (beginning-of-line 0)
5908 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5910 (if (looking-at "[ \t]*$")
5911 (setq ind1 ind-empty)
5912 (skip-chars-forward " \t")
5913 (setq ind1 (current-column)))
5914 (if (< ind1 ind)
5915 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5917 (goto-char pos)
5918 (error "Not in an item")))))
5920 (defun org-end-of-item ()
5921 "Go to the end of the current hand-formatted item.
5922 If the cursor is not in an item, throw an error."
5923 (interactive)
5924 (let* ((pos (point))
5925 ind1
5926 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5927 (limit (save-excursion (outline-next-heading) (point)))
5928 (ind (save-excursion
5929 (org-beginning-of-item)
5930 (skip-chars-forward " \t")
5931 (current-column)))
5932 (end (catch 'exit
5933 (while t
5934 (beginning-of-line 2)
5935 (if (eobp) (throw 'exit (point)))
5936 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5937 (if (looking-at "[ \t]*$")
5938 (setq ind1 ind-empty)
5939 (skip-chars-forward " \t")
5940 (setq ind1 (current-column)))
5941 (if (<= ind1 ind)
5942 (throw 'exit (point-at-bol)))))))
5943 (if end
5944 (goto-char end)
5945 (goto-char pos)
5946 (error "Not in an item"))))
5948 (defun org-next-item ()
5949 "Move to the beginning of the next item in the current plain list.
5950 Error if not at a plain list, or if this is the last item in the list."
5951 (interactive)
5952 (let (ind ind1 (pos (point)))
5953 (org-beginning-of-item)
5954 (setq ind (org-get-indentation))
5955 (org-end-of-item)
5956 (setq ind1 (org-get-indentation))
5957 (unless (and (org-at-item-p) (= ind ind1))
5958 (goto-char pos)
5959 (error "On last item"))))
5961 (defun org-previous-item ()
5962 "Move to the beginning of the previous item in the current plain list.
5963 Error if not at a plain list, or if this is the first item in the list."
5964 (interactive)
5965 (let (beg ind ind1 (pos (point)))
5966 (org-beginning-of-item)
5967 (setq beg (point))
5968 (setq ind (org-get-indentation))
5969 (goto-char beg)
5970 (catch 'exit
5971 (while t
5972 (beginning-of-line 0)
5973 (if (looking-at "[ \t]*$")
5975 (if (<= (setq ind1 (org-get-indentation)) ind)
5976 (throw 'exit t)))))
5977 (condition-case nil
5978 (if (or (not (org-at-item-p))
5979 (< ind1 (1- ind)))
5980 (error "")
5981 (org-beginning-of-item))
5982 (error (goto-char pos)
5983 (error "On first item")))))
5985 (defun org-first-list-item-p ()
5986 "Is this heading the item in a plain list?"
5987 (unless (org-at-item-p)
5988 (error "Not at a plain list item"))
5989 (org-beginning-of-item)
5990 (= (point) (save-excursion (org-beginning-of-item-list))))
5992 (defun org-move-item-down ()
5993 "Move the plain list item at point down, i.e. swap with following item.
5994 Subitems (items with larger indentation) are considered part of the item,
5995 so this really moves item trees."
5996 (interactive)
5997 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5998 (org-beginning-of-item)
5999 (setq beg0 (point))
6000 (save-excursion
6001 (setq ne-beg (org-back-over-empty-lines))
6002 (setq beg (point)))
6003 (goto-char beg0)
6004 (setq ind (org-get-indentation))
6005 (org-end-of-item)
6006 (setq end0 (point))
6007 (setq ind1 (org-get-indentation))
6008 (setq ne-end (org-back-over-empty-lines))
6009 (setq end (point))
6010 (goto-char beg0)
6011 (when (and (org-first-list-item-p) (< ne-end ne-beg))
6012 ;; include less whitespace
6013 (save-excursion
6014 (goto-char beg)
6015 (forward-line (- ne-beg ne-end))
6016 (setq beg (point))))
6017 (goto-char end0)
6018 (if (and (org-at-item-p) (= ind ind1))
6019 (progn
6020 (org-end-of-item)
6021 (org-back-over-empty-lines)
6022 (setq txt (buffer-substring beg end))
6023 (save-excursion
6024 (delete-region beg end))
6025 (setq pos (point))
6026 (insert txt)
6027 (goto-char pos) (org-skip-whitespace)
6028 (org-maybe-renumber-ordered-list))
6029 (goto-char pos)
6030 (error "Cannot move this item further down"))))
6032 (defun org-move-item-up (arg)
6033 "Move the plain list item at point up, i.e. swap with previous item.
6034 Subitems (items with larger indentation) are considered part of the item,
6035 so this really moves item trees."
6036 (interactive "p")
6037 (let (beg beg0 end ind ind1 (pos (point)) txt
6038 ne-beg ne-ins ins-end)
6039 (org-beginning-of-item)
6040 (setq beg0 (point))
6041 (setq ind (org-get-indentation))
6042 (save-excursion
6043 (setq ne-beg (org-back-over-empty-lines))
6044 (setq beg (point)))
6045 (goto-char beg0)
6046 (org-end-of-item)
6047 (org-back-over-empty-lines)
6048 (setq end (point))
6049 (goto-char beg0)
6050 (catch 'exit
6051 (while t
6052 (beginning-of-line 0)
6053 (if (looking-at "[ \t]*$")
6054 (if org-empty-line-terminates-plain-lists
6055 (progn
6056 (goto-char pos)
6057 (error "Cannot move this item further up"))
6058 nil)
6059 (if (<= (setq ind1 (org-get-indentation)) ind)
6060 (throw 'exit t)))))
6061 (condition-case nil
6062 (org-beginning-of-item)
6063 (error (goto-char beg0)
6064 (error "Cannot move this item further up")))
6065 (setq ind1 (org-get-indentation))
6066 (if (and (org-at-item-p) (= ind ind1))
6067 (progn
6068 (setq ne-ins (org-back-over-empty-lines))
6069 (setq txt (buffer-substring beg end))
6070 (save-excursion
6071 (delete-region beg end))
6072 (setq pos (point))
6073 (insert txt)
6074 (setq ins-end (point))
6075 (goto-char pos) (org-skip-whitespace)
6077 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
6078 ;; Move whitespace back to beginning
6079 (save-excursion
6080 (goto-char ins-end)
6081 (let ((kill-whole-line t))
6082 (kill-line (- ne-ins ne-beg)) (point)))
6083 (insert (make-string (- ne-ins ne-beg) ?\n)))
6085 (org-maybe-renumber-ordered-list))
6086 (goto-char pos)
6087 (error "Cannot move this item further up"))))
6089 (defun org-maybe-renumber-ordered-list ()
6090 "Renumber the ordered list at point if setup allows it.
6091 This tests the user option `org-auto-renumber-ordered-lists' before
6092 doing the renumbering."
6093 (interactive)
6094 (when (and org-auto-renumber-ordered-lists
6095 (org-at-item-p))
6096 (if (match-beginning 3)
6097 (org-renumber-ordered-list 1)
6098 (org-fix-bullet-type))))
6100 (defun org-maybe-renumber-ordered-list-safe ()
6101 (condition-case nil
6102 (save-excursion
6103 (org-maybe-renumber-ordered-list))
6104 (error nil)))
6106 (defun org-cycle-list-bullet (&optional which)
6107 "Cycle through the different itemize/enumerate bullets.
6108 This cycle the entire list level through the sequence:
6110 `-' -> `+' -> `*' -> `1.' -> `1)'
6112 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6113 0 meand `-', 1 means `+' etc."
6114 (interactive "P")
6115 (org-preserve-lc
6116 (org-beginning-of-item-list)
6117 (org-at-item-p)
6118 (beginning-of-line 1)
6119 (let ((current (match-string 0))
6120 (prevp (eq which 'previous))
6121 new)
6122 (setq new (cond
6123 ((and (numberp which)
6124 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6125 ((string-match "-" current) (if prevp "1)" "+"))
6126 ((string-match "\\+" current)
6127 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6128 ((string-match "\\*" current) (if prevp "+" "1."))
6129 ((string-match "\\." current) (if prevp "*" "1)"))
6130 ((string-match ")" current) (if prevp "1." "-"))
6131 (t (error "This should not happen"))))
6132 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6133 (org-fix-bullet-type)
6134 (org-maybe-renumber-ordered-list))))
6136 (defun org-get-string-indentation (s)
6137 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6138 (let ((n -1) (i 0) (w tab-width) c)
6139 (catch 'exit
6140 (while (< (setq n (1+ n)) (length s))
6141 (setq c (aref s n))
6142 (cond ((= c ?\ ) (setq i (1+ i)))
6143 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6144 (t (throw 'exit t)))))
6147 (defun org-renumber-ordered-list (arg)
6148 "Renumber an ordered plain list.
6149 Cursor needs to be in the first line of an item, the line that starts
6150 with something like \"1.\" or \"2)\"."
6151 (interactive "p")
6152 (unless (and (org-at-item-p)
6153 (match-beginning 3))
6154 (error "This is not an ordered list"))
6155 (let ((line (org-current-line))
6156 (col (current-column))
6157 (ind (org-get-string-indentation
6158 (buffer-substring (point-at-bol) (match-beginning 3))))
6159 ;; (term (substring (match-string 3) -1))
6160 ind1 (n (1- arg))
6161 fmt bobp)
6162 ;; find where this list begins
6163 (org-beginning-of-item-list)
6164 (setq bobp (bobp))
6165 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6166 (setq fmt (concat "%d" (match-string 1)))
6167 (beginning-of-line 0)
6168 ;; walk forward and replace these numbers
6169 (catch 'exit
6170 (while t
6171 (catch 'next
6172 (if bobp (setq bobp nil) (beginning-of-line 2))
6173 (if (eobp) (throw 'exit nil))
6174 (if (looking-at "[ \t]*$") (throw 'next nil))
6175 (skip-chars-forward " \t") (setq ind1 (current-column))
6176 (if (> ind1 ind) (throw 'next t))
6177 (if (< ind1 ind) (throw 'exit t))
6178 (if (not (org-at-item-p)) (throw 'exit nil))
6179 (delete-region (match-beginning 2) (match-end 2))
6180 (goto-char (match-beginning 2))
6181 (insert (format fmt (setq n (1+ n)))))))
6182 (goto-line line)
6183 (org-move-to-column col)))
6185 (defun org-fix-bullet-type ()
6186 "Make sure all items in this list have the same bullet as the firsst item."
6187 (interactive)
6188 (unless (org-at-item-p) (error "This is not a list"))
6189 (let ((line (org-current-line))
6190 (col (current-column))
6191 (ind (current-indentation))
6192 ind1 bullet)
6193 ;; find where this list begins
6194 (org-beginning-of-item-list)
6195 (beginning-of-line 1)
6196 ;; find out what the bullet type is
6197 (looking-at "[ \t]*\\(\\S-+\\)")
6198 (setq bullet (match-string 1))
6199 ;; walk forward and replace these numbers
6200 (beginning-of-line 0)
6201 (catch 'exit
6202 (while t
6203 (catch 'next
6204 (beginning-of-line 2)
6205 (if (eobp) (throw 'exit nil))
6206 (if (looking-at "[ \t]*$") (throw 'next nil))
6207 (skip-chars-forward " \t") (setq ind1 (current-column))
6208 (if (> ind1 ind) (throw 'next t))
6209 (if (< ind1 ind) (throw 'exit t))
6210 (if (not (org-at-item-p)) (throw 'exit nil))
6211 (skip-chars-forward " \t")
6212 (looking-at "\\S-+")
6213 (replace-match bullet))))
6214 (goto-line line)
6215 (org-move-to-column col)
6216 (if (string-match "[0-9]" bullet)
6217 (org-renumber-ordered-list 1))))
6219 (defun org-beginning-of-item-list ()
6220 "Go to the beginning of the current item list.
6221 I.e. to the first item in this list."
6222 (interactive)
6223 (org-beginning-of-item)
6224 (let ((pos (point-at-bol))
6225 (ind (org-get-indentation))
6226 ind1)
6227 ;; find where this list begins
6228 (catch 'exit
6229 (while t
6230 (catch 'next
6231 (beginning-of-line 0)
6232 (if (looking-at "[ \t]*$")
6233 (throw (if (bobp) 'exit 'next) t))
6234 (skip-chars-forward " \t") (setq ind1 (current-column))
6235 (if (or (< ind1 ind)
6236 (and (= ind1 ind)
6237 (not (org-at-item-p)))
6238 (and (= (point-at-bol) (point-min))
6239 (setq pos (point-min))))
6240 (throw 'exit t)
6241 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6242 (goto-char pos)))
6245 (defun org-end-of-item-list ()
6246 "Go to the end of the current item list.
6247 I.e. to the text after the last item."
6248 (interactive)
6249 (org-beginning-of-item)
6250 (let ((pos (point-at-bol))
6251 (ind (org-get-indentation))
6252 ind1)
6253 ;; find where this list begins
6254 (catch 'exit
6255 (while t
6256 (catch 'next
6257 (beginning-of-line 2)
6258 (if (looking-at "[ \t]*$")
6259 (throw (if (eobp) 'exit 'next) t))
6260 (skip-chars-forward " \t") (setq ind1 (current-column))
6261 (if (or (< ind1 ind)
6262 (and (= ind1 ind)
6263 (not (org-at-item-p)))
6264 (eobp))
6265 (progn
6266 (setq pos (point-at-bol))
6267 (throw 'exit t))))))
6268 (goto-char pos)))
6271 (defvar org-last-indent-begin-marker (make-marker))
6272 (defvar org-last-indent-end-marker (make-marker))
6274 (defun org-outdent-item (arg)
6275 "Outdent a local list item."
6276 (interactive "p")
6277 (org-indent-item (- arg)))
6279 (defun org-indent-item (arg)
6280 "Indent a local list item."
6281 (interactive "p")
6282 (unless (org-at-item-p)
6283 (error "Not on an item"))
6284 (save-excursion
6285 (let (beg end ind ind1 tmp delta ind-down ind-up)
6286 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6287 (setq beg org-last-indent-begin-marker
6288 end org-last-indent-end-marker)
6289 (org-beginning-of-item)
6290 (setq beg (move-marker org-last-indent-begin-marker (point)))
6291 (org-end-of-item)
6292 (setq end (move-marker org-last-indent-end-marker (point))))
6293 (goto-char beg)
6294 (setq tmp (org-item-indent-positions)
6295 ind (car tmp)
6296 ind-down (nth 2 tmp)
6297 ind-up (nth 1 tmp)
6298 delta (if (> arg 0)
6299 (if ind-down (- ind-down ind) 2)
6300 (if ind-up (- ind-up ind) -2)))
6301 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6302 (while (< (point) end)
6303 (beginning-of-line 1)
6304 (skip-chars-forward " \t") (setq ind1 (current-column))
6305 (delete-region (point-at-bol) (point))
6306 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6307 (beginning-of-line 2))))
6308 (org-fix-bullet-type)
6309 (org-maybe-renumber-ordered-list-safe)
6310 (save-excursion
6311 (beginning-of-line 0)
6312 (condition-case nil (org-beginning-of-item) (error nil))
6313 (org-maybe-renumber-ordered-list-safe)))
6315 (defun org-item-indent-positions ()
6316 "Return indentation for plain list items.
6317 This returns a list with three values: The current indentation, the
6318 parent indentation and the indentation a child should habe.
6319 Assumes cursor in item line."
6320 (let* ((bolpos (point-at-bol))
6321 (ind (org-get-indentation))
6322 ind-down ind-up pos)
6323 (save-excursion
6324 (org-beginning-of-item-list)
6325 (skip-chars-backward "\n\r \t")
6326 (when (org-in-item-p)
6327 (org-beginning-of-item)
6328 (setq ind-up (org-get-indentation))))
6329 (setq pos (point))
6330 (save-excursion
6331 (cond
6332 ((and (condition-case nil (progn (org-previous-item) t)
6333 (error nil))
6334 (or (forward-char 1) t)
6335 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6336 (setq ind-down (org-get-indentation)))
6337 ((and (goto-char pos)
6338 (org-at-item-p))
6339 (goto-char (match-end 0))
6340 (skip-chars-forward " \t")
6341 (setq ind-down (current-column)))))
6342 (list ind ind-up ind-down)))
6344 ;;; The orgstruct minor mode
6346 ;; Define a minor mode which can be used in other modes in order to
6347 ;; integrate the org-mode structure editing commands.
6349 ;; This is really a hack, because the org-mode structure commands use
6350 ;; keys which normally belong to the major mode. Here is how it
6351 ;; works: The minor mode defines all the keys necessary to operate the
6352 ;; structure commands, but wraps the commands into a function which
6353 ;; tests if the cursor is currently at a headline or a plain list
6354 ;; item. If that is the case, the structure command is used,
6355 ;; temporarily setting many Org-mode variables like regular
6356 ;; expressions for filling etc. However, when any of those keys is
6357 ;; used at a different location, function uses `key-binding' to look
6358 ;; up if the key has an associated command in another currently active
6359 ;; keymap (minor modes, major mode, global), and executes that
6360 ;; command. There might be problems if any of the keys is otherwise
6361 ;; used as a prefix key.
6363 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6364 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6365 ;; addresses this by checking explicitly for both bindings.
6367 (defvar orgstruct-mode-map (make-sparse-keymap)
6368 "Keymap for the minor `orgstruct-mode'.")
6370 (defvar org-local-vars nil
6371 "List of local variables, for use by `orgstruct-mode'")
6373 ;;;###autoload
6374 (define-minor-mode orgstruct-mode
6375 "Toggle the minor more `orgstruct-mode'.
6376 This mode is for using Org-mode structure commands in other modes.
6377 The following key behave as if Org-mode was active, if the cursor
6378 is on a headline, or on a plain list item (both in the definition
6379 of Org-mode).
6381 M-up Move entry/item up
6382 M-down Move entry/item down
6383 M-left Promote
6384 M-right Demote
6385 M-S-up Move entry/item up
6386 M-S-down Move entry/item down
6387 M-S-left Promote subtree
6388 M-S-right Demote subtree
6389 M-q Fill paragraph and items like in Org-mode
6390 C-c ^ Sort entries
6391 C-c - Cycle list bullet
6392 TAB Cycle item visibility
6393 M-RET Insert new heading/item
6394 S-M-RET Insert new TODO heading / Chekbox item
6395 C-c C-c Set tags / toggle checkbox"
6396 nil " OrgStruct" nil
6397 (org-load-modules-maybe)
6398 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6400 ;;;###autoload
6401 (defun turn-on-orgstruct ()
6402 "Unconditionally turn on `orgstruct-mode'."
6403 (orgstruct-mode 1))
6405 ;;;###autoload
6406 (defun turn-on-orgstruct++ ()
6407 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6408 In addition to setting orgstruct-mode, this also exports all indentation and
6409 autofilling variables from org-mode into the buffer. Note that turning
6410 off orgstruct-mode will *not* remove these additional settings."
6411 (orgstruct-mode 1)
6412 (let (var val)
6413 (mapc
6414 (lambda (x)
6415 (when (string-match
6416 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6417 (symbol-name (car x)))
6418 (setq var (car x) val (nth 1 x))
6419 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6420 org-local-vars)))
6422 (defun orgstruct-error ()
6423 "Error when there is no default binding for a structure key."
6424 (interactive)
6425 (error "This key has no function outside structure elements"))
6427 (defun orgstruct-setup ()
6428 "Setup orgstruct keymaps."
6429 (let ((nfunc 0)
6430 (bindings
6431 (list
6432 '([(meta up)] org-metaup)
6433 '([(meta down)] org-metadown)
6434 '([(meta left)] org-metaleft)
6435 '([(meta right)] org-metaright)
6436 '([(meta shift up)] org-shiftmetaup)
6437 '([(meta shift down)] org-shiftmetadown)
6438 '([(meta shift left)] org-shiftmetaleft)
6439 '([(meta shift right)] org-shiftmetaright)
6440 '([(shift up)] org-shiftup)
6441 '([(shift down)] org-shiftdown)
6442 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6443 '("\M-q" fill-paragraph)
6444 '("\C-c^" org-sort)
6445 '("\C-c-" org-cycle-list-bullet)))
6446 elt key fun cmd)
6447 (while (setq elt (pop bindings))
6448 (setq nfunc (1+ nfunc))
6449 (setq key (org-key (car elt))
6450 fun (nth 1 elt)
6451 cmd (orgstruct-make-binding fun nfunc key))
6452 (org-defkey orgstruct-mode-map key cmd))
6454 ;; Special treatment needed for TAB and RET
6455 (org-defkey orgstruct-mode-map [(tab)]
6456 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6457 (org-defkey orgstruct-mode-map "\C-i"
6458 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6460 (org-defkey orgstruct-mode-map "\M-\C-m"
6461 (orgstruct-make-binding 'org-insert-heading 105
6462 "\M-\C-m" [(meta return)]))
6463 (org-defkey orgstruct-mode-map [(meta return)]
6464 (orgstruct-make-binding 'org-insert-heading 106
6465 [(meta return)] "\M-\C-m"))
6467 (org-defkey orgstruct-mode-map [(shift meta return)]
6468 (orgstruct-make-binding 'org-insert-todo-heading 107
6469 [(meta return)] "\M-\C-m"))
6471 (unless org-local-vars
6472 (setq org-local-vars (org-get-local-variables)))
6476 (defun orgstruct-make-binding (fun n &rest keys)
6477 "Create a function for binding in the structure minor mode.
6478 FUN is the command to call inside a table. N is used to create a unique
6479 command name. KEYS are keys that should be checked in for a command
6480 to execute outside of tables."
6481 (eval
6482 (list 'defun
6483 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6484 '(arg)
6485 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6486 "Outside of structure, run the binding of `"
6487 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6488 "'.")
6489 '(interactive "p")
6490 (list 'if
6491 '(org-context-p 'headline 'item)
6492 (list 'org-run-like-in-org-mode (list 'quote fun))
6493 (list 'let '(orgstruct-mode)
6494 (list 'call-interactively
6495 (append '(or)
6496 (mapcar (lambda (k)
6497 (list 'key-binding k))
6498 keys)
6499 '('orgstruct-error))))))))
6501 (defun org-context-p (&rest contexts)
6502 "Check if local context is any of CONTEXTS.
6503 Possible values in the list of contexts are `table', `headline', and `item'."
6504 (let ((pos (point)))
6505 (goto-char (point-at-bol))
6506 (prog1 (or (and (memq 'table contexts)
6507 (looking-at "[ \t]*|"))
6508 (and (memq 'headline contexts)
6509 ;;????????? (looking-at "\\*+"))
6510 (looking-at outline-regexp))
6511 (and (memq 'item contexts)
6512 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6513 (goto-char pos))))
6515 (defun org-get-local-variables ()
6516 "Return a list of all local variables in an org-mode buffer."
6517 (let (varlist)
6518 (with-current-buffer (get-buffer-create "*Org tmp*")
6519 (erase-buffer)
6520 (org-mode)
6521 (setq varlist (buffer-local-variables)))
6522 (kill-buffer "*Org tmp*")
6523 (delq nil
6524 (mapcar
6525 (lambda (x)
6526 (setq x
6527 (if (symbolp x)
6528 (list x)
6529 (list (car x) (list 'quote (cdr x)))))
6530 (if (string-match
6531 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6532 (symbol-name (car x)))
6533 x nil))
6534 varlist))))
6536 ;;;###autoload
6537 (defun org-run-like-in-org-mode (cmd)
6538 (org-load-modules-maybe)
6539 (unless org-local-vars
6540 (setq org-local-vars (org-get-local-variables)))
6541 (eval (list 'let org-local-vars
6542 (list 'call-interactively (list 'quote cmd)))))
6544 ;;;; Archiving
6546 (defun org-get-category (&optional pos)
6547 "Get the category applying to position POS."
6548 (get-text-property (or pos (point)) 'org-category))
6550 (defun org-refresh-category-properties ()
6551 "Refresh category text properties in the buffer."
6552 (let ((def-cat (cond
6553 ((null org-category)
6554 (if buffer-file-name
6555 (file-name-sans-extension
6556 (file-name-nondirectory buffer-file-name))
6557 "???"))
6558 ((symbolp org-category) (symbol-name org-category))
6559 (t org-category)))
6560 beg end cat pos optionp)
6561 (org-unmodified
6562 (save-excursion
6563 (save-restriction
6564 (widen)
6565 (goto-char (point-min))
6566 (put-text-property (point) (point-max) 'org-category def-cat)
6567 (while (re-search-forward
6568 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6569 (setq pos (match-end 0)
6570 optionp (equal (char-after (match-beginning 0)) ?#)
6571 cat (org-trim (match-string 2)))
6572 (if optionp
6573 (setq beg (point-at-bol) end (point-max))
6574 (org-back-to-heading t)
6575 (setq beg (point) end (org-end-of-subtree t t)))
6576 (put-text-property beg end 'org-category cat)
6577 (goto-char pos)))))))
6580 ;;;; Link Stuff
6582 ;;; Link abbreviations
6584 (defun org-link-expand-abbrev (link)
6585 "Apply replacements as defined in `org-link-abbrev-alist."
6586 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6587 (let* ((key (match-string 1 link))
6588 (as (or (assoc key org-link-abbrev-alist-local)
6589 (assoc key org-link-abbrev-alist)))
6590 (tag (and (match-end 2) (match-string 3 link)))
6591 rpl)
6592 (if (not as)
6593 link
6594 (setq rpl (cdr as))
6595 (cond
6596 ((symbolp rpl) (funcall rpl tag))
6597 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6598 (t (concat rpl tag)))))
6599 link))
6601 ;;; Storing and inserting links
6603 (defvar org-insert-link-history nil
6604 "Minibuffer history for links inserted with `org-insert-link'.")
6606 (defvar org-stored-links nil
6607 "Contains the links stored with `org-store-link'.")
6609 (defvar org-store-link-plist nil
6610 "Plist with info about the most recently link created with `org-store-link'.")
6612 (defvar org-link-protocols nil
6613 "Link protocols added to Org-mode using `org-add-link-type'.")
6615 (defvar org-store-link-functions nil
6616 "List of functions that are called to create and store a link.
6617 Each function will be called in turn until one returns a non-nil
6618 value. Each function should check if it is responsible for creating
6619 this link (for example by looking at the major mode).
6620 If not, it must exit and return nil.
6621 If yes, it should return a non-nil value after a calling
6622 `org-store-link-props' with a list of properties and values.
6623 Special properties are:
6625 :type The link prefix. like \"http\". This must be given.
6626 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6627 This is obligatory as well.
6628 :description Optional default description for the second pair
6629 of brackets in an Org-mode link. The user can still change
6630 this when inserting this link into an Org-mode buffer.
6632 In addition to these, any additional properties can be specified
6633 and then used in remember templates.")
6635 (defun org-add-link-type (type &optional follow export)
6636 "Add TYPE to the list of `org-link-types'.
6637 Re-compute all regular expressions depending on `org-link-types'
6639 FOLLOW and EXPORT are two functions.
6641 FOLLOW should take the link path as the single argument and do whatever
6642 is necessary to follow the link, for example find a file or display
6643 a mail message.
6645 EXPORT should format the link path for export to one of the export formats.
6646 It should be a function accepting three arguments:
6648 path the path of the link, the text after the prefix (like \"http:\")
6649 desc the description of the link, if any, nil if there was no descripton
6650 format the export format, a symbol like `html' or `latex'.
6652 The function may use the FORMAT information to return different values
6653 depending on the format. The return value will be put literally into
6654 the exported file.
6655 Org-mode has a built-in default for exporting links. If you are happy with
6656 this default, there is no need to define an export function for the link
6657 type. For a simple example of an export function, see `org-bbdb.el'."
6658 (add-to-list 'org-link-types type t)
6659 (org-make-link-regexps)
6660 (if (assoc type org-link-protocols)
6661 (setcdr (assoc type org-link-protocols) (list follow export))
6662 (push (list type follow export) org-link-protocols)))
6665 ;;;###autoload
6666 (defun org-store-link (arg)
6667 "\\<org-mode-map>Store an org-link to the current location.
6668 This link is added to `org-stored-links' and can later be inserted
6669 into an org-buffer with \\[org-insert-link].
6671 For some link types, a prefix arg is interpreted:
6672 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6673 For file links, arg negates `org-context-in-file-links'."
6674 (interactive "P")
6675 (org-load-modules-maybe)
6676 (setq org-store-link-plist nil) ; reset
6677 (let (link cpltxt desc description search txt)
6678 (cond
6680 ((run-hook-with-args-until-success 'org-store-link-functions)
6681 (setq link (plist-get org-store-link-plist :link)
6682 desc (or (plist-get org-store-link-plist :description) link)))
6684 ((eq major-mode 'calendar-mode)
6685 (let ((cd (calendar-cursor-to-date)))
6686 (setq link
6687 (format-time-string
6688 (car org-time-stamp-formats)
6689 (apply 'encode-time
6690 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6691 nil nil nil))))
6692 (org-store-link-props :type "calendar" :date cd)))
6694 ((eq major-mode 'w3-mode)
6695 (setq cpltxt (url-view-url t)
6696 link (org-make-link cpltxt))
6697 (org-store-link-props :type "w3" :url (url-view-url t)))
6699 ((eq major-mode 'w3m-mode)
6700 (setq cpltxt (or w3m-current-title w3m-current-url)
6701 link (org-make-link w3m-current-url))
6702 (org-store-link-props :type "w3m" :url (url-view-url t)))
6704 ((setq search (run-hook-with-args-until-success
6705 'org-create-file-search-functions))
6706 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6707 "::" search))
6708 (setq cpltxt (or description link)))
6710 ((eq major-mode 'image-mode)
6711 (setq cpltxt (concat "file:"
6712 (abbreviate-file-name buffer-file-name))
6713 link (org-make-link cpltxt))
6714 (org-store-link-props :type "image" :file buffer-file-name))
6716 ((eq major-mode 'dired-mode)
6717 ;; link to the file in the current line
6718 (setq cpltxt (concat "file:"
6719 (abbreviate-file-name
6720 (expand-file-name
6721 (dired-get-filename nil t))))
6722 link (org-make-link cpltxt)))
6724 ((and buffer-file-name (org-mode-p))
6725 ;; Just link to current headline
6726 (setq cpltxt (concat "file:"
6727 (abbreviate-file-name buffer-file-name)))
6728 ;; Add a context search string
6729 (when (org-xor org-context-in-file-links arg)
6730 ;; Check if we are on a target
6731 (if (org-in-regexp "<<\\(.*?\\)>>")
6732 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6733 (setq txt (cond
6734 ((org-on-heading-p) nil)
6735 ((org-region-active-p)
6736 (buffer-substring (region-beginning) (region-end)))
6737 (t nil)))
6738 (when (or (null txt) (string-match "\\S-" txt))
6739 (setq cpltxt
6740 (concat cpltxt "::"
6741 (condition-case nil
6742 (org-make-org-heading-search-string txt)
6743 (error "")))
6744 desc "NONE"))))
6745 (if (string-match "::\\'" cpltxt)
6746 (setq cpltxt (substring cpltxt 0 -2)))
6747 (setq link (org-make-link cpltxt)))
6749 ((buffer-file-name (buffer-base-buffer))
6750 ;; Just link to this file here.
6751 (setq cpltxt (concat "file:"
6752 (abbreviate-file-name
6753 (buffer-file-name (buffer-base-buffer)))))
6754 ;; Add a context string
6755 (when (org-xor org-context-in-file-links arg)
6756 (setq txt (if (org-region-active-p)
6757 (buffer-substring (region-beginning) (region-end))
6758 (buffer-substring (point-at-bol) (point-at-eol))))
6759 ;; Only use search option if there is some text.
6760 (when (string-match "\\S-" txt)
6761 (setq cpltxt
6762 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6763 desc "NONE")))
6764 (setq link (org-make-link cpltxt)))
6766 ((interactive-p)
6767 (error "Cannot link to a buffer which is not visiting a file"))
6769 (t (setq link nil)))
6771 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6772 (setq link (or link cpltxt)
6773 desc (or desc cpltxt))
6774 (if (equal desc "NONE") (setq desc nil))
6776 (if (and (interactive-p) link)
6777 (progn
6778 (setq org-stored-links
6779 (cons (list link desc) org-stored-links))
6780 (message "Stored: %s" (or desc link)))
6781 (and link (org-make-link-string link desc)))))
6783 (defun org-store-link-props (&rest plist)
6784 "Store link properties, extract names and addresses."
6785 (let (x adr)
6786 (when (setq x (plist-get plist :from))
6787 (setq adr (mail-extract-address-components x))
6788 (plist-put plist :fromname (car adr))
6789 (plist-put plist :fromaddress (nth 1 adr)))
6790 (when (setq x (plist-get plist :to))
6791 (setq adr (mail-extract-address-components x))
6792 (plist-put plist :toname (car adr))
6793 (plist-put plist :toaddress (nth 1 adr))))
6794 (let ((from (plist-get plist :from))
6795 (to (plist-get plist :to)))
6796 (when (and from to org-from-is-user-regexp)
6797 (plist-put plist :fromto
6798 (if (string-match org-from-is-user-regexp from)
6799 (concat "to %t")
6800 (concat "from %f")))))
6801 (setq org-store-link-plist plist))
6803 (defun org-add-link-props (&rest plist)
6804 "Add these properties to the link property list."
6805 (let (key value)
6806 (while plist
6807 (setq key (pop plist) value (pop plist))
6808 (setq org-store-link-plist
6809 (plist-put org-store-link-plist key value)))))
6811 (defun org-email-link-description (&optional fmt)
6812 "Return the description part of an email link.
6813 This takes information from `org-store-link-plist' and formats it
6814 according to FMT (default from `org-email-link-description-format')."
6815 (setq fmt (or fmt org-email-link-description-format))
6816 (let* ((p org-store-link-plist)
6817 (to (plist-get p :toaddress))
6818 (from (plist-get p :fromaddress))
6819 (table
6820 (list
6821 (cons "%c" (plist-get p :fromto))
6822 (cons "%F" (plist-get p :from))
6823 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6824 (cons "%T" (plist-get p :to))
6825 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6826 (cons "%s" (plist-get p :subject))
6827 (cons "%m" (plist-get p :message-id)))))
6828 (when (string-match "%c" fmt)
6829 ;; Check if the user wrote this message
6830 (if (and org-from-is-user-regexp from to
6831 (save-match-data (string-match org-from-is-user-regexp from)))
6832 (setq fmt (replace-match "to %t" t t fmt))
6833 (setq fmt (replace-match "from %f" t t fmt))))
6834 (org-replace-escapes fmt table)))
6836 (defun org-make-org-heading-search-string (&optional string heading)
6837 "Make search string for STRING or current headline."
6838 (interactive)
6839 (let ((s (or string (org-get-heading))))
6840 (unless (and string (not heading))
6841 ;; We are using a headline, clean up garbage in there.
6842 (if (string-match org-todo-regexp s)
6843 (setq s (replace-match "" t t s)))
6844 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6845 (setq s (replace-match "" t t s)))
6846 (setq s (org-trim s))
6847 (if (string-match (concat "^\\(" org-quote-string "\\|"
6848 org-comment-string "\\)") s)
6849 (setq s (replace-match "" t t s)))
6850 (while (string-match org-ts-regexp s)
6851 (setq s (replace-match "" t t s))))
6852 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6853 (setq s (replace-match " " t t s)))
6854 (or string (setq s (concat "*" s))) ; Add * for headlines
6855 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6857 (defun org-make-link (&rest strings)
6858 "Concatenate STRINGS."
6859 (apply 'concat strings))
6861 (defun org-make-link-string (link &optional description)
6862 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6863 (unless (string-match "\\S-" link)
6864 (error "Empty link"))
6865 (when (stringp description)
6866 ;; Remove brackets from the description, they are fatal.
6867 (while (string-match "\\[" description)
6868 (setq description (replace-match "{" t t description)))
6869 (while (string-match "\\]" description)
6870 (setq description (replace-match "}" t t description))))
6871 (when (equal (org-link-escape link) description)
6872 ;; No description needed, it is identical
6873 (setq description nil))
6874 (when (and (not description)
6875 (not (equal link (org-link-escape link))))
6876 (setq description (org-extract-attributes link)))
6877 (concat "[[" (org-link-escape link) "]"
6878 (if description (concat "[" description "]") "")
6879 "]"))
6881 (defconst org-link-escape-chars
6882 '((?\ . "%20")
6883 (?\[ . "%5B")
6884 (?\] . "%5D")
6885 (?\340 . "%E0") ; `a
6886 (?\342 . "%E2") ; ^a
6887 (?\347 . "%E7") ; ,c
6888 (?\350 . "%E8") ; `e
6889 (?\351 . "%E9") ; 'e
6890 (?\352 . "%EA") ; ^e
6891 (?\356 . "%EE") ; ^i
6892 (?\364 . "%F4") ; ^o
6893 (?\371 . "%F9") ; `u
6894 (?\373 . "%FB") ; ^u
6895 (?\; . "%3B")
6896 (?? . "%3F")
6897 (?= . "%3D")
6898 (?+ . "%2B")
6900 "Association list of escapes for some characters problematic in links.
6901 This is the list that is used for internal purposes.")
6903 (defconst org-link-escape-chars-browser
6904 '((?\ . "%20")) ; 32 for the SPC char
6905 "Association list of escapes for some characters problematic in links.
6906 This is the list that is used before handing over to the browser.")
6908 (defun org-link-escape (text &optional table)
6909 "Escape charaters in TEXT that are problematic for links."
6910 (setq table (or table org-link-escape-chars))
6911 (when text
6912 (let ((re (mapconcat (lambda (x) (regexp-quote
6913 (char-to-string (car x))))
6914 table "\\|")))
6915 (while (string-match re text)
6916 (setq text
6917 (replace-match
6918 (cdr (assoc (string-to-char (match-string 0 text))
6919 table))
6920 t t text)))
6921 text)))
6923 (defun org-link-unescape (text &optional table)
6924 "Reverse the action of `org-link-escape'."
6925 (setq table (or table org-link-escape-chars))
6926 (when text
6927 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6928 table "\\|")))
6929 (while (string-match re text)
6930 (setq text
6931 (replace-match
6932 (char-to-string (car (rassoc (match-string 0 text) table)))
6933 t t text)))
6934 text)))
6936 (defun org-xor (a b)
6937 "Exclusive or."
6938 (if a (not b) b))
6940 (defun org-get-header (header)
6941 "Find a header field in the current buffer."
6942 (save-excursion
6943 (goto-char (point-min))
6944 (let ((case-fold-search t) s)
6945 (cond
6946 ((eq header 'from)
6947 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6948 (setq s (match-string 1)))
6949 (while (string-match "\"" s)
6950 (setq s (replace-match "" t t s)))
6951 (if (string-match "[<(].*" s)
6952 (setq s (replace-match "" t t s))))
6953 ((eq header 'message-id)
6954 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6955 (setq s (match-string 1))))
6956 ((eq header 'subject)
6957 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6958 (setq s (match-string 1)))))
6959 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6960 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6961 s)))
6964 (defun org-fixup-message-id-for-http (s)
6965 "Replace special characters in a message id, so it can be used in an http query."
6966 (while (string-match "<" s)
6967 (setq s (replace-match "%3C" t t s)))
6968 (while (string-match ">" s)
6969 (setq s (replace-match "%3E" t t s)))
6970 (while (string-match "@" s)
6971 (setq s (replace-match "%40" t t s)))
6974 ;;;###autoload
6975 (defun org-insert-link-global ()
6976 "Insert a link like Org-mode does.
6977 This command can be called in any mode to insert a link in Org-mode syntax."
6978 (interactive)
6979 (org-load-modules-maybe)
6980 (org-run-like-in-org-mode 'org-insert-link))
6982 (defun org-insert-link (&optional complete-file link-location)
6983 "Insert a link. At the prompt, enter the link.
6985 Completion can be used to select a link previously stored with
6986 `org-store-link'. When the empty string is entered (i.e. if you just
6987 press RET at the prompt), the link defaults to the most recently
6988 stored link. As SPC triggers completion in the minibuffer, you need to
6989 use M-SPC or C-q SPC to force the insertion of a space character.
6991 You will also be prompted for a description, and if one is given, it will
6992 be displayed in the buffer instead of the link.
6994 If there is already a link at point, this command will allow you to edit link
6995 and description parts.
6997 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6998 be selected using completion. The path to the file will be relative to the
6999 current directory if the file is in the current directory or a subdirectory.
7000 Otherwise, the link will be the absolute path as completed in the minibuffer
7001 \(i.e. normally ~/path/to/file).
7003 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7004 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
7005 of `org-keep-stored-link-after-insertion'.
7007 If `org-make-link-description-function' is non-nil, this function will be
7008 called with the link target, and the result will be the default
7009 link description.
7011 If the LINK-LOCATION parameter is non-nil, this value will be
7012 used as the link location instead of reading one interactively."
7013 (interactive "P")
7014 (let* ((wcf (current-window-configuration))
7015 (region (if (org-region-active-p)
7016 (buffer-substring (region-beginning) (region-end))))
7017 (remove (and region (list (region-beginning) (region-end))))
7018 (desc region)
7019 tmphist ; byte-compile incorrectly complains about this
7020 (link link-location)
7021 entry file)
7022 (cond
7023 (link-location) ; specified by arg, just use it.
7024 ((org-in-regexp org-bracket-link-regexp 1)
7025 ;; We do have a link at point, and we are going to edit it.
7026 (setq remove (list (match-beginning 0) (match-end 0)))
7027 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7028 (setq link (read-string "Link: "
7029 (org-link-unescape
7030 (org-match-string-no-properties 1)))))
7031 ((or (org-in-regexp org-angle-link-re)
7032 (org-in-regexp org-plain-link-re))
7033 ;; Convert to bracket link
7034 (setq remove (list (match-beginning 0) (match-end 0))
7035 link (read-string "Link: "
7036 (org-remove-angle-brackets (match-string 0)))))
7037 ((equal complete-file '(4))
7038 ;; Completing read for file names.
7039 (setq file (read-file-name "File: "))
7040 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7041 (pwd1 (file-name-as-directory (abbreviate-file-name
7042 (expand-file-name ".")))))
7043 (cond
7044 ((equal complete-file '(16))
7045 (setq link (org-make-link
7046 "file:"
7047 (abbreviate-file-name (expand-file-name file)))))
7048 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7049 (setq link (org-make-link "file:" (match-string 1 file))))
7050 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7051 (expand-file-name file))
7052 (setq link (org-make-link
7053 "file:" (match-string 1 (expand-file-name file)))))
7054 (t (setq link (org-make-link "file:" file))))))
7056 ;; Read link, with completion for stored links.
7057 (with-output-to-temp-buffer "*Org Links*"
7058 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7059 (when org-stored-links
7060 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7061 (princ (mapconcat
7062 (lambda (x)
7063 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7064 (reverse org-stored-links) "\n"))))
7065 (let ((cw (selected-window)))
7066 (select-window (get-buffer-window "*Org Links*"))
7067 (shrink-window-if-larger-than-buffer)
7068 (setq truncate-lines t)
7069 (select-window cw))
7070 ;; Fake a link history, containing the stored links.
7071 (setq tmphist (append (mapcar 'car org-stored-links)
7072 org-insert-link-history))
7073 (unwind-protect
7074 (setq link (org-completing-read
7075 "Link: "
7076 (append
7077 (mapcar (lambda (x) (list (concat (car x) ":")))
7078 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7079 (mapcar (lambda (x) (list (concat x ":")))
7080 org-link-types))
7081 nil nil nil
7082 'tmphist
7083 (or (car (car org-stored-links)))))
7084 (set-window-configuration wcf)
7085 (kill-buffer "*Org Links*"))
7086 (setq entry (assoc link org-stored-links))
7087 (or entry (push link org-insert-link-history))
7088 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7089 (not org-keep-stored-link-after-insertion))
7090 (setq org-stored-links (delq (assoc link org-stored-links)
7091 org-stored-links)))
7092 (setq desc (or desc (nth 1 entry)))))
7094 (if (string-match org-plain-link-re link)
7095 ;; URL-like link, normalize the use of angular brackets.
7096 (setq link (org-make-link (org-remove-angle-brackets link))))
7098 ;; Check if we are linking to the current file with a search option
7099 ;; If yes, simplify the link by using only the search option.
7100 (when (and buffer-file-name
7101 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7102 (let* ((path (match-string 1 link))
7103 (case-fold-search nil)
7104 (search (match-string 2 link)))
7105 (save-match-data
7106 (if (equal (file-truename buffer-file-name) (file-truename path))
7107 ;; We are linking to this same file, with a search option
7108 (setq link search)))))
7110 ;; Check if we can/should use a relative path. If yes, simplify the link
7111 (when (string-match "\\<file:\\(.*\\)" link)
7112 (let* ((path (match-string 1 link))
7113 (origpath path)
7114 (case-fold-search nil))
7115 (cond
7116 ((eq org-link-file-path-type 'absolute)
7117 (setq path (abbreviate-file-name (expand-file-name path))))
7118 ((eq org-link-file-path-type 'noabbrev)
7119 (setq path (expand-file-name path)))
7120 ((eq org-link-file-path-type 'relative)
7121 (setq path (file-relative-name path)))
7123 (save-match-data
7124 (if (string-match (concat "^" (regexp-quote
7125 (file-name-as-directory
7126 (expand-file-name "."))))
7127 (expand-file-name path))
7128 ;; We are linking a file with relative path name.
7129 (setq path (substring (expand-file-name path)
7130 (match-end 0)))))))
7131 (setq link (concat "file:" path))
7132 (if (equal desc origpath)
7133 (setq desc path))))
7135 (if org-make-link-description-function
7136 (setq desc (funcall org-make-link-description-function link desc)))
7138 (setq desc (read-string "Description: " desc))
7139 (unless (string-match "\\S-" desc) (setq desc nil))
7140 (if remove (apply 'delete-region remove))
7141 (insert (org-make-link-string link desc))))
7143 (defun org-completing-read (&rest args)
7144 (let ((minibuffer-local-completion-map
7145 (copy-keymap minibuffer-local-completion-map)))
7146 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7147 (apply 'completing-read args)))
7149 (defun org-extract-attributes (s)
7150 "Extract the attributes cookie from a string and set as text property."
7151 (let (a attr (start 0) key value)
7152 (save-match-data
7153 (when (string-match "{{\\([^}]+\\)}}$" s)
7154 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7155 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7156 (setq key (match-string 1 a) value (match-string 2 a)
7157 start (match-end 0)
7158 attr (plist-put attr (intern key) value))))
7159 (org-add-props s nil 'org-attributes attr))
7162 (defun org-attributes-to-string (plist)
7163 "Format a property list into an HTML attribute list."
7164 (let ((s "") key value)
7165 (while plist
7166 (setq key (pop plist) value (pop plist))
7167 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7170 ;;; Opening/following a link
7172 (defvar org-link-search-failed nil)
7174 (defun org-next-link ()
7175 "Move forward to the next link.
7176 If the link is in hidden text, expose it."
7177 (interactive)
7178 (when (and org-link-search-failed (eq this-command last-command))
7179 (goto-char (point-min))
7180 (message "Link search wrapped back to beginning of buffer"))
7181 (setq org-link-search-failed nil)
7182 (let* ((pos (point))
7183 (ct (org-context))
7184 (a (assoc :link ct)))
7185 (if a (goto-char (nth 2 a)))
7186 (if (re-search-forward org-any-link-re nil t)
7187 (progn
7188 (goto-char (match-beginning 0))
7189 (if (org-invisible-p) (org-show-context)))
7190 (goto-char pos)
7191 (setq org-link-search-failed t)
7192 (error "No further link found"))))
7194 (defun org-previous-link ()
7195 "Move backward to the previous link.
7196 If the link is in hidden text, expose it."
7197 (interactive)
7198 (when (and org-link-search-failed (eq this-command last-command))
7199 (goto-char (point-max))
7200 (message "Link search wrapped back to end of buffer"))
7201 (setq org-link-search-failed nil)
7202 (let* ((pos (point))
7203 (ct (org-context))
7204 (a (assoc :link ct)))
7205 (if a (goto-char (nth 1 a)))
7206 (if (re-search-backward org-any-link-re nil t)
7207 (progn
7208 (goto-char (match-beginning 0))
7209 (if (org-invisible-p) (org-show-context)))
7210 (goto-char pos)
7211 (setq org-link-search-failed t)
7212 (error "No further link found"))))
7214 (defun org-find-file-at-mouse (ev)
7215 "Open file link or URL at mouse."
7216 (interactive "e")
7217 (mouse-set-point ev)
7218 (org-open-at-point 'in-emacs))
7220 (defun org-open-at-mouse (ev)
7221 "Open file link or URL at mouse."
7222 (interactive "e")
7223 (mouse-set-point ev)
7224 (org-open-at-point))
7226 (defvar org-window-config-before-follow-link nil
7227 "The window configuration before following a link.
7228 This is saved in case the need arises to restore it.")
7230 (defvar org-open-link-marker (make-marker)
7231 "Marker pointing to the location where `org-open-at-point; was called.")
7233 ;;;###autoload
7234 (defun org-open-at-point-global ()
7235 "Follow a link like Org-mode does.
7236 This command can be called in any mode to follow a link that has
7237 Org-mode syntax."
7238 (interactive)
7239 (org-run-like-in-org-mode 'org-open-at-point))
7241 ;;;###autoload
7242 (defun org-open-link-from-string (s &optional arg)
7243 "Open a link in the string S, as if it was in Org-mode."
7244 (interactive "sLink: \nP")
7245 (with-temp-buffer
7246 (let ((org-inhibit-startup t))
7247 (org-mode)
7248 (insert s)
7249 (goto-char (point-min))
7250 (org-open-at-point arg))))
7252 (defun org-open-at-point (&optional in-emacs)
7253 "Open link at or after point.
7254 If there is no link at point, this function will search forward up to
7255 the end of the current subtree.
7256 Normally, files will be opened by an appropriate application. If the
7257 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7258 (interactive "P")
7259 (org-load-modules-maybe)
7260 (move-marker org-open-link-marker (point))
7261 (setq org-window-config-before-follow-link (current-window-configuration))
7262 (org-remove-occur-highlights nil nil t)
7263 (if (org-at-timestamp-p t)
7264 (org-follow-timestamp-link)
7265 (let (type path link line search (pos (point)))
7266 (catch 'match
7267 (save-excursion
7268 (skip-chars-forward "^]\n\r")
7269 (when (org-in-regexp org-bracket-link-regexp)
7270 (setq link (org-extract-attributes
7271 (org-link-unescape (org-match-string-no-properties 1))))
7272 (while (string-match " *\n *" link)
7273 (setq link (replace-match " " t t link)))
7274 (setq link (org-link-expand-abbrev link))
7275 (cond
7276 ((or (file-name-absolute-p link)
7277 (string-match "^\\.\\.?/" link))
7278 (setq type "file" path link))
7279 ((string-match org-link-re-with-space2 link)
7280 (setq type (match-string 1 link) path (match-string 2 link)))
7281 (t (setq type "thisfile" path link)))
7282 (throw 'match t)))
7284 (when (get-text-property (point) 'org-linked-text)
7285 (setq type "thisfile"
7286 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7287 (1+ (point)) (point))
7288 path (buffer-substring
7289 (previous-single-property-change pos 'org-linked-text)
7290 (next-single-property-change pos 'org-linked-text)))
7291 (throw 'match t))
7293 (save-excursion
7294 (when (or (org-in-regexp org-angle-link-re)
7295 (org-in-regexp org-plain-link-re))
7296 (setq type (match-string 1) path (match-string 2))
7297 (throw 'match t)))
7298 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7299 (setq type "tree-match"
7300 path (match-string 1))
7301 (throw 'match t))
7302 (save-excursion
7303 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7304 (setq type "tags"
7305 path (match-string 1))
7306 (while (string-match ":" path)
7307 (setq path (replace-match "+" t t path)))
7308 (throw 'match t))))
7309 (unless path
7310 (error "No link found"))
7311 ;; Remove any trailing spaces in path
7312 (if (string-match " +\\'" path)
7313 (setq path (replace-match "" t t path)))
7315 (cond
7317 ((assoc type org-link-protocols)
7318 (funcall (nth 1 (assoc type org-link-protocols)) path))
7320 ((equal type "mailto")
7321 (let ((cmd (car org-link-mailto-program))
7322 (args (cdr org-link-mailto-program)) args1
7323 (address path) (subject "") a)
7324 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7325 (setq address (match-string 1 path)
7326 subject (org-link-escape (match-string 2 path))))
7327 (while args
7328 (cond
7329 ((not (stringp (car args))) (push (pop args) args1))
7330 (t (setq a (pop args))
7331 (if (string-match "%a" a)
7332 (setq a (replace-match address t t a)))
7333 (if (string-match "%s" a)
7334 (setq a (replace-match subject t t a)))
7335 (push a args1))))
7336 (apply cmd (nreverse args1))))
7338 ((member type '("http" "https" "ftp" "news"))
7339 (browse-url (concat type ":" (org-link-escape
7340 path org-link-escape-chars-browser))))
7342 ((member type '("message"))
7343 (browse-url (concat type ":" path)))
7345 ((string= type "tags")
7346 (org-tags-view in-emacs path))
7347 ((string= type "thisfile")
7348 (if in-emacs
7349 (switch-to-buffer-other-window
7350 (org-get-buffer-for-internal-link (current-buffer)))
7351 (org-mark-ring-push))
7352 (let ((cmd `(org-link-search
7353 ,path
7354 ,(cond ((equal in-emacs '(4)) 'occur)
7355 ((equal in-emacs '(16)) 'org-occur)
7356 (t nil))
7357 ,pos)))
7358 (condition-case nil (eval cmd)
7359 (error (progn (widen) (eval cmd))))))
7361 ((string= type "tree-match")
7362 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7364 ((string= type "file")
7365 (if (string-match "::\\([0-9]+\\)\\'" path)
7366 (setq line (string-to-number (match-string 1 path))
7367 path (substring path 0 (match-beginning 0)))
7368 (if (string-match "::\\(.+\\)\\'" path)
7369 (setq search (match-string 1 path)
7370 path (substring path 0 (match-beginning 0)))))
7371 (if (string-match "[*?{]" (file-name-nondirectory path))
7372 (dired path)
7373 (org-open-file path in-emacs line search)))
7375 ((string= type "news")
7376 (require 'org-gnus)
7377 (org-gnus-follow-link path))
7379 ((string= type "shell")
7380 (let ((cmd path))
7381 (if (or (not org-confirm-shell-link-function)
7382 (funcall org-confirm-shell-link-function
7383 (format "Execute \"%s\" in shell? "
7384 (org-add-props cmd nil
7385 'face 'org-warning))))
7386 (progn
7387 (message "Executing %s" cmd)
7388 (shell-command cmd))
7389 (error "Abort"))))
7391 ((string= type "elisp")
7392 (let ((cmd path))
7393 (if (or (not org-confirm-elisp-link-function)
7394 (funcall org-confirm-elisp-link-function
7395 (format "Execute \"%s\" as elisp? "
7396 (org-add-props cmd nil
7397 'face 'org-warning))))
7398 (message "%s => %s" cmd (eval (read cmd)))
7399 (error "Abort"))))
7402 (browse-url-at-point)))))
7403 (move-marker org-open-link-marker nil)
7404 (run-hook-with-args 'org-follow-link-hook))
7406 ;;;; Time estimates
7408 (defun org-get-effort (&optional pom)
7409 "Get the effort estimate for the current entry."
7410 (org-entry-get pom org-effort-property))
7412 ;;; File search
7414 (defvar org-create-file-search-functions nil
7415 "List of functions to construct the right search string for a file link.
7416 These functions are called in turn with point at the location to
7417 which the link should point.
7419 A function in the hook should first test if it would like to
7420 handle this file type, for example by checking the major-mode or
7421 the file extension. If it decides not to handle this file, it
7422 should just return nil to give other functions a chance. If it
7423 does handle the file, it must return the search string to be used
7424 when following the link. The search string will be part of the
7425 file link, given after a double colon, and `org-open-at-point'
7426 will automatically search for it. If special measures must be
7427 taken to make the search successful, another function should be
7428 added to the companion hook `org-execute-file-search-functions',
7429 which see.
7431 A function in this hook may also use `setq' to set the variable
7432 `description' to provide a suggestion for the descriptive text to
7433 be used for this link when it gets inserted into an Org-mode
7434 buffer with \\[org-insert-link].")
7436 (defvar org-execute-file-search-functions nil
7437 "List of functions to execute a file search triggered by a link.
7439 Functions added to this hook must accept a single argument, the
7440 search string that was part of the file link, the part after the
7441 double colon. The function must first check if it would like to
7442 handle this search, for example by checking the major-mode or the
7443 file extension. If it decides not to handle this search, it
7444 should just return nil to give other functions a chance. If it
7445 does handle the search, it must return a non-nil value to keep
7446 other functions from trying.
7448 Each function can access the current prefix argument through the
7449 variable `current-prefix-argument'. Note that a single prefix is
7450 used to force opening a link in Emacs, so it may be good to only
7451 use a numeric or double prefix to guide the search function.
7453 In case this is needed, a function in this hook can also restore
7454 the window configuration before `org-open-at-point' was called using:
7456 (set-window-configuration org-window-config-before-follow-link)")
7458 (defun org-link-search (s &optional type avoid-pos)
7459 "Search for a link search option.
7460 If S is surrounded by forward slashes, it is interpreted as a
7461 regular expression. In org-mode files, this will create an `org-occur'
7462 sparse tree. In ordinary files, `occur' will be used to list matches.
7463 If the current buffer is in `dired-mode', grep will be used to search
7464 in all files. If AVOID-POS is given, ignore matches near that position."
7465 (let ((case-fold-search t)
7466 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7467 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7468 (append '(("") (" ") ("\t") ("\n"))
7469 org-emphasis-alist)
7470 "\\|") "\\)"))
7471 (pos (point))
7472 (pre nil) (post nil)
7473 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7474 (cond
7475 ;; First check if there are any special
7476 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7477 ;; Now try the builtin stuff
7478 ((save-excursion
7479 (goto-char (point-min))
7480 (and
7481 (re-search-forward
7482 (concat "<<" (regexp-quote s0) ">>") nil t)
7483 (setq type 'dedicated
7484 pos (match-beginning 0))))
7485 ;; There is an exact target for this
7486 (goto-char pos))
7487 ((string-match "^/\\(.*\\)/$" s)
7488 ;; A regular expression
7489 (cond
7490 ((org-mode-p)
7491 (org-occur (match-string 1 s)))
7492 ;;((eq major-mode 'dired-mode)
7493 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7494 (t (org-do-occur (match-string 1 s)))))
7496 ;; A normal search strings
7497 (when (equal (string-to-char s) ?*)
7498 ;; Anchor on headlines, post may include tags.
7499 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7500 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7501 s (substring s 1)))
7502 (remove-text-properties
7503 0 (length s)
7504 '(face nil mouse-face nil keymap nil fontified nil) s)
7505 ;; Make a series of regular expressions to find a match
7506 (setq words (org-split-string s "[ \n\r\t]+")
7508 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7509 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7510 "\\)" markers)
7511 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7512 re2a (concat "[ \t\r\n]" re2a_)
7513 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7514 re4 (concat "[^a-zA-Z_]" re4_)
7516 re1 (concat pre re2 post)
7517 re3 (concat pre (if pre re4_ re4) post)
7518 re5 (concat pre ".*" re4)
7519 re2 (concat pre re2)
7520 re2a (concat pre (if pre re2a_ re2a))
7521 re4 (concat pre (if pre re4_ re4))
7522 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7523 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7524 re5 "\\)"
7526 (cond
7527 ((eq type 'org-occur) (org-occur reall))
7528 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7529 (t (goto-char (point-min))
7530 (setq type 'fuzzy)
7531 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7532 (org-search-not-self 1 re1 nil t)
7533 (org-search-not-self 1 re2 nil t)
7534 (org-search-not-self 1 re2a nil t)
7535 (org-search-not-self 1 re3 nil t)
7536 (org-search-not-self 1 re4 nil t)
7537 (org-search-not-self 1 re5 nil t)
7539 (goto-char (match-beginning 1))
7540 (goto-char pos)
7541 (error "No match")))))
7543 ;; Normal string-search
7544 (goto-char (point-min))
7545 (if (search-forward s nil t)
7546 (goto-char (match-beginning 0))
7547 (error "No match"))))
7548 (and (org-mode-p) (org-show-context 'link-search))
7549 type))
7551 (defun org-search-not-self (group &rest args)
7552 "Execute `re-search-forward', but only accept matches that do not
7553 enclose the position of `org-open-link-marker'."
7554 (let ((m org-open-link-marker))
7555 (catch 'exit
7556 (while (apply 're-search-forward args)
7557 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7558 (goto-char (match-end group))
7559 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7560 (> (match-beginning 0) (marker-position m))
7561 (< (match-end 0) (marker-position m)))
7562 (save-match-data
7563 (or (not (org-in-regexp
7564 org-bracket-link-analytic-regexp 1))
7565 (not (match-end 4)) ; no description
7566 (and (<= (match-beginning 4) (point))
7567 (>= (match-end 4) (point))))))
7568 (throw 'exit (point))))))))
7570 (defun org-get-buffer-for-internal-link (buffer)
7571 "Return a buffer to be used for displaying the link target of internal links."
7572 (cond
7573 ((not org-display-internal-link-with-indirect-buffer)
7574 buffer)
7575 ((string-match "(Clone)$" (buffer-name buffer))
7576 (message "Buffer is already a clone, not making another one")
7577 ;; we also do not modify visibility in this case
7578 buffer)
7579 (t ; make a new indirect buffer for displaying the link
7580 (let* ((bn (buffer-name buffer))
7581 (ibn (concat bn "(Clone)"))
7582 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7583 (with-current-buffer ib (org-overview))
7584 ib))))
7586 (defun org-do-occur (regexp &optional cleanup)
7587 "Call the Emacs command `occur'.
7588 If CLEANUP is non-nil, remove the printout of the regular expression
7589 in the *Occur* buffer. This is useful if the regex is long and not useful
7590 to read."
7591 (occur regexp)
7592 (when cleanup
7593 (let ((cwin (selected-window)) win beg end)
7594 (when (setq win (get-buffer-window "*Occur*"))
7595 (select-window win))
7596 (goto-char (point-min))
7597 (when (re-search-forward "match[a-z]+" nil t)
7598 (setq beg (match-end 0))
7599 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7600 (setq end (1- (match-beginning 0)))))
7601 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7602 (goto-char (point-min))
7603 (select-window cwin))))
7605 ;;; The mark ring for links jumps
7607 (defvar org-mark-ring nil
7608 "Mark ring for positions before jumps in Org-mode.")
7609 (defvar org-mark-ring-last-goto nil
7610 "Last position in the mark ring used to go back.")
7611 ;; Fill and close the ring
7612 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7613 (loop for i from 1 to org-mark-ring-length do
7614 (push (make-marker) org-mark-ring))
7615 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7616 org-mark-ring)
7618 (defun org-mark-ring-push (&optional pos buffer)
7619 "Put the current position or POS into the mark ring and rotate it."
7620 (interactive)
7621 (setq pos (or pos (point)))
7622 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7623 (move-marker (car org-mark-ring)
7624 (or pos (point))
7625 (or buffer (current-buffer)))
7626 (message "%s"
7627 (substitute-command-keys
7628 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7630 (defun org-mark-ring-goto (&optional n)
7631 "Jump to the previous position in the mark ring.
7632 With prefix arg N, jump back that many stored positions. When
7633 called several times in succession, walk through the entire ring.
7634 Org-mode commands jumping to a different position in the current file,
7635 or to another Org-mode file, automatically push the old position
7636 onto the ring."
7637 (interactive "p")
7638 (let (p m)
7639 (if (eq last-command this-command)
7640 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7641 (setq p org-mark-ring))
7642 (setq org-mark-ring-last-goto p)
7643 (setq m (car p))
7644 (switch-to-buffer (marker-buffer m))
7645 (goto-char m)
7646 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7648 (defun org-remove-angle-brackets (s)
7649 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7650 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7652 (defun org-add-angle-brackets (s)
7653 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7654 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7656 (defun org-remove-double-quotes (s)
7657 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7658 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7661 ;;; Following specific links
7663 (defun org-follow-timestamp-link ()
7664 (cond
7665 ((org-at-date-range-p t)
7666 (let ((org-agenda-start-on-weekday)
7667 (t1 (match-string 1))
7668 (t2 (match-string 2)))
7669 (setq t1 (time-to-days (org-time-string-to-time t1))
7670 t2 (time-to-days (org-time-string-to-time t2)))
7671 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7672 ((org-at-timestamp-p t)
7673 (org-agenda-list nil (time-to-days (org-time-string-to-time
7674 (substring (match-string 1) 0 10)))
7676 (t (error "This should not happen"))))
7679 ;;; Following file links
7680 (defvar org-wait nil)
7681 (defun org-open-file (path &optional in-emacs line search)
7682 "Open the file at PATH.
7683 First, this expands any special file name abbreviations. Then the
7684 configuration variable `org-file-apps' is checked if it contains an
7685 entry for this file type, and if yes, the corresponding command is launched.
7686 If no application is found, Emacs simply visits the file.
7687 With optional argument IN-EMACS, Emacs will visit the file.
7688 Optional LINE specifies a line to go to, optional SEARCH a string to
7689 search for. If LINE or SEARCH is given, the file will always be
7690 opened in Emacs.
7691 If the file does not exist, an error is thrown."
7692 (setq in-emacs (or in-emacs line search))
7693 (let* ((file (if (equal path "")
7694 buffer-file-name
7695 (substitute-in-file-name (expand-file-name path))))
7696 (apps (append org-file-apps (org-default-apps)))
7697 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7698 (dirp (if remp nil (file-directory-p file)))
7699 (file (if (and dirp org-open-directory-means-index-dot-org)
7700 (concat (file-name-as-directory file) "index.org")
7701 file))
7702 (dfile (downcase file))
7703 (old-buffer (current-buffer))
7704 (old-pos (point))
7705 (old-mode major-mode)
7706 ext cmd)
7707 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7708 (setq ext (match-string 1 dfile))
7709 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7710 (setq ext (match-string 1 dfile))))
7711 (if in-emacs
7712 (setq cmd 'emacs)
7713 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7714 (and dirp (cdr (assoc 'directory apps)))
7715 (cdr (assoc ext apps))
7716 (cdr (assoc t apps)))))
7717 (when (eq cmd 'mailcap)
7718 (require 'mailcap)
7719 (mailcap-parse-mailcaps)
7720 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7721 (command (mailcap-mime-info mime-type)))
7722 (if (stringp command)
7723 (setq cmd command)
7724 (setq cmd 'emacs))))
7725 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7726 (not (file-exists-p file))
7727 (not org-open-non-existing-files))
7728 (error "No such file: %s" file))
7729 (cond
7730 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7731 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7732 (while (string-match "['\"]%s['\"]" cmd)
7733 (setq cmd (replace-match "%s" t t cmd)))
7734 (while (string-match "%s" cmd)
7735 (setq cmd (replace-match
7736 (save-match-data
7737 (shell-quote-argument
7738 (convert-standard-filename file)))
7739 t t cmd)))
7740 (save-window-excursion
7741 (start-process-shell-command cmd nil cmd)
7742 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7744 ((or (stringp cmd)
7745 (eq cmd 'emacs))
7746 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7747 (widen)
7748 (if line (goto-line line)
7749 (if search (org-link-search search))))
7750 ((consp cmd)
7751 (let ((file (convert-standard-filename file)))
7752 (eval cmd)))
7753 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7754 (and (org-mode-p) (eq old-mode 'org-mode)
7755 (or (not (equal old-buffer (current-buffer)))
7756 (not (equal old-pos (point))))
7757 (org-mark-ring-push old-pos old-buffer))))
7759 (defun org-default-apps ()
7760 "Return the default applications for this operating system."
7761 (cond
7762 ((eq system-type 'darwin)
7763 org-file-apps-defaults-macosx)
7764 ((eq system-type 'windows-nt)
7765 org-file-apps-defaults-windowsnt)
7766 (t org-file-apps-defaults-gnu)))
7768 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7769 (defun org-file-remote-p (file)
7770 "Test whether FILE specifies a location on a remote system.
7771 Return non-nil if the location is indeed remote.
7773 For example, the filename \"/user@host:/foo\" specifies a location
7774 on the system \"/user@host:\"."
7775 (cond ((fboundp 'file-remote-p)
7776 (file-remote-p file))
7777 ((fboundp 'tramp-handle-file-remote-p)
7778 (tramp-handle-file-remote-p file))
7779 ((and (boundp 'ange-ftp-name-format)
7780 (string-match (car ange-ftp-name-format) file))
7782 (t nil)))
7785 ;;;; Refiling
7787 (defun org-get-org-file ()
7788 "Read a filename, with default directory `org-directory'."
7789 (let ((default (or org-default-notes-file remember-data-file)))
7790 (read-file-name (format "File name [%s]: " default)
7791 (file-name-as-directory org-directory)
7792 default)))
7794 (defun org-notes-order-reversed-p ()
7795 "Check if the current file should receive notes in reversed order."
7796 (cond
7797 ((not org-reverse-note-order) nil)
7798 ((eq t org-reverse-note-order) t)
7799 ((not (listp org-reverse-note-order)) nil)
7800 (t (catch 'exit
7801 (let ((all org-reverse-note-order)
7802 entry)
7803 (while (setq entry (pop all))
7804 (if (string-match (car entry) buffer-file-name)
7805 (throw 'exit (cdr entry))))
7806 nil)))))
7808 (defvar org-refile-target-table nil
7809 "The list of refile targets, created by `org-refile'.")
7811 (defvar org-agenda-new-buffers nil
7812 "Buffers created to visit agenda files.")
7814 (defun org-get-refile-targets (&optional default-buffer)
7815 "Produce a table with refile targets."
7816 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7817 targets txt re files f desc descre)
7818 (with-current-buffer (or default-buffer (current-buffer))
7819 (while (setq entry (pop entries))
7820 (setq files (car entry) desc (cdr entry))
7821 (cond
7822 ((null files) (setq files (list (current-buffer))))
7823 ((eq files 'org-agenda-files)
7824 (setq files (org-agenda-files 'unrestricted)))
7825 ((and (symbolp files) (fboundp files))
7826 (setq files (funcall files)))
7827 ((and (symbolp files) (boundp files))
7828 (setq files (symbol-value files))))
7829 (if (stringp files) (setq files (list files)))
7830 (cond
7831 ((eq (car desc) :tag)
7832 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7833 ((eq (car desc) :todo)
7834 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7835 ((eq (car desc) :regexp)
7836 (setq descre (cdr desc)))
7837 ((eq (car desc) :level)
7838 (setq descre (concat "^\\*\\{" (number-to-string
7839 (if org-odd-levels-only
7840 (1- (* 2 (cdr desc)))
7841 (cdr desc)))
7842 "\\}[ \t]")))
7843 ((eq (car desc) :maxlevel)
7844 (setq descre (concat "^\\*\\{1," (number-to-string
7845 (if org-odd-levels-only
7846 (1- (* 2 (cdr desc)))
7847 (cdr desc)))
7848 "\\}[ \t]")))
7849 (t (error "Bad refiling target description %s" desc)))
7850 (while (setq f (pop files))
7851 (save-excursion
7852 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7853 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7854 (save-excursion
7855 (save-restriction
7856 (widen)
7857 (goto-char (point-min))
7858 (while (re-search-forward descre nil t)
7859 (goto-char (point-at-bol))
7860 (when (looking-at org-complex-heading-regexp)
7861 (setq txt (match-string 4)
7862 re (concat "^" (regexp-quote
7863 (buffer-substring (match-beginning 1)
7864 (match-end 4)))))
7865 (if (match-end 5) (setq re (concat re "[ \t]+"
7866 (regexp-quote
7867 (match-string 5)))))
7868 (setq re (concat re "[ \t]*$"))
7869 (when org-refile-use-outline-path
7870 (setq txt (mapconcat 'identity
7871 (append
7872 (if (eq org-refile-use-outline-path 'file)
7873 (list (file-name-nondirectory
7874 (buffer-file-name (buffer-base-buffer))))
7875 (if (eq org-refile-use-outline-path 'full-file-path)
7876 (list (buffer-file-name (buffer-base-buffer)))))
7877 (org-get-outline-path)
7878 (list txt))
7879 "/")))
7880 (push (list txt f re (point)) targets))
7881 (goto-char (point-at-eol))))))))
7882 (nreverse targets))))
7884 (defun org-get-outline-path ()
7885 "Return the outline path to the current entry, as a list."
7886 (let (rtn)
7887 (save-excursion
7888 (while (org-up-heading-safe)
7889 (when (looking-at org-complex-heading-regexp)
7890 (push (org-match-string-no-properties 4) rtn)))
7891 rtn)))
7893 (defvar org-refile-history nil
7894 "History for refiling operations.")
7896 (defun org-refile (&optional goto default-buffer)
7897 "Move the entry at point to another heading.
7898 The list of target headings is compiled using the information in
7899 `org-refile-targets', which see. This list is created before each use
7900 and will therefore always be up-to-date.
7902 At the target location, the entry is filed as a subitem of the target heading.
7903 Depending on `org-reverse-note-order', the new subitem will either be the
7904 first of the last subitem.
7906 With prefix arg GOTO, the command will only visit the target location,
7907 not actually move anything.
7908 With a double prefix `C-u C-u', go to the location where the last refiling
7909 operation has put the subtree."
7910 (interactive "P")
7911 (let* ((cbuf (current-buffer))
7912 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7913 pos it nbuf file re level reversed)
7914 (if (equal goto '(16))
7915 (org-refile-goto-last-stored)
7916 (when (setq it (org-refile-get-location
7917 (if goto "Goto: " "Refile to: ") default-buffer))
7918 (setq file (nth 1 it)
7919 re (nth 2 it)
7920 pos (nth 3 it))
7921 (setq nbuf (or (find-buffer-visiting file)
7922 (find-file-noselect file)))
7923 (if goto
7924 (progn
7925 (switch-to-buffer nbuf)
7926 (goto-char pos)
7927 (org-show-context 'org-goto))
7928 (org-copy-subtree 1 nil t)
7929 (save-excursion
7930 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7931 (find-file-noselect file))))
7932 (setq reversed (org-notes-order-reversed-p))
7933 (save-excursion
7934 (save-restriction
7935 (widen)
7936 (goto-char pos)
7937 (looking-at outline-regexp)
7938 (setq level (org-get-valid-level (funcall outline-level) 1))
7939 (goto-char
7940 (if reversed
7941 (outline-next-heading)
7942 (or (save-excursion (outline-get-next-sibling))
7943 (org-end-of-subtree t t)
7944 (point-max))))
7945 (bookmark-set "org-refile-last-stored")
7946 (org-paste-subtree level))))
7947 (org-cut-subtree)
7948 (setq org-markers-to-move nil)
7949 (message "Entry refiled to \"%s\"" (car it)))))))
7951 (defun org-refile-goto-last-stored ()
7952 "Go to the location where the last refile was stored."
7953 (interactive)
7954 (bookmark-jump "org-refile-last-stored")
7955 (message "This is the location of the last refile"))
7957 (defun org-refile-get-location (&optional prompt default-buffer)
7958 "Prompt the user for a refile location, using PROMPT."
7959 (let ((org-refile-targets org-refile-targets)
7960 (org-refile-use-outline-path org-refile-use-outline-path))
7961 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7962 (unless org-refile-target-table
7963 (error "No refile targets"))
7964 (let* ((cbuf (current-buffer))
7965 (cfunc (if org-refile-use-outline-path
7966 'org-olpath-completing-read
7967 'completing-read))
7968 (extra (if org-refile-use-outline-path "/" ""))
7969 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7970 (fname (and filename (file-truename filename)))
7971 (tbl (mapcar
7972 (lambda (x)
7973 (if (not (equal fname (file-truename (nth 1 x))))
7974 (cons (concat (car x) extra " ("
7975 (file-name-nondirectory (nth 1 x)) ")")
7976 (cdr x))
7977 (cons (concat (car x) extra) (cdr x))))
7978 org-refile-target-table))
7979 (completion-ignore-case t))
7980 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7981 tbl)))
7983 (defun org-olpath-completing-read (prompt collection &rest args)
7984 "Read an outline path like a file name."
7985 (let ((thetable collection))
7986 (apply
7987 'completing-read prompt
7988 (lambda (string predicate &optional flag)
7989 (let (rtn r s f (l (length string)))
7990 (cond
7991 ((eq flag nil)
7992 ;; try completion
7993 (try-completion string thetable))
7994 ((eq flag t)
7995 ;; all-completions
7996 (setq rtn (all-completions string thetable predicate))
7997 (mapcar
7998 (lambda (x)
7999 (setq r (substring x l))
8000 (if (string-match " ([^)]*)$" x)
8001 (setq f (match-string 0 x))
8002 (setq f ""))
8003 (if (string-match "/" r)
8004 (concat string (substring r 0 (match-end 0)) f)
8006 rtn))
8007 ((eq flag 'lambda)
8008 ;; exact match?
8009 (assoc string thetable)))
8011 args)))
8013 ;;;; Dynamic blocks
8015 (defun org-find-dblock (name)
8016 "Find the first dynamic block with name NAME in the buffer.
8017 If not found, stay at current position and return nil."
8018 (let (pos)
8019 (save-excursion
8020 (goto-char (point-min))
8021 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8022 nil t)
8023 (match-beginning 0))))
8024 (if pos (goto-char pos))
8025 pos))
8027 (defconst org-dblock-start-re
8028 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8029 "Matches the startline of a dynamic block, with parameters.")
8031 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8032 "Matches the end of a dyhamic block.")
8034 (defun org-create-dblock (plist)
8035 "Create a dynamic block section, with parameters taken from PLIST.
8036 PLIST must containe a :name entry which is used as name of the block."
8037 (unless (bolp) (newline))
8038 (let ((name (plist-get plist :name)))
8039 (insert "#+BEGIN: " name)
8040 (while plist
8041 (if (eq (car plist) :name)
8042 (setq plist (cddr plist))
8043 (insert " " (prin1-to-string (pop plist)))))
8044 (insert "\n\n#+END:\n")
8045 (beginning-of-line -2)))
8047 (defun org-prepare-dblock ()
8048 "Prepare dynamic block for refresh.
8049 This empties the block, puts the cursor at the insert position and returns
8050 the property list including an extra property :name with the block name."
8051 (unless (looking-at org-dblock-start-re)
8052 (error "Not at a dynamic block"))
8053 (let* ((begdel (1+ (match-end 0)))
8054 (name (org-no-properties (match-string 1)))
8055 (params (append (list :name name)
8056 (read (concat "(" (match-string 3) ")")))))
8057 (unless (re-search-forward org-dblock-end-re nil t)
8058 (error "Dynamic block not terminated"))
8059 (setq params
8060 (append params
8061 (list :content (buffer-substring
8062 begdel (match-beginning 0)))))
8063 (delete-region begdel (match-beginning 0))
8064 (goto-char begdel)
8065 (open-line 1)
8066 params))
8068 (defun org-map-dblocks (&optional command)
8069 "Apply COMMAND to all dynamic blocks in the current buffer.
8070 If COMMAND is not given, use `org-update-dblock'."
8071 (let ((cmd (or command 'org-update-dblock))
8072 pos)
8073 (save-excursion
8074 (goto-char (point-min))
8075 (while (re-search-forward org-dblock-start-re nil t)
8076 (goto-char (setq pos (match-beginning 0)))
8077 (condition-case nil
8078 (funcall cmd)
8079 (error (message "Error during update of dynamic block")))
8080 (goto-char pos)
8081 (unless (re-search-forward org-dblock-end-re nil t)
8082 (error "Dynamic block not terminated"))))))
8084 (defun org-dblock-update (&optional arg)
8085 "User command for updating dynamic blocks.
8086 Update the dynamic block at point. With prefix ARG, update all dynamic
8087 blocks in the buffer."
8088 (interactive "P")
8089 (if arg
8090 (org-update-all-dblocks)
8091 (or (looking-at org-dblock-start-re)
8092 (org-beginning-of-dblock))
8093 (org-update-dblock)))
8095 (defun org-update-dblock ()
8096 "Update the dynamic block at point
8097 This means to empty the block, parse for parameters and then call
8098 the correct writing function."
8099 (save-window-excursion
8100 (let* ((pos (point))
8101 (line (org-current-line))
8102 (params (org-prepare-dblock))
8103 (name (plist-get params :name))
8104 (cmd (intern (concat "org-dblock-write:" name))))
8105 (message "Updating dynamic block `%s' at line %d..." name line)
8106 (funcall cmd params)
8107 (message "Updating dynamic block `%s' at line %d...done" name line)
8108 (goto-char pos))))
8110 (defun org-beginning-of-dblock ()
8111 "Find the beginning of the dynamic block at point.
8112 Error if there is no scuh block at point."
8113 (let ((pos (point))
8114 beg)
8115 (end-of-line 1)
8116 (if (and (re-search-backward org-dblock-start-re nil t)
8117 (setq beg (match-beginning 0))
8118 (re-search-forward org-dblock-end-re nil t)
8119 (> (match-end 0) pos))
8120 (goto-char beg)
8121 (goto-char pos)
8122 (error "Not in a dynamic block"))))
8124 (defun org-update-all-dblocks ()
8125 "Update all dynamic blocks in the buffer.
8126 This function can be used in a hook."
8127 (when (org-mode-p)
8128 (org-map-dblocks 'org-update-dblock)))
8131 ;;;; Completion
8133 (defconst org-additional-option-like-keywords
8134 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8135 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8136 "BEGIN_EXAMPLE" "END_EXAMPLE"
8137 "BEGIN_QUOTE" "END_QUOTE"
8138 "BEGIN_VERSE" "END_VERSE"
8139 "BEGIN_SRC" "END_SRC"))
8141 (defcustom org-structure-template-alist
8143 ("s" "#+begin_src ?\n\n#+end_src"
8144 "<src lang=\"?\">\n\n</src>")
8145 ("e" "#+begin_example\n?\n#+end_example"
8146 "<example>\n?\n</example>")
8147 ("q" "#+begin_quote\n?\n#+end_quote"
8148 "<quote>\n?\n</quote>")
8149 ("v" "#+begin_verse\n?\n#+end_verse"
8150 "<verse>\n?\n/verse>")
8151 ("l" "#+begin_latex\n?\n#+end_latex"
8152 "<literal style=\"latex\">\n?\n</literal>")
8153 ("L" "#+latex: "
8154 "<literal style=\"latex\">?</literal>")
8155 ("h" "#+begin_html\n?\n#+end_html"
8156 "<literal style=\"html\">\n?\n</literal>")
8157 ("H" "#+html: "
8158 "<literal style=\"html\">?</literal>")
8159 ("a" "#+begin_ascii\n?\n#+end_ascii")
8160 ("A" "#+ascii: ")
8161 ("i" "#+include %file ?"
8162 "<include file=%file markup=\"?\">")
8164 "Structure completion elements.
8165 This is a list of abbreviation keys and values. The value gets inserted
8166 it you type @samp{.} followed by the key and then the completion key,
8167 usually `M-TAB'. %file will be replaced by a file name after prompting
8168 for the file uning completion.
8169 There are two templates for each key, the first uses the original Org syntax,
8170 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8171 the default when the /org-mtags.el/ module has been loaded. See also the
8172 variable `org-mtags-prefere-muse-templates'.
8173 This is an experimental feature, it is undecided if it is going to stay in."
8174 :group 'org-completion
8175 :type '(repeat
8176 (string :tag "Key")
8177 (string :tag "Template")
8178 (string :tag "Muse Template")))
8180 (defun org-try-structure-completion ()
8181 "Try to complete a structure template before point.
8182 This looks for strings like \"<e\" on an otherwise empty line and
8183 expands them."
8184 (let ((l (buffer-substring (point-at-bol) (point)))
8186 (when (and (looking-at "[ \t]*$")
8187 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8188 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8189 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8190 (match-beginning 1)) a)
8191 t)))
8193 (defun org-complete-expand-structure-template (start cell)
8194 "Expand a structure template."
8195 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8196 (rpl (nth (if musep 2 1) cell)))
8197 (delete-region start (point))
8198 (when (string-match "\\`#\\+" rpl)
8199 (cond
8200 ((bolp))
8201 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8202 (delete-region (point-at-bol) (point)))
8203 (t (newline))))
8204 (setq start (point))
8205 (if (string-match "%file" rpl)
8206 (setq rpl (replace-match
8207 (concat
8208 "\""
8209 (save-match-data
8210 (abbreviate-file-name (read-file-name "Include file: ")))
8211 "\"")
8212 t t rpl)))
8213 (insert rpl)
8214 (if (re-search-backward "\\?" start t) (delete-char 1))))
8217 (defun org-complete (&optional arg)
8218 "Perform completion on word at point.
8219 At the beginning of a headline, this completes TODO keywords as given in
8220 `org-todo-keywords'.
8221 If the current word is preceded by a backslash, completes the TeX symbols
8222 that are supported for HTML support.
8223 If the current word is preceded by \"#+\", completes special words for
8224 setting file options.
8225 In the line after \"#+STARTUP:, complete valid keywords.\"
8226 At all other locations, this simply calls the value of
8227 `org-completion-fallback-command'."
8228 (interactive "P")
8229 (org-without-partial-completion
8230 (catch 'exit
8231 (let* ((a nil)
8232 (end (point))
8233 (beg1 (save-excursion
8234 (skip-chars-backward (org-re "[:alnum:]_@"))
8235 (point)))
8236 (beg (save-excursion
8237 (skip-chars-backward "a-zA-Z0-9_:$")
8238 (point)))
8239 (confirm (lambda (x) (stringp (car x))))
8240 (searchhead (equal (char-before beg) ?*))
8241 (struct
8242 (when (and (member (char-before beg1) '(?. ?<))
8243 (setq a (assoc (buffer-substring beg1 (point))
8244 org-structure-template-alist)))
8245 (org-complete-expand-structure-template (1- beg1) a)
8246 (throw 'exit t)))
8247 (tag (and (equal (char-before beg1) ?:)
8248 (equal (char-after (point-at-bol)) ?*)))
8249 (prop (and (equal (char-before beg1) ?:)
8250 (not (equal (char-after (point-at-bol)) ?*))))
8251 (texp (equal (char-before beg) ?\\))
8252 (link (equal (char-before beg) ?\[))
8253 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8254 beg)
8255 "#+"))
8256 (startup (string-match "^#\\+STARTUP:.*"
8257 (buffer-substring (point-at-bol) (point))))
8258 (completion-ignore-case opt)
8259 (type nil)
8260 (tbl nil)
8261 (table (cond
8262 (opt
8263 (setq type :opt)
8264 (require 'org-exp)
8265 (append
8266 (mapcar
8267 (lambda (x)
8268 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8269 (cons (match-string 2 x) (match-string 1 x)))
8270 (org-split-string (org-get-current-options) "\n"))
8271 (mapcar 'list org-additional-option-like-keywords)))
8272 (startup
8273 (setq type :startup)
8274 org-startup-options)
8275 (link (append org-link-abbrev-alist-local
8276 org-link-abbrev-alist))
8277 (texp
8278 (setq type :tex)
8279 org-html-entities)
8280 ((string-match "\\`\\*+[ \t]+\\'"
8281 (buffer-substring (point-at-bol) beg))
8282 (setq type :todo)
8283 (mapcar 'list org-todo-keywords-1))
8284 (searchhead
8285 (setq type :searchhead)
8286 (save-excursion
8287 (goto-char (point-min))
8288 (while (re-search-forward org-todo-line-regexp nil t)
8289 (push (list
8290 (org-make-org-heading-search-string
8291 (match-string 3) t))
8292 tbl)))
8293 tbl)
8294 (tag (setq type :tag beg beg1)
8295 (or org-tag-alist (org-get-buffer-tags)))
8296 (prop (setq type :prop beg beg1)
8297 (mapcar 'list (org-buffer-property-keys nil t t)))
8298 (t (progn
8299 (call-interactively org-completion-fallback-command)
8300 (throw 'exit nil)))))
8301 (pattern (buffer-substring-no-properties beg end))
8302 (completion (try-completion pattern table confirm)))
8303 (cond ((eq completion t)
8304 (if (not (assoc (upcase pattern) table))
8305 (message "Already complete")
8306 (if (and (equal type :opt)
8307 (not (member (car (assoc (upcase pattern) table))
8308 org-additional-option-like-keywords)))
8309 (insert (substring (cdr (assoc (upcase pattern) table))
8310 (length pattern)))
8311 (if (memq type '(:tag :prop)) (insert ":")))))
8312 ((null completion)
8313 (message "Can't find completion for \"%s\"" pattern)
8314 (ding))
8315 ((not (string= pattern completion))
8316 (delete-region beg end)
8317 (if (string-match " +$" completion)
8318 (setq completion (replace-match "" t t completion)))
8319 (insert completion)
8320 (if (get-buffer-window "*Completions*")
8321 (delete-window (get-buffer-window "*Completions*")))
8322 (if (assoc completion table)
8323 (if (eq type :todo) (insert " ")
8324 (if (memq type '(:tag :prop)) (insert ":"))))
8325 (if (and (equal type :opt) (assoc completion table))
8326 (message "%s" (substitute-command-keys
8327 "Press \\[org-complete] again to insert example settings"))))
8329 (message "Making completion list...")
8330 (let ((list (sort (all-completions pattern table confirm)
8331 'string<)))
8332 (with-output-to-temp-buffer "*Completions*"
8333 (condition-case nil
8334 ;; Protection needed for XEmacs and emacs 21
8335 (display-completion-list list pattern)
8336 (error (display-completion-list list)))))
8337 (message "Making completion list...%s" "done")))))))
8339 ;;;; TODO, DEADLINE, Comments
8341 (defun org-toggle-comment ()
8342 "Change the COMMENT state of an entry."
8343 (interactive)
8344 (save-excursion
8345 (org-back-to-heading)
8346 (let (case-fold-search)
8347 (if (looking-at (concat outline-regexp
8348 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8349 (replace-match "" t t nil 1)
8350 (if (looking-at outline-regexp)
8351 (progn
8352 (goto-char (match-end 0))
8353 (insert org-comment-string " ")))))))
8355 (defvar org-last-todo-state-is-todo nil
8356 "This is non-nil when the last TODO state change led to a TODO state.
8357 If the last change removed the TODO tag or switched to DONE, then
8358 this is nil.")
8360 (defvar org-setting-tags nil) ; dynamically skiped
8362 (defun org-parse-local-options (string var)
8363 "Parse STRING for startup setting relevant for variable VAR."
8364 (let ((rtn (symbol-value var))
8365 e opts)
8366 (save-match-data
8367 (if (or (not string) (not (string-match "\\S-" string)))
8369 (setq opts (delq nil (mapcar (lambda (x)
8370 (setq e (assoc x org-startup-options))
8371 (if (eq (nth 1 e) var) e nil))
8372 (org-split-string string "[ \t]+"))))
8373 (if (not opts)
8375 (setq rtn nil)
8376 (while (setq e (pop opts))
8377 (if (not (nth 3 e))
8378 (setq rtn (nth 2 e))
8379 (if (not (listp rtn)) (setq rtn nil))
8380 (push (nth 2 e) rtn)))
8381 rtn)))))
8383 (defvar org-blocker-hook nil
8384 "Hook for functions that are allowed to block a state change.
8386 Each function gets as its single argument a property list, see
8387 `org-trigger-hook' for more information about this list.
8389 If any of the functions in this hook returns nil, the state change
8390 is blocked.")
8392 (defvar org-trigger-hook nil
8393 "Hook for functions that are triggered by a state change.
8395 Each function gets as its single argument a property list with at least
8396 the following elements:
8398 (:type type-of-change :position pos-at-entry-start
8399 :from old-state :to new-state)
8401 Depending on the type, more properties may be present.
8403 This mechanism is currently implemented for:
8405 TODO state changes
8406 ------------------
8407 :type todo-state-change
8408 :from previous state (keyword as a string), or nil
8409 :to new state (keyword as a string), or nil")
8412 (defun org-todo (&optional arg)
8413 "Change the TODO state of an item.
8414 The state of an item is given by a keyword at the start of the heading,
8415 like
8416 *** TODO Write paper
8417 *** DONE Call mom
8419 The different keywords are specified in the variable `org-todo-keywords'.
8420 By default the available states are \"TODO\" and \"DONE\".
8421 So for this example: when the item starts with TODO, it is changed to DONE.
8422 When it starts with DONE, the DONE is removed. And when neither TODO nor
8423 DONE are present, add TODO at the beginning of the heading.
8425 With C-u prefix arg, use completion to determine the new state.
8426 With numeric prefix arg, switch to that state.
8428 For calling through lisp, arg is also interpreted in the following way:
8429 'none -> empty state
8430 \"\"(empty string) -> switch to empty state
8431 'done -> switch to DONE
8432 'nextset -> switch to the next set of keywords
8433 'previousset -> switch to the previous set of keywords
8434 \"WAITING\" -> switch to the specified keyword, but only if it
8435 really is a member of `org-todo-keywords'."
8436 (interactive "P")
8437 (save-excursion
8438 (catch 'exit
8439 (org-back-to-heading)
8440 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8441 (or (looking-at (concat " +" org-todo-regexp " *"))
8442 (looking-at " *"))
8443 (let* ((match-data (match-data))
8444 (startpos (point-at-bol))
8445 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8446 (org-log-done org-log-done)
8447 (org-log-repeat org-log-repeat)
8448 (org-todo-log-states org-todo-log-states)
8449 (this (match-string 1))
8450 (hl-pos (match-beginning 0))
8451 (head (org-get-todo-sequence-head this))
8452 (ass (assoc head org-todo-kwd-alist))
8453 (interpret (nth 1 ass))
8454 (done-word (nth 3 ass))
8455 (final-done-word (nth 4 ass))
8456 (last-state (or this ""))
8457 (completion-ignore-case t)
8458 (member (member this org-todo-keywords-1))
8459 (tail (cdr member))
8460 (state (cond
8461 ((and org-todo-key-trigger
8462 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8463 (and (not arg) org-use-fast-todo-selection
8464 (not (eq org-use-fast-todo-selection 'prefix)))))
8465 ;; Use fast selection
8466 (org-fast-todo-selection))
8467 ((and (equal arg '(4))
8468 (or (not org-use-fast-todo-selection)
8469 (not org-todo-key-trigger)))
8470 ;; Read a state with completion
8471 (completing-read "State: " (mapcar (lambda(x) (list x))
8472 org-todo-keywords-1)
8473 nil t))
8474 ((eq arg 'right)
8475 (if this
8476 (if tail (car tail) nil)
8477 (car org-todo-keywords-1)))
8478 ((eq arg 'left)
8479 (if (equal member org-todo-keywords-1)
8481 (if this
8482 (nth (- (length org-todo-keywords-1) (length tail) 2)
8483 org-todo-keywords-1)
8484 (org-last org-todo-keywords-1))))
8485 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8486 (setq arg nil))) ; hack to fall back to cycling
8487 (arg
8488 ;; user or caller requests a specific state
8489 (cond
8490 ((equal arg "") nil)
8491 ((eq arg 'none) nil)
8492 ((eq arg 'done) (or done-word (car org-done-keywords)))
8493 ((eq arg 'nextset)
8494 (or (car (cdr (member head org-todo-heads)))
8495 (car org-todo-heads)))
8496 ((eq arg 'previousset)
8497 (let ((org-todo-heads (reverse org-todo-heads)))
8498 (or (car (cdr (member head org-todo-heads)))
8499 (car org-todo-heads))))
8500 ((car (member arg org-todo-keywords-1)))
8501 ((nth (1- (prefix-numeric-value arg))
8502 org-todo-keywords-1))))
8503 ((null member) (or head (car org-todo-keywords-1)))
8504 ((equal this final-done-word) nil) ;; -> make empty
8505 ((null tail) nil) ;; -> first entry
8506 ((eq interpret 'sequence)
8507 (car tail))
8508 ((memq interpret '(type priority))
8509 (if (eq this-command last-command)
8510 (car tail)
8511 (if (> (length tail) 0)
8512 (or done-word (car org-done-keywords))
8513 nil)))
8514 (t nil)))
8515 (next (if state (concat " " state " ") " "))
8516 (change-plist (list :type 'todo-state-change :from this :to state
8517 :position startpos))
8518 dolog now-done-p)
8519 (when org-blocker-hook
8520 (unless (save-excursion
8521 (save-match-data
8522 (run-hook-with-args-until-failure
8523 'org-blocker-hook change-plist)))
8524 (if (interactive-p)
8525 (error "TODO state change from %s to %s blocked" this state)
8526 ;; fail silently
8527 (message "TODO state change from %s to %s blocked" this state)
8528 (throw 'exit nil))))
8529 (store-match-data match-data)
8530 (replace-match next t t)
8531 (unless (pos-visible-in-window-p hl-pos)
8532 (message "TODO state changed to %s" (org-trim next)))
8533 (unless head
8534 (setq head (org-get-todo-sequence-head state)
8535 ass (assoc head org-todo-kwd-alist)
8536 interpret (nth 1 ass)
8537 done-word (nth 3 ass)
8538 final-done-word (nth 4 ass)))
8539 (when (memq arg '(nextset previousset))
8540 (message "Keyword-Set %d/%d: %s"
8541 (- (length org-todo-sets) -1
8542 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8543 (length org-todo-sets)
8544 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8545 (setq org-last-todo-state-is-todo
8546 (not (member state org-done-keywords)))
8547 (setq now-done-p (and (member state org-done-keywords)
8548 (not (member this org-done-keywords))))
8549 (and logging (org-local-logging logging))
8550 (when (and (or org-todo-log-states org-log-done)
8551 (not (memq arg '(nextset previousset))))
8552 ;; we need to look at recording a time and note
8553 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8554 (nth 2 (assoc this org-todo-log-states))))
8555 (when (and state
8556 (member state org-not-done-keywords)
8557 (not (member this org-not-done-keywords)))
8558 ;; This is now a todo state and was not one before
8559 ;; If there was a CLOSED time stamp, get rid of it.
8560 (org-add-planning-info nil nil 'closed))
8561 (when (and now-done-p org-log-done)
8562 ;; It is now done, and it was not done before
8563 (org-add-planning-info 'closed (org-current-time))
8564 (if (and (not dolog) (eq 'note org-log-done))
8565 (org-add-log-setup 'done state 'findpos 'note)))
8566 (when (and state dolog)
8567 ;; This is a non-nil state, and we need to log it
8568 (org-add-log-setup 'state state 'findpos dolog)))
8569 ;; Fixup tag positioning
8570 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8571 (when org-provide-todo-statistics
8572 (org-update-parent-todo-statistics))
8573 (run-hooks 'org-after-todo-state-change-hook)
8574 (if (and arg (not (member state org-done-keywords)))
8575 (setq head (org-get-todo-sequence-head state)))
8576 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8577 ;; Do we need to trigger a repeat?
8578 (when now-done-p (org-auto-repeat-maybe state))
8579 ;; Fixup cursor location if close to the keyword
8580 (if (and (outline-on-heading-p)
8581 (not (bolp))
8582 (save-excursion (beginning-of-line 1)
8583 (looking-at org-todo-line-regexp))
8584 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8585 (progn
8586 (goto-char (or (match-end 2) (match-end 1)))
8587 (just-one-space)))
8588 (when org-trigger-hook
8589 (save-excursion
8590 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8592 (defun org-update-parent-todo-statistics ()
8593 "Update any statistics cookie in the parent of the current headline."
8594 (interactive)
8595 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8596 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8597 (catch 'exit
8598 (save-excursion
8599 (setq level (org-up-heading-safe))
8600 (unless (and level
8601 (re-search-forward box-re (point-at-eol) t))
8602 (throw 'exit nil))
8603 (setq is-percent (match-end 2))
8604 (save-match-data
8605 (unless (outline-next-heading) (throw 'exit nil))
8606 (while (looking-at org-todo-line-regexp)
8607 (setq kwd (match-string 2))
8608 (and kwd (setq cnt-all (1+ cnt-all)))
8609 (and (member kwd org-done-keywords)
8610 (setq cnt-done (1+ cnt-done)))
8611 (condition-case nil
8612 (outline-forward-same-level 1)
8613 (error (end-of-line 1)))))
8614 (replace-match
8615 (if is-percent
8616 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8617 (format "[%d/%d]" cnt-done cnt-all)))
8618 (run-hook-with-args 'org-after-todo-statistics-hook
8619 cnt-done (- cnt-all cnt-done))))))
8621 (defvar org-after-todo-statistics-hook nil
8622 "Hook that is called after a TODO statistics cookie has been updated.
8623 Each function is called with two arguments: the number of not-done entries
8624 and the number of done entries.
8626 For example, the following function, when added to this hook, will switch
8627 an entry to DONE when all children are done, and back to TODO when new
8628 entries are set to a TODO status. Note that this hook is only called
8629 when there is a statistics cookie in the headline!
8631 (defun org-summary-todo (n-done n-not-done)
8632 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8633 (let (org-log-done org-log-states) ; turn off logging
8634 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8637 (defun org-local-logging (value)
8638 "Get logging settings from a property VALUE."
8639 (let* (words w a)
8640 ;; directly set the variables, they are already local.
8641 (setq org-log-done nil
8642 org-log-repeat nil
8643 org-todo-log-states nil)
8644 (setq words (org-split-string value))
8645 (while (setq w (pop words))
8646 (cond
8647 ((setq a (assoc w org-startup-options))
8648 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8649 (set (nth 1 a) (nth 2 a))))
8650 ((setq a (org-extract-log-state-settings w))
8651 (and (member (car a) org-todo-keywords-1)
8652 (push a org-todo-log-states)))))))
8654 (defun org-get-todo-sequence-head (kwd)
8655 "Return the head of the TODO sequence to which KWD belongs.
8656 If KWD is not set, check if there is a text property remembering the
8657 right sequence."
8658 (let (p)
8659 (cond
8660 ((not kwd)
8661 (or (get-text-property (point-at-bol) 'org-todo-head)
8662 (progn
8663 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8664 nil (point-at-eol)))
8665 (get-text-property p 'org-todo-head))))
8666 ((not (member kwd org-todo-keywords-1))
8667 (car org-todo-keywords-1))
8668 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8670 (defun org-fast-todo-selection ()
8671 "Fast TODO keyword selection with single keys.
8672 Returns the new TODO keyword, or nil if no state change should occur."
8673 (let* ((fulltable org-todo-key-alist)
8674 (done-keywords org-done-keywords) ;; needed for the faces.
8675 (maxlen (apply 'max (mapcar
8676 (lambda (x)
8677 (if (stringp (car x)) (string-width (car x)) 0))
8678 fulltable)))
8679 (expert nil)
8680 (fwidth (+ maxlen 3 1 3))
8681 (ncol (/ (- (window-width) 4) fwidth))
8682 tg cnt e c tbl
8683 groups ingroup)
8684 (save-window-excursion
8685 (if expert
8686 (set-buffer (get-buffer-create " *Org todo*"))
8687 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8688 (erase-buffer)
8689 (org-set-local 'org-done-keywords done-keywords)
8690 (setq tbl fulltable cnt 0)
8691 (while (setq e (pop tbl))
8692 (cond
8693 ((equal e '(:startgroup))
8694 (push '() groups) (setq ingroup t)
8695 (when (not (= cnt 0))
8696 (setq cnt 0)
8697 (insert "\n"))
8698 (insert "{ "))
8699 ((equal e '(:endgroup))
8700 (setq ingroup nil cnt 0)
8701 (insert "}\n"))
8703 (setq tg (car e) c (cdr e))
8704 (if ingroup (push tg (car groups)))
8705 (setq tg (org-add-props tg nil 'face
8706 (org-get-todo-face tg)))
8707 (if (and (= cnt 0) (not ingroup)) (insert " "))
8708 (insert "[" c "] " tg (make-string
8709 (- fwidth 4 (length tg)) ?\ ))
8710 (when (= (setq cnt (1+ cnt)) ncol)
8711 (insert "\n")
8712 (if ingroup (insert " "))
8713 (setq cnt 0)))))
8714 (insert "\n")
8715 (goto-char (point-min))
8716 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8717 (fit-window-to-buffer))
8718 (message "[a-z..]:Set [SPC]:clear")
8719 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8720 (cond
8721 ((or (= c ?\C-g)
8722 (and (= c ?q) (not (rassoc c fulltable))))
8723 (setq quit-flag t))
8724 ((= c ?\ ) nil)
8725 ((setq e (rassoc c fulltable) tg (car e))
8727 (t (setq quit-flag t))))))
8729 (defun org-entry-is-todo-p ()
8730 (member (org-get-todo-state) org-not-done-keywords))
8732 (defun org-entry-is-done-p ()
8733 (member (org-get-todo-state) org-done-keywords))
8735 (defun org-get-todo-state ()
8736 (save-excursion
8737 (org-back-to-heading t)
8738 (and (looking-at org-todo-line-regexp)
8739 (match-end 2)
8740 (match-string 2))))
8742 (defun org-at-date-range-p (&optional inactive-ok)
8743 "Is the cursor inside a date range?"
8744 (interactive)
8745 (save-excursion
8746 (catch 'exit
8747 (let ((pos (point)))
8748 (skip-chars-backward "^[<\r\n")
8749 (skip-chars-backward "<[")
8750 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8751 (>= (match-end 0) pos)
8752 (throw 'exit t))
8753 (skip-chars-backward "^<[\r\n")
8754 (skip-chars-backward "<[")
8755 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8756 (>= (match-end 0) pos)
8757 (throw 'exit t)))
8758 nil)))
8760 (defun org-get-repeat ()
8761 "Check if there is a deadline/schedule with repeater in this entry."
8762 (save-match-data
8763 (save-excursion
8764 (org-back-to-heading t)
8765 (if (re-search-forward
8766 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8767 (match-string 1)))))
8769 (defvar org-last-changed-timestamp)
8770 (defvar org-last-inserted-timestamp)
8771 (defvar org-log-post-message)
8772 (defvar org-log-note-purpose)
8773 (defvar org-log-note-how)
8774 (defvar org-log-note-extra)
8775 (defun org-auto-repeat-maybe (done-word)
8776 "Check if the current headline contains a repeated deadline/schedule.
8777 If yes, set TODO state back to what it was and change the base date
8778 of repeating deadline/scheduled time stamps to new date.
8779 This function is run automatically after each state change to a DONE state."
8780 ;; last-state is dynamically scoped into this function
8781 (let* ((repeat (org-get-repeat))
8782 (aa (assoc last-state org-todo-kwd-alist))
8783 (interpret (nth 1 aa))
8784 (head (nth 2 aa))
8785 (whata '(("d" . day) ("m" . month) ("y" . year)))
8786 (msg "Entry repeats: ")
8787 (org-log-done nil)
8788 (org-todo-log-states nil)
8789 (nshiftmax 10) (nshift 0)
8790 re type n what ts mb0 time)
8791 (when repeat
8792 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8793 (org-todo (if (eq interpret 'type) last-state head))
8794 (when org-log-repeat
8795 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8796 (memq 'org-add-log-note post-command-hook))
8797 ;; OK, we are already setup for some record
8798 (if (eq org-log-repeat 'note)
8799 ;; make sure we take a note, not only a time stamp
8800 (setq org-log-note-how 'note))
8801 ;; Set up for taking a record
8802 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8803 'findpos org-log-repeat)))
8804 (org-back-to-heading t)
8805 (org-add-planning-info nil nil 'closed)
8806 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8807 org-deadline-time-regexp "\\)\\|\\("
8808 org-ts-regexp "\\)"))
8809 (while (re-search-forward
8810 re (save-excursion (outline-next-heading) (point)) t)
8811 (setq type (if (match-end 1) org-scheduled-string
8812 (if (match-end 3) org-deadline-string "Plain:"))
8813 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8814 mb0 (match-beginning 0))
8815 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8816 (setq n (string-to-number (match-string 2 ts))
8817 what (match-string 3 ts))
8818 (if (equal what "w") (setq n (* n 7) what "d"))
8819 ;; Preparation, see if we need to modify the start date for the change
8820 (when (match-end 1)
8821 (setq time (save-match-data (org-time-string-to-time ts)))
8822 (cond
8823 ((equal (match-string 1 ts) ".")
8824 ;; Shift starting date to today
8825 (org-timestamp-change
8826 (- (time-to-days (current-time)) (time-to-days time))
8827 'day))
8828 ((equal (match-string 1 ts) "+")
8829 (while (or (= nshift 0)
8830 (<= (time-to-days time) (time-to-days (current-time))))
8831 (when (= (incf nshift) nshiftmax)
8832 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8833 (error "Abort")))
8834 (org-timestamp-change n (cdr (assoc what whata)))
8835 (org-at-timestamp-p t)
8836 (setq ts (match-string 1))
8837 (setq time (save-match-data (org-time-string-to-time ts))))
8838 (org-timestamp-change (- n) (cdr (assoc what whata)))
8839 ;; rematch, so that we have everything in place for the real shift
8840 (org-at-timestamp-p t)
8841 (setq ts (match-string 1))
8842 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8843 (org-timestamp-change n (cdr (assoc what whata)))
8844 (setq msg (concat msg type org-last-changed-timestamp " "))))
8845 (setq org-log-post-message msg)
8846 (message "%s" msg))))
8848 (defun org-show-todo-tree (arg)
8849 "Make a compact tree which shows all headlines marked with TODO.
8850 The tree will show the lines where the regexp matches, and all higher
8851 headlines above the match.
8852 With a \\[universal-argument] prefix, also show the DONE entries.
8853 With a numeric prefix N, construct a sparse tree for the Nth element
8854 of `org-todo-keywords-1'."
8855 (interactive "P")
8856 (let ((case-fold-search nil)
8857 (kwd-re
8858 (cond ((null arg) org-not-done-regexp)
8859 ((equal arg '(4))
8860 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8861 (mapcar 'list org-todo-keywords-1))))
8862 (concat "\\("
8863 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8864 "\\)\\>")))
8865 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8866 (regexp-quote (nth (1- (prefix-numeric-value arg))
8867 org-todo-keywords-1)))
8868 (t (error "Invalid prefix argument: %s" arg)))))
8869 (message "%d TODO entries found"
8870 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8872 (defun org-deadline (&optional remove time)
8873 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8874 With argument REMOVE, remove any deadline from the item.
8875 When TIME is set, it should be an internal time specification, and the
8876 scheduling will use the corresponding date."
8877 (interactive "P")
8878 (if remove
8879 (progn
8880 (org-remove-timestamp-with-keyword org-deadline-string)
8881 (message "Item no longer has a deadline."))
8882 (if (org-get-repeat)
8883 (error "Cannot change deadline on task with repeater, please do that by hand")
8884 (org-add-planning-info 'deadline time 'closed)
8885 (message "Deadline on %s" org-last-inserted-timestamp))))
8887 (defun org-schedule (&optional remove time)
8888 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8889 With argument REMOVE, remove any scheduling date from the item.
8890 When TIME is set, it should be an internal time specification, and the
8891 scheduling will use the corresponding date."
8892 (interactive "P")
8893 (if remove
8894 (progn
8895 (org-remove-timestamp-with-keyword org-scheduled-string)
8896 (message "Item is no longer scheduled."))
8897 (if (org-get-repeat)
8898 (error "Cannot reschedule task with repeater, please do that by hand")
8899 (org-add-planning-info 'scheduled time 'closed)
8900 (message "Scheduled to %s" org-last-inserted-timestamp))))
8902 (defun org-remove-timestamp-with-keyword (keyword)
8903 "Remove all time stamps with KEYWORD in the current entry."
8904 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8905 beg)
8906 (save-excursion
8907 (org-back-to-heading t)
8908 (setq beg (point))
8909 (org-end-of-subtree t t)
8910 (while (re-search-backward re beg t)
8911 (replace-match "")
8912 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8913 (equal (char-before) ?\ ))
8914 (backward-delete-char 1)
8915 (if (string-match "^[ \t]*$" (buffer-substring
8916 (point-at-bol) (point-at-eol)))
8917 (delete-region (point-at-bol)
8918 (min (point-max) (1+ (point-at-eol))))))))))
8920 (defun org-add-planning-info (what &optional time &rest remove)
8921 "Insert new timestamp with keyword in the line directly after the headline.
8922 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8923 If non is given, the user is prompted for a date.
8924 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8925 be removed."
8926 (interactive)
8927 (let (org-time-was-given org-end-time-was-given ts
8928 end default-time default-input)
8930 (when (and (not time) (memq what '(scheduled deadline)))
8931 ;; Try to get a default date/time from existing timestamp
8932 (save-excursion
8933 (org-back-to-heading t)
8934 (setq end (save-excursion (outline-next-heading) (point)))
8935 (when (re-search-forward (if (eq what 'scheduled)
8936 org-scheduled-time-regexp
8937 org-deadline-time-regexp)
8938 end t)
8939 (setq ts (match-string 1)
8940 default-time
8941 (apply 'encode-time (org-parse-time-string ts))
8942 default-input (and ts (org-get-compact-tod ts))))))
8943 (when what
8944 ;; If necessary, get the time from the user
8945 (setq time (or time (org-read-date nil 'to-time nil nil
8946 default-time default-input))))
8948 (when (and org-insert-labeled-timestamps-at-point
8949 (member what '(scheduled deadline)))
8950 (insert
8951 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8952 (org-insert-time-stamp time org-time-was-given
8953 nil nil nil (list org-end-time-was-given))
8954 (setq what nil))
8955 (save-excursion
8956 (save-restriction
8957 (let (col list elt ts buffer-invisibility-spec)
8958 (org-back-to-heading t)
8959 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8960 (goto-char (match-end 1))
8961 (setq col (current-column))
8962 (goto-char (match-end 0))
8963 (if (eobp) (insert "\n") (forward-char 1))
8964 (if (and (not (looking-at outline-regexp))
8965 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8966 "[^\r\n]*"))
8967 (not (equal (match-string 1) org-clock-string)))
8968 (narrow-to-region (match-beginning 0) (match-end 0))
8969 (insert-before-markers "\n")
8970 (backward-char 1)
8971 (narrow-to-region (point) (point))
8972 (and org-adapt-indentation (org-indent-to-column col)))
8973 ;; Check if we have to remove something.
8974 (setq list (cons what remove))
8975 (while list
8976 (setq elt (pop list))
8977 (goto-char (point-min))
8978 (when (or (and (eq elt 'scheduled)
8979 (re-search-forward org-scheduled-time-regexp nil t))
8980 (and (eq elt 'deadline)
8981 (re-search-forward org-deadline-time-regexp nil t))
8982 (and (eq elt 'closed)
8983 (re-search-forward org-closed-time-regexp nil t)))
8984 (replace-match "")
8985 (if (looking-at "--+<[^>]+>") (replace-match ""))
8986 (if (looking-at " +") (replace-match ""))))
8987 (goto-char (point-max))
8988 (when what
8989 (insert
8990 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8991 (cond ((eq what 'scheduled) org-scheduled-string)
8992 ((eq what 'deadline) org-deadline-string)
8993 ((eq what 'closed) org-closed-string))
8994 " ")
8995 (setq ts (org-insert-time-stamp
8996 time
8997 (or org-time-was-given
8998 (and (eq what 'closed) org-log-done-with-time))
8999 (eq what 'closed)
9000 nil nil (list org-end-time-was-given)))
9001 (end-of-line 1))
9002 (goto-char (point-min))
9003 (widen)
9004 (if (and (looking-at "[ \t]+\n")
9005 (equal (char-before) ?\n))
9006 (delete-region (1- (point)) (point-at-eol)))
9007 ts)))))
9009 (defvar org-log-note-marker (make-marker))
9010 (defvar org-log-note-purpose nil)
9011 (defvar org-log-note-state nil)
9012 (defvar org-log-note-how nil)
9013 (defvar org-log-note-extra nil)
9014 (defvar org-log-note-window-configuration nil)
9015 (defvar org-log-note-return-to (make-marker))
9016 (defvar org-log-post-message nil
9017 "Message to be displayed after a log note has been stored.
9018 The auto-repeater uses this.")
9020 (defun org-add-note ()
9021 "Add a note to the current entry.
9022 This is done in the same way as adding a state change note."
9023 (interactive)
9024 (org-add-log-setup 'note nil t nil))
9026 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9027 "Set up the post command hook to take a note.
9028 If this is about to TODO state change, the new state is expected in STATE.
9029 When FINDPOS is non-nil, find the correct position for the note in
9030 the current entry. If not, assume that it can be inserted at point.
9031 HOW is an indicator what kind of note should be created.
9032 EXTRA is additional text that will be inserted into the notes buffer."
9033 (save-excursion
9034 (when findpos
9035 (org-back-to-heading t)
9036 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9037 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9038 "[^\r\n]*\\)?"))
9039 (goto-char (match-end 0))
9040 (unless org-log-states-order-reversed
9041 (and (= (char-after) ?\n) (forward-char 1))
9042 (org-skip-over-state-notes)
9043 (skip-chars-backward " \t\n\r")))
9044 (move-marker org-log-note-marker (point))
9045 (setq org-log-note-purpose purpose
9046 org-log-note-state state
9047 org-log-note-how how
9048 org-log-note-extra extra)
9049 (add-hook 'post-command-hook 'org-add-log-note 'append)))
9051 (defun org-skip-over-state-notes ()
9052 "Skip past the list of State notes in an entry."
9053 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9054 (while (looking-at "[ \t]*- State")
9055 (condition-case nil
9056 (org-next-item)
9057 (error (org-end-of-item)))))
9059 (defun org-add-log-note (&optional purpose)
9060 "Pop up a window for taking a note, and add this note later at point."
9061 (remove-hook 'post-command-hook 'org-add-log-note)
9062 (setq org-log-note-window-configuration (current-window-configuration))
9063 (delete-other-windows)
9064 (move-marker org-log-note-return-to (point))
9065 (switch-to-buffer (marker-buffer org-log-note-marker))
9066 (goto-char org-log-note-marker)
9067 (org-switch-to-buffer-other-window "*Org Note*")
9068 (erase-buffer)
9069 (if (memq org-log-note-how '(time state))
9070 (org-store-log-note)
9071 (let ((org-inhibit-startup t)) (org-mode))
9072 (insert (format "# Insert note for %s.
9073 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9074 (cond
9075 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9076 ((eq org-log-note-purpose 'done) "closed todo item")
9077 ((eq org-log-note-purpose 'state)
9078 (format "state change to \"%s\"" org-log-note-state))
9079 ((eq org-log-note-purpose 'note)
9080 "this entry")
9081 (t (error "This should not happen")))))
9082 (if org-log-note-extra (insert org-log-note-extra))
9083 (org-set-local 'org-finish-function 'org-store-log-note)))
9085 (defvar org-note-abort nil) ; dynamically scoped
9086 (defun org-store-log-note ()
9087 "Finish taking a log note, and insert it to where it belongs."
9088 (let ((txt (buffer-string))
9089 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9090 lines ind)
9091 (kill-buffer (current-buffer))
9092 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9093 (setq txt (replace-match "" t t txt)))
9094 (if (string-match "\\s-+\\'" txt)
9095 (setq txt (replace-match "" t t txt)))
9096 (setq lines (org-split-string txt "\n"))
9097 (when (and note (string-match "\\S-" note))
9098 (setq note
9099 (org-replace-escapes
9100 note
9101 (list (cons "%u" (user-login-name))
9102 (cons "%U" user-full-name)
9103 (cons "%t" (format-time-string
9104 (org-time-stamp-format 'long 'inactive)
9105 (current-time)))
9106 (cons "%s" (if org-log-note-state
9107 (concat "\"" org-log-note-state "\"")
9108 "")))))
9109 (if lines (setq note (concat note " \\\\")))
9110 (push note lines))
9111 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9112 (when lines
9113 (save-excursion
9114 (set-buffer (marker-buffer org-log-note-marker))
9115 (save-excursion
9116 (goto-char org-log-note-marker)
9117 (move-marker org-log-note-marker nil)
9118 (end-of-line 1)
9119 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9120 (indent-relative nil)
9121 (insert "- " (pop lines))
9122 (org-indent-line-function)
9123 (beginning-of-line 1)
9124 (looking-at "[ \t]*")
9125 (setq ind (concat (match-string 0) " "))
9126 (end-of-line 1)
9127 (while lines (insert "\n" ind (pop lines)))))))
9128 (set-window-configuration org-log-note-window-configuration)
9129 (with-current-buffer (marker-buffer org-log-note-return-to)
9130 (goto-char org-log-note-return-to))
9131 (move-marker org-log-note-return-to nil)
9132 (and org-log-post-message (message "%s" org-log-post-message)))
9134 (defun org-sparse-tree (&optional arg)
9135 "Create a sparse tree, prompt for the details.
9136 This command can create sparse trees. You first need to select the type
9137 of match used to create the tree:
9139 t Show entries with a specific TODO keyword.
9140 T Show entries selected by a tags match.
9141 p Enter a property name and its value (both with completion on existing
9142 names/values) and show entries with that property.
9143 r Show entries matching a regular expression
9144 d Show deadlines due within `org-deadline-warning-days'."
9145 (interactive "P")
9146 (let (ans kwd value)
9147 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9148 (setq ans (read-char-exclusive))
9149 (cond
9150 ((equal ans ?d)
9151 (call-interactively 'org-check-deadlines))
9152 ((equal ans ?b)
9153 (call-interactively 'org-check-before-date))
9154 ((equal ans ?t)
9155 (org-show-todo-tree '(4)))
9156 ((equal ans ?T)
9157 (call-interactively 'org-tags-sparse-tree))
9158 ((member ans '(?p ?P))
9159 (setq kwd (completing-read "Property: "
9160 (mapcar 'list (org-buffer-property-keys))))
9161 (setq value (completing-read "Value: "
9162 (mapcar 'list (org-property-values kwd))))
9163 (unless (string-match "\\`{.*}\\'" value)
9164 (setq value (concat "\"" value "\"")))
9165 (org-tags-sparse-tree arg (concat kwd "=" value)))
9166 ((member ans '(?r ?R ?/))
9167 (call-interactively 'org-occur))
9168 (t (error "No such sparse tree command \"%c\"" ans)))))
9170 (defvar org-occur-highlights nil
9171 "List of overlays used for occur matches.")
9172 (make-variable-buffer-local 'org-occur-highlights)
9173 (defvar org-occur-parameters nil
9174 "Parameters of the active org-occur calls.
9175 This is a list, each call to org-occur pushes as cons cell,
9176 containing the regular expression and the callback, onto the list.
9177 The list can contain several entries if `org-occur' has been called
9178 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9179 will only contain one set of parameters. When the highlights are
9180 removed (for example with `C-c C-c', or with the next edit (depending
9181 on `org-remove-highlights-with-change'), this variable is emptied
9182 as well.")
9183 (make-variable-buffer-local 'org-occur-parameters)
9185 (defun org-occur (regexp &optional keep-previous callback)
9186 "Make a compact tree which shows all matches of REGEXP.
9187 The tree will show the lines where the regexp matches, and all higher
9188 headlines above the match. It will also show the heading after the match,
9189 to make sure editing the matching entry is easy.
9190 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9191 call to `org-occur' will be kept, to allow stacking of calls to this
9192 command.
9193 If CALLBACK is non-nil, it is a function which is called to confirm
9194 that the match should indeed be shown."
9195 (interactive "sRegexp: \nP")
9196 (unless keep-previous
9197 (org-remove-occur-highlights nil nil t))
9198 (push (cons regexp callback) org-occur-parameters)
9199 (let ((cnt 0))
9200 (save-excursion
9201 (goto-char (point-min))
9202 (if (or (not keep-previous) ; do not want to keep
9203 (not org-occur-highlights)) ; no previous matches
9204 ;; hide everything
9205 (org-overview))
9206 (while (re-search-forward regexp nil t)
9207 (when (or (not callback)
9208 (save-match-data (funcall callback)))
9209 (setq cnt (1+ cnt))
9210 (when org-highlight-sparse-tree-matches
9211 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9212 (org-show-context 'occur-tree))))
9213 (when org-remove-highlights-with-change
9214 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9215 nil 'local))
9216 (unless org-sparse-tree-open-archived-trees
9217 (org-hide-archived-subtrees (point-min) (point-max)))
9218 (run-hooks 'org-occur-hook)
9219 (if (interactive-p)
9220 (message "%d match(es) for regexp %s" cnt regexp))
9221 cnt))
9223 (defun org-show-context (&optional key)
9224 "Make sure point and context and visible.
9225 How much context is shown depends upon the variables
9226 `org-show-hierarchy-above', `org-show-following-heading'. and
9227 `org-show-siblings'."
9228 (let ((heading-p (org-on-heading-p t))
9229 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9230 (following-p (org-get-alist-option org-show-following-heading key))
9231 (entry-p (org-get-alist-option org-show-entry-below key))
9232 (siblings-p (org-get-alist-option org-show-siblings key)))
9233 (catch 'exit
9234 ;; Show heading or entry text
9235 (if (and heading-p (not entry-p))
9236 (org-flag-heading nil) ; only show the heading
9237 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9238 (org-show-hidden-entry))) ; show entire entry
9239 (when following-p
9240 ;; Show next sibling, or heading below text
9241 (save-excursion
9242 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9243 (org-flag-heading nil))))
9244 (when siblings-p (org-show-siblings))
9245 (when hierarchy-p
9246 ;; show all higher headings, possibly with siblings
9247 (save-excursion
9248 (while (and (condition-case nil
9249 (progn (org-up-heading-all 1) t)
9250 (error nil))
9251 (not (bobp)))
9252 (org-flag-heading nil)
9253 (when siblings-p (org-show-siblings))))))))
9255 (defun org-reveal (&optional siblings)
9256 "Show current entry, hierarchy above it, and the following headline.
9257 This can be used to show a consistent set of context around locations
9258 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9259 not t for the search context.
9261 With optional argument SIBLINGS, on each level of the hierarchy all
9262 siblings are shown. This repairs the tree structure to what it would
9263 look like when opened with hierarchical calls to `org-cycle'."
9264 (interactive "P")
9265 (let ((org-show-hierarchy-above t)
9266 (org-show-following-heading t)
9267 (org-show-siblings (if siblings t org-show-siblings)))
9268 (org-show-context nil)))
9270 (defun org-highlight-new-match (beg end)
9271 "Highlight from BEG to END and mark the highlight is an occur headline."
9272 (let ((ov (org-make-overlay beg end)))
9273 (org-overlay-put ov 'face 'secondary-selection)
9274 (push ov org-occur-highlights)))
9276 (defun org-remove-occur-highlights (&optional beg end noremove)
9277 "Remove the occur highlights from the buffer.
9278 BEG and END are ignored. If NOREMOVE is nil, remove this function
9279 from the `before-change-functions' in the current buffer."
9280 (interactive)
9281 (unless org-inhibit-highlight-removal
9282 (mapc 'org-delete-overlay org-occur-highlights)
9283 (setq org-occur-highlights nil)
9284 (setq org-occur-parameters nil)
9285 (unless noremove
9286 (remove-hook 'before-change-functions
9287 'org-remove-occur-highlights 'local))))
9289 ;;;; Priorities
9291 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9292 "Regular expression matching the priority indicator.")
9294 (defvar org-remove-priority-next-time nil)
9296 (defun org-priority-up ()
9297 "Increase the priority of the current item."
9298 (interactive)
9299 (org-priority 'up))
9301 (defun org-priority-down ()
9302 "Decrease the priority of the current item."
9303 (interactive)
9304 (org-priority 'down))
9306 (defun org-priority (&optional action)
9307 "Change the priority of an item by ARG.
9308 ACTION can be `set', `up', `down', or a character."
9309 (interactive)
9310 (setq action (or action 'set))
9311 (let (current new news have remove)
9312 (save-excursion
9313 (org-back-to-heading)
9314 (if (looking-at org-priority-regexp)
9315 (setq current (string-to-char (match-string 2))
9316 have t)
9317 (setq current org-default-priority))
9318 (cond
9319 ((or (eq action 'set)
9320 (if (featurep 'xemacs) (characterp action) (integerp action)))
9321 (if (not (eq action 'set))
9322 (setq new action)
9323 (message "Priority %c-%c, SPC to remove: "
9324 org-highest-priority org-lowest-priority)
9325 (setq new (read-char-exclusive)))
9326 (if (and (= (upcase org-highest-priority) org-highest-priority)
9327 (= (upcase org-lowest-priority) org-lowest-priority))
9328 (setq new (upcase new)))
9329 (cond ((equal new ?\ ) (setq remove t))
9330 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9331 (error "Priority must be between `%c' and `%c'"
9332 org-highest-priority org-lowest-priority))))
9333 ((eq action 'up)
9334 (if (and (not have) (eq last-command this-command))
9335 (setq new org-lowest-priority)
9336 (setq new (if (and org-priority-start-cycle-with-default (not have))
9337 org-default-priority (1- current)))))
9338 ((eq action 'down)
9339 (if (and (not have) (eq last-command this-command))
9340 (setq new org-highest-priority)
9341 (setq new (if (and org-priority-start-cycle-with-default (not have))
9342 org-default-priority (1+ current)))))
9343 (t (error "Invalid action")))
9344 (if (or (< (upcase new) org-highest-priority)
9345 (> (upcase new) org-lowest-priority))
9346 (setq remove t))
9347 (setq news (format "%c" new))
9348 (if have
9349 (if remove
9350 (replace-match "" t t nil 1)
9351 (replace-match news t t nil 2))
9352 (if remove
9353 (error "No priority cookie found in line")
9354 (looking-at org-todo-line-regexp)
9355 (if (match-end 2)
9356 (progn
9357 (goto-char (match-end 2))
9358 (insert " [#" news "]"))
9359 (goto-char (match-beginning 3))
9360 (insert "[#" news "] ")))))
9361 (org-preserve-lc (org-set-tags nil 'align))
9362 (if remove
9363 (message "Priority removed")
9364 (message "Priority of current item set to %s" news))))
9367 (defun org-get-priority (s)
9368 "Find priority cookie and return priority."
9369 (save-match-data
9370 (if (not (string-match org-priority-regexp s))
9371 (* 1000 (- org-lowest-priority org-default-priority))
9372 (* 1000 (- org-lowest-priority
9373 (string-to-char (match-string 2 s)))))))
9375 ;;;; Tags
9377 (defvar org-agenda-archives-mode)
9378 (defun org-scan-tags (action matcher &optional todo-only)
9379 "Scan headline tags with inheritance and produce output ACTION.
9381 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9382 or `agenda' to produce an entry list for an agenda view. It can also be
9383 a Lisp form or a function that should be called at each matched headline, in
9384 this case the return value is a list of all return values from these calls.
9386 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9387 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9388 only lines with a TODO keyword are included in the output."
9389 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9390 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9391 (org-re
9392 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9393 (props (list 'face 'default
9394 'done-face 'org-done
9395 'undone-face 'default
9396 'mouse-face 'highlight
9397 'org-not-done-regexp org-not-done-regexp
9398 'org-todo-regexp org-todo-regexp
9399 'keymap org-agenda-keymap
9400 'help-echo
9401 (format "mouse-2 or RET jump to org file %s"
9402 (abbreviate-file-name
9403 (or (buffer-file-name (buffer-base-buffer))
9404 (buffer-name (buffer-base-buffer)))))))
9405 (case-fold-search nil)
9406 lspos tags tags-list
9407 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9408 (llast 0) rtn rtn1 level category i txt
9409 todo marker entry priority)
9410 (when (not (member action '(agenda sparse-tree)))
9411 (setq action (list 'lambda nil action)))
9412 (save-excursion
9413 (goto-char (point-min))
9414 (when (eq action 'sparse-tree)
9415 (org-overview)
9416 (org-remove-occur-highlights))
9417 (while (re-search-forward re nil t)
9418 (catch :skip
9419 (setq todo (if (match-end 1) (match-string 2))
9420 tags (if (match-end 4) (match-string 4)))
9421 (goto-char (setq lspos (1+ (match-beginning 0))))
9422 (setq level (org-reduced-level (funcall outline-level))
9423 category (org-get-category))
9424 (setq i llast llast level)
9425 ;; remove tag lists from same and sublevels
9426 (while (>= i level)
9427 (when (setq entry (assoc i tags-alist))
9428 (setq tags-alist (delete entry tags-alist)))
9429 (setq i (1- i)))
9430 ;; add the next tags
9431 (when tags
9432 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9433 tags-alist
9434 (cons (cons level tags) tags-alist)))
9435 ;; compile tags for current headline
9436 (setq tags-list
9437 (if org-use-tag-inheritance
9438 (apply 'append (mapcar 'cdr tags-alist))
9439 tags))
9440 (when (and tags org-use-tag-inheritance
9441 (not (eq t org-use-tag-inheritance)))
9442 ;; selective inheritance, remove uninherited ones
9443 (setcdr (car tags-alist)
9444 (org-remove-uniherited-tags (cdar tags-alist))))
9445 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9446 (eval matcher)
9448 (not (member org-archive-tag tags-list))
9449 ;; we have an archive tag, should we use this anyway?
9450 (or (not org-agenda-skip-archived-trees)
9451 (and (eq action 'agenda) org-agenda-archives-mode))))
9452 (unless (eq action 'sparse-tree) (org-agenda-skip))
9454 ;; select this headline
9456 (cond
9457 ((eq action 'sparse-tree)
9458 (and org-highlight-sparse-tree-matches
9459 (org-get-heading) (match-end 0)
9460 (org-highlight-new-match
9461 (match-beginning 0) (match-beginning 1)))
9462 (org-show-context 'tags-tree))
9463 ((eq action 'agenda)
9464 (setq txt (org-format-agenda-item
9466 (concat
9467 (if org-tags-match-list-sublevels
9468 (make-string (1- level) ?.) "")
9469 (org-get-heading))
9470 category tags-list)
9471 priority (org-get-priority txt))
9472 (goto-char lspos)
9473 (setq marker (org-agenda-new-marker))
9474 (org-add-props txt props
9475 'org-marker marker 'org-hd-marker marker 'org-category category
9476 'priority priority 'type "tagsmatch")
9477 (push txt rtn))
9478 ((functionp action)
9479 (save-excursion
9480 (setq rtn1 (funcall action))
9481 (push rtn1 rtn))
9482 (goto-char (point-at-eol)))
9483 (t (error "Invalid action")))
9485 ;; if we are to skip sublevels, jump to end of subtree
9486 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9487 (when (and (eq action 'sparse-tree)
9488 (not org-sparse-tree-open-archived-trees))
9489 (org-hide-archived-subtrees (point-min) (point-max)))
9490 (nreverse rtn)))
9492 (defun org-remove-uniherited-tags (tags)
9493 "Remove all tags that are not inherited from the list TAGS."
9494 (cond
9495 ((eq org-use-tag-inheritance t) tags)
9496 ((not org-use-tag-inheritance) nil)
9497 ((stringp org-use-tag-inheritance)
9498 (delq nil (mapcar
9499 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9500 tags)))
9501 ((listp org-use-tag-inheritance)
9502 (org-delete-all org-use-tag-inheritance tags))))
9504 (defvar todo-only) ;; dynamically scoped
9506 (defun org-tags-sparse-tree (&optional todo-only match)
9507 "Create a sparse tree according to tags string MATCH.
9508 MATCH can contain positive and negative selection of tags, like
9509 \"+WORK+URGENT-WITHBOSS\".
9510 If optional argument TODO_ONLY is non-nil, only select lines that are
9511 also TODO lines."
9512 (interactive "P")
9513 (org-prepare-agenda-buffers (list (current-buffer)))
9514 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9516 (defvar org-cached-props nil)
9517 (defun org-cached-entry-get (pom property)
9518 (if (or (eq t org-use-property-inheritance)
9519 (and (stringp org-use-property-inheritance)
9520 (string-match org-use-property-inheritance property))
9521 (and (listp org-use-property-inheritance)
9522 (member property org-use-property-inheritance)))
9523 ;; Caching is not possible, check it directly
9524 (org-entry-get pom property 'inherit)
9525 ;; Get all properties, so that we can do complicated checks easily
9526 (cdr (assoc property (or org-cached-props
9527 (setq org-cached-props
9528 (org-entry-properties pom)))))))
9530 (defun org-global-tags-completion-table (&optional files)
9531 "Return the list of all tags in all agenda buffer/files."
9532 (save-excursion
9533 (org-uniquify
9534 (delq nil
9535 (apply 'append
9536 (mapcar
9537 (lambda (file)
9538 (set-buffer (find-file-noselect file))
9539 (append (org-get-buffer-tags)
9540 (mapcar (lambda (x) (if (stringp (car-safe x))
9541 (list (car-safe x)) nil))
9542 org-tag-alist)))
9543 (if (and files (car files))
9544 files
9545 (org-agenda-files))))))))
9547 (defun org-make-tags-matcher (match)
9548 "Create the TAGS//TODO matcher form for the selection string MATCH."
9549 ;; todo-only is scoped dynamically into this function, and the function
9550 ;; may change it it the matcher asksk for it.
9551 (unless match
9552 ;; Get a new match request, with completion
9553 (let ((org-last-tags-completion-table
9554 (org-global-tags-completion-table)))
9555 (setq match (completing-read
9556 "Match: " 'org-tags-completion-function nil nil nil
9557 'org-tags-history))))
9559 ;; Parse the string and create a lisp form
9560 (let ((match0 match)
9561 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9562 minus tag mm
9563 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9564 orterms term orlist re-p str-p level-p level-op time-p
9565 prop-p pn pv po cat-p gv)
9566 (if (string-match "/+" match)
9567 ;; match contains also a todo-matching request
9568 (progn
9569 (setq tagsmatch (substring match 0 (match-beginning 0))
9570 todomatch (substring match (match-end 0)))
9571 (if (string-match "^!" todomatch)
9572 (setq todo-only t todomatch (substring todomatch 1)))
9573 (if (string-match "^\\s-*$" todomatch)
9574 (setq todomatch nil)))
9575 ;; only matching tags
9576 (setq tagsmatch match todomatch nil))
9578 ;; Make the tags matcher
9579 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9580 (setq tagsmatcher t)
9581 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9582 (while (setq term (pop orterms))
9583 (while (and (equal (substring term -1) "\\") orterms)
9584 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9585 (while (string-match re term)
9586 (setq minus (and (match-end 1)
9587 (equal (match-string 1 term) "-"))
9588 tag (match-string 2 term)
9589 re-p (equal (string-to-char tag) ?{)
9590 level-p (match-end 4)
9591 prop-p (match-end 5)
9592 mm (cond
9593 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9594 (level-p
9595 (setq level-op (org-op-to-function (match-string 3 term)))
9596 `(,level-op level ,(string-to-number
9597 (match-string 4 term))))
9598 (prop-p
9599 (setq pn (match-string 5 term)
9600 po (match-string 6 term)
9601 pv (match-string 7 term)
9602 cat-p (equal pn "CATEGORY")
9603 re-p (equal (string-to-char pv) ?{)
9604 str-p (equal (string-to-char pv) ?\")
9605 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9606 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9607 (if time-p (setq pv (org-matcher-time pv)))
9608 (setq po (org-op-to-function po (if time-p 'time str-p)))
9609 (if (equal pn "CATEGORY")
9610 (setq gv '(get-text-property (point) 'org-category))
9611 (setq gv `(org-cached-entry-get nil ,pn)))
9612 (if re-p
9613 (if (eq po 'org<>)
9614 `(not (string-match ,pv (or ,gv "")))
9615 `(string-match ,pv (or ,gv "")))
9616 (if str-p
9617 `(,po (or ,gv "") ,pv)
9618 `(,po (string-to-number (or ,gv ""))
9619 ,(string-to-number pv) ))))
9620 (t `(member ,(downcase tag) tags-list)))
9621 mm (if minus (list 'not mm) mm)
9622 term (substring term (match-end 0)))
9623 (push mm tagsmatcher))
9624 (push (if (> (length tagsmatcher) 1)
9625 (cons 'and tagsmatcher)
9626 (car tagsmatcher))
9627 orlist)
9628 (setq tagsmatcher nil))
9629 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9630 (setq tagsmatcher
9631 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9632 ;; Make the todo matcher
9633 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9634 (setq todomatcher t)
9635 (setq orterms (org-split-string todomatch "|") orlist nil)
9636 (while (setq term (pop orterms))
9637 (while (string-match re term)
9638 (setq minus (and (match-end 1)
9639 (equal (match-string 1 term) "-"))
9640 kwd (match-string 2 term)
9641 re-p (equal (string-to-char kwd) ?{)
9642 term (substring term (match-end 0))
9643 mm (if re-p
9644 `(string-match ,(substring kwd 1 -1) todo)
9645 (list 'equal 'todo kwd))
9646 mm (if minus (list 'not mm) mm))
9647 (push mm todomatcher))
9648 (push (if (> (length todomatcher) 1)
9649 (cons 'and todomatcher)
9650 (car todomatcher))
9651 orlist)
9652 (setq todomatcher nil))
9653 (setq todomatcher (if (> (length orlist) 1)
9654 (cons 'or orlist) (car orlist))))
9656 ;; Return the string and lisp forms of the matcher
9657 (setq matcher (if todomatcher
9658 (list 'and tagsmatcher todomatcher)
9659 tagsmatcher))
9660 (cons match0 matcher)))
9662 (defun org-op-to-function (op &optional stringp)
9663 "Turn an operator into the appropriate function."
9664 (setq op
9665 (cond
9666 ((equal op "<" ) '(< string< org-time<))
9667 ((equal op ">" ) '(> org-string> org-time>))
9668 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9669 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9670 ((member op '("=" "==")) '(= string= org-time=))
9671 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9672 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9674 (defun org<> (a b) (not (= a b)))
9675 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9676 (defun org-string>= (a b) (not (string< a b)))
9677 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9678 (defun org-string<> (a b) (not (string= a b)))
9679 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9680 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9681 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9682 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9683 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9684 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9685 (defun org-2ft (s)
9686 "Convert S to a floating point time.
9687 If S is already a number, just return it. If it is a string, parse
9688 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9689 (cond
9690 ((numberp s) s)
9691 ((stringp s)
9692 (condition-case nil
9693 (float-time (apply 'encode-time (org-parse-time-string s)))
9694 (error 0.)))
9695 (t 0.)))
9697 (defun org-matcher-time (s)
9698 (cond
9699 ((equal s "<now>") (float-time))
9700 ((equal s "<today>")
9701 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9702 (t (org-2ft s))))
9704 (defun org-match-any-p (re list)
9705 "Does re match any element of list?"
9706 (setq list (mapcar (lambda (x) (string-match re x)) list))
9707 (delq nil list))
9709 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9710 (defvar org-tags-overlay (org-make-overlay 1 1))
9711 (org-detach-overlay org-tags-overlay)
9713 (defun org-get-tags-at (&optional pos)
9714 "Get a list of all headline tags applicable at POS.
9715 POS defaults to point. If tags are inherited, the list contains
9716 the targets in the same sequence as the headlines appear, i.e.
9717 the tags of the current headline come last."
9718 (interactive)
9719 (let (tags ltags lastpos parent)
9720 (save-excursion
9721 (save-restriction
9722 (widen)
9723 (goto-char (or pos (point)))
9724 (save-match-data
9725 (condition-case nil
9726 (progn
9727 (org-back-to-heading t)
9728 (while (not (equal lastpos (point)))
9729 (setq lastpos (point))
9730 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9731 (setq ltags (org-split-string
9732 (org-match-string-no-properties 1) ":"))
9733 (setq tags (append (org-remove-uniherited-tags ltags)
9734 tags)))
9735 (or org-use-tag-inheritance (error ""))
9736 (org-up-heading-all 1)
9737 (setq parent t)))
9738 (error nil))))
9739 (append (org-remove-uniherited-tags org-file-tags) tags))))
9741 (defun org-toggle-tag (tag &optional onoff)
9742 "Toggle the tag TAG for the current line.
9743 If ONOFF is `on' or `off', don't toggle but set to this state."
9744 (unless (org-on-heading-p t) (error "Not on headling"))
9745 (let (res current)
9746 (save-excursion
9747 (beginning-of-line)
9748 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9749 (point-at-eol) t)
9750 (progn
9751 (setq current (match-string 1))
9752 (replace-match ""))
9753 (setq current ""))
9754 (setq current (nreverse (org-split-string current ":")))
9755 (cond
9756 ((eq onoff 'on)
9757 (setq res t)
9758 (or (member tag current) (push tag current)))
9759 ((eq onoff 'off)
9760 (or (not (member tag current)) (setq current (delete tag current))))
9761 (t (if (member tag current)
9762 (setq current (delete tag current))
9763 (setq res t)
9764 (push tag current))))
9765 (end-of-line 1)
9766 (if current
9767 (progn
9768 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9769 (org-set-tags nil t))
9770 (delete-horizontal-space))
9771 (run-hooks 'org-after-tags-change-hook))
9772 res))
9774 (defun org-align-tags-here (to-col)
9775 ;; Assumes that this is a headline
9776 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9777 (beginning-of-line 1)
9778 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9779 (< pos (match-beginning 2)))
9780 (progn
9781 (setq tags-l (- (match-end 2) (match-beginning 2)))
9782 (goto-char (match-beginning 1))
9783 (insert " ")
9784 (delete-region (point) (1+ (match-beginning 2)))
9785 (setq ncol (max (1+ (current-column))
9786 (1+ col)
9787 (if (> to-col 0)
9788 to-col
9789 (- (abs to-col) tags-l))))
9790 (setq p (point))
9791 (insert (make-string (- ncol (current-column)) ?\ ))
9792 (setq ncol (current-column))
9793 (when indent-tabs-mode (tabify p (point-at-eol)))
9794 (org-move-to-column (min ncol col) t))
9795 (goto-char pos))))
9797 (defun org-set-tags (&optional arg just-align)
9798 "Set the tags for the current headline.
9799 With prefix ARG, realign all tags in headings in the current buffer."
9800 (interactive "P")
9801 (let* ((re (concat "^" outline-regexp))
9802 (current (org-get-tags-string))
9803 (col (current-column))
9804 (org-setting-tags t)
9805 table current-tags inherited-tags ; computed below when needed
9806 tags p0 c0 c1 rpl)
9807 (if arg
9808 (save-excursion
9809 (goto-char (point-min))
9810 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9811 (while (re-search-forward re nil t)
9812 (org-set-tags nil t)
9813 (end-of-line 1)))
9814 (message "All tags realigned to column %d" org-tags-column))
9815 (if just-align
9816 (setq tags current)
9817 ;; Get a new set of tags from the user
9818 (save-excursion
9819 (setq table (or org-tag-alist (org-get-buffer-tags))
9820 org-last-tags-completion-table table
9821 current-tags (org-split-string current ":")
9822 inherited-tags (nreverse
9823 (nthcdr (length current-tags)
9824 (nreverse (org-get-tags-at))))
9825 tags
9826 (if (or (eq t org-use-fast-tag-selection)
9827 (and org-use-fast-tag-selection
9828 (delq nil (mapcar 'cdr table))))
9829 (org-fast-tag-selection
9830 current-tags inherited-tags table
9831 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9832 (let ((org-add-colon-after-tag-completion t))
9833 (org-trim
9834 (org-without-partial-completion
9835 (completing-read "Tags: " 'org-tags-completion-function
9836 nil nil current 'org-tags-history)))))))
9837 (while (string-match "[-+&]+" tags)
9838 ;; No boolean logic, just a list
9839 (setq tags (replace-match ":" t t tags))))
9841 (if (string-match "\\`[\t ]*\\'" tags)
9842 (setq tags "")
9843 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9844 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9846 ;; Insert new tags at the correct column
9847 (beginning-of-line 1)
9848 (cond
9849 ((and (equal current "") (equal tags "")))
9850 ((re-search-forward
9851 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9852 (point-at-eol) t)
9853 (if (equal tags "")
9854 (setq rpl "")
9855 (goto-char (match-beginning 0))
9856 (setq c0 (current-column) p0 (point)
9857 c1 (max (1+ c0) (if (> org-tags-column 0)
9858 org-tags-column
9859 (- (- org-tags-column) (length tags))))
9860 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9861 (replace-match rpl t t)
9862 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9863 tags)
9864 (t (error "Tags alignment failed")))
9865 (org-move-to-column col)
9866 (unless just-align
9867 (run-hooks 'org-after-tags-change-hook)))))
9869 (defun org-change-tag-in-region (beg end tag off)
9870 "Add or remove TAG for each entry in the region.
9871 This works in the agenda, and also in an org-mode buffer."
9872 (interactive
9873 (list (region-beginning) (region-end)
9874 (let ((org-last-tags-completion-table
9875 (if (org-mode-p)
9876 (org-get-buffer-tags)
9877 (org-global-tags-completion-table))))
9878 (completing-read
9879 "Tag: " 'org-tags-completion-function nil nil nil
9880 'org-tags-history))
9881 (progn
9882 (message "[s]et or [r]emove? ")
9883 (equal (read-char-exclusive) ?r))))
9884 (if (fboundp 'deactivate-mark) (deactivate-mark))
9885 (let ((agendap (equal major-mode 'org-agenda-mode))
9886 l1 l2 m buf pos newhead (cnt 0))
9887 (goto-char end)
9888 (setq l2 (1- (org-current-line)))
9889 (goto-char beg)
9890 (setq l1 (org-current-line))
9891 (loop for l from l1 to l2 do
9892 (goto-line l)
9893 (setq m (get-text-property (point) 'org-hd-marker))
9894 (when (or (and (org-mode-p) (org-on-heading-p))
9895 (and agendap m))
9896 (setq buf (if agendap (marker-buffer m) (current-buffer))
9897 pos (if agendap m (point)))
9898 (with-current-buffer buf
9899 (save-excursion
9900 (save-restriction
9901 (goto-char pos)
9902 (setq cnt (1+ cnt))
9903 (org-toggle-tag tag (if off 'off 'on))
9904 (setq newhead (org-get-heading)))))
9905 (and agendap (org-agenda-change-all-lines newhead m))))
9906 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9908 (defun org-tags-completion-function (string predicate &optional flag)
9909 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9910 (confirm (lambda (x) (stringp (car x)))))
9911 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9912 (setq s1 (match-string 1 string)
9913 s2 (match-string 2 string))
9914 (setq s1 "" s2 string))
9915 (cond
9916 ((eq flag nil)
9917 ;; try completion
9918 (setq rtn (try-completion s2 ctable confirm))
9919 (if (stringp rtn)
9920 (setq rtn
9921 (concat s1 s2 (substring rtn (length s2))
9922 (if (and org-add-colon-after-tag-completion
9923 (assoc rtn ctable))
9924 ":" ""))))
9925 rtn)
9926 ((eq flag t)
9927 ;; all-completions
9928 (all-completions s2 ctable confirm)
9930 ((eq flag 'lambda)
9931 ;; exact match?
9932 (assoc s2 ctable)))
9935 (defun org-fast-tag-insert (kwd tags face &optional end)
9936 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9937 (insert (format "%-12s" (concat kwd ":"))
9938 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9939 (or end "")))
9941 (defun org-fast-tag-show-exit (flag)
9942 (save-excursion
9943 (goto-line 3)
9944 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9945 (replace-match ""))
9946 (when flag
9947 (end-of-line 1)
9948 (org-move-to-column (- (window-width) 19) t)
9949 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9951 (defun org-set-current-tags-overlay (current prefix)
9952 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9953 (if (featurep 'xemacs)
9954 (org-overlay-display org-tags-overlay (concat prefix s)
9955 'secondary-selection)
9956 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9957 (org-overlay-display org-tags-overlay (concat prefix s)))))
9959 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9960 "Fast tag selection with single keys.
9961 CURRENT is the current list of tags in the headline, INHERITED is the
9962 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9963 possibly with grouping information. TODO-TABLE is a similar table with
9964 TODO keywords, should these have keys assigned to them.
9965 If the keys are nil, a-z are automatically assigned.
9966 Returns the new tags string, or nil to not change the current settings."
9967 (let* ((fulltable (append table todo-table))
9968 (maxlen (apply 'max (mapcar
9969 (lambda (x)
9970 (if (stringp (car x)) (string-width (car x)) 0))
9971 fulltable)))
9972 (buf (current-buffer))
9973 (expert (eq org-fast-tag-selection-single-key 'expert))
9974 (buffer-tags nil)
9975 (fwidth (+ maxlen 3 1 3))
9976 (ncol (/ (- (window-width) 4) fwidth))
9977 (i-face 'org-done)
9978 (c-face 'org-todo)
9979 tg cnt e c char c1 c2 ntable tbl rtn
9980 ov-start ov-end ov-prefix
9981 (exit-after-next org-fast-tag-selection-single-key)
9982 (done-keywords org-done-keywords)
9983 groups ingroup)
9984 (save-excursion
9985 (beginning-of-line 1)
9986 (if (looking-at
9987 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9988 (setq ov-start (match-beginning 1)
9989 ov-end (match-end 1)
9990 ov-prefix "")
9991 (setq ov-start (1- (point-at-eol))
9992 ov-end (1+ ov-start))
9993 (skip-chars-forward "^\n\r")
9994 (setq ov-prefix
9995 (concat
9996 (buffer-substring (1- (point)) (point))
9997 (if (> (current-column) org-tags-column)
9999 (make-string (- org-tags-column (current-column)) ?\ ))))))
10000 (org-move-overlay org-tags-overlay ov-start ov-end)
10001 (save-window-excursion
10002 (if expert
10003 (set-buffer (get-buffer-create " *Org tags*"))
10004 (delete-other-windows)
10005 (split-window-vertically)
10006 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10007 (erase-buffer)
10008 (org-set-local 'org-done-keywords done-keywords)
10009 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10010 (org-fast-tag-insert "Current" current c-face "\n\n")
10011 (org-fast-tag-show-exit exit-after-next)
10012 (org-set-current-tags-overlay current ov-prefix)
10013 (setq tbl fulltable char ?a cnt 0)
10014 (while (setq e (pop tbl))
10015 (cond
10016 ((equal e '(:startgroup))
10017 (push '() groups) (setq ingroup t)
10018 (when (not (= cnt 0))
10019 (setq cnt 0)
10020 (insert "\n"))
10021 (insert "{ "))
10022 ((equal e '(:endgroup))
10023 (setq ingroup nil cnt 0)
10024 (insert "}\n"))
10026 (setq tg (car e) c2 nil)
10027 (if (cdr e)
10028 (setq c (cdr e))
10029 ;; automatically assign a character.
10030 (setq c1 (string-to-char
10031 (downcase (substring
10032 tg (if (= (string-to-char tg) ?@) 1 0)))))
10033 (if (or (rassoc c1 ntable) (rassoc c1 table))
10034 (while (or (rassoc char ntable) (rassoc char table))
10035 (setq char (1+ char)))
10036 (setq c2 c1))
10037 (setq c (or c2 char)))
10038 (if ingroup (push tg (car groups)))
10039 (setq tg (org-add-props tg nil 'face
10040 (cond
10041 ((not (assoc tg table))
10042 (org-get-todo-face tg))
10043 ((member tg current) c-face)
10044 ((member tg inherited) i-face)
10045 (t nil))))
10046 (if (and (= cnt 0) (not ingroup)) (insert " "))
10047 (insert "[" c "] " tg (make-string
10048 (- fwidth 4 (length tg)) ?\ ))
10049 (push (cons tg c) ntable)
10050 (when (= (setq cnt (1+ cnt)) ncol)
10051 (insert "\n")
10052 (if ingroup (insert " "))
10053 (setq cnt 0)))))
10054 (setq ntable (nreverse ntable))
10055 (insert "\n")
10056 (goto-char (point-min))
10057 (if (and (not expert) (fboundp 'fit-window-to-buffer))
10058 (fit-window-to-buffer))
10059 (setq rtn
10060 (catch 'exit
10061 (while t
10062 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10063 (if groups " [!] no groups" " [!]groups")
10064 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10065 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10066 (cond
10067 ((= c ?\r) (throw 'exit t))
10068 ((= c ?!)
10069 (setq groups (not groups))
10070 (goto-char (point-min))
10071 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10072 ((= c ?\C-c)
10073 (if (not expert)
10074 (org-fast-tag-show-exit
10075 (setq exit-after-next (not exit-after-next)))
10076 (setq expert nil)
10077 (delete-other-windows)
10078 (split-window-vertically)
10079 (org-switch-to-buffer-other-window " *Org tags*")
10080 (and (fboundp 'fit-window-to-buffer)
10081 (fit-window-to-buffer))))
10082 ((or (= c ?\C-g)
10083 (and (= c ?q) (not (rassoc c ntable))))
10084 (org-detach-overlay org-tags-overlay)
10085 (setq quit-flag t))
10086 ((= c ?\ )
10087 (setq current nil)
10088 (if exit-after-next (setq exit-after-next 'now)))
10089 ((= c ?\t)
10090 (condition-case nil
10091 (setq tg (completing-read
10092 "Tag: "
10093 (or buffer-tags
10094 (with-current-buffer buf
10095 (org-get-buffer-tags)))))
10096 (quit (setq tg "")))
10097 (when (string-match "\\S-" tg)
10098 (add-to-list 'buffer-tags (list tg))
10099 (if (member tg current)
10100 (setq current (delete tg current))
10101 (push tg current)))
10102 (if exit-after-next (setq exit-after-next 'now)))
10103 ((setq e (rassoc c todo-table) tg (car e))
10104 (with-current-buffer buf
10105 (save-excursion (org-todo tg)))
10106 (if exit-after-next (setq exit-after-next 'now)))
10107 ((setq e (rassoc c ntable) tg (car e))
10108 (if (member tg current)
10109 (setq current (delete tg current))
10110 (loop for g in groups do
10111 (if (member tg g)
10112 (mapc (lambda (x)
10113 (setq current (delete x current)))
10114 g)))
10115 (push tg current))
10116 (if exit-after-next (setq exit-after-next 'now))))
10118 ;; Create a sorted list
10119 (setq current
10120 (sort current
10121 (lambda (a b)
10122 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10123 (if (eq exit-after-next 'now) (throw 'exit t))
10124 (goto-char (point-min))
10125 (beginning-of-line 2)
10126 (delete-region (point) (point-at-eol))
10127 (org-fast-tag-insert "Current" current c-face)
10128 (org-set-current-tags-overlay current ov-prefix)
10129 (while (re-search-forward
10130 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10131 (setq tg (match-string 1))
10132 (add-text-properties
10133 (match-beginning 1) (match-end 1)
10134 (list 'face
10135 (cond
10136 ((member tg current) c-face)
10137 ((member tg inherited) i-face)
10138 (t (get-text-property (match-beginning 1) 'face))))))
10139 (goto-char (point-min)))))
10140 (org-detach-overlay org-tags-overlay)
10141 (if rtn
10142 (mapconcat 'identity current ":")
10143 nil))))
10145 (defun org-get-tags-string ()
10146 "Get the TAGS string in the current headline."
10147 (unless (org-on-heading-p t)
10148 (error "Not on a heading"))
10149 (save-excursion
10150 (beginning-of-line 1)
10151 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10152 (org-match-string-no-properties 1)
10153 "")))
10155 (defun org-get-tags ()
10156 "Get the list of tags specified in the current headline."
10157 (org-split-string (org-get-tags-string) ":"))
10159 (defun org-get-buffer-tags ()
10160 "Get a table of all tags used in the buffer, for completion."
10161 (let (tags)
10162 (save-excursion
10163 (goto-char (point-min))
10164 (while (re-search-forward
10165 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10166 (when (equal (char-after (point-at-bol 0)) ?*)
10167 (mapc (lambda (x) (add-to-list 'tags x))
10168 (org-split-string (org-match-string-no-properties 1) ":")))))
10169 (mapcar 'list tags)))
10171 ;;;; The mapping API
10173 ;;;###autoload
10174 (defun org-map-entries (func &optional match scope &rest skip)
10175 "Call FUNC at each headline selected by MATCH in SCOPE.
10177 FUNC is a function or a lisp form. The function will be called without
10178 arguments, with the cursor positioned at the beginning of the headline.
10179 The return values of all calls to the function will be collected and
10180 returned as a list.
10182 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10183 Only headlines that are matched by this query will be considered during
10184 the iteration. When MATCH is nil or t, all headlines will be
10185 visited by the iteration.
10187 SCOPE determines the scope of this command. It can be any of:
10189 nil The current buffer, respecting the restriction if any
10190 tree The subtree started with the entry at point
10191 file The current buffer, without restriction
10192 file-with-archives
10193 The current buffer, and any archives associated with it
10194 agenda All agenda files
10195 agenda-with-archives
10196 All agenda files with any archive files associated with them
10197 \(file1 file2 ...)
10198 If this is a list, all files in the list will be scanned
10200 The remaining args are treated as settings for the skipping facilities of
10201 the scanner. The following items can be given here:
10203 archive skip trees with the archive tag.
10204 comment skip trees with the COMMENT keyword
10205 function or Emacs Lisp form:
10206 will be used as value for `org-agenda-skip-function', so whenever
10207 the the function returns t, FUNC will not be called for that
10208 entry and search will continue from the point where the
10209 function leaves it."
10210 (let* ((org-agenda-archives-mode nil) ; just to make sure
10211 (org-agenda-skip-archived-trees (memq 'archive skip))
10212 (org-agenda-skip-comment-trees (memq 'comment skip))
10213 (org-agenda-skip-function
10214 (car (org-delete-all '(comment archive) skip)))
10215 (org-tags-match-list-sublevels t)
10216 matcher pos file)
10218 (cond
10219 ((eq match t) (setq matcher t))
10220 ((eq match nil) (setq matcher t))
10221 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10223 (when (eq scope 'tree)
10224 (org-back-to-heading t)
10225 (org-narrow-to-subtree)
10226 (setq scope nil))
10228 (if (not scope)
10229 (progn
10230 (org-prepare-agenda-buffers
10231 (list (buffer-file-name (current-buffer))))
10232 (org-scan-tags func matcher))
10233 ;; Get the right scope
10234 (setq pos (point))
10235 (cond
10236 ((and scope (listp scope) (symbolp (car scope)))
10237 (setq scope (eval scope)))
10238 ((eq scope 'agenda)
10239 (setq scope (org-agenda-files t)))
10240 ((eq scope 'agenda-with-archives)
10241 (setq scope (org-agenda-files t))
10242 (setq scope (org-add-archive-files scope)))
10243 ((eq scope 'file)
10244 (setq scope (list (buffer-file-name))))
10245 ((eq scope 'file-with-archives)
10246 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10247 (org-prepare-agenda-buffers scope)
10248 (while (setq file (pop scope))
10249 (with-current-buffer (org-find-base-buffer-visiting file)
10250 (save-excursion
10251 (save-restriction
10252 (widen)
10253 (goto-char (point-min))
10254 (org-scan-tags func matcher))))))))
10256 ;;;; Properties
10258 ;;; Setting and retrieving properties
10260 (defconst org-special-properties
10261 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10262 "TIMESTAMP" "TIMESTAMP_IA")
10263 "The special properties valid in Org-mode.
10265 These are properties that are not defined in the property drawer,
10266 but in some other way.")
10268 (defconst org-default-properties
10269 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10270 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10271 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10272 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10273 "Some properties that are used by Org-mode for various purposes.
10274 Being in this list makes sure that they are offered for completion.")
10276 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10277 "Regular expression matching the first line of a property drawer.")
10279 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10280 "Regular expression matching the first line of a property drawer.")
10282 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10283 "Regular expression matching the first line of a property drawer.")
10285 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10286 "Regular expression matching the first line of a property drawer.")
10288 (defconst org-property-drawer-re
10289 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10290 org-property-end-re "\\)\n?")
10291 "Matches an entire property drawer.")
10293 (defconst org-clock-drawer-re
10294 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10295 org-property-end-re "\\)\n?")
10296 "Matches an entire clock drawer.")
10298 (defun org-property-action ()
10299 "Do an action on properties."
10300 (interactive)
10301 (let (c)
10302 (org-at-property-p)
10303 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10304 (setq c (read-char-exclusive))
10305 (cond
10306 ((equal c ?s)
10307 (call-interactively 'org-set-property))
10308 ((equal c ?d)
10309 (call-interactively 'org-delete-property))
10310 ((equal c ?D)
10311 (call-interactively 'org-delete-property-globally))
10312 ((equal c ?c)
10313 (call-interactively 'org-compute-property-at-point))
10314 (t (error "No such property action %c" c)))))
10316 (defun org-at-property-p ()
10317 "Is the cursor in a property line?"
10318 ;; FIXME: Does not check if we are actually in the drawer.
10319 ;; FIXME: also returns true on any drawers.....
10320 ;; This is used by C-c C-c for property action.
10321 (save-excursion
10322 (beginning-of-line 1)
10323 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10325 (defun org-get-property-block (&optional beg end force)
10326 "Return the (beg . end) range of the body of the property drawer.
10327 BEG and END can be beginning and end of subtree, if not given
10328 they will be found.
10329 If the drawer does not exist and FORCE is non-nil, create the drawer."
10330 (catch 'exit
10331 (save-excursion
10332 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10333 (end (or end (progn (outline-next-heading) (point)))))
10334 (goto-char beg)
10335 (if (re-search-forward org-property-start-re end t)
10336 (setq beg (1+ (match-end 0)))
10337 (if force
10338 (save-excursion
10339 (org-insert-property-drawer)
10340 (setq end (progn (outline-next-heading) (point))))
10341 (throw 'exit nil))
10342 (goto-char beg)
10343 (if (re-search-forward org-property-start-re end t)
10344 (setq beg (1+ (match-end 0)))))
10345 (if (re-search-forward org-property-end-re end t)
10346 (setq end (match-beginning 0))
10347 (or force (throw 'exit nil))
10348 (goto-char beg)
10349 (setq end beg)
10350 (org-indent-line-function)
10351 (insert ":END:\n"))
10352 (cons beg end)))))
10354 (defun org-entry-properties (&optional pom which)
10355 "Get all properties of the entry at point-or-marker POM.
10356 This includes the TODO keyword, the tags, time strings for deadline,
10357 scheduled, and clocking, and any additional properties defined in the
10358 entry. The return value is an alist, keys may occur multiple times
10359 if the property key was used several times.
10360 POM may also be nil, in which case the current entry is used.
10361 If WHICH is nil or `all', get all properties. If WHICH is
10362 `special' or `standard', only get that subclass."
10363 (setq which (or which 'all))
10364 (org-with-point-at pom
10365 (let ((clockstr (substring org-clock-string 0 -1))
10366 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10367 beg end range props sum-props key value string clocksum)
10368 (save-excursion
10369 (when (condition-case nil (org-back-to-heading t) (error nil))
10370 (setq beg (point))
10371 (setq sum-props (get-text-property (point) 'org-summaries))
10372 (setq clocksum (get-text-property (point) :org-clock-minutes))
10373 (outline-next-heading)
10374 (setq end (point))
10375 (when (memq which '(all special))
10376 ;; Get the special properties, like TODO and tags
10377 (goto-char beg)
10378 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10379 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10380 (when (looking-at org-priority-regexp)
10381 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10382 (when (and (setq value (org-get-tags-string))
10383 (string-match "\\S-" value))
10384 (push (cons "TAGS" value) props))
10385 (when (setq value (org-get-tags-at))
10386 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10387 props))
10388 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10389 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10390 string (if (equal key clockstr)
10391 (org-no-properties
10392 (org-trim
10393 (buffer-substring
10394 (match-beginning 3) (goto-char (point-at-eol)))))
10395 (substring (org-match-string-no-properties 3) 1 -1)))
10396 (unless key
10397 (if (= (char-after (match-beginning 3)) ?\[)
10398 (setq key "TIMESTAMP_IA")
10399 (setq key "TIMESTAMP")))
10400 (when (or (equal key clockstr) (not (assoc key props)))
10401 (push (cons key string) props)))
10405 (when (memq which '(all standard))
10406 ;; Get the standard properties, like :PORP: ...
10407 (setq range (org-get-property-block beg end))
10408 (when range
10409 (goto-char (car range))
10410 (while (re-search-forward
10411 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10412 (cdr range) t)
10413 (setq key (org-match-string-no-properties 1)
10414 value (org-trim (or (org-match-string-no-properties 2) "")))
10415 (unless (member key excluded)
10416 (push (cons key (or value "")) props)))))
10417 (if clocksum
10418 (push (cons "CLOCKSUM"
10419 (org-columns-number-to-string (/ (float clocksum) 60.)
10420 'add_times))
10421 props))
10422 (append sum-props (nreverse props)))))))
10424 (defun org-entry-get (pom property &optional inherit)
10425 "Get value of PROPERTY for entry at point-or-marker POM.
10426 If INHERIT is non-nil and the entry does not have the property,
10427 then also check higher levels of the hierarchy.
10428 If INHERIT is the symbol `selective', use inheritance only if the setting
10429 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10430 If the property is present but empty, the return value is the empty string.
10431 If the property is not present at all, nil is returned."
10432 (org-with-point-at pom
10433 (if (and inherit (if (eq inherit 'selective)
10434 (org-property-inherit-p property)
10436 (org-entry-get-with-inheritance property)
10437 (if (member property org-special-properties)
10438 ;; We need a special property. Use brute force, get all properties.
10439 (cdr (assoc property (org-entry-properties nil 'special)))
10440 (let ((range (org-get-property-block)))
10441 (if (and range
10442 (goto-char (car range))
10443 (re-search-forward
10444 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10445 (cdr range) t))
10446 ;; Found the property, return it.
10447 (if (match-end 1)
10448 (org-match-string-no-properties 1)
10449 "")))))))
10451 (defun org-property-or-variable-value (var &optional inherit)
10452 "Check if there is a property fixing the value of VAR.
10453 If yes, return this value. If not, return the current value of the variable."
10454 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10455 (if (and prop (stringp prop) (string-match "\\S-" prop))
10456 (read prop)
10457 (symbol-value var))))
10459 (defun org-entry-delete (pom property)
10460 "Delete the property PROPERTY from entry at point-or-marker POM."
10461 (org-with-point-at pom
10462 (if (member property org-special-properties)
10463 nil ; cannot delete these properties.
10464 (let ((range (org-get-property-block)))
10465 (if (and range
10466 (goto-char (car range))
10467 (re-search-forward
10468 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10469 (cdr range) t))
10470 (progn
10471 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10473 nil)))))
10475 ;; Multi-values properties are properties that contain multiple values
10476 ;; These values are assumed to be single words, separated by whitespace.
10477 (defun org-entry-add-to-multivalued-property (pom property value)
10478 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10479 (let* ((old (org-entry-get pom property))
10480 (values (and old (org-split-string old "[ \t]"))))
10481 (unless (member value values)
10482 (setq values (cons value values))
10483 (org-entry-put pom property
10484 (mapconcat 'identity values " ")))))
10486 (defun org-entry-remove-from-multivalued-property (pom property value)
10487 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10488 (let* ((old (org-entry-get pom property))
10489 (values (and old (org-split-string old "[ \t]"))))
10490 (when (member value values)
10491 (setq values (delete value values))
10492 (org-entry-put pom property
10493 (mapconcat 'identity values " ")))))
10495 (defun org-entry-member-in-multivalued-property (pom property value)
10496 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10497 (let* ((old (org-entry-get pom property))
10498 (values (and old (org-split-string old "[ \t]"))))
10499 (member value values)))
10501 (defvar org-entry-property-inherited-from (make-marker))
10503 (defun org-entry-get-with-inheritance (property)
10504 "Get entry property, and search higher levels if not present."
10505 (let (tmp)
10506 (save-excursion
10507 (save-restriction
10508 (widen)
10509 (catch 'ex
10510 (while t
10511 (when (setq tmp (org-entry-get nil property))
10512 (org-back-to-heading t)
10513 (move-marker org-entry-property-inherited-from (point))
10514 (throw 'ex tmp))
10515 (or (org-up-heading-safe) (throw 'ex nil)))))
10516 (or tmp
10517 (cdr (assoc property org-file-properties))
10518 (cdr (assoc property org-global-properties))
10519 (cdr (assoc property org-global-properties-fixed))))))
10521 (defun org-entry-put (pom property value)
10522 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10523 (org-with-point-at pom
10524 (org-back-to-heading t)
10525 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10526 range)
10527 (cond
10528 ((equal property "TODO")
10529 (when (and (stringp value) (string-match "\\S-" value)
10530 (not (member value org-todo-keywords-1)))
10531 (error "\"%s\" is not a valid TODO state" value))
10532 (if (or (not value)
10533 (not (string-match "\\S-" value)))
10534 (setq value 'none))
10535 (org-todo value)
10536 (org-set-tags nil 'align))
10537 ((equal property "PRIORITY")
10538 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10539 (string-to-char value) ?\ ))
10540 (org-set-tags nil 'align))
10541 ((equal property "SCHEDULED")
10542 (if (re-search-forward org-scheduled-time-regexp end t)
10543 (cond
10544 ((eq value 'earlier) (org-timestamp-change -1 'day))
10545 ((eq value 'later) (org-timestamp-change 1 'day))
10546 (t (call-interactively 'org-schedule)))
10547 (call-interactively 'org-schedule)))
10548 ((equal property "DEADLINE")
10549 (if (re-search-forward org-deadline-time-regexp end t)
10550 (cond
10551 ((eq value 'earlier) (org-timestamp-change -1 'day))
10552 ((eq value 'later) (org-timestamp-change 1 'day))
10553 (t (call-interactively 'org-deadline)))
10554 (call-interactively 'org-deadline)))
10555 ((member property org-special-properties)
10556 (error "The %s property can not yet be set with `org-entry-put'"
10557 property))
10558 (t ; a non-special property
10559 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10560 (setq range (org-get-property-block beg end 'force))
10561 (goto-char (car range))
10562 (if (re-search-forward
10563 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10564 (progn
10565 (delete-region (match-beginning 1) (match-end 1))
10566 (goto-char (match-beginning 1)))
10567 (goto-char (cdr range))
10568 (insert "\n")
10569 (backward-char 1)
10570 (org-indent-line-function)
10571 (insert ":" property ":"))
10572 (and value (insert " " value))
10573 (org-indent-line-function)))))))
10575 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10576 "Get all property keys in the current buffer.
10577 With INCLUDE-SPECIALS, also list the special properties that relect things
10578 like tags and TODO state.
10579 With INCLUDE-DEFAULTS, also include properties that has special meaning
10580 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10581 With INCLUDE-COLUMNS, also include property names given in COLUMN
10582 formats in the current buffer."
10583 (let (rtn range cfmt cols s p)
10584 (save-excursion
10585 (save-restriction
10586 (widen)
10587 (goto-char (point-min))
10588 (while (re-search-forward org-property-start-re nil t)
10589 (setq range (org-get-property-block))
10590 (goto-char (car range))
10591 (while (re-search-forward
10592 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10593 (cdr range) t)
10594 (add-to-list 'rtn (org-match-string-no-properties 1)))
10595 (outline-next-heading))))
10597 (when include-specials
10598 (setq rtn (append org-special-properties rtn)))
10600 (when include-defaults
10601 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10603 (when include-columns
10604 (save-excursion
10605 (save-restriction
10606 (widen)
10607 (goto-char (point-min))
10608 (while (re-search-forward
10609 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10610 nil t)
10611 (setq cfmt (match-string 2) s 0)
10612 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10613 cfmt s)
10614 (setq s (match-end 0)
10615 p (match-string 1 cfmt))
10616 (unless (or (equal p "ITEM")
10617 (member p org-special-properties))
10618 (add-to-list 'rtn (match-string 1 cfmt))))))))
10620 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10622 (defun org-property-values (key)
10623 "Return a list of all values of property KEY."
10624 (save-excursion
10625 (save-restriction
10626 (widen)
10627 (goto-char (point-min))
10628 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10629 values)
10630 (while (re-search-forward re nil t)
10631 (add-to-list 'values (org-trim (match-string 1))))
10632 (delete "" values)))))
10634 (defun org-insert-property-drawer ()
10635 "Insert a property drawer into the current entry."
10636 (interactive)
10637 (org-back-to-heading t)
10638 (looking-at outline-regexp)
10639 (let ((indent (- (match-end 0)(match-beginning 0)))
10640 (beg (point))
10641 (re (concat "^[ \t]*" org-keyword-time-regexp))
10642 end hiddenp)
10643 (outline-next-heading)
10644 (setq end (point))
10645 (goto-char beg)
10646 (while (re-search-forward re end t))
10647 (setq hiddenp (org-invisible-p))
10648 (end-of-line 1)
10649 (and (equal (char-after) ?\n) (forward-char 1))
10650 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10651 (beginning-of-line 2))
10652 (org-skip-over-state-notes)
10653 (skip-chars-backward " \t\n\r")
10654 (if (eq (char-before) ?*) (forward-char 1))
10655 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10656 (beginning-of-line 0)
10657 (org-indent-to-column indent)
10658 (beginning-of-line 2)
10659 (org-indent-to-column indent)
10660 (beginning-of-line 0)
10661 (if hiddenp
10662 (save-excursion
10663 (org-back-to-heading t)
10664 (hide-entry))
10665 (org-flag-drawer t))))
10667 (defun org-set-property (property value)
10668 "In the current entry, set PROPERTY to VALUE.
10669 When called interactively, this will prompt for a property name, offering
10670 completion on existing and default properties. And then it will prompt
10671 for a value, offering competion either on allowed values (via an inherited
10672 xxx_ALL property) or on existing values in other instances of this property
10673 in the current file."
10674 (interactive
10675 (let* ((completion-ignore-case t)
10676 (keys (org-buffer-property-keys nil t t))
10677 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10678 (prop (if (member prop0 keys)
10679 prop0
10680 (or (cdr (assoc (downcase prop0)
10681 (mapcar (lambda (x) (cons (downcase x) x))
10682 keys)))
10683 prop0)))
10684 (cur (org-entry-get nil prop))
10685 (allowed (org-property-get-allowed-values nil prop 'table))
10686 (existing (mapcar 'list (org-property-values prop)))
10687 (val (if allowed
10688 (org-completing-read "Value: " allowed nil 'req-match)
10689 (org-completing-read
10690 (concat "Value" (if (and cur (string-match "\\S-" cur))
10691 (concat "[" cur "]") "")
10692 ": ")
10693 existing nil nil "" nil cur))))
10694 (list prop (if (equal val "") cur val))))
10695 (unless (equal (org-entry-get nil property) value)
10696 (org-entry-put nil property value)))
10698 (defun org-delete-property (property)
10699 "In the current entry, delete PROPERTY."
10700 (interactive
10701 (let* ((completion-ignore-case t)
10702 (prop (completing-read
10703 "Property: " (org-entry-properties nil 'standard))))
10704 (list prop)))
10705 (message "Property %s %s" property
10706 (if (org-entry-delete nil property)
10707 "deleted"
10708 "was not present in the entry")))
10710 (defun org-delete-property-globally (property)
10711 "Remove PROPERTY globally, from all entries."
10712 (interactive
10713 (let* ((completion-ignore-case t)
10714 (prop (completing-read
10715 "Globally remove property: "
10716 (mapcar 'list (org-buffer-property-keys)))))
10717 (list prop)))
10718 (save-excursion
10719 (save-restriction
10720 (widen)
10721 (goto-char (point-min))
10722 (let ((cnt 0))
10723 (while (re-search-forward
10724 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10725 nil t)
10726 (setq cnt (1+ cnt))
10727 (replace-match ""))
10728 (message "Property \"%s\" removed from %d entries" property cnt)))))
10730 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10732 (defun org-compute-property-at-point ()
10733 "Compute the property at point.
10734 This looks for an enclosing column format, extracts the operator and
10735 then applies it to the proerty in the column format's scope."
10736 (interactive)
10737 (unless (org-at-property-p)
10738 (error "Not at a property"))
10739 (let ((prop (org-match-string-no-properties 2)))
10740 (org-columns-get-format-and-top-level)
10741 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10742 (error "No operator defined for property %s" prop))
10743 (org-columns-compute prop)))
10745 (defun org-property-get-allowed-values (pom property &optional table)
10746 "Get allowed values for the property PROPERTY.
10747 When TABLE is non-nil, return an alist that can directly be used for
10748 completion."
10749 (let (vals)
10750 (cond
10751 ((equal property "TODO")
10752 (setq vals (org-with-point-at pom
10753 (append org-todo-keywords-1 '("")))))
10754 ((equal property "PRIORITY")
10755 (let ((n org-lowest-priority))
10756 (while (>= n org-highest-priority)
10757 (push (char-to-string n) vals)
10758 (setq n (1- n)))))
10759 ((member property org-special-properties))
10761 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10763 (when (and vals (string-match "\\S-" vals))
10764 (setq vals (car (read-from-string (concat "(" vals ")"))))
10765 (setq vals (mapcar (lambda (x)
10766 (cond ((stringp x) x)
10767 ((numberp x) (number-to-string x))
10768 ((symbolp x) (symbol-name x))
10769 (t "???")))
10770 vals)))))
10771 (if table (mapcar 'list vals) vals)))
10773 (defun org-property-previous-allowed-value (&optional previous)
10774 "Switch to the next allowed value for this property."
10775 (interactive)
10776 (org-property-next-allowed-value t))
10778 (defun org-property-next-allowed-value (&optional previous)
10779 "Switch to the next allowed value for this property."
10780 (interactive)
10781 (unless (org-at-property-p)
10782 (error "Not at a property"))
10783 (let* ((key (match-string 2))
10784 (value (match-string 3))
10785 (allowed (or (org-property-get-allowed-values (point) key)
10786 (and (member value '("[ ]" "[-]" "[X]"))
10787 '("[ ]" "[X]"))))
10788 nval)
10789 (unless allowed
10790 (error "Allowed values for this property have not been defined"))
10791 (if previous (setq allowed (reverse allowed)))
10792 (if (member value allowed)
10793 (setq nval (car (cdr (member value allowed)))))
10794 (setq nval (or nval (car allowed)))
10795 (if (equal nval value)
10796 (error "Only one allowed value for this property"))
10797 (org-at-property-p)
10798 (replace-match (concat " :" key ": " nval) t t)
10799 (org-indent-line-function)
10800 (beginning-of-line 1)
10801 (skip-chars-forward " \t")))
10803 (defun org-find-entry-with-id (ident)
10804 "Locate the entry that contains the ID property with exact value IDENT.
10805 IDENT can be a string, a symbol or a number, this function will search for
10806 the string representation of it.
10807 Return the position where this entry starts, or nil if there is no such entry."
10808 (let ((id (cond
10809 ((stringp ident) ident)
10810 ((symbol-name ident) (symbol-name ident))
10811 ((numberp ident) (number-to-string ident))
10812 (t (error "IDENT %s must be a string, symbol or number" ident))))
10813 (case-fold-search nil))
10814 (save-excursion
10815 (save-restriction
10816 (widen)
10817 (goto-char (point-min))
10818 (when (re-search-forward
10819 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10820 nil t)
10821 (org-back-to-heading)
10822 (point))))))
10824 ;;;; Timestamps
10826 (defvar org-last-changed-timestamp nil)
10827 (defvar org-last-inserted-timestamp nil
10828 "The last time stamp inserted with `org-insert-time-stamp'.")
10829 (defvar org-time-was-given) ; dynamically scoped parameter
10830 (defvar org-end-time-was-given) ; dynamically scoped parameter
10831 (defvar org-ts-what) ; dynamically scoped parameter
10833 (defun org-time-stamp (arg)
10834 "Prompt for a date/time and insert a time stamp.
10835 If the user specifies a time like HH:MM, or if this command is called
10836 with a prefix argument, the time stamp will contain date and time.
10837 Otherwise, only the date will be included. All parts of a date not
10838 specified by the user will be filled in from the current date/time.
10839 So if you press just return without typing anything, the time stamp
10840 will represent the current date/time. If there is already a timestamp
10841 at the cursor, it will be modified."
10842 (interactive "P")
10843 (let* ((ts nil)
10844 (default-time
10845 ;; Default time is either today, or, when entering a range,
10846 ;; the range start.
10847 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10848 (save-excursion
10849 (re-search-backward
10850 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10851 (- (point) 20) t)))
10852 (apply 'encode-time (org-parse-time-string (match-string 1)))
10853 (current-time)))
10854 (default-input (and ts (org-get-compact-tod ts)))
10855 org-time-was-given org-end-time-was-given time)
10856 (cond
10857 ((and (org-at-timestamp-p)
10858 (eq last-command 'org-time-stamp)
10859 (eq this-command 'org-time-stamp))
10860 (insert "--")
10861 (setq time (let ((this-command this-command))
10862 (org-read-date arg 'totime nil nil default-time default-input)))
10863 (org-insert-time-stamp time (or org-time-was-given arg)))
10864 ((org-at-timestamp-p)
10865 (setq time (let ((this-command this-command))
10866 (org-read-date arg 'totime nil nil default-time default-input)))
10867 (when (org-at-timestamp-p) ; just to get the match data
10868 (replace-match "")
10869 (setq org-last-changed-timestamp
10870 (org-insert-time-stamp
10871 time (or org-time-was-given arg)
10872 nil nil nil (list org-end-time-was-given))))
10873 (message "Timestamp updated"))
10875 (setq time (let ((this-command this-command))
10876 (org-read-date arg 'totime nil nil default-time default-input)))
10877 (org-insert-time-stamp time (or org-time-was-given arg)
10878 nil nil nil (list org-end-time-was-given))))))
10880 ;; FIXME: can we use this for something else, like computing time differences?
10881 (defun org-get-compact-tod (s)
10882 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10883 (let* ((t1 (match-string 1 s))
10884 (h1 (string-to-number (match-string 2 s)))
10885 (m1 (string-to-number (match-string 3 s)))
10886 (t2 (and (match-end 4) (match-string 5 s)))
10887 (h2 (and t2 (string-to-number (match-string 6 s))))
10888 (m2 (and t2 (string-to-number (match-string 7 s))))
10889 dh dm)
10890 (if (not t2)
10892 (setq dh (- h2 h1) dm (- m2 m1))
10893 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10894 (concat t1 "+" (number-to-string dh)
10895 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10897 (defun org-time-stamp-inactive (&optional arg)
10898 "Insert an inactive time stamp.
10899 An inactive time stamp is enclosed in square brackets instead of angle
10900 brackets. It is inactive in the sense that it does not trigger agenda entries,
10901 does not link to the calendar and cannot be changed with the S-cursor keys.
10902 So these are more for recording a certain time/date."
10903 (interactive "P")
10904 (let (org-time-was-given org-end-time-was-given time)
10905 (setq time (org-read-date arg 'totime))
10906 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10907 nil nil (list org-end-time-was-given))))
10909 (defvar org-date-ovl (org-make-overlay 1 1))
10910 (org-overlay-put org-date-ovl 'face 'org-warning)
10911 (org-detach-overlay org-date-ovl)
10913 (defvar org-ans1) ; dynamically scoped parameter
10914 (defvar org-ans2) ; dynamically scoped parameter
10916 (defvar org-plain-time-of-day-regexp) ; defined below
10918 (defvar org-overriding-default-time nil) ; dynamically scoped
10919 (defvar org-read-date-overlay nil)
10920 (defvar org-dcst nil) ; dynamically scoped
10922 (defun org-read-date (&optional with-time to-time from-string prompt
10923 default-time default-input)
10924 "Read a date, possibly a time, and make things smooth for the user.
10925 The prompt will suggest to enter an ISO date, but you can also enter anything
10926 which will at least partially be understood by `parse-time-string'.
10927 Unrecognized parts of the date will default to the current day, month, year,
10928 hour and minute. If this command is called to replace a timestamp at point,
10929 of to enter the second timestamp of a range, the default time is taken from the
10930 existing stamp. For example,
10931 3-2-5 --> 2003-02-05
10932 feb 15 --> currentyear-02-15
10933 sep 12 9 --> 2009-09-12
10934 12:45 --> today 12:45
10935 22 sept 0:34 --> currentyear-09-22 0:34
10936 12 --> currentyear-currentmonth-12
10937 Fri --> nearest Friday (today or later)
10938 etc.
10940 Furthermore you can specify a relative date by giving, as the *first* thing
10941 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10942 change in days weeks, months, years.
10943 With a single plus or minus, the date is relative to today. With a double
10944 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10945 +4d --> four days from today
10946 +4 --> same as above
10947 +2w --> two weeks from today
10948 ++5 --> five days from default date
10950 The function understands only English month and weekday abbreviations,
10951 but this can be configured with the variables `parse-time-months' and
10952 `parse-time-weekdays'.
10954 While prompting, a calendar is popped up - you can also select the
10955 date with the mouse (button 1). The calendar shows a period of three
10956 months. To scroll it to other months, use the keys `>' and `<'.
10957 If you don't like the calendar, turn it off with
10958 \(setq org-read-date-popup-calendar nil)
10960 With optional argument TO-TIME, the date will immediately be converted
10961 to an internal time.
10962 With an optional argument WITH-TIME, the prompt will suggest to also
10963 insert a time. Note that when WITH-TIME is not set, you can still
10964 enter a time, and this function will inform the calling routine about
10965 this change. The calling routine may then choose to change the format
10966 used to insert the time stamp into the buffer to include the time.
10967 With optional argument FROM-STRING, read from this string instead from
10968 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10969 the time/date that is used for everything that is not specified by the
10970 user."
10971 (require 'parse-time)
10972 (let* ((org-time-stamp-rounding-minutes
10973 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10974 (org-dcst org-display-custom-times)
10975 (ct (org-current-time))
10976 (def (or org-overriding-default-time default-time ct))
10977 (defdecode (decode-time def))
10978 (dummy (progn
10979 (when (< (nth 2 defdecode) org-extend-today-until)
10980 (setcar (nthcdr 2 defdecode) -1)
10981 (setcar (nthcdr 1 defdecode) 59)
10982 (setq def (apply 'encode-time defdecode)
10983 defdecode (decode-time def)))))
10984 (calendar-move-hook nil)
10985 (calendar-view-diary-initially-flag nil)
10986 (view-diary-entries-initially nil)
10987 (calendar-view-holidays-initially-flag nil)
10988 (view-calendar-holidays-initially nil)
10989 (timestr (format-time-string
10990 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10991 (prompt (concat (if prompt (concat prompt " ") "")
10992 (format "Date+time [%s]: " timestr)))
10993 ans (org-ans0 "") org-ans1 org-ans2 final)
10995 (cond
10996 (from-string (setq ans from-string))
10997 (org-read-date-popup-calendar
10998 (save-excursion
10999 (save-window-excursion
11000 (calendar)
11001 (calendar-forward-day (- (time-to-days def)
11002 (calendar-absolute-from-gregorian
11003 (calendar-current-date))))
11004 (org-eval-in-calendar nil t)
11005 (let* ((old-map (current-local-map))
11006 (map (copy-keymap calendar-mode-map))
11007 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11008 (org-defkey map (kbd "RET") 'org-calendar-select)
11009 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11010 'org-calendar-select-mouse)
11011 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11012 'org-calendar-select-mouse)
11013 (org-defkey minibuffer-local-map [(meta shift left)]
11014 (lambda () (interactive)
11015 (org-eval-in-calendar '(calendar-backward-month 1))))
11016 (org-defkey minibuffer-local-map [(meta shift right)]
11017 (lambda () (interactive)
11018 (org-eval-in-calendar '(calendar-forward-month 1))))
11019 (org-defkey minibuffer-local-map [(meta shift up)]
11020 (lambda () (interactive)
11021 (org-eval-in-calendar '(calendar-backward-year 1))))
11022 (org-defkey minibuffer-local-map [(meta shift down)]
11023 (lambda () (interactive)
11024 (org-eval-in-calendar '(calendar-forward-year 1))))
11025 (org-defkey minibuffer-local-map [(shift up)]
11026 (lambda () (interactive)
11027 (org-eval-in-calendar '(calendar-backward-week 1))))
11028 (org-defkey minibuffer-local-map [(shift down)]
11029 (lambda () (interactive)
11030 (org-eval-in-calendar '(calendar-forward-week 1))))
11031 (org-defkey minibuffer-local-map [(shift left)]
11032 (lambda () (interactive)
11033 (org-eval-in-calendar '(calendar-backward-day 1))))
11034 (org-defkey minibuffer-local-map [(shift right)]
11035 (lambda () (interactive)
11036 (org-eval-in-calendar '(calendar-forward-day 1))))
11037 (org-defkey minibuffer-local-map ">"
11038 (lambda () (interactive)
11039 (org-eval-in-calendar '(scroll-calendar-left 1))))
11040 (org-defkey minibuffer-local-map "<"
11041 (lambda () (interactive)
11042 (org-eval-in-calendar '(scroll-calendar-right 1))))
11043 (unwind-protect
11044 (progn
11045 (use-local-map map)
11046 (add-hook 'post-command-hook 'org-read-date-display)
11047 (setq org-ans0 (read-string prompt default-input nil nil))
11048 ;; org-ans0: from prompt
11049 ;; org-ans1: from mouse click
11050 ;; org-ans2: from calendar motion
11051 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11052 (remove-hook 'post-command-hook 'org-read-date-display)
11053 (use-local-map old-map)
11054 (when org-read-date-overlay
11055 (org-delete-overlay org-read-date-overlay)
11056 (setq org-read-date-overlay nil)))))))
11058 (t ; Naked prompt only
11059 (unwind-protect
11060 (setq ans (read-string prompt default-input nil timestr))
11061 (when org-read-date-overlay
11062 (org-delete-overlay org-read-date-overlay)
11063 (setq org-read-date-overlay nil)))))
11065 (setq final (org-read-date-analyze ans def defdecode))
11067 (if to-time
11068 (apply 'encode-time final)
11069 (if (and (boundp 'org-time-was-given) org-time-was-given)
11070 (format "%04d-%02d-%02d %02d:%02d"
11071 (nth 5 final) (nth 4 final) (nth 3 final)
11072 (nth 2 final) (nth 1 final))
11073 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11074 (defvar def)
11075 (defvar defdecode)
11076 (defvar with-time)
11077 (defun org-read-date-display ()
11078 "Display the currrent date prompt interpretation in the minibuffer."
11079 (when org-read-date-display-live
11080 (when org-read-date-overlay
11081 (org-delete-overlay org-read-date-overlay))
11082 (let ((p (point)))
11083 (end-of-line 1)
11084 (while (not (equal (buffer-substring
11085 (max (point-min) (- (point) 4)) (point))
11086 " "))
11087 (insert " "))
11088 (goto-char p))
11089 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11090 " " (or org-ans1 org-ans2)))
11091 (org-end-time-was-given nil)
11092 (f (org-read-date-analyze ans def defdecode))
11093 (fmts (if org-dcst
11094 org-time-stamp-custom-formats
11095 org-time-stamp-formats))
11096 (fmt (if (or with-time
11097 (and (boundp 'org-time-was-given) org-time-was-given))
11098 (cdr fmts)
11099 (car fmts)))
11100 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11101 (when (and org-end-time-was-given
11102 (string-match org-plain-time-of-day-regexp txt))
11103 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11104 org-end-time-was-given
11105 (substring txt (match-end 0)))))
11106 (setq org-read-date-overlay
11107 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11108 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11110 (defun org-read-date-analyze (ans def defdecode)
11111 "Analyze the combined answer of the date prompt."
11112 ;; FIXME: cleanup and comment
11113 (let (delta deltan deltaw deltadef year month day
11114 hour minute second wday pm h2 m2 tl wday1
11115 iso-year iso-weekday iso-week iso-year iso-date)
11117 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11118 (setq ans "+0"))
11120 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11121 (setq ans (replace-match "" t t ans)
11122 deltan (car delta)
11123 deltaw (nth 1 delta)
11124 deltadef (nth 2 delta)))
11126 ;; Check if there is an iso week date in there
11127 ;; If yes, sore the info and ostpone interpreting it until the rest
11128 ;; of the parsing is done
11129 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11130 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11131 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11132 iso-week (string-to-number (match-string 2 ans)))
11133 (setq ans (replace-match "" t t ans)))
11135 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11136 (when (string-match
11137 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11138 (setq year (if (match-end 2)
11139 (string-to-number (match-string 2 ans))
11140 (string-to-number (format-time-string "%Y")))
11141 month (string-to-number (match-string 3 ans))
11142 day (string-to-number (match-string 4 ans)))
11143 (if (< year 100) (setq year (+ 2000 year)))
11144 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11145 t nil ans)))
11146 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11147 ;; If there is a time with am/pm, and *no* time without it, we convert
11148 ;; so that matching will be successful.
11149 (loop for i from 1 to 2 do ; twice, for end time as well
11150 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11151 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11152 (setq hour (string-to-number (match-string 1 ans))
11153 minute (if (match-end 3)
11154 (string-to-number (match-string 3 ans))
11156 pm (equal ?p
11157 (string-to-char (downcase (match-string 4 ans)))))
11158 (if (and (= hour 12) (not pm))
11159 (setq hour 0)
11160 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11161 (setq ans (replace-match (format "%02d:%02d" hour minute)
11162 t t ans))))
11164 ;; Check if a time range is given as a duration
11165 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11166 (setq hour (string-to-number (match-string 1 ans))
11167 h2 (+ hour (string-to-number (match-string 3 ans)))
11168 minute (string-to-number (match-string 2 ans))
11169 m2 (+ minute (if (match-end 5) (string-to-number
11170 (match-string 5 ans))0)))
11171 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11172 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11173 t t ans)))
11175 ;; Check if there is a time range
11176 (when (boundp 'org-end-time-was-given)
11177 (setq org-time-was-given nil)
11178 (when (and (string-match org-plain-time-of-day-regexp ans)
11179 (match-end 8))
11180 (setq org-end-time-was-given (match-string 8 ans))
11181 (setq ans (concat (substring ans 0 (match-beginning 7))
11182 (substring ans (match-end 7))))))
11184 (setq tl (parse-time-string ans)
11185 day (or (nth 3 tl) (nth 3 defdecode))
11186 month (or (nth 4 tl)
11187 (if (and org-read-date-prefer-future
11188 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11189 (1+ (nth 4 defdecode))
11190 (nth 4 defdecode)))
11191 year (or (nth 5 tl)
11192 (if (and org-read-date-prefer-future
11193 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11194 (1+ (nth 5 defdecode))
11195 (nth 5 defdecode)))
11196 hour (or (nth 2 tl) (nth 2 defdecode))
11197 minute (or (nth 1 tl) (nth 1 defdecode))
11198 second (or (nth 0 tl) 0)
11199 wday (nth 6 tl))
11201 ;; Special date definitions below
11202 (cond
11203 (iso-week
11204 ;; There was an iso week
11205 (setq year (or iso-year year)
11206 day (or iso-weekday wday 1)
11207 wday nil ; to make sure that the trigger below does not match
11208 iso-date (calendar-gregorian-from-absolute
11209 (calendar-absolute-from-iso
11210 (list iso-week day year))))
11211 ; FIXME: Should we also push ISO weeks into the future?
11212 ; (when (and org-read-date-prefer-future
11213 ; (not iso-year)
11214 ; (< (calendar-absolute-from-gregorian iso-date)
11215 ; (time-to-days (current-time))))
11216 ; (setq year (1+ year)
11217 ; iso-date (calendar-gregorian-from-absolute
11218 ; (calendar-absolute-from-iso
11219 ; (list iso-week day year)))))
11220 (setq month (car iso-date)
11221 year (nth 2 iso-date)
11222 day (nth 1 iso-date)))
11223 (deltan
11224 (unless deltadef
11225 (let ((now (decode-time (current-time))))
11226 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11227 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11228 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11229 ((equal deltaw "m") (setq month (+ month deltan)))
11230 ((equal deltaw "y") (setq year (+ year deltan)))))
11231 ((and wday (not (nth 3 tl)))
11232 ;; Weekday was given, but no day, so pick that day in the week
11233 ;; on or after the derived date.
11234 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11235 (unless (equal wday wday1)
11236 (setq day (+ day (% (- wday wday1 -7) 7))))))
11237 (if (and (boundp 'org-time-was-given)
11238 (nth 2 tl))
11239 (setq org-time-was-given t))
11240 (if (< year 100) (setq year (+ 2000 year)))
11241 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11242 (list second minute hour day month year)))
11244 (defvar parse-time-weekdays)
11246 (defun org-read-date-get-relative (s today default)
11247 "Check string S for special relative date string.
11248 TODAY and DEFAULT are internal times, for today and for a default.
11249 Return shift list (N what def-flag)
11250 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11251 N is the number of WHATs to shift.
11252 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11253 the DEFAULT date rather than TODAY."
11254 (when (and
11255 (string-match
11256 (concat
11257 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11258 "\\([0-9]+\\)?"
11259 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11260 "\\([ \t]\\|$\\)") s)
11261 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11262 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11263 (string-to-char (substring (match-string 1 s) -1))
11264 ?+))
11265 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11266 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11267 (what (if (match-end 3) (match-string 3 s) "d"))
11268 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11269 (date (if rel default today))
11270 (wday (nth 6 (decode-time date)))
11271 delta)
11272 (if wday1
11273 (progn
11274 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11275 (if (= dir ?-) (setq delta (- delta 7)))
11276 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11277 (list delta "d" rel))
11278 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11280 (defun org-eval-in-calendar (form &optional keepdate)
11281 "Eval FORM in the calendar window and return to current window.
11282 Also, store the cursor date in variable org-ans2."
11283 (let ((sw (selected-window)))
11284 (select-window (get-buffer-window "*Calendar*"))
11285 (eval form)
11286 (when (and (not keepdate) (calendar-cursor-to-date))
11287 (let* ((date (calendar-cursor-to-date))
11288 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11289 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11290 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11291 (select-window sw)))
11293 ; ;; Update the prompt to show new default date
11294 ; (save-excursion
11295 ; (goto-char (point-min))
11296 ; (when (and org-ans2
11297 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11298 ; (get-text-property (match-end 0) 'field))
11299 ; (let ((inhibit-read-only t))
11300 ; (replace-match (concat "[" org-ans2 "]") t t)
11301 ; (add-text-properties (point-min) (1+ (match-end 0))
11302 ; (text-properties-at (1+ (point-min)))))))))
11304 (defun org-calendar-select ()
11305 "Return to `org-read-date' with the date currently selected.
11306 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11307 (interactive)
11308 (when (calendar-cursor-to-date)
11309 (let* ((date (calendar-cursor-to-date))
11310 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11311 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11312 (if (active-minibuffer-window) (exit-minibuffer))))
11314 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11315 "Insert a date stamp for the date given by the internal TIME.
11316 WITH-HM means, use the stamp format that includes the time of the day.
11317 INACTIVE means use square brackets instead of angular ones, so that the
11318 stamp will not contribute to the agenda.
11319 PRE and POST are optional strings to be inserted before and after the
11320 stamp.
11321 The command returns the inserted time stamp."
11322 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11323 stamp)
11324 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11325 (insert-before-markers (or pre ""))
11326 (insert-before-markers (setq stamp (format-time-string fmt time)))
11327 (when (listp extra)
11328 (setq extra (car extra))
11329 (if (and (stringp extra)
11330 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11331 (setq extra (format "-%02d:%02d"
11332 (string-to-number (match-string 1 extra))
11333 (string-to-number (match-string 2 extra))))
11334 (setq extra nil)))
11335 (when extra
11336 (backward-char 1)
11337 (insert-before-markers extra)
11338 (forward-char 1))
11339 (insert-before-markers (or post ""))
11340 (setq org-last-inserted-timestamp stamp)))
11342 (defun org-toggle-time-stamp-overlays ()
11343 "Toggle the use of custom time stamp formats."
11344 (interactive)
11345 (setq org-display-custom-times (not org-display-custom-times))
11346 (unless org-display-custom-times
11347 (let ((p (point-min)) (bmp (buffer-modified-p)))
11348 (while (setq p (next-single-property-change p 'display))
11349 (if (and (get-text-property p 'display)
11350 (eq (get-text-property p 'face) 'org-date))
11351 (remove-text-properties
11352 p (setq p (next-single-property-change p 'display))
11353 '(display t))))
11354 (set-buffer-modified-p bmp)))
11355 (if (featurep 'xemacs)
11356 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11357 (org-restart-font-lock)
11358 (setq org-table-may-need-update t)
11359 (if org-display-custom-times
11360 (message "Time stamps are overlayed with custom format")
11361 (message "Time stamp overlays removed")))
11363 (defun org-display-custom-time (beg end)
11364 "Overlay modified time stamp format over timestamp between BEG and END."
11365 (let* ((ts (buffer-substring beg end))
11366 t1 w1 with-hm tf time str w2 (off 0))
11367 (save-match-data
11368 (setq t1 (org-parse-time-string ts t))
11369 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11370 (setq off (- (match-end 0) (match-beginning 0)))))
11371 (setq end (- end off))
11372 (setq w1 (- end beg)
11373 with-hm (and (nth 1 t1) (nth 2 t1))
11374 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11375 time (org-fix-decoded-time t1)
11376 str (org-add-props
11377 (format-time-string
11378 (substring tf 1 -1) (apply 'encode-time time))
11379 nil 'mouse-face 'highlight)
11380 w2 (length str))
11381 (if (not (= w2 w1))
11382 (add-text-properties (1+ beg) (+ 2 beg)
11383 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11384 (if (featurep 'xemacs)
11385 (progn
11386 (put-text-property beg end 'invisible t)
11387 (put-text-property beg end 'end-glyph (make-glyph str)))
11388 (put-text-property beg end 'display str))))
11390 (defun org-translate-time (string)
11391 "Translate all timestamps in STRING to custom format.
11392 But do this only if the variable `org-display-custom-times' is set."
11393 (when org-display-custom-times
11394 (save-match-data
11395 (let* ((start 0)
11396 (re org-ts-regexp-both)
11397 t1 with-hm inactive tf time str beg end)
11398 (while (setq start (string-match re string start))
11399 (setq beg (match-beginning 0)
11400 end (match-end 0)
11401 t1 (save-match-data
11402 (org-parse-time-string (substring string beg end) t))
11403 with-hm (and (nth 1 t1) (nth 2 t1))
11404 inactive (equal (substring string beg (1+ beg)) "[")
11405 tf (funcall (if with-hm 'cdr 'car)
11406 org-time-stamp-custom-formats)
11407 time (org-fix-decoded-time t1)
11408 str (format-time-string
11409 (concat
11410 (if inactive "[" "<") (substring tf 1 -1)
11411 (if inactive "]" ">"))
11412 (apply 'encode-time time))
11413 string (replace-match str t t string)
11414 start (+ start (length str)))))))
11415 string)
11417 (defun org-fix-decoded-time (time)
11418 "Set 0 instead of nil for the first 6 elements of time.
11419 Don't touch the rest."
11420 (let ((n 0))
11421 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11423 (defun org-days-to-time (timestamp-string)
11424 "Difference between TIMESTAMP-STRING and now in days."
11425 (- (time-to-days (org-time-string-to-time timestamp-string))
11426 (time-to-days (current-time))))
11428 (defun org-deadline-close (timestamp-string &optional ndays)
11429 "Is the time in TIMESTAMP-STRING close to the current date?"
11430 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11431 (and (< (org-days-to-time timestamp-string) ndays)
11432 (not (org-entry-is-done-p))))
11434 (defun org-get-wdays (ts)
11435 "Get the deadline lead time appropriate for timestring TS."
11436 (cond
11437 ((<= org-deadline-warning-days 0)
11438 ;; 0 or negative, enforce this value no matter what
11439 (- org-deadline-warning-days))
11440 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11441 ;; lead time is specified.
11442 (floor (* (string-to-number (match-string 1 ts))
11443 (cdr (assoc (match-string 2 ts)
11444 '(("d" . 1) ("w" . 7)
11445 ("m" . 30.4) ("y" . 365.25)))))))
11446 ;; go for the default.
11447 (t org-deadline-warning-days)))
11449 (defun org-calendar-select-mouse (ev)
11450 "Return to `org-read-date' with the date currently selected.
11451 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11452 (interactive "e")
11453 (mouse-set-point ev)
11454 (when (calendar-cursor-to-date)
11455 (let* ((date (calendar-cursor-to-date))
11456 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11457 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11458 (if (active-minibuffer-window) (exit-minibuffer))))
11460 (defun org-check-deadlines (ndays)
11461 "Check if there are any deadlines due or past due.
11462 A deadline is considered due if it happens within `org-deadline-warning-days'
11463 days from today's date. If the deadline appears in an entry marked DONE,
11464 it is not shown. The prefix arg NDAYS can be used to test that many
11465 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11466 (interactive "P")
11467 (let* ((org-warn-days
11468 (cond
11469 ((equal ndays '(4)) 100000)
11470 (ndays (prefix-numeric-value ndays))
11471 (t (abs org-deadline-warning-days))))
11472 (case-fold-search nil)
11473 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11474 (callback
11475 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11477 (message "%d deadlines past-due or due within %d days"
11478 (org-occur regexp nil callback)
11479 org-warn-days)))
11481 (defun org-check-before-date (date)
11482 "Check if there are deadlines or scheduled entries before DATE."
11483 (interactive (list (org-read-date)))
11484 (let ((case-fold-search nil)
11485 (regexp (concat "\\<\\(" org-deadline-string
11486 "\\|" org-scheduled-string
11487 "\\) *<\\([^>]+\\)>"))
11488 (callback
11489 (lambda () (time-less-p
11490 (org-time-string-to-time (match-string 2))
11491 (org-time-string-to-time date)))))
11492 (message "%d entries before %s"
11493 (org-occur regexp nil callback) date)))
11495 (defun org-evaluate-time-range (&optional to-buffer)
11496 "Evaluate a time range by computing the difference between start and end.
11497 Normally the result is just printed in the echo area, but with prefix arg
11498 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11499 If the time range is actually in a table, the result is inserted into the
11500 next column.
11501 For time difference computation, a year is assumed to be exactly 365
11502 days in order to avoid rounding problems."
11503 (interactive "P")
11505 (org-clock-update-time-maybe)
11506 (save-excursion
11507 (unless (org-at-date-range-p t)
11508 (goto-char (point-at-bol))
11509 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11510 (if (not (org-at-date-range-p t))
11511 (error "Not at a time-stamp range, and none found in current line")))
11512 (let* ((ts1 (match-string 1))
11513 (ts2 (match-string 2))
11514 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11515 (match-end (match-end 0))
11516 (time1 (org-time-string-to-time ts1))
11517 (time2 (org-time-string-to-time ts2))
11518 (t1 (time-to-seconds time1))
11519 (t2 (time-to-seconds time2))
11520 (diff (abs (- t2 t1)))
11521 (negative (< (- t2 t1) 0))
11522 ;; (ys (floor (* 365 24 60 60)))
11523 (ds (* 24 60 60))
11524 (hs (* 60 60))
11525 (fy "%dy %dd %02d:%02d")
11526 (fy1 "%dy %dd")
11527 (fd "%dd %02d:%02d")
11528 (fd1 "%dd")
11529 (fh "%02d:%02d")
11530 y d h m align)
11531 (if havetime
11532 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11534 d (floor (/ diff ds)) diff (mod diff ds)
11535 h (floor (/ diff hs)) diff (mod diff hs)
11536 m (floor (/ diff 60)))
11537 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11539 d (floor (+ (/ diff ds) 0.5))
11540 h 0 m 0))
11541 (if (not to-buffer)
11542 (message "%s" (org-make-tdiff-string y d h m))
11543 (if (org-at-table-p)
11544 (progn
11545 (goto-char match-end)
11546 (setq align t)
11547 (and (looking-at " *|") (goto-char (match-end 0))))
11548 (goto-char match-end))
11549 (if (looking-at
11550 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11551 (replace-match ""))
11552 (if negative (insert " -"))
11553 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11554 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11555 (insert " " (format fh h m))))
11556 (if align (org-table-align))
11557 (message "Time difference inserted")))))
11559 (defun org-make-tdiff-string (y d h m)
11560 (let ((fmt "")
11561 (l nil))
11562 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11563 l (push y l)))
11564 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11565 l (push d l)))
11566 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11567 l (push h l)))
11568 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11569 l (push m l)))
11570 (apply 'format fmt (nreverse l))))
11572 (defun org-time-string-to-time (s)
11573 (apply 'encode-time (org-parse-time-string s)))
11575 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11576 "Convert a time stamp to an absolute day number.
11577 If there is a specifyer for a cyclic time stamp, get the closest date to
11578 DAYNR.
11579 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11580 (cond
11581 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11582 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11583 daynr
11584 (+ daynr 1000)))
11585 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11586 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11587 (time-to-days (current-time))) (match-string 0 s)
11588 prefer show-all))
11589 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11591 (defun org-days-to-iso-week (days)
11592 "Return the iso week number."
11593 (require 'cal-iso)
11594 (car (calendar-iso-from-absolute days)))
11596 (defun org-small-year-to-year (year)
11597 "Convert 2-digit years into 4-digit years.
11598 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11599 The year 2000 cannot be abbreviated. Any year lager than 99
11600 is retrned unchanged."
11601 (if (< year 38)
11602 (setq year (+ 2000 year))
11603 (if (< year 100)
11604 (setq year (+ 1900 year))))
11605 year)
11607 (defun org-time-from-absolute (d)
11608 "Return the time corresponding to date D.
11609 D may be an absolute day number, or a calendar-type list (month day year)."
11610 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11611 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11613 (defun org-calendar-holiday ()
11614 "List of holidays, for Diary display in Org-mode."
11615 (require 'holidays)
11616 (let ((hl (funcall
11617 (if (fboundp 'calendar-check-holidays)
11618 'calendar-check-holidays 'check-calendar-holidays) date)))
11619 (if hl (mapconcat 'identity hl "; "))))
11621 (defun org-diary-sexp-entry (sexp entry date)
11622 "Process a SEXP diary ENTRY for DATE."
11623 (require 'diary-lib)
11624 (let ((result (if calendar-debug-sexp
11625 (let ((stack-trace-on-error t))
11626 (eval (car (read-from-string sexp))))
11627 (condition-case nil
11628 (eval (car (read-from-string sexp)))
11629 (error
11630 (beep)
11631 (message "Bad sexp at line %d in %s: %s"
11632 (org-current-line)
11633 (buffer-file-name) sexp)
11634 (sleep-for 2))))))
11635 (cond ((stringp result) result)
11636 ((and (consp result)
11637 (stringp (cdr result))) (cdr result))
11638 (result entry)
11639 (t nil))))
11641 (defun org-diary-to-ical-string (frombuf)
11642 "Get iCalendar entries from diary entries in buffer FROMBUF.
11643 This uses the icalendar.el library."
11644 (let* ((tmpdir (if (featurep 'xemacs)
11645 (temp-directory)
11646 temporary-file-directory))
11647 (tmpfile (make-temp-name
11648 (expand-file-name "orgics" tmpdir)))
11649 buf rtn b e)
11650 (save-excursion
11651 (set-buffer frombuf)
11652 (icalendar-export-region (point-min) (point-max) tmpfile)
11653 (setq buf (find-buffer-visiting tmpfile))
11654 (set-buffer buf)
11655 (goto-char (point-min))
11656 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11657 (setq b (match-beginning 0)))
11658 (goto-char (point-max))
11659 (if (re-search-backward "^END:VEVENT" nil t)
11660 (setq e (match-end 0)))
11661 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11662 (kill-buffer buf)
11663 (delete-file tmpfile)
11664 rtn))
11666 (defun org-closest-date (start current change prefer show-all)
11667 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11668 When PREFER is `past' return a date that is either CURRENT or past.
11669 When PREFER is `future', return a date that is either CURRENT or future.
11670 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11671 ;; Make the proper lists from the dates
11672 (catch 'exit
11673 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11674 dn dw sday cday n1 n2
11675 d m y y1 y2 date1 date2 nmonths nm ny m2)
11677 (setq start (org-date-to-gregorian start)
11678 current (org-date-to-gregorian
11679 (if show-all
11680 current
11681 (time-to-days (current-time))))
11682 sday (calendar-absolute-from-gregorian start)
11683 cday (calendar-absolute-from-gregorian current))
11685 (if (<= cday sday) (throw 'exit sday))
11687 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11688 (setq dn (string-to-number (match-string 1 change))
11689 dw (cdr (assoc (match-string 2 change) a1)))
11690 (error "Invalid change specifyer: %s" change))
11691 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11692 (cond
11693 ((eq dw 'day)
11694 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11695 n2 (+ n1 dn)))
11696 ((eq dw 'year)
11697 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11698 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11699 (setq date1 (list m d y1)
11700 n1 (calendar-absolute-from-gregorian date1)
11701 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11702 n2 (calendar-absolute-from-gregorian date2)))
11703 ((eq dw 'month)
11704 ;; approx number of month between the two dates
11705 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11706 ;; How often does dn fit in there?
11707 (setq d (nth 1 start) m (car start) y (nth 2 start)
11708 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11709 m (+ m nm)
11710 ny (floor (/ m 12))
11711 y (+ y ny)
11712 m (- m (* ny 12)))
11713 (while (> m 12) (setq m (- m 12) y (1+ y)))
11714 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11715 (setq m2 (+ m dn) y2 y)
11716 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11717 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11718 (while (<= n2 cday)
11719 (setq n1 n2 m m2 y y2)
11720 (setq m2 (+ m dn) y2 y)
11721 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11722 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11723 (if show-all
11724 (cond
11725 ((eq prefer 'past) n1)
11726 ((eq prefer 'future) (if (= cday n1) n1 n2))
11727 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11728 (cond
11729 ((eq prefer 'past) n1)
11730 ((eq prefer 'future) (if (= cday n1) n1 n2))
11731 (t (if (= cday n1) n1 n2)))))))
11733 (defun org-date-to-gregorian (date)
11734 "Turn any specification of DATE into a gregorian date for the calendar."
11735 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11736 ((and (listp date) (= (length date) 3)) date)
11737 ((stringp date)
11738 (setq date (org-parse-time-string date))
11739 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11740 ((listp date)
11741 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11743 (defun org-parse-time-string (s &optional nodefault)
11744 "Parse the standard Org-mode time string.
11745 This should be a lot faster than the normal `parse-time-string'.
11746 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11747 hour and minute fields will be nil if not given."
11748 (if (string-match org-ts-regexp0 s)
11749 (list 0
11750 (if (or (match-beginning 8) (not nodefault))
11751 (string-to-number (or (match-string 8 s) "0")))
11752 (if (or (match-beginning 7) (not nodefault))
11753 (string-to-number (or (match-string 7 s) "0")))
11754 (string-to-number (match-string 4 s))
11755 (string-to-number (match-string 3 s))
11756 (string-to-number (match-string 2 s))
11757 nil nil nil)
11758 (make-list 9 0)))
11760 (defun org-timestamp-up (&optional arg)
11761 "Increase the date item at the cursor by one.
11762 If the cursor is on the year, change the year. If it is on the month or
11763 the day, change that.
11764 With prefix ARG, change by that many units."
11765 (interactive "p")
11766 (org-timestamp-change (prefix-numeric-value arg)))
11768 (defun org-timestamp-down (&optional arg)
11769 "Decrease the date item at the cursor by one.
11770 If the cursor is on the year, change the year. If it is on the month or
11771 the day, change that.
11772 With prefix ARG, change by that many units."
11773 (interactive "p")
11774 (org-timestamp-change (- (prefix-numeric-value arg))))
11776 (defun org-timestamp-up-day (&optional arg)
11777 "Increase the date in the time stamp by one day.
11778 With prefix ARG, change that many days."
11779 (interactive "p")
11780 (if (and (not (org-at-timestamp-p t))
11781 (org-on-heading-p))
11782 (org-todo 'up)
11783 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11785 (defun org-timestamp-down-day (&optional arg)
11786 "Decrease the date in the time stamp by one day.
11787 With prefix ARG, change that many days."
11788 (interactive "p")
11789 (if (and (not (org-at-timestamp-p t))
11790 (org-on-heading-p))
11791 (org-todo 'down)
11792 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11794 (defun org-at-timestamp-p (&optional inactive-ok)
11795 "Determine if the cursor is in or at a timestamp."
11796 (interactive)
11797 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11798 (pos (point))
11799 (ans (or (looking-at tsr)
11800 (save-excursion
11801 (skip-chars-backward "^[<\n\r\t")
11802 (if (> (point) (point-min)) (backward-char 1))
11803 (and (looking-at tsr)
11804 (> (- (match-end 0) pos) -1))))))
11805 (and ans
11806 (boundp 'org-ts-what)
11807 (setq org-ts-what
11808 (cond
11809 ((= pos (match-beginning 0)) 'bracket)
11810 ((= pos (1- (match-end 0))) 'bracket)
11811 ((org-pos-in-match-range pos 2) 'year)
11812 ((org-pos-in-match-range pos 3) 'month)
11813 ((org-pos-in-match-range pos 7) 'hour)
11814 ((org-pos-in-match-range pos 8) 'minute)
11815 ((or (org-pos-in-match-range pos 4)
11816 (org-pos-in-match-range pos 5)) 'day)
11817 ((and (> pos (or (match-end 8) (match-end 5)))
11818 (< pos (match-end 0)))
11819 (- pos (or (match-end 8) (match-end 5))))
11820 (t 'day))))
11821 ans))
11823 (defun org-toggle-timestamp-type ()
11824 "Toggle the type (<active> or [inactive]) of a time stamp."
11825 (interactive)
11826 (when (org-at-timestamp-p t)
11827 (save-excursion
11828 (goto-char (match-beginning 0))
11829 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11830 (goto-char (1- (match-end 0)))
11831 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11832 (message "Timestamp is now %sactive"
11833 (if (equal (char-before) ?>) "in" ""))))
11835 (defun org-timestamp-change (n &optional what)
11836 "Change the date in the time stamp at point.
11837 The date will be changed by N times WHAT. WHAT can be `day', `month',
11838 `year', `minute', `second'. If WHAT is not given, the cursor position
11839 in the timestamp determines what will be changed."
11840 (let ((pos (point))
11841 with-hm inactive
11842 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11843 org-ts-what
11844 extra rem
11845 ts time time0)
11846 (if (not (org-at-timestamp-p t))
11847 (error "Not at a timestamp"))
11848 (if (and (not what) (eq org-ts-what 'bracket))
11849 (org-toggle-timestamp-type)
11850 (if (and (not what) (not (eq org-ts-what 'day))
11851 org-display-custom-times
11852 (get-text-property (point) 'display)
11853 (not (get-text-property (1- (point)) 'display)))
11854 (setq org-ts-what 'day))
11855 (setq org-ts-what (or what org-ts-what)
11856 inactive (= (char-after (match-beginning 0)) ?\[)
11857 ts (match-string 0))
11858 (replace-match "")
11859 (if (string-match
11860 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11862 (setq extra (match-string 1 ts)))
11863 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11864 (setq with-hm t))
11865 (setq time0 (org-parse-time-string ts))
11866 (when (and (eq org-ts-what 'minute)
11867 (eq current-prefix-arg nil))
11868 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11869 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11870 (setcar (cdr time0) (+ (nth 1 time0)
11871 (if (> n 0) (- rem) (- dm rem))))))
11872 (setq time
11873 (encode-time (or (car time0) 0)
11874 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11875 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11876 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11877 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11878 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11879 (nthcdr 6 time0)))
11880 (when (integerp org-ts-what)
11881 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11882 (if (eq what 'calendar)
11883 (let ((cal-date (org-get-date-from-calendar)))
11884 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11885 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11886 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11887 (setcar time0 (or (car time0) 0))
11888 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11889 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11890 (setq time (apply 'encode-time time0))))
11891 (setq org-last-changed-timestamp
11892 (org-insert-time-stamp time with-hm inactive nil nil extra))
11893 (org-clock-update-time-maybe)
11894 (goto-char pos)
11895 ;; Try to recenter the calendar window, if any
11896 (if (and org-calendar-follow-timestamp-change
11897 (get-buffer-window "*Calendar*" t)
11898 (memq org-ts-what '(day month year)))
11899 (org-recenter-calendar (time-to-days time))))))
11901 (defun org-modify-ts-extra (s pos n dm)
11902 "Change the different parts of the lead-time and repeat fields in timestamp."
11903 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11904 ng h m new rem)
11905 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11906 (cond
11907 ((or (org-pos-in-match-range pos 2)
11908 (org-pos-in-match-range pos 3))
11909 (setq m (string-to-number (match-string 3 s))
11910 h (string-to-number (match-string 2 s)))
11911 (if (org-pos-in-match-range pos 2)
11912 (setq h (+ h n))
11913 (setq n (* dm (org-no-warnings (signum n))))
11914 (when (not (= 0 (setq rem (% m dm))))
11915 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11916 (setq m (+ m n)))
11917 (if (< m 0) (setq m (+ m 60) h (1- h)))
11918 (if (> m 59) (setq m (- m 60) h (1+ h)))
11919 (setq h (min 24 (max 0 h)))
11920 (setq ng 1 new (format "-%02d:%02d" h m)))
11921 ((org-pos-in-match-range pos 6)
11922 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11923 ((org-pos-in-match-range pos 5)
11924 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11926 ((org-pos-in-match-range pos 9)
11927 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11928 ((org-pos-in-match-range pos 8)
11929 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11931 (when ng
11932 (setq s (concat
11933 (substring s 0 (match-beginning ng))
11935 (substring s (match-end ng))))))
11938 (defun org-recenter-calendar (date)
11939 "If the calendar is visible, recenter it to DATE."
11940 (let* ((win (selected-window))
11941 (cwin (get-buffer-window "*Calendar*" t))
11942 (calendar-move-hook nil))
11943 (when cwin
11944 (select-window cwin)
11945 (calendar-goto-date (if (listp date) date
11946 (calendar-gregorian-from-absolute date)))
11947 (select-window win))))
11949 (defun org-goto-calendar (&optional arg)
11950 "Go to the Emacs calendar at the current date.
11951 If there is a time stamp in the current line, go to that date.
11952 A prefix ARG can be used to force the current date."
11953 (interactive "P")
11954 (let ((tsr org-ts-regexp) diff
11955 (calendar-move-hook nil)
11956 (calendar-view-holidays-initially-flag nil)
11957 (view-calendar-holidays-initially nil)
11958 (calendar-view-diary-initially-flag nil)
11959 (view-diary-entries-initially nil))
11960 (if (or (org-at-timestamp-p)
11961 (save-excursion
11962 (beginning-of-line 1)
11963 (looking-at (concat ".*" tsr))))
11964 (let ((d1 (time-to-days (current-time)))
11965 (d2 (time-to-days
11966 (org-time-string-to-time (match-string 1)))))
11967 (setq diff (- d2 d1))))
11968 (calendar)
11969 (calendar-goto-today)
11970 (if (and diff (not arg)) (calendar-forward-day diff))))
11972 (defun org-get-date-from-calendar ()
11973 "Return a list (month day year) of date at point in calendar."
11974 (with-current-buffer "*Calendar*"
11975 (save-match-data
11976 (calendar-cursor-to-date))))
11978 (defun org-date-from-calendar ()
11979 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11980 If there is already a time stamp at the cursor position, update it."
11981 (interactive)
11982 (if (org-at-timestamp-p t)
11983 (org-timestamp-change 0 'calendar)
11984 (let ((cal-date (org-get-date-from-calendar)))
11985 (org-insert-time-stamp
11986 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11988 (defun org-minutes-to-hh:mm-string (m)
11989 "Compute H:MM from a number of minutes."
11990 (let ((h (/ m 60)))
11991 (setq m (- m (* 60 h)))
11992 (format org-time-clocksum-format h m)))
11994 (defun org-hh:mm-string-to-minutes (s)
11995 "Convert a string H:MM to a number of minutes."
11996 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11997 (+ (* (string-to-number (match-string 1 s)) 60)
11998 (string-to-number (match-string 2 s)))
12001 ;;;; Agenda files
12003 ;;;###autoload
12004 (defun org-iswitchb (&optional arg)
12005 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12006 With a prefix argument, restrict available to files.
12007 With two prefix arguments, restrict available buffers to agenda files.
12009 Due to some yet unresolved reason, the global function
12010 `iswitchb-mode' needs to be active for this function to work."
12011 (interactive "P")
12012 (require 'iswitchb)
12013 (let ((enabled iswitchb-mode) blist)
12014 (or enabled (iswitchb-mode 1))
12015 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12016 ((equal arg '(16)) (org-buffer-list 'agenda))
12017 (t (org-buffer-list))))
12018 (unwind-protect
12019 (let ((iswitchb-make-buflist-hook
12020 (lambda ()
12021 (setq iswitchb-temp-buflist
12022 (mapcar 'buffer-name blist)))))
12023 (switch-to-buffer
12024 (iswitchb-read-buffer
12025 "Switch-to: " nil t))
12026 (or enabled (iswitchb-mode -1))))))
12028 (defun org-buffer-list (&optional predicate exclude-tmp)
12029 "Return a list of Org buffers.
12030 PREDICATE can be `export', `files' or `agenda'.
12032 export restrict the list to Export buffers.
12033 files restrict the list to buffers visiting Org files.
12034 agenda restrict the list to buffers visiting agenda files.
12036 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12037 (let* ((bfn nil)
12038 (agenda-files (and (eq predicate 'agenda)
12039 (mapcar 'file-truename (org-agenda-files t))))
12040 (filter
12041 (cond
12042 ((eq predicate 'files)
12043 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12044 ((eq predicate 'export)
12045 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12046 ((eq predicate 'agenda)
12047 (lambda (b)
12048 (with-current-buffer b
12049 (and (eq major-mode 'org-mode)
12050 (setq bfn (buffer-file-name b))
12051 (member (file-truename bfn) agenda-files)))))
12052 (t (lambda (b) (with-current-buffer b
12053 (or (eq major-mode 'org-mode)
12054 (string-match "\*Org .*Export"
12055 (buffer-name b)))))))))
12056 (delq nil
12057 (mapcar
12058 (lambda(b)
12059 (if (and (funcall filter b)
12060 (or (not exclude-tmp)
12061 (not (string-match "tmp" (buffer-name b)))))
12063 nil))
12064 (buffer-list)))))
12066 (defun org-agenda-files (&optional unrestricted archives)
12067 "Get the list of agenda files.
12068 Optional UNRESTRICTED means return the full list even if a restriction
12069 is currently in place.
12070 When ARCHIVES is t, include all archive files hat are really being
12071 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12072 `org-agenda-archives-mode' is t."
12073 (let ((files
12074 (cond
12075 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12076 ((stringp org-agenda-files) (org-read-agenda-file-list))
12077 ((listp org-agenda-files) org-agenda-files)
12078 (t (error "Invalid value of `org-agenda-files'")))))
12079 (setq files (apply 'append
12080 (mapcar (lambda (f)
12081 (if (file-directory-p f)
12082 (directory-files
12083 f t org-agenda-file-regexp)
12084 (list f)))
12085 files)))
12086 (when org-agenda-skip-unavailable-files
12087 (setq files (delq nil
12088 (mapcar (function
12089 (lambda (file)
12090 (and (file-readable-p file) file)))
12091 files))))
12092 (when (or (eq archives t)
12093 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12094 (setq files (org-add-archive-files files)))
12095 files))
12097 (defun org-edit-agenda-file-list ()
12098 "Edit the list of agenda files.
12099 Depending on setup, this either uses customize to edit the variable
12100 `org-agenda-files', or it visits the file that is holding the list. In the
12101 latter case, the buffer is set up in a way that saving it automatically kills
12102 the buffer and restores the previous window configuration."
12103 (interactive)
12104 (if (stringp org-agenda-files)
12105 (let ((cw (current-window-configuration)))
12106 (find-file org-agenda-files)
12107 (org-set-local 'org-window-configuration cw)
12108 (org-add-hook 'after-save-hook
12109 (lambda ()
12110 (set-window-configuration
12111 (prog1 org-window-configuration
12112 (kill-buffer (current-buffer))))
12113 (org-install-agenda-files-menu)
12114 (message "New agenda file list installed"))
12115 nil 'local)
12116 (message "%s" (substitute-command-keys
12117 "Edit list and finish with \\[save-buffer]")))
12118 (customize-variable 'org-agenda-files)))
12120 (defun org-store-new-agenda-file-list (list)
12121 "Set new value for the agenda file list and save it correcly."
12122 (if (stringp org-agenda-files)
12123 (let ((f org-agenda-files) b)
12124 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12125 (with-temp-file f
12126 (insert (mapconcat 'identity list "\n") "\n")))
12127 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12128 (setq org-agenda-files list)
12129 (customize-save-variable 'org-agenda-files org-agenda-files))))
12131 (defun org-read-agenda-file-list ()
12132 "Read the list of agenda files from a file."
12133 (when (file-directory-p org-agenda-files)
12134 (error "`org-agenda-files' cannot be a single directory"))
12135 (when (stringp org-agenda-files)
12136 (with-temp-buffer
12137 (insert-file-contents org-agenda-files)
12138 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12141 ;;;###autoload
12142 (defun org-cycle-agenda-files ()
12143 "Cycle through the files in `org-agenda-files'.
12144 If the current buffer visits an agenda file, find the next one in the list.
12145 If the current buffer does not, find the first agenda file."
12146 (interactive)
12147 (let* ((fs (org-agenda-files t))
12148 (files (append fs (list (car fs))))
12149 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12150 file)
12151 (unless files (error "No agenda files"))
12152 (catch 'exit
12153 (while (setq file (pop files))
12154 (if (equal (file-truename file) tcf)
12155 (when (car files)
12156 (find-file (car files))
12157 (throw 'exit t))))
12158 (find-file (car fs)))
12159 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12161 (defun org-agenda-file-to-front (&optional to-end)
12162 "Move/add the current file to the top of the agenda file list.
12163 If the file is not present in the list, it is added to the front. If it is
12164 present, it is moved there. With optional argument TO-END, add/move to the
12165 end of the list."
12166 (interactive "P")
12167 (let ((org-agenda-skip-unavailable-files nil)
12168 (file-alist (mapcar (lambda (x)
12169 (cons (file-truename x) x))
12170 (org-agenda-files t)))
12171 (ctf (file-truename buffer-file-name))
12172 x had)
12173 (setq x (assoc ctf file-alist) had x)
12175 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12176 (if to-end
12177 (setq file-alist (append (delq x file-alist) (list x)))
12178 (setq file-alist (cons x (delq x file-alist))))
12179 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12180 (org-install-agenda-files-menu)
12181 (message "File %s to %s of agenda file list"
12182 (if had "moved" "added") (if to-end "end" "front"))))
12184 (defun org-remove-file (&optional file)
12185 "Remove current file from the list of files in variable `org-agenda-files'.
12186 These are the files which are being checked for agenda entries.
12187 Optional argument FILE means, use this file instead of the current."
12188 (interactive)
12189 (let* ((org-agenda-skip-unavailable-files nil)
12190 (file (or file buffer-file-name))
12191 (true-file (file-truename file))
12192 (afile (abbreviate-file-name file))
12193 (files (delq nil (mapcar
12194 (lambda (x)
12195 (if (equal true-file
12196 (file-truename x))
12197 nil x))
12198 (org-agenda-files t)))))
12199 (if (not (= (length files) (length (org-agenda-files t))))
12200 (progn
12201 (org-store-new-agenda-file-list files)
12202 (org-install-agenda-files-menu)
12203 (message "Removed file: %s" afile))
12204 (message "File was not in list: %s (not removed)" afile))))
12206 (defun org-file-menu-entry (file)
12207 (vector file (list 'find-file file) t))
12209 (defun org-check-agenda-file (file)
12210 "Make sure FILE exists. If not, ask user what to do."
12211 (when (not (file-exists-p file))
12212 (message "non-existent file %s. [R]emove from list or [A]bort?"
12213 (abbreviate-file-name file))
12214 (let ((r (downcase (read-char-exclusive))))
12215 (cond
12216 ((equal r ?r)
12217 (org-remove-file file)
12218 (throw 'nextfile t))
12219 (t (error "Abort"))))))
12221 (defun org-get-agenda-file-buffer (file)
12222 "Get a buffer visiting FILE. If the buffer needs to be created, add
12223 it to the list of buffers which might be released later."
12224 (let ((buf (org-find-base-buffer-visiting file)))
12225 (if buf
12226 buf ; just return it
12227 ;; Make a new buffer and remember it
12228 (setq buf (find-file-noselect file))
12229 (if buf (push buf org-agenda-new-buffers))
12230 buf)))
12232 (defun org-release-buffers (blist)
12233 "Release all buffers in list, asking the user for confirmation when needed.
12234 When a buffer is unmodified, it is just killed. When modified, it is saved
12235 \(if the user agrees) and then killed."
12236 (let (buf file)
12237 (while (setq buf (pop blist))
12238 (setq file (buffer-file-name buf))
12239 (when (and (buffer-modified-p buf)
12240 file
12241 (y-or-n-p (format "Save file %s? " file)))
12242 (with-current-buffer buf (save-buffer)))
12243 (kill-buffer buf))))
12245 (defun org-prepare-agenda-buffers (files)
12246 "Create buffers for all agenda files, protect archived trees and comments."
12247 (interactive)
12248 (let ((pa '(:org-archived t))
12249 (pc '(:org-comment t))
12250 (pall '(:org-archived t :org-comment t))
12251 (inhibit-read-only t)
12252 (rea (concat ":" org-archive-tag ":"))
12253 bmp file re)
12254 (save-excursion
12255 (save-restriction
12256 (while (setq file (pop files))
12257 (if (bufferp file)
12258 (set-buffer file)
12259 (org-check-agenda-file file)
12260 (set-buffer (org-get-agenda-file-buffer file)))
12261 (widen)
12262 (setq bmp (buffer-modified-p))
12263 (org-refresh-category-properties)
12264 (setq org-todo-keywords-for-agenda
12265 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12266 (setq org-done-keywords-for-agenda
12267 (append org-done-keywords-for-agenda org-done-keywords))
12268 (setq org-todo-keyword-alist-for-agenda
12269 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12270 (setq org-tag-alist-for-agenda
12271 (append org-tag-alist-for-agenda org-tag-alist))
12273 (save-excursion
12274 (remove-text-properties (point-min) (point-max) pall)
12275 (when org-agenda-skip-archived-trees
12276 (goto-char (point-min))
12277 (while (re-search-forward rea nil t)
12278 (if (org-on-heading-p t)
12279 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12280 (goto-char (point-min))
12281 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12282 (while (re-search-forward re nil t)
12283 (add-text-properties
12284 (match-beginning 0) (org-end-of-subtree t) pc)))
12285 (set-buffer-modified-p bmp))))
12286 (setq org-todo-keyword-alist-for-agenda
12287 (org-uniquify org-todo-keyword-alist-for-agenda)
12288 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12290 ;;;; Embedded LaTeX
12292 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12293 "Keymap for the minor `org-cdlatex-mode'.")
12295 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12296 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12297 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12298 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12299 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12301 (defvar org-cdlatex-texmathp-advice-is-done nil
12302 "Flag remembering if we have applied the advice to texmathp already.")
12304 (define-minor-mode org-cdlatex-mode
12305 "Toggle the minor `org-cdlatex-mode'.
12306 This mode supports entering LaTeX environment and math in LaTeX fragments
12307 in Org-mode.
12308 \\{org-cdlatex-mode-map}"
12309 nil " OCDL" nil
12310 (when org-cdlatex-mode (require 'cdlatex))
12311 (unless org-cdlatex-texmathp-advice-is-done
12312 (setq org-cdlatex-texmathp-advice-is-done t)
12313 (defadvice texmathp (around org-math-always-on activate)
12314 "Always return t in org-mode buffers.
12315 This is because we want to insert math symbols without dollars even outside
12316 the LaTeX math segments. If Orgmode thinks that point is actually inside
12317 en embedded LaTeX fragement, let texmathp do its job.
12318 \\[org-cdlatex-mode-map]"
12319 (interactive)
12320 (let (p)
12321 (cond
12322 ((not (org-mode-p)) ad-do-it)
12323 ((eq this-command 'cdlatex-math-symbol)
12324 (setq ad-return-value t
12325 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12327 (let ((p (org-inside-LaTeX-fragment-p)))
12328 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12329 (setq ad-return-value t
12330 texmathp-why '("Org-mode embedded math" . 0))
12331 (if p ad-do-it)))))))))
12333 (defun turn-on-org-cdlatex ()
12334 "Unconditionally turn on `org-cdlatex-mode'."
12335 (org-cdlatex-mode 1))
12337 (defun org-inside-LaTeX-fragment-p ()
12338 "Test if point is inside a LaTeX fragment.
12339 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12340 sequence appearing also before point.
12341 Even though the matchers for math are configurable, this function assumes
12342 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12343 delimiters are skipped when they have been removed by customization.
12344 The return value is nil, or a cons cell with the delimiter and
12345 and the position of this delimiter.
12347 This function does a reasonably good job, but can locally be fooled by
12348 for example currency specifications. For example it will assume being in
12349 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12350 fragments that are properly closed, but during editing, we have to live
12351 with the uncertainty caused by missing closing delimiters. This function
12352 looks only before point, not after."
12353 (catch 'exit
12354 (let ((pos (point))
12355 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12356 (lim (progn
12357 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12358 (point)))
12359 dd-on str (start 0) m re)
12360 (goto-char pos)
12361 (when dodollar
12362 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12363 re (nth 1 (assoc "$" org-latex-regexps)))
12364 (while (string-match re str start)
12365 (cond
12366 ((= (match-end 0) (length str))
12367 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12368 ((= (match-end 0) (- (length str) 5))
12369 (throw 'exit nil))
12370 (t (setq start (match-end 0))))))
12371 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12372 (goto-char pos)
12373 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12374 (and (match-beginning 2) (throw 'exit nil))
12375 ;; count $$
12376 (while (re-search-backward "\\$\\$" lim t)
12377 (setq dd-on (not dd-on)))
12378 (goto-char pos)
12379 (if dd-on (cons "$$" m))))))
12382 (defun org-try-cdlatex-tab ()
12383 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12384 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12385 - inside a LaTeX fragment, or
12386 - after the first word in a line, where an abbreviation expansion could
12387 insert a LaTeX environment."
12388 (when org-cdlatex-mode
12389 (cond
12390 ((save-excursion
12391 (skip-chars-backward "a-zA-Z0-9*")
12392 (skip-chars-backward " \t")
12393 (bolp))
12394 (cdlatex-tab) t)
12395 ((org-inside-LaTeX-fragment-p)
12396 (cdlatex-tab) t)
12397 (t nil))))
12399 (defun org-cdlatex-underscore-caret (&optional arg)
12400 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12401 Revert to the normal definition outside of these fragments."
12402 (interactive "P")
12403 (if (org-inside-LaTeX-fragment-p)
12404 (call-interactively 'cdlatex-sub-superscript)
12405 (let (org-cdlatex-mode)
12406 (call-interactively (key-binding (vector last-input-event))))))
12408 (defun org-cdlatex-math-modify (&optional arg)
12409 "Execute `cdlatex-math-modify' in LaTeX fragments.
12410 Revert to the normal definition outside of these fragments."
12411 (interactive "P")
12412 (if (org-inside-LaTeX-fragment-p)
12413 (call-interactively 'cdlatex-math-modify)
12414 (let (org-cdlatex-mode)
12415 (call-interactively (key-binding (vector last-input-event))))))
12417 (defvar org-latex-fragment-image-overlays nil
12418 "List of overlays carrying the images of latex fragments.")
12419 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12421 (defun org-remove-latex-fragment-image-overlays ()
12422 "Remove all overlays with LaTeX fragment images in current buffer."
12423 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12424 (setq org-latex-fragment-image-overlays nil))
12426 (defun org-preview-latex-fragment (&optional subtree)
12427 "Preview the LaTeX fragment at point, or all locally or globally.
12428 If the cursor is in a LaTeX fragment, create the image and overlay
12429 it over the source code. If there is no fragment at point, display
12430 all fragments in the current text, from one headline to the next. With
12431 prefix SUBTREE, display all fragments in the current subtree. With a
12432 double prefix `C-u C-u', or when the cursor is before the first headline,
12433 display all fragments in the buffer.
12434 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12435 (interactive "P")
12436 (org-remove-latex-fragment-image-overlays)
12437 (save-excursion
12438 (save-restriction
12439 (let (beg end at msg)
12440 (cond
12441 ((or (equal subtree '(16))
12442 (not (save-excursion
12443 (re-search-backward (concat "^" outline-regexp) nil t))))
12444 (setq beg (point-min) end (point-max)
12445 msg "Creating images for buffer...%s"))
12446 ((equal subtree '(4))
12447 (org-back-to-heading)
12448 (setq beg (point) end (org-end-of-subtree t)
12449 msg "Creating images for subtree...%s"))
12451 (if (setq at (org-inside-LaTeX-fragment-p))
12452 (goto-char (max (point-min) (- (cdr at) 2)))
12453 (org-back-to-heading))
12454 (setq beg (point) end (progn (outline-next-heading) (point))
12455 msg (if at "Creating image...%s"
12456 "Creating images for entry...%s"))))
12457 (message msg "")
12458 (narrow-to-region beg end)
12459 (goto-char beg)
12460 (org-format-latex
12461 (concat "ltxpng/" (file-name-sans-extension
12462 (file-name-nondirectory
12463 buffer-file-name)))
12464 default-directory 'overlays msg at 'forbuffer)
12465 (message msg "done. Use `C-c C-c' to remove images.")))))
12467 (defvar org-latex-regexps
12468 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12469 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12470 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12471 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12472 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12473 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12474 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12475 "Regular expressions for matching embedded LaTeX.")
12477 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12478 "Replace LaTeX fragments with links to an image, and produce images."
12479 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12480 (let* ((prefixnodir (file-name-nondirectory prefix))
12481 (absprefix (expand-file-name prefix dir))
12482 (todir (file-name-directory absprefix))
12483 (opt org-format-latex-options)
12484 (matchers (plist-get opt :matchers))
12485 (re-list org-latex-regexps)
12486 (cnt 0) txt link beg end re e checkdir
12487 m n block linkfile movefile ov)
12488 ;; Check if there are old images files with this prefix, and remove them
12489 (when (file-directory-p todir)
12490 (mapc 'delete-file
12491 (directory-files
12492 todir 'full
12493 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12494 ;; Check the different regular expressions
12495 (while (setq e (pop re-list))
12496 (setq m (car e) re (nth 1 e) n (nth 2 e)
12497 block (if (nth 3 e) "\n\n" ""))
12498 (when (member m matchers)
12499 (goto-char (point-min))
12500 (while (re-search-forward re nil t)
12501 (when (or (not at) (equal (cdr at) (match-beginning n)))
12502 (setq txt (match-string n)
12503 beg (match-beginning n) end (match-end n)
12504 cnt (1+ cnt)
12505 linkfile (format "%s_%04d.png" prefix cnt)
12506 movefile (format "%s_%04d.png" absprefix cnt)
12507 link (concat block "[[file:" linkfile "]]" block))
12508 (if msg (message msg cnt))
12509 (goto-char beg)
12510 (unless checkdir ; make sure the directory exists
12511 (setq checkdir t)
12512 (or (file-directory-p todir) (make-directory todir)))
12513 (org-create-formula-image
12514 txt movefile opt forbuffer)
12515 (if overlays
12516 (progn
12517 (setq ov (org-make-overlay beg end))
12518 (if (featurep 'xemacs)
12519 (progn
12520 (org-overlay-put ov 'invisible t)
12521 (org-overlay-put
12522 ov 'end-glyph
12523 (make-glyph (vector 'png :file movefile))))
12524 (org-overlay-put
12525 ov 'display
12526 (list 'image :type 'png :file movefile :ascent 'center)))
12527 (push ov org-latex-fragment-image-overlays)
12528 (goto-char end))
12529 (delete-region beg end)
12530 (insert link))))))))
12532 ;; This function borrows from Ganesh Swami's latex2png.el
12533 (defun org-create-formula-image (string tofile options buffer)
12534 (let* ((tmpdir (if (featurep 'xemacs)
12535 (temp-directory)
12536 temporary-file-directory))
12537 (texfilebase (make-temp-name
12538 (expand-file-name "orgtex" tmpdir)))
12539 (texfile (concat texfilebase ".tex"))
12540 (dvifile (concat texfilebase ".dvi"))
12541 (pngfile (concat texfilebase ".png"))
12542 (fnh (if (featurep 'xemacs)
12543 (font-height (get-face-font 'default))
12544 (face-attribute 'default :height nil)))
12545 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12546 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12547 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12548 "Black"))
12549 (bg (or (plist-get options (if buffer :background :html-background))
12550 "Transparent")))
12551 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12552 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12553 (with-temp-file texfile
12554 (insert org-format-latex-header
12555 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12556 (let ((dir default-directory))
12557 (condition-case nil
12558 (progn
12559 (cd tmpdir)
12560 (call-process "latex" nil nil nil texfile))
12561 (error nil))
12562 (cd dir))
12563 (if (not (file-exists-p dvifile))
12564 (progn (message "Failed to create dvi file from %s" texfile) nil)
12565 (condition-case nil
12566 (call-process "dvipng" nil nil nil
12567 "-E" "-fg" fg "-bg" bg
12568 "-D" dpi
12569 ;;"-x" scale "-y" scale
12570 "-T" "tight"
12571 "-o" pngfile
12572 dvifile)
12573 (error nil))
12574 (if (not (file-exists-p pngfile))
12575 (progn (message "Failed to create png file from %s" texfile) nil)
12576 ;; Use the requested file name and clean up
12577 (copy-file pngfile tofile 'replace)
12578 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12579 (delete-file (concat texfilebase e)))
12580 pngfile))))
12582 (defun org-dvipng-color (attr)
12583 "Return an rgb color specification for dvipng."
12584 (apply 'format "rgb %s %s %s"
12585 (mapcar 'org-normalize-color
12586 (color-values (face-attribute 'default attr nil)))))
12588 (defun org-normalize-color (value)
12589 "Return string to be used as color value for an RGB component."
12590 (format "%g" (/ value 65535.0)))
12593 ;;;; Key bindings
12595 ;; Make `C-c C-x' a prefix key
12596 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12598 ;; TAB key with modifiers
12599 (org-defkey org-mode-map "\C-i" 'org-cycle)
12600 (org-defkey org-mode-map [(tab)] 'org-cycle)
12601 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12602 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12603 (org-defkey org-mode-map "\M-\t" 'org-complete)
12604 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12605 ;; The following line is necessary under Suse GNU/Linux
12606 (unless (featurep 'xemacs)
12607 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12608 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12609 (define-key org-mode-map [backtab] 'org-shifttab)
12611 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12612 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12613 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12615 ;; Cursor keys with modifiers
12616 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12617 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12618 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12619 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12621 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12622 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12623 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12624 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12626 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12627 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12628 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12629 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12631 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12632 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12634 ;;; Extra keys for tty access.
12635 ;; We only set them when really needed because otherwise the
12636 ;; menus don't show the simple keys
12638 (when (or org-use-extra-keys
12639 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12640 (not window-system))
12641 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12642 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12643 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12644 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12645 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12646 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12647 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12648 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12649 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12650 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12651 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12652 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12653 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12654 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12655 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12656 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12657 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12658 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12659 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12660 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12661 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12662 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12664 ;; All the other keys
12666 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12667 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12668 (if (boundp 'narrow-map)
12669 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12670 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12671 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12672 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12673 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12674 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12675 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12676 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12677 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12678 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12679 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12680 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12681 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12682 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12683 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12684 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12685 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12686 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12687 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12688 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12689 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12690 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12691 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12692 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12693 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12694 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12695 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12696 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12697 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12698 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12699 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12700 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12701 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12702 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12703 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12704 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12705 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12706 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12707 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12708 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12709 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12710 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12711 (org-defkey org-mode-map "\C-c^" 'org-sort)
12712 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12713 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12714 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12715 (org-defkey org-mode-map "\C-m" 'org-return)
12716 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12717 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12718 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12719 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12720 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12721 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12722 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12723 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12724 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12725 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12726 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12727 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12728 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12729 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12730 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12731 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12733 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12734 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12735 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12736 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12738 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12739 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12740 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12741 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12742 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12743 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12744 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12745 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12746 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12747 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12748 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12749 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12751 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12753 (when (featurep 'xemacs)
12754 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12756 (defvar org-table-auto-blank-field) ; defined in org-table.el
12757 (defun org-self-insert-command (N)
12758 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12759 If the cursor is in a table looking at whitespace, the whitespace is
12760 overwritten, and the table is not marked as requiring realignment."
12761 (interactive "p")
12762 (if (and (org-table-p)
12763 (progn
12764 ;; check if we blank the field, and if that triggers align
12765 (and (featurep 'org-table) org-table-auto-blank-field
12766 (member last-command
12767 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12768 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12769 ;; got extra space, this field does not determine column width
12770 (let (org-table-may-need-update) (org-table-blank-field))
12771 ;; no extra space, this field may determine column width
12772 (org-table-blank-field)))
12774 (eq N 1)
12775 (looking-at "[^|\n]* |"))
12776 (let (org-table-may-need-update)
12777 (goto-char (1- (match-end 0)))
12778 (delete-backward-char 1)
12779 (goto-char (match-beginning 0))
12780 (self-insert-command N))
12781 (setq org-table-may-need-update t)
12782 (self-insert-command N)
12783 (org-fix-tags-on-the-fly)))
12785 (defun org-fix-tags-on-the-fly ()
12786 (when (and (equal (char-after (point-at-bol)) ?*)
12787 (org-on-heading-p))
12788 (org-align-tags-here org-tags-column)))
12790 (defun org-delete-backward-char (N)
12791 "Like `delete-backward-char', insert whitespace at field end in tables.
12792 When deleting backwards, 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 (eq N 1)
12799 (string-match "|" (buffer-substring (point-at-bol) (point)))
12800 (looking-at ".*?|"))
12801 (let ((pos (point))
12802 (noalign (looking-at "[^|\n\r]* |"))
12803 (c org-table-may-need-update))
12804 (backward-delete-char N)
12805 (skip-chars-forward "^|")
12806 (insert " ")
12807 (goto-char (1- pos))
12808 ;; noalign: if there were two spaces at the end, this field
12809 ;; does not determine the width of the column.
12810 (if noalign (setq org-table-may-need-update c)))
12811 (backward-delete-char N)
12812 (org-fix-tags-on-the-fly)))
12814 (defun org-delete-char (N)
12815 "Like `delete-char', but insert whitespace at field end in tables.
12816 When deleting characters, in tables this function will insert whitespace in
12817 front of the next \"|\" separator, to keep the table aligned. The table will
12818 still be marked for re-alignment if the field did fill the entire column,
12819 because, in this case the deletion might narrow the column."
12820 (interactive "p")
12821 (if (and (org-table-p)
12822 (not (bolp))
12823 (not (= (char-after) ?|))
12824 (eq N 1))
12825 (if (looking-at ".*?|")
12826 (let ((pos (point))
12827 (noalign (looking-at "[^|\n\r]* |"))
12828 (c org-table-may-need-update))
12829 (replace-match (concat
12830 (substring (match-string 0) 1 -1)
12831 " |"))
12832 (goto-char pos)
12833 ;; noalign: if there were two spaces at the end, this field
12834 ;; does not determine the width of the column.
12835 (if noalign (setq org-table-may-need-update c)))
12836 (delete-char N))
12837 (delete-char N)
12838 (org-fix-tags-on-the-fly)))
12840 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12841 (put 'org-self-insert-command 'delete-selection t)
12842 (put 'orgtbl-self-insert-command 'delete-selection t)
12843 (put 'org-delete-char 'delete-selection 'supersede)
12844 (put 'org-delete-backward-char 'delete-selection 'supersede)
12846 ;; Make `flyspell-mode' delay after some commands
12847 (put 'org-self-insert-command 'flyspell-delayed t)
12848 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12849 (put 'org-delete-char 'flyspell-delayed t)
12850 (put 'org-delete-backward-char 'flyspell-delayed t)
12852 ;; Make pabbrev-mode expand after org-mode commands
12853 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12854 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12856 ;; How to do this: Measure non-white length of current string
12857 ;; If equal to column width, we should realign.
12859 (defun org-remap (map &rest commands)
12860 "In MAP, remap the functions given in COMMANDS.
12861 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12862 (let (new old)
12863 (while commands
12864 (setq old (pop commands) new (pop commands))
12865 (if (fboundp 'command-remapping)
12866 (org-defkey map (vector 'remap old) new)
12867 (substitute-key-definition old new map global-map)))))
12869 (when (eq org-enable-table-editor 'optimized)
12870 ;; If the user wants maximum table support, we need to hijack
12871 ;; some standard editing functions
12872 (org-remap org-mode-map
12873 'self-insert-command 'org-self-insert-command
12874 'delete-char 'org-delete-char
12875 'delete-backward-char 'org-delete-backward-char)
12876 (org-defkey org-mode-map "|" 'org-force-self-insert))
12878 (defun org-shiftcursor-error ()
12879 "Throw an error because Shift-Cursor command was applied in wrong context."
12880 (error "This command is active in special context like tables, headlines or timestamps"))
12882 (defun org-shifttab (&optional arg)
12883 "Global visibility cycling or move to previous table field.
12884 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12885 on context.
12886 See the individual commands for more information."
12887 (interactive "P")
12888 (cond
12889 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12890 ((integerp arg)
12891 (message "Content view to level: %d" arg)
12892 (org-content (prefix-numeric-value arg))
12893 (setq org-cycle-global-status 'overview))
12894 (t (call-interactively 'org-global-cycle))))
12896 (defun org-shiftmetaleft ()
12897 "Promote subtree or delete table column.
12898 Calls `org-promote-subtree', `org-outdent-item',
12899 or `org-table-delete-column', depending on context.
12900 See the individual commands for more information."
12901 (interactive)
12902 (cond
12903 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12904 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12905 ((org-at-item-p) (call-interactively 'org-outdent-item))
12906 (t (org-shiftcursor-error))))
12908 (defun org-shiftmetaright ()
12909 "Demote subtree or insert table column.
12910 Calls `org-demote-subtree', `org-indent-item',
12911 or `org-table-insert-column', depending on context.
12912 See the individual commands for more information."
12913 (interactive)
12914 (cond
12915 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12916 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12917 ((org-at-item-p) (call-interactively 'org-indent-item))
12918 (t (org-shiftcursor-error))))
12920 (defun org-shiftmetaup (&optional arg)
12921 "Move subtree up or kill table row.
12922 Calls `org-move-subtree-up' or `org-table-kill-row' or
12923 `org-move-item-up' depending on context. See the individual commands
12924 for more information."
12925 (interactive "P")
12926 (cond
12927 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12928 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12929 ((org-at-item-p) (call-interactively 'org-move-item-up))
12930 (t (org-shiftcursor-error))))
12931 (defun org-shiftmetadown (&optional arg)
12932 "Move subtree down or insert table row.
12933 Calls `org-move-subtree-down' or `org-table-insert-row' or
12934 `org-move-item-down', depending on context. See the individual
12935 commands for more information."
12936 (interactive "P")
12937 (cond
12938 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12939 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12940 ((org-at-item-p) (call-interactively 'org-move-item-down))
12941 (t (org-shiftcursor-error))))
12943 (defun org-metaleft (&optional arg)
12944 "Promote heading or move table column to left.
12945 Calls `org-do-promote' or `org-table-move-column', depending on context.
12946 With no specific context, calls the Emacs default `backward-word'.
12947 See the individual commands for more information."
12948 (interactive "P")
12949 (cond
12950 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12951 ((or (org-on-heading-p) (org-region-active-p))
12952 (call-interactively 'org-do-promote))
12953 ((org-at-item-p) (call-interactively 'org-outdent-item))
12954 (t (call-interactively 'backward-word))))
12956 (defun org-metaright (&optional arg)
12957 "Demote subtree or move table column to right.
12958 Calls `org-do-demote' or `org-table-move-column', depending on context.
12959 With no specific context, calls the Emacs default `forward-word'.
12960 See the individual commands for more information."
12961 (interactive "P")
12962 (cond
12963 ((org-at-table-p) (call-interactively 'org-table-move-column))
12964 ((or (org-on-heading-p) (org-region-active-p))
12965 (call-interactively 'org-do-demote))
12966 ((org-at-item-p) (call-interactively 'org-indent-item))
12967 (t (call-interactively 'forward-word))))
12969 (defun org-metaup (&optional arg)
12970 "Move subtree up or move table row up.
12971 Calls `org-move-subtree-up' or `org-table-move-row' or
12972 `org-move-item-up', depending on context. See the individual commands
12973 for more information."
12974 (interactive "P")
12975 (cond
12976 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12977 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12978 ((org-at-item-p) (call-interactively 'org-move-item-up))
12979 (t (transpose-lines 1) (beginning-of-line -1))))
12981 (defun org-metadown (&optional arg)
12982 "Move subtree down or move table row down.
12983 Calls `org-move-subtree-down' or `org-table-move-row' or
12984 `org-move-item-down', depending on context. See the individual
12985 commands for more information."
12986 (interactive "P")
12987 (cond
12988 ((org-at-table-p) (call-interactively 'org-table-move-row))
12989 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12990 ((org-at-item-p) (call-interactively 'org-move-item-down))
12991 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12993 (defun org-shiftup (&optional arg)
12994 "Increase item in timestamp or increase priority of current headline.
12995 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12996 depending on context. See the individual commands for more information."
12997 (interactive "P")
12998 (cond
12999 ((org-at-timestamp-p t)
13000 (call-interactively (if org-edit-timestamp-down-means-later
13001 'org-timestamp-down 'org-timestamp-up)))
13002 ((org-on-heading-p) (call-interactively 'org-priority-up))
13003 ((org-at-item-p) (call-interactively 'org-previous-item))
13004 ((org-clocktable-try-shift 'up arg))
13005 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13007 (defun org-shiftdown (&optional arg)
13008 "Decrease item in timestamp or decrease priority of current headline.
13009 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13010 depending on context. See the individual commands for more information."
13011 (interactive "P")
13012 (cond
13013 ((org-at-timestamp-p t)
13014 (call-interactively (if org-edit-timestamp-down-means-later
13015 'org-timestamp-up 'org-timestamp-down)))
13016 ((org-on-heading-p) (call-interactively 'org-priority-down))
13017 ((org-clocktable-try-shift 'down arg))
13018 (t (call-interactively 'org-next-item))))
13020 (defun org-shiftright (&optional arg)
13021 "Next TODO keyword or timestamp one day later, depending on context."
13022 (interactive "P")
13023 (cond
13024 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13025 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13026 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13027 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13028 ((org-clocktable-try-shift 'right arg))
13029 (t (org-shiftcursor-error))))
13031 (defun org-shiftleft (&optional arg)
13032 "Previous TODO keyword or timestamp one day earlier, depending on context."
13033 (interactive "P")
13034 (cond
13035 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13036 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13037 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13038 ((org-at-property-p)
13039 (call-interactively 'org-property-previous-allowed-value))
13040 ((org-clocktable-try-shift 'left arg))
13041 (t (org-shiftcursor-error))))
13043 (defun org-shiftcontrolright ()
13044 "Switch to next TODO set."
13045 (interactive)
13046 (cond
13047 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13048 (t (org-shiftcursor-error))))
13050 (defun org-shiftcontrolleft ()
13051 "Switch to previous TODO set."
13052 (interactive)
13053 (cond
13054 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13055 (t (org-shiftcursor-error))))
13057 (defun org-ctrl-c-ret ()
13058 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13059 (interactive)
13060 (cond
13061 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13062 (t (call-interactively 'org-insert-heading))))
13064 (defun org-copy-special ()
13065 "Copy region in table or copy current subtree.
13066 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13067 See the individual commands for more information."
13068 (interactive)
13069 (call-interactively
13070 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13072 (defun org-cut-special ()
13073 "Cut region in table or cut current subtree.
13074 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13075 See the individual commands for more information."
13076 (interactive)
13077 (call-interactively
13078 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13080 (defun org-paste-special (arg)
13081 "Paste rectangular region into table, or past subtree relative to level.
13082 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13083 See the individual commands for more information."
13084 (interactive "P")
13085 (if (org-at-table-p)
13086 (org-table-paste-rectangle)
13087 (org-paste-subtree arg)))
13089 (defun org-edit-special ()
13090 "Call a special editor for the stuff at point.
13091 When at a table, call the formula editor with `org-table-edit-formulas'.
13092 When at the first line of an src example, call `org-edit-src-code'.
13093 When in an #+include line, visit the include file. Otherwise call
13094 `ffap' to visit the file at point."
13095 (interactive)
13096 (cond
13097 ((org-at-table-p)
13098 (call-interactively 'org-table-edit-formulas))
13099 ((save-excursion
13100 (beginning-of-line 1)
13101 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13102 (find-file (org-trim (match-string 1))))
13103 ((org-edit-src-code))
13104 ((org-edit-fixed-width-region))
13105 (t (call-interactively 'ffap))))
13107 (defun org-ctrl-c-ctrl-c (&optional arg)
13108 "Set tags in headline, or update according to changed information at point.
13110 This command does many different things, depending on context:
13112 - If the cursor is in a headline, prompt for tags and insert them
13113 into the current line, aligned to `org-tags-column'. When called
13114 with prefix arg, realign all tags in the current buffer.
13116 - If the cursor is in one of the special #+KEYWORD lines, this
13117 triggers scanning the buffer for these lines and updating the
13118 information.
13120 - If the cursor is inside a table, realign the table. This command
13121 works even if the automatic table editor has been turned off.
13123 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13124 the entire table.
13126 - If the cursor is a the beginning of a dynamic block, update it.
13128 - If the cursor is inside a table created by the table.el package,
13129 activate that table.
13131 - If the current buffer is a remember buffer, close note and file it.
13132 with a prefix argument, file it without further interaction to the default
13133 location.
13135 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13136 links in this buffer.
13138 - If the cursor is on a numbered item in a plain list, renumber the
13139 ordered list.
13141 - If the cursor is on a checkbox, toggle it."
13142 (interactive "P")
13143 (let ((org-enable-table-editor t))
13144 (cond
13145 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13146 org-occur-highlights
13147 org-latex-fragment-image-overlays)
13148 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13149 (org-remove-occur-highlights)
13150 (org-remove-latex-fragment-image-overlays)
13151 (message "Temporary highlights/overlays removed from current buffer"))
13152 ((and (local-variable-p 'org-finish-function (current-buffer))
13153 (fboundp org-finish-function))
13154 (funcall org-finish-function))
13155 ((org-at-property-p)
13156 (call-interactively 'org-property-action))
13157 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13158 ((org-on-heading-p) (call-interactively 'org-set-tags))
13159 ((org-at-table.el-p)
13160 (require 'table)
13161 (beginning-of-line 1)
13162 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13163 (call-interactively 'table-recognize-table))
13164 ((org-at-table-p)
13165 (org-table-maybe-eval-formula)
13166 (if arg
13167 (call-interactively 'org-table-recalculate)
13168 (org-table-maybe-recalculate-line))
13169 (call-interactively 'org-table-align))
13170 ((org-at-item-checkbox-p)
13171 (call-interactively 'org-toggle-checkbox))
13172 ((org-at-item-p)
13173 (call-interactively 'org-maybe-renumber-ordered-list))
13174 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13175 ;; Dynamic block
13176 (beginning-of-line 1)
13177 (save-excursion (org-update-dblock)))
13178 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13179 (cond
13180 ((equal (match-string 1) "TBLFM")
13181 ;; Recalculate the table before this line
13182 (save-excursion
13183 (beginning-of-line 1)
13184 (skip-chars-backward " \r\n\t")
13185 (if (org-at-table-p)
13186 (org-call-with-arg 'org-table-recalculate t))))
13188 ; (org-set-regexps-and-options)
13189 ; (org-restart-font-lock)
13190 (let ((org-inhibit-startup t)) (org-mode-restart))
13191 (message "Local setup has been refreshed"))))
13192 (t (error "C-c C-c can do nothing useful at this location.")))))
13194 (defun org-mode-restart ()
13195 "Restart Org-mode, to scan again for special lines.
13196 Also updates the keyword regular expressions."
13197 (interactive)
13198 (org-mode)
13199 (message "Org-mode restarted"))
13201 (defun org-kill-note-or-show-branches ()
13202 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13203 (interactive)
13204 (if (not org-finish-function)
13205 (call-interactively 'show-branches)
13206 (let ((org-note-abort t))
13207 (funcall org-finish-function))))
13209 (defun org-return (&optional indent)
13210 "Goto next table row or insert a newline.
13211 Calls `org-table-next-row' or `newline', depending on context.
13212 See the individual commands for more information."
13213 (interactive)
13214 (cond
13215 ((bobp) (if indent (newline-and-indent) (newline)))
13216 ((and (org-at-heading-p)
13217 (looking-at
13218 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13219 (org-show-entry)
13220 (end-of-line 1)
13221 (newline))
13222 ((org-at-table-p)
13223 (org-table-justify-field-maybe)
13224 (call-interactively 'org-table-next-row))
13225 (t (if indent (newline-and-indent) (newline)))))
13227 (defun org-return-indent ()
13228 "Goto next table row or insert a newline and indent.
13229 Calls `org-table-next-row' or `newline-and-indent', depending on
13230 context. See the individual commands for more information."
13231 (interactive)
13232 (org-return t))
13234 (defun org-ctrl-c-star ()
13235 "Compute table, or change heading status of lines.
13236 Calls `org-table-recalculate' or `org-toggle-region-headings',
13237 depending on context. This will also turn a plain list item or a normal
13238 line into a subheading."
13239 (interactive)
13240 (cond
13241 ((org-at-table-p)
13242 (call-interactively 'org-table-recalculate))
13243 ((org-region-active-p)
13244 ;; Convert all lines in region to list items
13245 (call-interactively 'org-toggle-region-headings))
13246 ((org-on-heading-p)
13247 (org-toggle-region-headings (point-at-bol)
13248 (min (1+ (point-at-eol)) (point-max))))
13249 ((org-at-item-p)
13250 ;; Convert to heading
13251 (let ((level (save-match-data
13252 (save-excursion
13253 (condition-case nil
13254 (progn
13255 (org-back-to-heading t)
13256 (funcall outline-level))
13257 (error 0))))))
13258 (replace-match
13259 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13260 (t (org-toggle-region-headings (point-at-bol)
13261 (min (1+ (point-at-eol)) (point-max))))))
13263 (defun org-ctrl-c-minus ()
13264 "Insert separator line in table or modify bullet status of line.
13265 Also turns a plain line or a region of lines into list items.
13266 Calls `org-table-insert-hline', `org-toggle-region-items', or
13267 `org-cycle-list-bullet', depending on context."
13268 (interactive)
13269 (cond
13270 ((org-at-table-p)
13271 (call-interactively 'org-table-insert-hline))
13272 ((org-on-heading-p)
13273 ;; Convert to item
13274 (save-excursion
13275 (beginning-of-line 1)
13276 (if (looking-at "\\*+ ")
13277 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13278 ((org-region-active-p)
13279 ;; Convert all lines in region to list items
13280 (call-interactively 'org-toggle-region-items))
13281 ((org-in-item-p)
13282 (call-interactively 'org-cycle-list-bullet))
13283 (t (org-toggle-region-items (point-at-bol)
13284 (min (1+ (point-at-eol)) (point-max))))))
13286 (defun org-toggle-region-items (beg end)
13287 "Convert all lines in region to list items.
13288 If the first line is already an item, convert all list items in the region
13289 to normal lines."
13290 (interactive "r")
13291 (let (l2 l)
13292 (save-excursion
13293 (goto-char end)
13294 (setq l2 (org-current-line))
13295 (goto-char beg)
13296 (beginning-of-line 1)
13297 (setq l (1- (org-current-line)))
13298 (if (org-at-item-p)
13299 ;; We already have items, de-itemize
13300 (while (< (setq l (1+ l)) l2)
13301 (when (org-at-item-p)
13302 (goto-char (match-beginning 2))
13303 (delete-region (match-beginning 2) (match-end 2))
13304 (and (looking-at "[ \t]+") (replace-match "")))
13305 (beginning-of-line 2))
13306 (while (< (setq l (1+ l)) l2)
13307 (unless (org-at-item-p)
13308 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13309 (replace-match "\\1- \\2")))
13310 (beginning-of-line 2))))))
13312 (defun org-toggle-region-headings (beg end)
13313 "Convert all lines in region to list items.
13314 If the first line is already an item, convert all list items in the region
13315 to normal lines."
13316 (interactive "r")
13317 (let (l2 l)
13318 (save-excursion
13319 (goto-char end)
13320 (setq l2 (org-current-line))
13321 (goto-char beg)
13322 (beginning-of-line 1)
13323 (setq l (1- (org-current-line)))
13324 (if (org-on-heading-p)
13325 ;; We already have headlines, de-star them
13326 (while (< (setq l (1+ l)) l2)
13327 (when (org-on-heading-p t)
13328 (and (looking-at outline-regexp) (replace-match "")))
13329 (beginning-of-line 2))
13330 (let* ((stars (save-excursion
13331 (re-search-backward org-complex-heading-regexp nil t)
13332 (or (match-string 1) "*")))
13333 (add-stars (if org-odd-levels-only "**" "*"))
13334 (rpl (concat stars add-stars " \\2")))
13335 (while (< (setq l (1+ l)) l2)
13336 (unless (org-on-heading-p)
13337 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13338 (replace-match rpl)))
13339 (beginning-of-line 2)))))))
13341 (defun org-meta-return (&optional arg)
13342 "Insert a new heading or wrap a region in a table.
13343 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13344 See the individual commands for more information."
13345 (interactive "P")
13346 (cond
13347 ((org-at-table-p)
13348 (call-interactively 'org-table-wrap-region))
13349 (t (call-interactively 'org-insert-heading))))
13351 ;;; Menu entries
13353 ;; Define the Org-mode menus
13354 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13355 '("Tbl"
13356 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13357 ["Next Field" org-cycle (org-at-table-p)]
13358 ["Previous Field" org-shifttab (org-at-table-p)]
13359 ["Next Row" org-return (org-at-table-p)]
13360 "--"
13361 ["Blank Field" org-table-blank-field (org-at-table-p)]
13362 ["Edit Field" org-table-edit-field (org-at-table-p)]
13363 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13364 "--"
13365 ("Column"
13366 ["Move Column Left" org-metaleft (org-at-table-p)]
13367 ["Move Column Right" org-metaright (org-at-table-p)]
13368 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13369 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13370 ("Row"
13371 ["Move Row Up" org-metaup (org-at-table-p)]
13372 ["Move Row Down" org-metadown (org-at-table-p)]
13373 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13374 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13375 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13376 "--"
13377 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13378 ("Rectangle"
13379 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13380 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13381 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13382 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13383 "--"
13384 ("Calculate"
13385 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13386 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13387 ["Edit Formulas" org-edit-special (org-at-table-p)]
13388 "--"
13389 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13390 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13391 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13392 "--"
13393 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13394 "--"
13395 ["Sum Column/Rectangle" org-table-sum
13396 (or (org-at-table-p) (org-region-active-p))]
13397 ["Which Column?" org-table-current-column (org-at-table-p)])
13398 ["Debug Formulas"
13399 org-table-toggle-formula-debugger
13400 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13401 ["Show Col/Row Numbers"
13402 org-table-toggle-coordinate-overlays
13403 :style toggle
13404 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13405 "--"
13406 ["Create" org-table-create (and (not (org-at-table-p))
13407 org-enable-table-editor)]
13408 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13409 ["Import from File" org-table-import (not (org-at-table-p))]
13410 ["Export to File" org-table-export (org-at-table-p)]
13411 "--"
13412 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13414 (easy-menu-define org-org-menu org-mode-map "Org menu"
13415 '("Org"
13416 ("Show/Hide"
13417 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13418 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13419 ["Sparse Tree..." org-sparse-tree t]
13420 ["Reveal Context" org-reveal t]
13421 ["Show All" show-all t]
13422 "--"
13423 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13424 "--"
13425 ["New Heading" org-insert-heading t]
13426 ("Navigate Headings"
13427 ["Up" outline-up-heading t]
13428 ["Next" outline-next-visible-heading t]
13429 ["Previous" outline-previous-visible-heading t]
13430 ["Next Same Level" outline-forward-same-level t]
13431 ["Previous Same Level" outline-backward-same-level t]
13432 "--"
13433 ["Jump" org-goto t])
13434 ("Edit Structure"
13435 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13436 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13437 "--"
13438 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13439 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13440 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13441 "--"
13442 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13443 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13444 ["Demote Heading" org-metaright (not (org-at-table-p))]
13445 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13446 "--"
13447 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13448 "--"
13449 ["Convert to odd levels" org-convert-to-odd-levels t]
13450 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13451 ("Editing"
13452 ["Emphasis..." org-emphasize t]
13453 ["Edit Source Example" org-edit-special t])
13454 ("Archive"
13455 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13456 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13457 ; :active t :keys "C-u C-c C-x C-a"]
13458 ["Sparse trees open ARCHIVE trees"
13459 (setq org-sparse-tree-open-archived-trees
13460 (not org-sparse-tree-open-archived-trees))
13461 :style toggle :selected org-sparse-tree-open-archived-trees]
13462 ["Cycling opens ARCHIVE trees"
13463 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13464 :style toggle :selected org-cycle-open-archived-trees]
13465 "--"
13466 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13467 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13468 ; ["Check and Move Children" (org-archive-subtree '(4))
13469 ; :active t :keys "C-u C-c C-x C-s"]
13471 "--"
13472 ("TODO Lists"
13473 ["TODO/DONE/-" org-todo t]
13474 ("Select keyword"
13475 ["Next keyword" org-shiftright (org-on-heading-p)]
13476 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13477 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13478 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13479 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13480 ["Show TODO Tree" org-show-todo-tree t]
13481 ["Global TODO list" org-todo-list t]
13482 "--"
13483 ["Set Priority" org-priority t]
13484 ["Priority Up" org-shiftup t]
13485 ["Priority Down" org-shiftdown t])
13486 ("TAGS and Properties"
13487 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13488 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13489 "--"
13490 ["Set property" 'org-set-property t]
13491 ["Column view of properties" org-columns t]
13492 ["Insert Column View DBlock" org-insert-columns-dblock t])
13493 ("Dates and Scheduling"
13494 ["Timestamp" org-time-stamp t]
13495 ["Timestamp (inactive)" org-time-stamp-inactive t]
13496 ("Change Date"
13497 ["1 Day Later" org-shiftright t]
13498 ["1 Day Earlier" org-shiftleft t]
13499 ["1 ... Later" org-shiftup t]
13500 ["1 ... Earlier" org-shiftdown t])
13501 ["Compute Time Range" org-evaluate-time-range t]
13502 ["Schedule Item" org-schedule t]
13503 ["Deadline" org-deadline t]
13504 "--"
13505 ["Custom time format" org-toggle-time-stamp-overlays
13506 :style radio :selected org-display-custom-times]
13507 "--"
13508 ["Goto Calendar" org-goto-calendar t]
13509 ["Date from Calendar" org-date-from-calendar t])
13510 ("Logging work"
13511 ["Clock in" org-clock-in t]
13512 ["Clock out" org-clock-out t]
13513 ["Clock cancel" org-clock-cancel t]
13514 ["Goto running clock" org-clock-goto t]
13515 ["Display times" org-clock-display t]
13516 ["Create clock table" org-clock-report t]
13517 "--"
13518 ["Record DONE time"
13519 (progn (setq org-log-done (not org-log-done))
13520 (message "Switching to %s will %s record a timestamp"
13521 (car org-done-keywords)
13522 (if org-log-done "automatically" "not")))
13523 :style toggle :selected org-log-done])
13524 "--"
13525 ["Agenda Command..." org-agenda t]
13526 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13527 ("File List for Agenda")
13528 ("Special views current file"
13529 ["TODO Tree" org-show-todo-tree t]
13530 ["Check Deadlines" org-check-deadlines t]
13531 ["Timeline" org-timeline t]
13532 ["Tags Tree" org-tags-sparse-tree t])
13533 "--"
13534 ("Hyperlinks"
13535 ["Store Link (Global)" org-store-link t]
13536 ["Insert Link" org-insert-link t]
13537 ["Follow Link" org-open-at-point t]
13538 "--"
13539 ["Next link" org-next-link t]
13540 ["Previous link" org-previous-link t]
13541 "--"
13542 ["Descriptive Links"
13543 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13544 :style radio
13545 :selected (member '(org-link) buffer-invisibility-spec)]
13546 ["Literal Links"
13547 (progn
13548 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13549 :style radio
13550 :selected (not (member '(org-link) buffer-invisibility-spec))])
13551 "--"
13552 ["Export/Publish..." org-export t]
13553 ("LaTeX"
13554 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13555 :selected org-cdlatex-mode]
13556 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13557 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13558 ["Modify math symbol" org-cdlatex-math-modify
13559 (org-inside-LaTeX-fragment-p)]
13560 ["Export LaTeX fragments as images"
13561 (if (featurep 'org-exp)
13562 (setq org-export-with-LaTeX-fragments
13563 (not org-export-with-LaTeX-fragments))
13564 (require 'org-exp))
13565 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13566 org-export-with-LaTeX-fragments)])
13567 "--"
13568 ("Documentation"
13569 ["Show Version" org-version t]
13570 ["Info Documentation" org-info t])
13571 ("Customize"
13572 ["Browse Org Group" org-customize t]
13573 "--"
13574 ["Expand This Menu" org-create-customize-menu
13575 (fboundp 'customize-menu-create)])
13576 "--"
13577 ["Refresh setup" org-mode-restart t]
13580 (defun org-info (&optional node)
13581 "Read documentation for Org-mode in the info system.
13582 With optional NODE, go directly to that node."
13583 (interactive)
13584 (info (format "(org)%s" (or node ""))))
13586 (defun org-install-agenda-files-menu ()
13587 (let ((bl (buffer-list)))
13588 (save-excursion
13589 (while bl
13590 (set-buffer (pop bl))
13591 (if (org-mode-p) (setq bl nil)))
13592 (when (org-mode-p)
13593 (easy-menu-change
13594 '("Org") "File List for Agenda"
13595 (append
13596 (list
13597 ["Edit File List" (org-edit-agenda-file-list) t]
13598 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13599 ["Remove Current File from List" org-remove-file t]
13600 ["Cycle through agenda files" org-cycle-agenda-files t]
13601 ["Occur in all agenda files" org-occur-in-agenda-files t]
13602 "--")
13603 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13605 ;;;; Documentation
13607 ;;;###autoload
13608 (defun org-require-autoloaded-modules ()
13609 (interactive)
13610 (mapc 'require
13611 '(org-agenda org-archive org-clock org-colview
13612 org-exp org-id org-export-latex org-publish
13613 org-remember org-table)))
13615 ;;;###autoload
13616 (defun org-customize ()
13617 "Call the customize function with org as argument."
13618 (interactive)
13619 (org-load-modules-maybe)
13620 (org-require-autoloaded-modules)
13621 (customize-browse 'org))
13623 (defun org-create-customize-menu ()
13624 "Create a full customization menu for Org-mode, insert it into the menu."
13625 (interactive)
13626 (org-load-modules-maybe)
13627 (org-require-autoloaded-modules)
13628 (if (fboundp 'customize-menu-create)
13629 (progn
13630 (easy-menu-change
13631 '("Org") "Customize"
13632 `(["Browse Org group" org-customize t]
13633 "--"
13634 ,(customize-menu-create 'org)
13635 ["Set" Custom-set t]
13636 ["Save" Custom-save t]
13637 ["Reset to Current" Custom-reset-current t]
13638 ["Reset to Saved" Custom-reset-saved t]
13639 ["Reset to Standard Settings" Custom-reset-standard t]))
13640 (message "\"Org\"-menu now contains full customization menu"))
13641 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13643 ;;;; Miscellaneous stuff
13645 ;;; Generally useful functions
13647 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13648 "Display the given MESSAGE as a warning."
13649 (if (fboundp 'display-warning)
13650 (display-warning 'org message
13651 (if (featurep 'xemacs)
13652 'warning
13653 :warning))
13654 (let ((buf (get-buffer-create "*Org warnings*")))
13655 (with-current-buffer buf
13656 (goto-char (point-max))
13657 (insert "Warning (Org): " message)
13658 (unless (bolp)
13659 (newline)))
13660 (display-buffer buf)
13661 (sit-for 0))))
13663 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13664 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13665 (if (and marker (marker-buffer marker)
13666 (buffer-live-p (marker-buffer marker)))
13667 (progn
13668 (switch-to-buffer (marker-buffer marker))
13669 (if (or (> marker (point-max)) (< marker (point-min)))
13670 (widen))
13671 (goto-char marker))
13672 (if bookmark
13673 (bookmark-jump bookmark)
13674 (error "Cannot find location"))))
13676 (defun org-quote-csv-field (s)
13677 "Quote field for inclusion in CSV material."
13678 (if (string-match "[\",]" s)
13679 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13682 (defun org-plist-delete (plist property)
13683 "Delete PROPERTY from PLIST.
13684 This is in contrast to merely setting it to 0."
13685 (let (p)
13686 (while plist
13687 (if (not (eq property (car plist)))
13688 (setq p (plist-put p (car plist) (nth 1 plist))))
13689 (setq plist (cddr plist)))
13692 (defun org-force-self-insert (N)
13693 "Needed to enforce self-insert under remapping."
13694 (interactive "p")
13695 (self-insert-command N))
13697 (defun org-string-width (s)
13698 "Compute width of string, ignoring invisible characters.
13699 This ignores character with invisibility property `org-link', and also
13700 characters with property `org-cwidth', because these will become invisible
13701 upon the next fontification round."
13702 (let (b l)
13703 (when (or (eq t buffer-invisibility-spec)
13704 (assq 'org-link buffer-invisibility-spec))
13705 (while (setq b (text-property-any 0 (length s)
13706 'invisible 'org-link s))
13707 (setq s (concat (substring s 0 b)
13708 (substring s (or (next-single-property-change
13709 b 'invisible s) (length s)))))))
13710 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13711 (setq s (concat (substring s 0 b)
13712 (substring s (or (next-single-property-change
13713 b 'org-cwidth s) (length s))))))
13714 (setq l (string-width s) b -1)
13715 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13716 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13719 (defun org-base-buffer (buffer)
13720 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13721 (if (not buffer)
13722 buffer
13723 (or (buffer-base-buffer buffer)
13724 buffer)))
13726 (defun org-trim (s)
13727 "Remove whitespace at beginning and end of string."
13728 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13729 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13732 (defun org-wrap (string &optional width lines)
13733 "Wrap string to either a number of lines, or a width in characters.
13734 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13735 that costs. If there is a word longer than WIDTH, the text is actually
13736 wrapped to the length of that word.
13737 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13738 many lines, whatever width that takes.
13739 The return value is a list of lines, without newlines at the end."
13740 (let* ((words (org-split-string string "[ \t\n]+"))
13741 (maxword (apply 'max (mapcar 'org-string-width words)))
13742 w ll)
13743 (cond (width
13744 (org-do-wrap words (max maxword width)))
13745 (lines
13746 (setq w maxword)
13747 (setq ll (org-do-wrap words maxword))
13748 (if (<= (length ll) lines)
13750 (setq ll words)
13751 (while (> (length ll) lines)
13752 (setq w (1+ w))
13753 (setq ll (org-do-wrap words w)))
13754 ll))
13755 (t (error "Cannot wrap this")))))
13757 (defun org-do-wrap (words width)
13758 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13759 (let (lines line)
13760 (while words
13761 (setq line (pop words))
13762 (while (and words (< (+ (length line) (length (car words))) width))
13763 (setq line (concat line " " (pop words))))
13764 (setq lines (push line lines)))
13765 (nreverse lines)))
13767 (defun org-split-string (string &optional separators)
13768 "Splits STRING into substrings at SEPARATORS.
13769 No empty strings are returned if there are matches at the beginning
13770 and end of string."
13771 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13772 (start 0)
13773 notfirst
13774 (list nil))
13775 (while (and (string-match rexp string
13776 (if (and notfirst
13777 (= start (match-beginning 0))
13778 (< start (length string)))
13779 (1+ start) start))
13780 (< (match-beginning 0) (length string)))
13781 (setq notfirst t)
13782 (or (eq (match-beginning 0) 0)
13783 (and (eq (match-beginning 0) (match-end 0))
13784 (eq (match-beginning 0) start))
13785 (setq list
13786 (cons (substring string start (match-beginning 0))
13787 list)))
13788 (setq start (match-end 0)))
13789 (or (eq start (length string))
13790 (setq list
13791 (cons (substring string start)
13792 list)))
13793 (nreverse list)))
13795 (defun org-context ()
13796 "Return a list of contexts of the current cursor position.
13797 If several contexts apply, all are returned.
13798 Each context entry is a list with a symbol naming the context, and
13799 two positions indicating start and end of the context. Possible
13800 contexts are:
13802 :headline anywhere in a headline
13803 :headline-stars on the leading stars in a headline
13804 :todo-keyword on a TODO keyword (including DONE) in a headline
13805 :tags on the TAGS in a headline
13806 :priority on the priority cookie in a headline
13807 :item on the first line of a plain list item
13808 :item-bullet on the bullet/number of a plain list item
13809 :checkbox on the checkbox in a plain list item
13810 :table in an org-mode table
13811 :table-special on a special filed in a table
13812 :table-table in a table.el table
13813 :link on a hyperlink
13814 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13815 :target on a <<target>>
13816 :radio-target on a <<<radio-target>>>
13817 :latex-fragment on a LaTeX fragment
13818 :latex-preview on a LaTeX fragment with overlayed preview image
13820 This function expects the position to be visible because it uses font-lock
13821 faces as a help to recognize the following contexts: :table-special, :link,
13822 and :keyword."
13823 (let* ((f (get-text-property (point) 'face))
13824 (faces (if (listp f) f (list f)))
13825 (p (point)) clist o)
13826 ;; First the large context
13827 (cond
13828 ((org-on-heading-p t)
13829 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13830 (when (progn
13831 (beginning-of-line 1)
13832 (looking-at org-todo-line-tags-regexp))
13833 (push (org-point-in-group p 1 :headline-stars) clist)
13834 (push (org-point-in-group p 2 :todo-keyword) clist)
13835 (push (org-point-in-group p 4 :tags) clist))
13836 (goto-char p)
13837 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13838 (if (looking-at "\\[#[A-Z0-9]\\]")
13839 (push (org-point-in-group p 0 :priority) clist)))
13841 ((org-at-item-p)
13842 (push (org-point-in-group p 2 :item-bullet) clist)
13843 (push (list :item (point-at-bol)
13844 (save-excursion (org-end-of-item) (point)))
13845 clist)
13846 (and (org-at-item-checkbox-p)
13847 (push (org-point-in-group p 0 :checkbox) clist)))
13849 ((org-at-table-p)
13850 (push (list :table (org-table-begin) (org-table-end)) clist)
13851 (if (memq 'org-formula faces)
13852 (push (list :table-special
13853 (previous-single-property-change p 'face)
13854 (next-single-property-change p 'face)) clist)))
13855 ((org-at-table-p 'any)
13856 (push (list :table-table) clist)))
13857 (goto-char p)
13859 ;; Now the small context
13860 (cond
13861 ((org-at-timestamp-p)
13862 (push (org-point-in-group p 0 :timestamp) clist))
13863 ((memq 'org-link faces)
13864 (push (list :link
13865 (previous-single-property-change p 'face)
13866 (next-single-property-change p 'face)) clist))
13867 ((memq 'org-special-keyword faces)
13868 (push (list :keyword
13869 (previous-single-property-change p 'face)
13870 (next-single-property-change p 'face)) clist))
13871 ((org-on-target-p)
13872 (push (org-point-in-group p 0 :target) clist)
13873 (goto-char (1- (match-beginning 0)))
13874 (if (looking-at org-radio-target-regexp)
13875 (push (org-point-in-group p 0 :radio-target) clist))
13876 (goto-char p))
13877 ((setq o (car (delq nil
13878 (mapcar
13879 (lambda (x)
13880 (if (memq x org-latex-fragment-image-overlays) x))
13881 (org-overlays-at (point))))))
13882 (push (list :latex-fragment
13883 (org-overlay-start o) (org-overlay-end o)) clist)
13884 (push (list :latex-preview
13885 (org-overlay-start o) (org-overlay-end o)) clist))
13886 ((org-inside-LaTeX-fragment-p)
13887 ;; FIXME: positions wrong.
13888 (push (list :latex-fragment (point) (point)) clist)))
13890 (setq clist (nreverse (delq nil clist)))
13891 clist))
13893 ;; FIXME: Compare with at-regexp-p Do we need both?
13894 (defun org-in-regexp (re &optional nlines visually)
13895 "Check if point is inside a match of regexp.
13896 Normally only the current line is checked, but you can include NLINES extra
13897 lines both before and after point into the search.
13898 If VISUALLY is set, require that the cursor is not after the match but
13899 really on, so that the block visually is on the match."
13900 (catch 'exit
13901 (let ((pos (point))
13902 (eol (point-at-eol (+ 1 (or nlines 0))))
13903 (inc (if visually 1 0)))
13904 (save-excursion
13905 (beginning-of-line (- 1 (or nlines 0)))
13906 (while (re-search-forward re eol t)
13907 (if (and (<= (match-beginning 0) pos)
13908 (>= (+ inc (match-end 0)) pos))
13909 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13911 (defun org-at-regexp-p (regexp)
13912 "Is point inside a match of REGEXP in the current line?"
13913 (catch 'exit
13914 (save-excursion
13915 (let ((pos (point)) (end (point-at-eol)))
13916 (beginning-of-line 1)
13917 (while (re-search-forward regexp end t)
13918 (if (and (<= (match-beginning 0) pos)
13919 (>= (match-end 0) pos))
13920 (throw 'exit t)))
13921 nil))))
13923 (defun org-occur-in-agenda-files (regexp &optional nlines)
13924 "Call `multi-occur' with buffers for all agenda files."
13925 (interactive "sOrg-files matching: \np")
13926 (let* ((files (org-agenda-files))
13927 (tnames (mapcar 'file-truename files))
13928 (extra org-agenda-text-search-extra-files)
13930 (when (eq (car extra) 'agenda-archives)
13931 (setq extra (cdr extra))
13932 (setq files (org-add-archive-files files)))
13933 (while (setq f (pop extra))
13934 (unless (member (file-truename f) tnames)
13935 (add-to-list 'files f 'append)
13936 (add-to-list 'tnames (file-truename f) 'append)))
13937 (multi-occur
13938 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13939 regexp)))
13941 (if (boundp 'occur-mode-find-occurrence-hook)
13942 ;; Emacs 23
13943 (add-hook 'occur-mode-find-occurrence-hook
13944 (lambda ()
13945 (when (org-mode-p)
13946 (org-reveal))))
13947 ;; Emacs 22
13948 (defadvice occur-mode-goto-occurrence
13949 (after org-occur-reveal activate)
13950 (and (org-mode-p) (org-reveal)))
13951 (defadvice occur-mode-goto-occurrence-other-window
13952 (after org-occur-reveal activate)
13953 (and (org-mode-p) (org-reveal)))
13954 (defadvice occur-mode-display-occurrence
13955 (after org-occur-reveal activate)
13956 (when (org-mode-p)
13957 (let ((pos (occur-mode-find-occurrence)))
13958 (with-current-buffer (marker-buffer pos)
13959 (save-excursion
13960 (goto-char pos)
13961 (org-reveal)))))))
13963 (defun org-uniquify (list)
13964 "Remove duplicate elements from LIST."
13965 (let (res)
13966 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13967 res))
13969 (defun org-delete-all (elts list)
13970 "Remove all elements in ELTS from LIST."
13971 (while elts
13972 (setq list (delete (pop elts) list)))
13973 list)
13975 (defun org-back-over-empty-lines ()
13976 "Move backwards over witespace, to the beginning of the first empty line.
13977 Returns the number of empty lines passed."
13978 (let ((pos (point)))
13979 (skip-chars-backward " \t\n\r")
13980 (beginning-of-line 2)
13981 (goto-char (min (point) pos))
13982 (count-lines (point) pos)))
13984 (defun org-skip-whitespace ()
13985 (skip-chars-forward " \t\n\r"))
13987 (defun org-point-in-group (point group &optional context)
13988 "Check if POINT is in match-group GROUP.
13989 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13990 match. If the match group does ot exist or point is not inside it,
13991 return nil."
13992 (and (match-beginning group)
13993 (>= point (match-beginning group))
13994 (<= point (match-end group))
13995 (if context
13996 (list context (match-beginning group) (match-end group))
13997 t)))
13999 (defun org-switch-to-buffer-other-window (&rest args)
14000 "Switch to buffer in a second window on the current frame.
14001 In particular, do not allow pop-up frames."
14002 (let (pop-up-frames special-display-buffer-names special-display-regexps
14003 special-display-function)
14004 (apply 'switch-to-buffer-other-window args)))
14006 (defun org-combine-plists (&rest plists)
14007 "Create a single property list from all plists in PLISTS.
14008 The process starts by copying the first list, and then setting properties
14009 from the other lists. Settings in the last list are the most significant
14010 ones and overrule settings in the other lists."
14011 (let ((rtn (copy-sequence (pop plists)))
14012 p v ls)
14013 (while plists
14014 (setq ls (pop plists))
14015 (while ls
14016 (setq p (pop ls) v (pop ls))
14017 (setq rtn (plist-put rtn p v))))
14018 rtn))
14020 (defun org-move-line-down (arg)
14021 "Move the current line down. With prefix argument, move it past ARG lines."
14022 (interactive "p")
14023 (let ((col (current-column))
14024 beg end pos)
14025 (beginning-of-line 1) (setq beg (point))
14026 (beginning-of-line 2) (setq end (point))
14027 (beginning-of-line (+ 1 arg))
14028 (setq pos (move-marker (make-marker) (point)))
14029 (insert (delete-and-extract-region beg end))
14030 (goto-char pos)
14031 (org-move-to-column col)))
14033 (defun org-move-line-up (arg)
14034 "Move the current line up. With prefix argument, move it past ARG lines."
14035 (interactive "p")
14036 (let ((col (current-column))
14037 beg end pos)
14038 (beginning-of-line 1) (setq beg (point))
14039 (beginning-of-line 2) (setq end (point))
14040 (beginning-of-line (- arg))
14041 (setq pos (move-marker (make-marker) (point)))
14042 (insert (delete-and-extract-region beg end))
14043 (goto-char pos)
14044 (org-move-to-column col)))
14046 (defun org-replace-escapes (string table)
14047 "Replace %-escapes in STRING with values in TABLE.
14048 TABLE is an association list with keys like \"%a\" and string values.
14049 The sequences in STRING may contain normal field width and padding information,
14050 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14051 so values can contain further %-escapes if they are define later in TABLE."
14052 (let ((case-fold-search nil)
14053 e re rpl)
14054 (while (setq e (pop table))
14055 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14056 (while (string-match re string)
14057 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14058 (cdr e)))
14059 (setq string (replace-match rpl t t string))))
14060 string))
14063 (defun org-sublist (list start end)
14064 "Return a section of LIST, from START to END.
14065 Counting starts at 1."
14066 (let (rtn (c start))
14067 (setq list (nthcdr (1- start) list))
14068 (while (and list (<= c end))
14069 (push (pop list) rtn)
14070 (setq c (1+ c)))
14071 (nreverse rtn)))
14073 (defun org-find-base-buffer-visiting (file)
14074 "Like `find-buffer-visiting' but alway return the base buffer and
14075 not an indirect buffer."
14076 (let ((buf (find-buffer-visiting file)))
14077 (if buf
14078 (or (buffer-base-buffer buf) buf)
14079 nil)))
14081 (defun org-image-file-name-regexp ()
14082 "Return regexp matching the file names of images."
14083 (if (fboundp 'image-file-name-regexp)
14084 (image-file-name-regexp)
14085 (let ((image-file-name-extensions
14086 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14087 "xbm" "xpm" "pbm" "pgm" "ppm")))
14088 (concat "\\."
14089 (regexp-opt (nconc (mapcar 'upcase
14090 image-file-name-extensions)
14091 image-file-name-extensions)
14093 "\\'"))))
14095 (defun org-file-image-p (file)
14096 "Return non-nil if FILE is an image."
14097 (save-match-data
14098 (string-match (org-image-file-name-regexp) file)))
14100 (defun org-get-cursor-date ()
14101 "Return the date at cursor in as a time.
14102 This works in the calendar and in the agenda, anywhere else it just
14103 returns the current time."
14104 (let (date day defd)
14105 (cond
14106 ((eq major-mode 'calendar-mode)
14107 (setq date (calendar-cursor-to-date)
14108 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14109 ((eq major-mode 'org-agenda-mode)
14110 (setq day (get-text-property (point) 'day))
14111 (if day
14112 (setq date (calendar-gregorian-from-absolute day)
14113 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14114 (nth 2 date))))))
14115 (or defd (current-time))))
14117 (defvar org-agenda-action-marker (make-marker)
14118 "Marker pointing to the entry for the next agenda action.")
14120 (defun org-mark-entry-for-agenda-action ()
14121 "Mark the current entry as target of an agenda action.
14122 Agenda actions are actions executed from the agenda with the key `k',
14123 which make use of the date at the cursor."
14124 (interactive)
14125 (move-marker org-agenda-action-marker
14126 (save-excursion (org-back-to-heading t) (point))
14127 (current-buffer))
14128 (message
14129 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14131 ;;; Paragraph filling stuff.
14132 ;; We want this to be just right, so use the full arsenal.
14134 (defun org-indent-line-function ()
14135 "Indent line like previous, but further if previous was headline or item."
14136 (interactive)
14137 (unless (org-edit-src-find-region-and-lang)
14138 (let* ((pos (point))
14139 (itemp (org-at-item-p))
14140 column bpos bcol tpos tcol bullet btype bullet-type)
14141 ;; Find the previous relevant line
14142 (beginning-of-line 1)
14143 (cond
14144 ((looking-at "#") (setq column 0))
14145 ((looking-at "\\*+ ") (setq column 0))
14147 (beginning-of-line 0)
14148 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14149 (beginning-of-line 0))
14150 (cond
14151 ((looking-at "\\*+[ \t]+")
14152 (if (not org-adapt-indentation)
14153 (setq column 0)
14154 (goto-char (match-end 0))
14155 (setq column (current-column))))
14156 ((org-in-item-p)
14157 (org-beginning-of-item)
14158 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14159 (setq bpos (match-beginning 1) tpos (match-end 0)
14160 bcol (progn (goto-char bpos) (current-column))
14161 tcol (progn (goto-char tpos) (current-column))
14162 bullet (match-string 1)
14163 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14164 (if (> tcol (+ bcol org-description-max-indent))
14165 (setq tcol (+ bcol 5)))
14166 (if (not itemp)
14167 (setq column tcol)
14168 (goto-char pos)
14169 (beginning-of-line 1)
14170 (if (looking-at "\\S-")
14171 (progn
14172 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14173 (setq bullet (match-string 1)
14174 btype (if (string-match "[0-9]" bullet) "n" bullet))
14175 (setq column (if (equal btype bullet-type) bcol tcol)))
14176 (setq column (org-get-indentation)))))
14177 (t (setq column (org-get-indentation))))))
14178 (goto-char pos)
14179 (if (<= (current-column) (current-indentation))
14180 (org-indent-line-to column)
14181 (save-excursion (org-indent-line-to column)))
14182 (setq column (current-column))
14183 (beginning-of-line 1)
14184 (if (looking-at
14185 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14186 (replace-match (concat "\\1" (format org-property-format
14187 (match-string 2) (match-string 3)))
14188 t nil))
14189 (org-move-to-column column))))
14191 (defun org-set-autofill-regexps ()
14192 (interactive)
14193 ;; In the paragraph separator we include headlines, because filling
14194 ;; text in a line directly attached to a headline would otherwise
14195 ;; fill the headline as well.
14196 (org-set-local 'comment-start-skip "^#+[ \t]*")
14197 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14198 ;; The paragraph starter includes hand-formatted lists.
14199 (org-set-local 'paragraph-start
14200 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14201 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14202 ;; But only if the user has not turned off tables or fixed-width regions
14203 (org-set-local
14204 'auto-fill-inhibit-regexp
14205 (concat "\\*+ \\|#\\+"
14206 "\\|[ \t]*" org-keyword-time-regexp
14207 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14208 (concat
14209 "\\|[ \t]*["
14210 (if org-enable-table-editor "|" "")
14211 (if org-enable-fixed-width-editor ":" "")
14212 "]"))))
14213 ;; We use our own fill-paragraph function, to make sure that tables
14214 ;; and fixed-width regions are not wrapped. That function will pass
14215 ;; through to `fill-paragraph' when appropriate.
14216 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14217 ; Adaptive filling: To get full control, first make sure that
14218 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14219 (org-set-local 'adaptive-fill-regexp "\000")
14220 (org-set-local 'adaptive-fill-function
14221 'org-adaptive-fill-function)
14222 (org-set-local
14223 'align-mode-rules-list
14224 '((org-in-buffer-settings
14225 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14226 (modes . '(org-mode))))))
14228 (defun org-fill-paragraph (&optional justify)
14229 "Re-align a table, pass through to fill-paragraph if no table."
14230 (let ((table-p (org-at-table-p))
14231 (table.el-p (org-at-table.el-p)))
14232 (cond ((and (equal (char-after (point-at-bol)) ?*)
14233 (save-excursion (goto-char (point-at-bol))
14234 (looking-at outline-regexp)))
14235 t) ; skip headlines
14236 (table.el-p t) ; skip table.el tables
14237 (table-p (org-table-align) t) ; align org-mode tables
14238 (t nil)))) ; call paragraph-fill
14240 ;; For reference, this is the default value of adaptive-fill-regexp
14241 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14243 (defun org-adaptive-fill-function ()
14244 "Return a fill prefix for org-mode files.
14245 In particular, this makes sure hanging paragraphs for hand-formatted lists
14246 work correctly."
14247 (cond ((looking-at "#[ \t]+")
14248 (match-string 0))
14249 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14250 (save-excursion
14251 (if (> (match-end 1) (+ (match-beginning 1)
14252 org-description-max-indent))
14253 (goto-char (+ (match-beginning 1) 5))
14254 (goto-char (match-end 0)))
14255 (make-string (current-column) ?\ )))
14256 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14257 (save-excursion
14258 (goto-char (match-end 0))
14259 (make-string (current-column) ?\ )))
14260 (t nil)))
14262 ;;; Other stuff.
14264 (defun org-toggle-fixed-width-section (arg)
14265 "Toggle the fixed-width export.
14266 If there is no active region, the QUOTE keyword at the current headline is
14267 inserted or removed. When present, it causes the text between this headline
14268 and the next to be exported as fixed-width text, and unmodified.
14269 If there is an active region, this command adds or removes a colon as the
14270 first character of this line. If the first character of a line is a colon,
14271 this line is also exported in fixed-width font."
14272 (interactive "P")
14273 (let* ((cc 0)
14274 (regionp (org-region-active-p))
14275 (beg (if regionp (region-beginning) (point)))
14276 (end (if regionp (region-end)))
14277 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14278 (case-fold-search nil)
14279 (re "[ \t]*\\(:\\)")
14280 off)
14281 (if regionp
14282 (save-excursion
14283 (goto-char beg)
14284 (setq cc (current-column))
14285 (beginning-of-line 1)
14286 (setq off (looking-at re))
14287 (while (> nlines 0)
14288 (setq nlines (1- nlines))
14289 (beginning-of-line 1)
14290 (cond
14291 (arg
14292 (org-move-to-column cc t)
14293 (insert ":\n")
14294 (forward-line -1))
14295 ((and off (looking-at re))
14296 (replace-match "" t t nil 1))
14297 ((not off) (org-move-to-column cc t) (insert ":")))
14298 (forward-line 1)))
14299 (save-excursion
14300 (org-back-to-heading)
14301 (if (looking-at (concat outline-regexp
14302 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14303 (replace-match "" t t nil 1)
14304 (if (looking-at outline-regexp)
14305 (progn
14306 (goto-char (match-end 0))
14307 (insert org-quote-string " "))))))))
14309 ;;;; Functions extending outline functionality
14311 (defun org-beginning-of-line (&optional arg)
14312 "Go to the beginning of the current line. If that is invisible, continue
14313 to a visible line beginning. This makes the function of C-a more intuitive.
14314 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14315 first attempt, and only move to after the tags when the cursor is already
14316 beyond the end of the headline."
14317 (interactive "P")
14318 (let ((pos (point)) refpos)
14319 (beginning-of-line 1)
14320 (if (bobp)
14322 (backward-char 1)
14323 (if (org-invisible-p)
14324 (while (and (not (bobp)) (org-invisible-p))
14325 (backward-char 1)
14326 (beginning-of-line 1))
14327 (forward-char 1)))
14328 (when org-special-ctrl-a/e
14329 (cond
14330 ((and (looking-at org-complex-heading-regexp)
14331 (= (char-after (match-end 1)) ?\ ))
14332 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14333 (point-at-eol)))
14334 (goto-char
14335 (if (eq org-special-ctrl-a/e t)
14336 (cond ((> pos refpos) refpos)
14337 ((= pos (point)) refpos)
14338 (t (point)))
14339 (cond ((> pos (point)) (point))
14340 ((not (eq last-command this-command)) (point))
14341 (t refpos)))))
14342 ((org-at-item-p)
14343 (goto-char
14344 (if (eq org-special-ctrl-a/e t)
14345 (cond ((> pos (match-end 4)) (match-end 4))
14346 ((= pos (point)) (match-end 4))
14347 (t (point)))
14348 (cond ((> pos (point)) (point))
14349 ((not (eq last-command this-command)) (point))
14350 (t (match-end 4))))))))
14351 (org-no-warnings
14352 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14354 (defun org-end-of-line (&optional arg)
14355 "Go to the end of the line.
14356 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14357 first attempt, and only move to after the tags when the cursor is already
14358 beyond the end of the headline."
14359 (interactive "P")
14360 (if (or (not org-special-ctrl-a/e)
14361 (not (org-on-heading-p)))
14362 (end-of-line arg)
14363 (let ((pos (point)))
14364 (beginning-of-line 1)
14365 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14366 (if (eq org-special-ctrl-a/e t)
14367 (if (or (< pos (match-beginning 1))
14368 (= pos (match-end 0)))
14369 (goto-char (match-beginning 1))
14370 (goto-char (match-end 0)))
14371 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14372 (goto-char (match-end 0))
14373 (goto-char (match-beginning 1))))
14374 (end-of-line arg))))
14375 (org-no-warnings
14376 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14379 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14380 (define-key org-mode-map "\C-e" 'org-end-of-line)
14382 (defun org-kill-line (&optional arg)
14383 "Kill line, to tags or end of line."
14384 (interactive "P")
14385 (cond
14386 ((or (not org-special-ctrl-k)
14387 (bolp)
14388 (not (org-on-heading-p)))
14389 (call-interactively 'kill-line))
14390 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14391 (kill-region (point) (match-beginning 1))
14392 (org-set-tags nil t))
14393 (t (kill-region (point) (point-at-eol)))))
14396 (define-key org-mode-map "\C-k" 'org-kill-line)
14398 (defun org-yank-and-fold-if-subtree ()
14399 "Yank, and if the yanked text is a single subtree, fold it."
14400 (interactive)
14401 (let ((pos (point)) p1)
14402 (call-interactively 'yank)
14403 (setq p1 (point))
14404 (goto-char pos)
14405 (when (and (bolp)
14406 (looking-at outline-regexp)
14407 (org-kill-is-subtree-p))
14408 (hide-subtree)
14409 (org-cycle-show-empty-lines 'folded))
14410 (goto-char p1)
14411 (skip-chars-forward " \t\n\r")))
14413 (defun org-invisible-p ()
14414 "Check if point is at a character currently not visible."
14415 ;; Early versions of noutline don't have `outline-invisible-p'.
14416 (if (fboundp 'outline-invisible-p)
14417 (outline-invisible-p)
14418 (get-char-property (point) 'invisible)))
14420 (defun org-invisible-p2 ()
14421 "Check if point is at a character currently not visible."
14422 (save-excursion
14423 (if (and (eolp) (not (bobp))) (backward-char 1))
14424 ;; Early versions of noutline don't have `outline-invisible-p'.
14425 (if (fboundp 'outline-invisible-p)
14426 (outline-invisible-p)
14427 (get-char-property (point) 'invisible))))
14429 (defalias 'org-back-to-heading 'outline-back-to-heading)
14430 (defalias 'org-on-heading-p 'outline-on-heading-p)
14431 (defalias 'org-at-heading-p 'outline-on-heading-p)
14432 (defun org-at-heading-or-item-p ()
14433 (or (org-on-heading-p) (org-at-item-p)))
14435 (defun org-on-target-p ()
14436 (or (org-in-regexp org-radio-target-regexp)
14437 (org-in-regexp org-target-regexp)))
14439 (defun org-up-heading-all (arg)
14440 "Move to the heading line of which the present line is a subheading.
14441 This function considers both visible and invisible heading lines.
14442 With argument, move up ARG levels."
14443 (if (fboundp 'outline-up-heading-all)
14444 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14445 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14447 (defun org-up-heading-safe ()
14448 "Move to the heading line of which the present line is a subheading.
14449 This version will not throw an error. It will return the level of the
14450 headline found, or nil if no higher level is found."
14451 (let ((pos (point)) start-level level
14452 (re (concat "^" outline-regexp)))
14453 (catch 'exit
14454 (outline-back-to-heading t)
14455 (setq start-level (funcall outline-level))
14456 (if (equal start-level 1) (throw 'exit nil))
14457 (while (re-search-backward re nil t)
14458 (setq level (funcall outline-level))
14459 (if (< level start-level) (throw 'exit level)))
14460 nil)))
14462 (defun org-first-sibling-p ()
14463 "Is this heading the first child of its parents?"
14464 (interactive)
14465 (let ((re (concat "^" outline-regexp))
14466 level l)
14467 (unless (org-at-heading-p t)
14468 (error "Not at a heading"))
14469 (setq level (funcall outline-level))
14470 (save-excursion
14471 (if (not (re-search-backward re nil t))
14473 (setq l (funcall outline-level))
14474 (< l level)))))
14476 (defun org-goto-sibling (&optional previous)
14477 "Goto the next sibling, even if it is invisible.
14478 When PREVIOUS is set, go to the previous sibling instead. Returns t
14479 when a sibling was found. When none is found, return nil and don't
14480 move point."
14481 (let ((fun (if previous 're-search-backward 're-search-forward))
14482 (pos (point))
14483 (re (concat "^" outline-regexp))
14484 level l)
14485 (when (condition-case nil (org-back-to-heading t) (error nil))
14486 (setq level (funcall outline-level))
14487 (catch 'exit
14488 (or previous (forward-char 1))
14489 (while (funcall fun re nil t)
14490 (setq l (funcall outline-level))
14491 (when (< l level) (goto-char pos) (throw 'exit nil))
14492 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14493 (goto-char pos)
14494 nil))))
14496 (defun org-show-siblings ()
14497 "Show all siblings of the current headline."
14498 (save-excursion
14499 (while (org-goto-sibling) (org-flag-heading nil)))
14500 (save-excursion
14501 (while (org-goto-sibling 'previous)
14502 (org-flag-heading nil))))
14504 (defun org-show-hidden-entry ()
14505 "Show an entry where even the heading is hidden."
14506 (save-excursion
14507 (org-show-entry)))
14509 (defun org-flag-heading (flag &optional entry)
14510 "Flag the current heading. FLAG non-nil means make invisible.
14511 When ENTRY is non-nil, show the entire entry."
14512 (save-excursion
14513 (org-back-to-heading t)
14514 ;; Check if we should show the entire entry
14515 (if entry
14516 (progn
14517 (org-show-entry)
14518 (save-excursion
14519 (and (outline-next-heading)
14520 (org-flag-heading nil))))
14521 (outline-flag-region (max (point-min) (1- (point)))
14522 (save-excursion (outline-end-of-heading) (point))
14523 flag))))
14525 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14526 ;; This is an exact copy of the original function, but it uses
14527 ;; `org-back-to-heading', to make it work also in invisible
14528 ;; trees. And is uses an invisible-OK argument.
14529 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14530 (org-back-to-heading invisible-OK)
14531 (let ((first t)
14532 (level (funcall outline-level)))
14533 (while (and (not (eobp))
14534 (or first (> (funcall outline-level) level)))
14535 (setq first nil)
14536 (outline-next-heading))
14537 (unless to-heading
14538 (if (memq (preceding-char) '(?\n ?\^M))
14539 (progn
14540 ;; Go to end of line before heading
14541 (forward-char -1)
14542 (if (memq (preceding-char) '(?\n ?\^M))
14543 ;; leave blank line before heading
14544 (forward-char -1))))))
14545 (point))
14547 (defun org-show-subtree ()
14548 "Show everything after this heading at deeper levels."
14549 (outline-flag-region
14550 (point)
14551 (save-excursion
14552 (outline-end-of-subtree) (outline-next-heading) (point))
14553 nil))
14555 (defun org-show-entry ()
14556 "Show the body directly following this heading.
14557 Show the heading too, if it is currently invisible."
14558 (interactive)
14559 (save-excursion
14560 (condition-case nil
14561 (progn
14562 (org-back-to-heading t)
14563 (outline-flag-region
14564 (max (point-min) (1- (point)))
14565 (save-excursion
14566 (re-search-forward
14567 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14568 (or (match-beginning 1) (point-max)))
14569 nil))
14570 (error nil))))
14572 (defun org-make-options-regexp (kwds)
14573 "Make a regular expression for keyword lines."
14574 (concat
14576 "#?[ \t]*\\+\\("
14577 (mapconcat 'regexp-quote kwds "\\|")
14578 "\\):[ \t]*"
14579 "\\(.+\\)"))
14581 ;; Make isearch reveal the necessary context
14582 (defun org-isearch-end ()
14583 "Reveal context after isearch exits."
14584 (when isearch-success ; only if search was successful
14585 (if (featurep 'xemacs)
14586 ;; Under XEmacs, the hook is run in the correct place,
14587 ;; we directly show the context.
14588 (org-show-context 'isearch)
14589 ;; In Emacs the hook runs *before* restoring the overlays.
14590 ;; So we have to use a one-time post-command-hook to do this.
14591 ;; (Emacs 22 has a special variable, see function `org-mode')
14592 (unless (and (boundp 'isearch-mode-end-hook-quit)
14593 isearch-mode-end-hook-quit)
14594 ;; Only when the isearch was not quitted.
14595 (org-add-hook 'post-command-hook 'org-isearch-post-command
14596 'append 'local)))))
14598 (defun org-isearch-post-command ()
14599 "Remove self from hook, and show context."
14600 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14601 (org-show-context 'isearch))
14604 ;;;; Integration with and fixes for other packages
14606 ;;; Imenu support
14608 (defvar org-imenu-markers nil
14609 "All markers currently used by Imenu.")
14610 (make-variable-buffer-local 'org-imenu-markers)
14612 (defun org-imenu-new-marker (&optional pos)
14613 "Return a new marker for use by Imenu, and remember the marker."
14614 (let ((m (make-marker)))
14615 (move-marker m (or pos (point)))
14616 (push m org-imenu-markers)
14619 (defun org-imenu-get-tree ()
14620 "Produce the index for Imenu."
14621 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14622 (setq org-imenu-markers nil)
14623 (let* ((n org-imenu-depth)
14624 (re (concat "^" outline-regexp))
14625 (subs (make-vector (1+ n) nil))
14626 (last-level 0)
14627 m tree level head)
14628 (save-excursion
14629 (save-restriction
14630 (widen)
14631 (goto-char (point-max))
14632 (while (re-search-backward re nil t)
14633 (setq level (org-reduced-level (funcall outline-level)))
14634 (when (<= level n)
14635 (looking-at org-complex-heading-regexp)
14636 (setq head (org-match-string-no-properties 4)
14637 m (org-imenu-new-marker))
14638 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14639 (if (>= level last-level)
14640 (push (cons head m) (aref subs level))
14641 (push (cons head (aref subs (1+ level))) (aref subs level))
14642 (loop for i from (1+ level) to n do (aset subs i nil)))
14643 (setq last-level level)))))
14644 (aref subs 1)))
14646 (eval-after-load "imenu"
14647 '(progn
14648 (add-hook 'imenu-after-jump-hook
14649 (lambda ()
14650 (if (eq major-mode 'org-mode)
14651 (org-show-context 'org-goto))))))
14653 ;; Speedbar support
14655 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14656 "Overlay marking the agenda restriction line in speedbar.")
14657 (org-overlay-put org-speedbar-restriction-lock-overlay
14658 'face 'org-agenda-restriction-lock)
14659 (org-overlay-put org-speedbar-restriction-lock-overlay
14660 'help-echo "Agendas are currently limited to this item.")
14661 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14663 (defun org-speedbar-set-agenda-restriction ()
14664 "Restrict future agenda commands to the location at point in speedbar.
14665 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14666 (interactive)
14667 (require 'org-agenda)
14668 (let (p m tp np dir txt w)
14669 (cond
14670 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14671 'org-imenu t))
14672 (setq m (get-text-property p 'org-imenu-marker))
14673 (save-excursion
14674 (save-restriction
14675 (set-buffer (marker-buffer m))
14676 (goto-char m)
14677 (org-agenda-set-restriction-lock 'subtree))))
14678 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14679 'speedbar-function 'speedbar-find-file))
14680 (setq tp (previous-single-property-change
14681 (1+ p) 'speedbar-function)
14682 np (next-single-property-change
14683 tp 'speedbar-function)
14684 dir (speedbar-line-directory)
14685 txt (buffer-substring-no-properties (or tp (point-min))
14686 (or np (point-max))))
14687 (save-excursion
14688 (save-restriction
14689 (set-buffer (find-file-noselect
14690 (let ((default-directory dir))
14691 (expand-file-name txt))))
14692 (unless (org-mode-p)
14693 (error "Cannot restrict to non-Org-mode file"))
14694 (org-agenda-set-restriction-lock 'file))))
14695 (t (error "Don't know how to restrict Org-mode's agenda")))
14696 (org-move-overlay org-speedbar-restriction-lock-overlay
14697 (point-at-bol) (point-at-eol))
14698 (setq current-prefix-arg nil)
14699 (org-agenda-maybe-redo)))
14701 (eval-after-load "speedbar"
14702 '(progn
14703 (speedbar-add-supported-extension ".org")
14704 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14705 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14706 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14707 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14708 (add-hook 'speedbar-visiting-tag-hook
14709 (lambda () (org-show-context 'org-goto)))))
14712 ;;; Fixes and Hacks for problems with other packages
14714 ;; Make flyspell not check words in links, to not mess up our keymap
14715 (defun org-mode-flyspell-verify ()
14716 "Don't let flyspell put overlays at active buttons."
14717 (not (get-text-property (point) 'keymap)))
14719 ;; Make `bookmark-jump' show the jump location if it was hidden.
14720 (eval-after-load "bookmark"
14721 '(if (boundp 'bookmark-after-jump-hook)
14722 ;; We can use the hook
14723 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14724 ;; Hook not available, use advice
14725 (defadvice bookmark-jump (after org-make-visible activate)
14726 "Make the position visible."
14727 (org-bookmark-jump-unhide))))
14729 (defun org-bookmark-jump-unhide ()
14730 "Unhide the current position, to show the bookmark location."
14731 (and (org-mode-p)
14732 (or (org-invisible-p)
14733 (save-excursion (goto-char (max (point-min) (1- (point))))
14734 (org-invisible-p)))
14735 (org-show-context 'bookmark-jump)))
14737 ;; Make session.el ignore our circular variable
14738 (eval-after-load "session"
14739 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14741 ;;;; Experimental code
14743 (defun org-closed-in-range ()
14744 "Sparse tree of items closed in a certain time range.
14745 Still experimental, may disappear in the future."
14746 (interactive)
14747 ;; Get the time interval from the user.
14748 (let* ((time1 (time-to-seconds
14749 (org-read-date nil 'to-time nil "Starting date: ")))
14750 (time2 (time-to-seconds
14751 (org-read-date nil 'to-time nil "End date:")))
14752 ;; callback function
14753 (callback (lambda ()
14754 (let ((time
14755 (time-to-seconds
14756 (apply 'encode-time
14757 (org-parse-time-string
14758 (match-string 1))))))
14759 ;; check if time in interval
14760 (and (>= time time1) (<= time time2))))))
14761 ;; make tree, check each match with the callback
14762 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14765 ;;;; Finish up
14767 (provide 'org)
14769 (run-hooks 'org-load-hook)
14771 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14773 ;;; org.el ends here