Release 6.04.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob651594aa7741079a624fca15d99361eeae9e4c87
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.04
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.04"
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-indented nil
224 "Non-nil means, turn on `org-indent-mode' on startup.
225 This can also be configured on a per-file basis by adding one of
226 the following lines anywhere in the buffer:
228 #+STARTUP: localindent
229 #+STARTUP: indent
230 #+STARTUP: noindent"
231 :group 'org-structure
232 :type '(choice
233 (const :tag "Not" nil)
234 (const :tag "Locally" local)
235 (const :tag "Globally (slow on startup in large files)" t)))
237 (defcustom org-startup-align-all-tables nil
238 "Non-nil means, align all tables when visiting a file.
239 This is useful when the column width in tables is forced with <N> cookies
240 in table fields. Such tables will look correct only after the first re-align.
241 This can also be configured on a per-file basis by adding one of
242 the following lines anywhere in the buffer:
243 #+STARTUP: align
244 #+STARTUP: noalign"
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-insert-mode-line-in-empty-file nil
249 "Non-nil means insert the first line setting Org-mode in empty files.
250 When the function `org-mode' is called interactively in an empty file, this
251 normally means that the file name does not automatically trigger Org-mode.
252 To ensure that the file will always be in Org-mode in the future, a
253 line enforcing Org-mode will be inserted into the buffer, if this option
254 has been set."
255 :group 'org-startup
256 :type 'boolean)
258 (defcustom org-replace-disputed-keys nil
259 "Non-nil means use alternative key bindings for some keys.
260 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
261 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
262 If you want to use Org-mode together with one of these other modes,
263 or more generally if you would like to move some Org-mode commands to
264 other keys, set this variable and configure the keys with the variable
265 `org-disputed-keys'.
267 This option is only relevant at load-time of Org-mode, and must be set
268 *before* org.el is loaded. Changing it requires a restart of Emacs to
269 become effective."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
558 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
559 org-cycle-hide-drawers
560 org-cycle-show-empty-lines
561 org-optimize-window-after-visibility-change)
562 "Hook that is run after `org-cycle' has changed the buffer visibility.
563 The function(s) in this hook must accept a single argument which indicates
564 the new state that was set by the most recent `org-cycle' command. The
565 argument is a symbol. After a global state change, it can have the values
566 `overview', `content', or `all'. After a local state change, it can have
567 the values `folded', `children', or `subtree'."
568 :group 'org-cycle
569 :type 'hook)
571 (defgroup org-edit-structure nil
572 "Options concerning structure editing in Org-mode."
573 :tag "Org Edit Structure"
574 :group 'org-structure)
576 (defcustom org-odd-levels-only nil
577 "Non-nil means, skip even levels and only use odd levels for the outline.
578 This has the effect that two stars are being added/taken away in
579 promotion/demotion commands. It also influences how levels are
580 handled by the exporters.
581 Changing it requires restart of `font-lock-mode' to become effective
582 for fontification also in regions already fontified.
583 You may also set this on a per-file basis by adding one of the following
584 lines to the buffer:
586 #+STARTUP: odd
587 #+STARTUP: oddeven"
588 :group 'org-edit-structure
589 :group 'org-font-lock
590 :type 'boolean)
592 (defcustom org-adapt-indentation t
593 "Non-nil means, adapt indentation when promoting and demoting.
594 When this is set and the *entire* text in an entry is indented, the
595 indentation is increased by one space in a demotion command, and
596 decreased by one in a promotion command. If any line in the entry
597 body starts at column 0, indentation is not changed at all."
598 :group 'org-edit-structure
599 :type 'boolean)
601 (defcustom org-special-ctrl-a/e nil
602 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
603 When t, `C-a' will bring back the cursor to the beginning of the
604 headline text, i.e. after the stars and after a possible TODO keyword.
605 In an item, this will be the position after the bullet.
606 When the cursor is already at that position, another `C-a' will bring
607 it to the beginning of the line.
608 `C-e' will jump to the end of the headline, ignoring the presence of tags
609 in the headline. A second `C-e' will then jump to the true end of the
610 line, after any tags.
611 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
612 and only a directly following, identical keypress will bring the cursor
613 to the special positions."
614 :group 'org-edit-structure
615 :type '(choice
616 (const :tag "off" nil)
617 (const :tag "after bullet first" t)
618 (const :tag "border first" reversed)))
620 (if (fboundp 'defvaralias)
621 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
623 (defcustom org-special-ctrl-k nil
624 "Non-nil means `C-k' will behave specially in headlines.
625 When nil, `C-k' will call the default `kill-line' command.
626 When t, the following will happen while the cursor is in the headline:
628 - When the cursor is at the beginning of a headline, kill the entire
629 line and possible the folded subtree below the line.
630 - When in the middle of the headline text, kill the headline up to the tags.
631 - When after the headline text, kill the tags."
632 :group 'org-edit-structure
633 :type 'boolean)
635 (defcustom org-M-RET-may-split-line '((default . t))
636 "Non-nil means, M-RET will split the line at the cursor position.
637 When nil, it will go to the end of the line before making a
638 new line.
639 You may also set this option in a different way for different
640 contexts. Valid contexts are:
642 headline when creating a new headline
643 item when creating a new item
644 table in a table field
645 default the value to be used for all contexts not explicitly
646 customized"
647 :group 'org-structure
648 :group 'org-table
649 :type '(choice
650 (const :tag "Always" t)
651 (const :tag "Never" nil)
652 (repeat :greedy t :tag "Individual contexts"
653 (cons
654 (choice :tag "Context"
655 (const headline)
656 (const item)
657 (const table)
658 (const default))
659 (boolean)))))
662 (defcustom org-blank-before-new-entry '((heading . nil)
663 (plain-list-item . nil))
664 "Should `org-insert-heading' leave a blank line before new heading/item?
665 The value is an alist, with `heading' and `plain-list-item' as car,
666 and a boolean flag as cdr."
667 :group 'org-edit-structure
668 :type '(list
669 (cons (const heading) (boolean))
670 (cons (const plain-list-item) (boolean))))
672 (defcustom org-insert-heading-hook nil
673 "Hook being run after inserting a new heading."
674 :group 'org-edit-structure
675 :type 'hook)
677 (defcustom org-enable-fixed-width-editor t
678 "Non-nil means, lines starting with \":\" are treated as fixed-width.
679 This currently only means, they are never auto-wrapped.
680 When nil, such lines will be treated like ordinary lines.
681 See also the QUOTE keyword."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-goto-auto-isearch t
686 "Non-nil means, typing characters in org-goto starts incremental search."
687 :group 'org-edit-structure
688 :type 'boolean)
690 (defgroup org-sparse-trees nil
691 "Options concerning sparse trees in Org-mode."
692 :tag "Org Sparse Trees"
693 :group 'org-structure)
695 (defcustom org-highlight-sparse-tree-matches t
696 "Non-nil means, highlight all matches that define a sparse tree.
697 The highlights will automatically disappear the next time the buffer is
698 changed by an edit command."
699 :group 'org-sparse-trees
700 :type 'boolean)
702 (defcustom org-remove-highlights-with-change t
703 "Non-nil means, any change to the buffer will remove temporary highlights.
704 Such highlights are created by `org-occur' and `org-clock-display'.
705 When nil, `C-c C-c needs to be used to get rid of the highlights.
706 The highlights created by `org-preview-latex-fragment' always need
707 `C-c C-c' to be removed."
708 :group 'org-sparse-trees
709 :group 'org-time
710 :type 'boolean)
713 (defcustom org-occur-hook '(org-first-headline-recenter)
714 "Hook that is run after `org-occur' has constructed a sparse tree.
715 This can be used to recenter the window to show as much of the structure
716 as possible."
717 :group 'org-sparse-trees
718 :type 'hook)
720 (defgroup org-plain-lists nil
721 "Options concerning plain lists in Org-mode."
722 :tag "Org Plain lists"
723 :group 'org-structure)
725 (defcustom org-cycle-include-plain-lists nil
726 "Non-nil means, include plain lists into visibility cycling.
727 This means that during cycling, plain list items will *temporarily* be
728 interpreted as outline headlines with a level given by 1000+i where i is the
729 indentation of the bullet. In all other operations, plain list items are
730 not seen as headlines. For example, you cannot assign a TODO keyword to
731 such an item."
732 :group 'org-plain-lists
733 :type 'boolean)
735 (defcustom org-plain-list-ordered-item-terminator t
736 "The character that makes a line with leading number an ordered list item.
737 Valid values are ?. and ?\). To get both terminators, use t. While
738 ?. may look nicer, it creates the danger that a line with leading
739 number may be incorrectly interpreted as an item. ?\) therefore is
740 the safe choice."
741 :group 'org-plain-lists
742 :type '(choice (const :tag "dot like in \"2.\"" ?.)
743 (const :tag "paren like in \"2)\"" ?\))
744 (const :tab "both" t)))
746 (defcustom org-empty-line-terminates-plain-lists nil
747 "Non-nil means, an empty line ends all plain list levels.
748 When nil, empty lines are part of the preceeding item."
749 :group 'org-plain-lists
750 :type 'boolean)
752 (defcustom org-auto-renumber-ordered-lists t
753 "Non-nil means, automatically renumber ordered plain lists.
754 Renumbering happens when the sequence have been changed with
755 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
756 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
757 :group 'org-plain-lists
758 :type 'boolean)
760 (defcustom org-provide-checkbox-statistics t
761 "Non-nil means, update checkbox statistics after insert and toggle.
762 When this is set, checkbox statistics is updated each time you either insert
763 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
764 with \\[org-ctrl-c-ctrl-c\\]."
765 :group 'org-plain-lists
766 :type 'boolean)
768 (defcustom org-description-max-indent 20
769 "Maximum indentation for the second line of a description list.
770 When the indentation would be larger than this, it will become
771 5 characters instead."
772 :group 'org-plain-lists
773 :type 'integer)
775 (defgroup org-imenu-and-speedbar nil
776 "Options concerning imenu and speedbar in Org-mode."
777 :tag "Org Imenu and Speedbar"
778 :group 'org-structure)
780 (defcustom org-imenu-depth 2
781 "The maximum level for Imenu access to Org-mode headlines.
782 This also applied for speedbar access."
783 :group 'org-imenu-and-speedbar
784 :type 'number)
786 (defgroup org-table nil
787 "Options concerning tables in Org-mode."
788 :tag "Org Table"
789 :group 'org)
791 (defcustom org-enable-table-editor 'optimized
792 "Non-nil means, lines starting with \"|\" are handled by the table editor.
793 When nil, such lines will be treated like ordinary lines.
795 When equal to the symbol `optimized', the table editor will be optimized to
796 do the following:
797 - Automatic overwrite mode in front of whitespace in table fields.
798 This makes the structure of the table stay in tact as long as the edited
799 field does not exceed the column width.
800 - Minimize the number of realigns. Normally, the table is aligned each time
801 TAB or RET are pressed to move to another field. With optimization this
802 happens only if changes to a field might have changed the column width.
803 Optimization requires replacing the functions `self-insert-command',
804 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
805 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
806 very good at guessing when a re-align will be necessary, but you can always
807 force one with \\[org-ctrl-c-ctrl-c].
809 If you would like to use the optimized version in Org-mode, but the
810 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
812 This variable can be used to turn on and off the table editor during a session,
813 but in order to toggle optimization, a restart is required.
815 See also the variable `org-table-auto-blank-field'."
816 :group 'org-table
817 :type '(choice
818 (const :tag "off" nil)
819 (const :tag "on" t)
820 (const :tag "on, optimized" optimized)))
822 (defcustom org-table-tab-recognizes-table.el t
823 "Non-nil means, TAB will automatically notice a table.el table.
824 When it sees such a table, it moves point into it and - if necessary -
825 calls `table-recognize-table'."
826 :group 'org-table-editing
827 :type 'boolean)
829 (defgroup org-link nil
830 "Options concerning links in Org-mode."
831 :tag "Org Link"
832 :group 'org)
834 (defvar org-link-abbrev-alist-local nil
835 "Buffer-local version of `org-link-abbrev-alist', which see.
836 The value of this is taken from the #+LINK lines.")
837 (make-variable-buffer-local 'org-link-abbrev-alist-local)
839 (defcustom org-link-abbrev-alist nil
840 "Alist of link abbreviations.
841 The car of each element is a string, to be replaced at the start of a link.
842 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
843 links in Org-mode buffers can have an optional tag after a double colon, e.g.
845 [[linkkey:tag][description]]
847 If REPLACE is a string, the tag will simply be appended to create the link.
848 If the string contains \"%s\", the tag will be inserted there.
850 REPLACE may also be a function that will be called with the tag as the
851 only argument to create the link, which should be returned as a string.
853 See the manual for examples."
854 :group 'org-link
855 :type 'alist)
857 (defcustom org-descriptive-links t
858 "Non-nil means, hide link part and only show description of bracket links.
859 Bracket links are like [[link][descritpion]]. This variable sets the initial
860 state in new org-mode buffers. The setting can then be toggled on a
861 per-buffer basis from the Org->Hyperlinks menu."
862 :group 'org-link
863 :type 'boolean)
865 (defcustom org-link-file-path-type 'adaptive
866 "How the path name in file links should be stored.
867 Valid values are:
869 relative Relative to the current directory, i.e. the directory of the file
870 into which the link is being inserted.
871 absolute Absolute path, if possible with ~ for home directory.
872 noabbrev Absolute path, no abbreviation of home directory.
873 adaptive Use relative path for files in the current directory and sub-
874 directories of it. For other files, use an absolute path."
875 :group 'org-link
876 :type '(choice
877 (const relative)
878 (const absolute)
879 (const noabbrev)
880 (const adaptive)))
882 (defcustom org-activate-links '(bracket angle plain radio tag date)
883 "Types of links that should be activated in Org-mode files.
884 This is a list of symbols, each leading to the activation of a certain link
885 type. In principle, it does not hurt to turn on most link types - there may
886 be a small gain when turning off unused link types. The types are:
888 bracket The recommended [[link][description]] or [[link]] links with hiding.
889 angular Links in angular brackes that may contain whitespace like
890 <bbdb:Carsten Dominik>.
891 plain Plain links in normal text, no whitespace, like http://google.com.
892 radio Text that is matched by a radio target, see manual for details.
893 tag Tag settings in a headline (link to tag search).
894 date Time stamps (link to calendar).
896 Changing this variable requires a restart of Emacs to become effective."
897 :group 'org-link
898 :type '(set (const :tag "Double bracket links (new style)" bracket)
899 (const :tag "Angular bracket links (old style)" angular)
900 (const :tag "Plain text links" plain)
901 (const :tag "Radio target matches" radio)
902 (const :tag "Tags" tag)
903 (const :tag "Timestamps" date)))
905 (defcustom org-make-link-description-function nil
906 "Function to use to generate link descriptions from links. If
907 nil the link location will be used. This function must take two
908 parameters; the first is the link and the second the description
909 org-insert-link has generated, and should return the description
910 to use."
911 :group 'org-link
912 :type 'function)
914 (defgroup org-link-store nil
915 "Options concerning storing links in Org-mode."
916 :tag "Org Store Link"
917 :group 'org-link)
919 (defcustom org-email-link-description-format "Email %c: %.30s"
920 "Format of the description part of a link to an email or usenet message.
921 The following %-excapes will be replaced by corresponding information:
923 %F full \"From\" field
924 %f name, taken from \"From\" field, address if no name
925 %T full \"To\" field
926 %t first name in \"To\" field, address if no name
927 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
928 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
929 %s subject
930 %m message-id.
932 You may use normal field width specification between the % and the letter.
933 This is for example useful to limit the length of the subject.
935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
936 :group 'org-link-store
937 :type 'string)
939 (defcustom org-from-is-user-regexp
940 (let (r1 r2)
941 (when (and user-mail-address (not (string= user-mail-address "")))
942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
943 (when (and user-full-name (not (string= user-full-name "")))
944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
946 "Regexp mached against the \"From:\" header of an email or usenet message.
947 It should match if the message is from the user him/herself."
948 :group 'org-link-store
949 :type 'regexp)
951 (defcustom org-context-in-file-links t
952 "Non-nil means, file links from `org-store-link' contain context.
953 A search string will be added to the file name with :: as separator and
954 used to find the context when the link is activated by the command
955 `org-open-at-point'.
956 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
957 negates this setting for the duration of the command."
958 :group 'org-link-store
959 :type 'boolean)
961 (defcustom org-keep-stored-link-after-insertion nil
962 "Non-nil means, keep link in list for entire session.
964 The command `org-store-link' adds a link pointing to the current
965 location to an internal list. These links accumulate during a session.
966 The command `org-insert-link' can be used to insert links into any
967 Org-mode file (offering completion for all stored links). When this
968 option is nil, every link which has been inserted once using \\[org-insert-link]
969 will be removed from the list, to make completing the unused links
970 more efficient."
971 :group 'org-link-store
972 :type 'boolean)
974 (defgroup org-link-follow nil
975 "Options concerning following links in Org-mode."
976 :tag "Org Follow Link"
977 :group 'org-link)
979 (defcustom org-follow-link-hook nil
980 "Hook that is run after a link has been followed."
981 :group 'org-link-follow
982 :type 'hook)
984 (defcustom org-tab-follows-link nil
985 "Non-nil means, on links TAB will follow the link.
986 Needs to be set before org.el is loaded."
987 :group 'org-link-follow
988 :type 'boolean)
990 (defcustom org-return-follows-link nil
991 "Non-nil means, on links RET will follow the link.
992 Needs to be set before org.el is loaded."
993 :group 'org-link-follow
994 :type 'boolean)
996 (defcustom org-mouse-1-follows-link
997 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
998 "Non-nil means, mouse-1 on a link will follow the link.
999 A longer mouse click will still set point. Does not work on XEmacs.
1000 Needs to be set before org.el is loaded."
1001 :group 'org-link-follow
1002 :type 'boolean)
1004 (defcustom org-mark-ring-length 4
1005 "Number of different positions to be recorded in the ring
1006 Changing this requires a restart of Emacs to work correctly."
1007 :group 'org-link-follow
1008 :type 'interger)
1010 (defcustom org-link-frame-setup
1011 '((vm . vm-visit-folder-other-frame)
1012 (gnus . gnus-other-frame)
1013 (file . find-file-other-window))
1014 "Setup the frame configuration for following links.
1015 When following a link with Emacs, it may often be useful to display
1016 this link in another window or frame. This variable can be used to
1017 set this up for the different types of links.
1018 For VM, use any of
1019 `vm-visit-folder'
1020 `vm-visit-folder-other-frame'
1021 For Gnus, use any of
1022 `gnus'
1023 `gnus-other-frame'
1024 For FILE, use any of
1025 `find-file'
1026 `find-file-other-window'
1027 `find-file-other-frame'
1028 For the calendar, use the variable `calendar-setup'.
1029 For BBDB, it is currently only possible to display the matches in
1030 another window."
1031 :group 'org-link-follow
1032 :type '(list
1033 (cons (const vm)
1034 (choice
1035 (const vm-visit-folder)
1036 (const vm-visit-folder-other-window)
1037 (const vm-visit-folder-other-frame)))
1038 (cons (const gnus)
1039 (choice
1040 (const gnus)
1041 (const gnus-other-frame)))
1042 (cons (const file)
1043 (choice
1044 (const find-file)
1045 (const find-file-other-window)
1046 (const find-file-other-frame)))))
1048 (defcustom org-display-internal-link-with-indirect-buffer nil
1049 "Non-nil means, use indirect buffer to display infile links.
1050 Activating internal links (from one location in a file to another location
1051 in the same file) normally just jumps to the location. When the link is
1052 activated with a C-u prefix (or with mouse-3), the link is displayed in
1053 another window. When this option is set, the other window actually displays
1054 an indirect buffer clone of the current buffer, to avoid any visibility
1055 changes to the current buffer."
1056 :group 'org-link-follow
1057 :type 'boolean)
1059 (defcustom org-open-non-existing-files nil
1060 "Non-nil means, `org-open-file' will open non-existing files.
1061 When nil, an error will be generated."
1062 :group 'org-link-follow
1063 :type 'boolean)
1065 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1066 "Function and arguments to call for following mailto links.
1067 This is a list with the first element being a lisp function, and the
1068 remaining elements being arguments to the function. In string arguments,
1069 %a will be replaced by the address, and %s will be replaced by the subject
1070 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1071 :group 'org-link-follow
1072 :type '(choice
1073 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1074 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1075 (const :tag "message-mail" (message-mail "%a" "%s"))
1076 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1078 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1079 "Non-nil means, ask for confirmation before executing shell links.
1080 Shell links can be dangerous: just think about a link
1082 [[shell:rm -rf ~/*][Google Search]]
1084 This link would show up in your Org-mode document as \"Google Search\",
1085 but really it would remove your entire home directory.
1086 Therefore we advise against setting this variable to nil.
1087 Just change it to `y-or-n-p' of you want to confirm with a
1088 single keystroke rather than having to type \"yes\"."
1089 :group 'org-link-follow
1090 :type '(choice
1091 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1092 (const :tag "with y-or-n (faster)" y-or-n-p)
1093 (const :tag "no confirmation (dangerous)" nil)))
1095 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1096 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1097 Elisp links can be dangerous: just think about a link
1099 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1101 This link would show up in your Org-mode document as \"Google Search\",
1102 but really it would remove your entire home directory.
1103 Therefore we advise against setting this variable to nil.
1104 Just change it to `y-or-n-p' of you want to confirm with a
1105 single keystroke rather than having to type \"yes\"."
1106 :group 'org-link-follow
1107 :type '(choice
1108 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1109 (const :tag "with y-or-n (faster)" y-or-n-p)
1110 (const :tag "no confirmation (dangerous)" nil)))
1112 (defconst org-file-apps-defaults-gnu
1113 '((remote . emacs)
1114 (t . mailcap))
1115 "Default file applications on a UNIX or GNU/Linux system.
1116 See `org-file-apps'.")
1118 (defconst org-file-apps-defaults-macosx
1119 '((remote . emacs)
1120 (t . "open %s")
1121 ("ps" . "gv %s")
1122 ("ps.gz" . "gv %s")
1123 ("eps" . "gv %s")
1124 ("eps.gz" . "gv %s")
1125 ("dvi" . "xdvi %s")
1126 ("fig" . "xfig %s"))
1127 "Default file applications on a MacOS X system.
1128 The system \"open\" is known as a default, but we use X11 applications
1129 for some files for which the OS does not have a good default.
1130 See `org-file-apps'.")
1132 (defconst org-file-apps-defaults-windowsnt
1133 (list
1134 '(remote . emacs)
1135 (cons t
1136 (list (if (featurep 'xemacs)
1137 'mswindows-shell-execute
1138 'w32-shell-execute)
1139 "open" 'file)))
1140 "Default file applications on a Windows NT system.
1141 The system \"open\" is used for most files.
1142 See `org-file-apps'.")
1144 (defcustom org-file-apps
1146 ("txt" . emacs)
1147 ("tex" . emacs)
1148 ("ltx" . emacs)
1149 ("org" . emacs)
1150 ("el" . emacs)
1151 ("bib" . emacs)
1153 "External applications for opening `file:path' items in a document.
1154 Org-mode uses system defaults for different file types, but
1155 you can use this variable to set the application for a given file
1156 extension. The entries in this list are cons cells where the car identifies
1157 files and the cdr the corresponding command. Possible values for the
1158 file identifier are
1159 \"ext\" A string identifying an extension
1160 `directory' Matches a directory
1161 `remote' Matches a remote file, accessible through tramp or efs.
1162 Remote files most likely should be visited through Emacs
1163 because external applications cannot handle such paths.
1164 t Default for all remaining files
1166 Possible values for the command are:
1167 `emacs' The file will be visited by the current Emacs process.
1168 `default' Use the default application for this file type.
1169 string A command to be executed by a shell; %s will be replaced
1170 by the path to the file.
1171 sexp A Lisp form which will be evaluated. The file path will
1172 be available in the Lisp variable `file'.
1173 For more examples, see the system specific constants
1174 `org-file-apps-defaults-macosx'
1175 `org-file-apps-defaults-windowsnt'
1176 `org-file-apps-defaults-gnu'."
1177 :group 'org-link-follow
1178 :type '(repeat
1179 (cons (choice :value ""
1180 (string :tag "Extension")
1181 (const :tag "Default for unrecognized files" t)
1182 (const :tag "Remote file" remote)
1183 (const :tag "Links to a directory" directory))
1184 (choice :value ""
1185 (const :tag "Visit with Emacs" emacs)
1186 (const :tag "Use system default" default)
1187 (string :tag "Command")
1188 (sexp :tag "Lisp form")))))
1190 (defgroup org-refile nil
1191 "Options concerning refiling entries in Org-mode."
1192 :tag "Org Remember"
1193 :group 'org)
1195 (defcustom org-directory "~/org"
1196 "Directory with org files.
1197 This directory will be used as default to prompt for org files.
1198 Used by the hooks for remember.el."
1199 :group 'org-refile
1200 :group 'org-remember
1201 :type 'directory)
1203 (defcustom org-default-notes-file "~/.notes"
1204 "Default target for storing notes.
1205 Used by the hooks for remember.el. This can be a string, or nil to mean
1206 the value of `remember-data-file'.
1207 You can set this on a per-template basis with the variable
1208 `org-remember-templates'."
1209 :group 'org-refile
1210 :group 'org-remember
1211 :type '(choice
1212 (const :tag "Default from remember-data-file" nil)
1213 file))
1215 (defcustom org-goto-interface 'outline
1216 "The default interface to be used for `org-goto'.
1217 Allowed vaues are:
1218 outline The interface shows an outline of the relevant file
1219 and the correct heading is found by moving through
1220 the outline or by searching with incremental search.
1221 outline-path-completion Headlines in the current buffer are offered via
1222 completion."
1223 :group 'org-refile
1224 :type '(choice
1225 (const :tag "Outline" outline)
1226 (const :tag "Outline-path-completion" outline-path-completion)))
1228 (defcustom org-reverse-note-order nil
1229 "Non-nil means, store new notes at the beginning of a file or entry.
1230 When nil, new notes will be filed to the end of a file or entry.
1231 This can also be a list with cons cells of regular expressions that
1232 are matched against file names, and values."
1233 :group 'org-remember
1234 :type '(choice
1235 (const :tag "Reverse always" t)
1236 (const :tag "Reverse never" nil)
1237 (repeat :tag "By file name regexp"
1238 (cons regexp boolean))))
1240 (defcustom org-refile-targets nil
1241 "Targets for refiling entries with \\[org-refile].
1242 This is list of cons cells. Each cell contains:
1243 - a specification of the files to be considered, either a list of files,
1244 or a symbol whose function or variable value will be used to retrieve
1245 a file name or a list of file names. Nil means, refile to a different
1246 heading in the current buffer.
1247 - A specification of how to find candidate refile targets. This may be
1248 any of
1249 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1250 This tag has to be present in all target headlines, inheritance will
1251 not be considered.
1252 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1253 todo keyword.
1254 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1255 headlines that are refiling targets.
1256 - a cons cell (:level . N). Any headline of level N is considered a target.
1257 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1258 :group 'org-remember
1259 :type '(repeat
1260 (cons
1261 (choice :value org-agenda-files
1262 (const :tag "All agenda files" org-agenda-files)
1263 (const :tag "Current buffer" nil)
1264 (function) (variable) (file))
1265 (choice :tag "Identify target headline by"
1266 (cons :tag "Specific tag" (const :tag) (string))
1267 (cons :tag "TODO keyword" (const :todo) (string))
1268 (cons :tag "Regular expression" (const :regexp) (regexp))
1269 (cons :tag "Level number" (const :level) (integer))
1270 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1272 (defcustom org-refile-use-outline-path nil
1273 "Non-nil means, provide refile targets as paths.
1274 So a level 3 headline will be available as level1/level2/level3.
1275 When the value is `file', also include the file name (without directory)
1276 into the path. When `full-file-path', include the full file path."
1277 :group 'org-remember
1278 :type '(choice
1279 (const :tag "Not" nil)
1280 (const :tag "Yes" t)
1281 (const :tag "Start with file name" file)
1282 (const :tag "Start with full file path" full-file-path)))
1284 (defgroup org-todo nil
1285 "Options concerning TODO items in Org-mode."
1286 :tag "Org TODO"
1287 :group 'org)
1289 (defgroup org-progress nil
1290 "Options concerning Progress logging in Org-mode."
1291 :tag "Org Progress"
1292 :group 'org-time)
1294 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1295 "List of TODO entry keyword sequences and their interpretation.
1296 \\<org-mode-map>This is a list of sequences.
1298 Each sequence starts with a symbol, either `sequence' or `type',
1299 indicating if the keywords should be interpreted as a sequence of
1300 action steps, or as different types of TODO items. The first
1301 keywords are states requiring action - these states will select a headline
1302 for inclusion into the global TODO list Org-mode produces. If one of
1303 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1304 signify that no further action is necessary. If \"|\" is not found,
1305 the last keyword is treated as the only DONE state of the sequence.
1307 The command \\[org-todo] cycles an entry through these states, and one
1308 additional state where no keyword is present. For details about this
1309 cycling, see the manual.
1311 TODO keywords and interpretation can also be set on a per-file basis with
1312 the special #+SEQ_TODO and #+TYP_TODO lines.
1314 Each keyword can optionally specify a character for fast state selection
1315 \(in combination with the variable `org-use-fast-todo-selection')
1316 and specifiers for state change logging, using the same syntax
1317 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1318 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1319 indicates to record a time stamp each time this state is selected.
1321 Each keyword may also specify if a timestamp or a note should be
1322 recorded when entering or leaving the state, by adding additional
1323 characters in the parenthesis after the keyword. This looks like this:
1324 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1325 record only the time of the state change. With X and Y being either
1326 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1327 Y when leaving the state if and only if the *target* state does not
1328 define X. You may omit any of the fast-selection key or X or /Y,
1329 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1331 For backward compatibility, this variable may also be just a list
1332 of keywords - in this case the interptetation (sequence or type) will be
1333 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1334 :group 'org-todo
1335 :group 'org-keywords
1336 :type '(choice
1337 (repeat :tag "Old syntax, just keywords"
1338 (string :tag "Keyword"))
1339 (repeat :tag "New syntax"
1340 (cons
1341 (choice
1342 :tag "Interpretation"
1343 (const :tag "Sequence (cycling hits every state)" sequence)
1344 (const :tag "Type (cycling directly to DONE)" type))
1345 (repeat
1346 (string :tag "Keyword"))))))
1348 (defvar org-todo-keywords-1 nil
1349 "All TODO and DONE keywords active in a buffer.")
1350 (make-variable-buffer-local 'org-todo-keywords-1)
1351 (defvar org-todo-keywords-for-agenda nil)
1352 (defvar org-done-keywords-for-agenda nil)
1353 (defvar org-agenda-contributing-files nil)
1354 (defvar org-not-done-keywords nil)
1355 (make-variable-buffer-local 'org-not-done-keywords)
1356 (defvar org-done-keywords nil)
1357 (make-variable-buffer-local 'org-done-keywords)
1358 (defvar org-todo-heads nil)
1359 (make-variable-buffer-local 'org-todo-heads)
1360 (defvar org-todo-sets nil)
1361 (make-variable-buffer-local 'org-todo-sets)
1362 (defvar org-todo-log-states nil)
1363 (make-variable-buffer-local 'org-todo-log-states)
1364 (defvar org-todo-kwd-alist nil)
1365 (make-variable-buffer-local 'org-todo-kwd-alist)
1366 (defvar org-todo-key-alist nil)
1367 (make-variable-buffer-local 'org-todo-key-alist)
1368 (defvar org-todo-key-trigger nil)
1369 (make-variable-buffer-local 'org-todo-key-trigger)
1371 (defcustom org-todo-interpretation 'sequence
1372 "Controls how TODO keywords are interpreted.
1373 This variable is in principle obsolete and is only used for
1374 backward compatibility, if the interpretation of todo keywords is
1375 not given already in `org-todo-keywords'. See that variable for
1376 more information."
1377 :group 'org-todo
1378 :group 'org-keywords
1379 :type '(choice (const sequence)
1380 (const type)))
1382 (defcustom org-use-fast-todo-selection 'prefix
1383 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1384 This variable describes if and under what circumstances the cycling
1385 mechanism for TODO keywords will be replaced by a single-key, direct
1386 selection scheme.
1388 When nil, fast selection is never used.
1390 When the symbol `prefix', it will be used when `org-todo' is called with
1391 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1392 in an agenda buffer.
1394 When t, fast selection is used by default. In this case, the prefix
1395 argument forces cycling instead.
1397 In all cases, the special interface is only used if access keys have actually
1398 been assigned by the user, i.e. if keywords in the configuration are followed
1399 by a letter in parenthesis, like TODO(t)."
1400 :group 'org-todo
1401 :type '(choice
1402 (const :tag "Never" nil)
1403 (const :tag "By default" t)
1404 (const :tag "Only with C-u C-c C-t" prefix)))
1406 (defcustom org-provide-todo-statistics t
1407 "Non-nil means, update todo statistics after insert and toggle.
1408 When this is set, todo statistics is updated in the parent of the current
1409 entry each time a todo state is changed."
1410 :group 'org-todo
1411 :type 'boolean)
1413 (defcustom org-after-todo-state-change-hook nil
1414 "Hook which is run after the state of a TODO item was changed.
1415 The new state (a string with a TODO keyword, or nil) is available in the
1416 Lisp variable `state'."
1417 :group 'org-todo
1418 :type 'hook)
1420 (defcustom org-log-done nil
1421 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1422 When equal to the list (done), also prompt for a closing note.
1423 This can also be configured on a per-file basis by adding one of
1424 the following lines anywhere in the buffer:
1426 #+STARTUP: logdone
1427 #+STARTUP: lognotedone
1428 #+STARTUP: nologdone"
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(choice
1432 (const :tag "No logging" nil)
1433 (const :tag "Record CLOSED timestamp" time)
1434 (const :tag "Record CLOSED timestamp with closing note." note)))
1436 ;; Normalize old uses of org-log-done.
1437 (cond
1438 ((eq org-log-done t) (setq org-log-done 'time))
1439 ((and (listp org-log-done) (memq 'done org-log-done))
1440 (setq org-log-done 'note)))
1442 (defcustom org-log-note-clock-out nil
1443 "Non-nil means, recored a note when clocking out of an item.
1444 This can also be configured on a per-file basis by adding one of
1445 the following lines anywhere in the buffer:
1447 #+STARTUP: lognoteclock-out
1448 #+STARTUP: nolognoteclock-out"
1449 :group 'org-todo
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-done-with-time t
1454 "Non-nil means, the CLOSED time stamp will contain date and time.
1455 When nil, only the date will be recorded."
1456 :group 'org-progress
1457 :type 'boolean)
1459 (defcustom org-log-note-headings
1460 '((done . "CLOSING NOTE %t")
1461 (state . "State %-12s %t")
1462 (note . "Note taken on %t")
1463 (clock-out . ""))
1464 "Headings for notes added to entries.
1465 The value is an alist, with the car being a symbol indicating the note
1466 context, and the cdr is the heading to be used. The heading may also be the
1467 empty string.
1468 %t in the heading will be replaced by a time stamp.
1469 %s will be replaced by the new TODO state, in double quotes.
1470 %u will be replaced by the user name.
1471 %U will be replaced by the full user name."
1472 :group 'org-todo
1473 :group 'org-progress
1474 :type '(list :greedy t
1475 (cons (const :tag "Heading when closing an item" done) string)
1476 (cons (const :tag
1477 "Heading when changing todo state (todo sequence only)"
1478 state) string)
1479 (cons (const :tag "Heading when just taking a note" note) string)
1480 (cons (const :tag "Heading when clocking out" clock-out) string)))
1482 (unless (assq 'note org-log-note-headings)
1483 (push '(note . "%t") org-log-note-headings))
1485 (defcustom org-log-states-order-reversed t
1486 "Non-nil means, the latest state change note will be directly after heading.
1487 When nil, the notes will be orderer according to time."
1488 :group 'org-todo
1489 :group 'org-progress
1490 :type 'boolean)
1492 (defcustom org-log-repeat 'time
1493 "Non-nil means, record moving through the DONE state when triggering repeat.
1494 An auto-repeating tasks is immediately switched back to TODO when marked
1495 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1496 the TODO keyword definition, or recording a closing note by setting
1497 `org-log-done', there will be no record of the task moving through DONE.
1498 This variable forces taking a note anyway. Possible values are:
1500 nil Don't force a record
1501 time Record a time stamp
1502 note Record a note
1504 This option can also be set with on a per-file-basis with
1506 #+STARTUP: logrepeat
1507 #+STARTUP: lognoterepeat
1508 #+STARTUP: nologrepeat
1510 You can have local logging settings for a subtree by setting the LOGGING
1511 property to one or more of these keywords."
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type '(choice
1515 (const :tag "Don't force a record" nil)
1516 (const :tag "Force recording the DONE state" time)
1517 (const :tag "Force recording a note with the DONE state" note)))
1520 (defgroup org-priorities nil
1521 "Priorities in Org-mode."
1522 :tag "Org Priorities"
1523 :group 'org-todo)
1525 (defcustom org-highest-priority ?A
1526 "The highest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a smaller ASCII number than `org-lowest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-lowest-priority ?C
1532 "The lowest priority of TODO items. A character like ?A, ?B etc.
1533 Must have a larger ASCII number than `org-highest-priority'."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-default-priority ?B
1538 "The default priority of TODO items.
1539 This is the priority an item get if no explicit priority is given."
1540 :group 'org-priorities
1541 :type 'character)
1543 (defcustom org-priority-start-cycle-with-default t
1544 "Non-nil means, start with default priority when starting to cycle.
1545 When this is nil, the first step in the cycle will be (depending on the
1546 command used) one higher or lower that the default priority."
1547 :group 'org-priorities
1548 :type 'boolean)
1550 (defgroup org-time nil
1551 "Options concerning time stamps and deadlines in Org-mode."
1552 :tag "Org Time"
1553 :group 'org)
1555 (defcustom org-insert-labeled-timestamps-at-point nil
1556 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1557 When nil, these labeled time stamps are forces into the second line of an
1558 entry, just after the headline. When scheduling from the global TODO list,
1559 the time stamp will always be forced into the second line."
1560 :group 'org-time
1561 :type 'boolean)
1563 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1564 "Formats for `format-time-string' which are used for time stamps.
1565 It is not recommended to change this constant.")
1567 (defcustom org-time-stamp-rounding-minutes '(0 5)
1568 "Number of minutes to round time stamps to.
1569 These are two values, the first applies when first creating a time stamp.
1570 The second applies when changing it with the commands `S-up' and `S-down'.
1571 When changing the time stamp, this means that it will change in steps
1572 of N minutes, as given by the second value.
1574 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1575 numbers should be factors of 60, so for example 5, 10, 15.
1577 When this is larger than 1, you can still force an exact time-stamp by using
1578 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1579 and by using a prefix arg to `S-up/down' to specify the exact number
1580 of minutes to shift."
1581 :group 'org-time
1582 :get '(lambda (var) ; Make sure all entries have 5 elements
1583 (if (integerp (default-value var))
1584 (list (default-value var) 5)
1585 (default-value var)))
1586 :type '(list
1587 (integer :tag "when inserting times")
1588 (integer :tag "when modifying times")))
1590 ;; Normalize old customizations of this variable.
1591 (when (integerp org-time-stamp-rounding-minutes)
1592 (setq org-time-stamp-rounding-minutes
1593 (list org-time-stamp-rounding-minutes
1594 org-time-stamp-rounding-minutes)))
1596 (defcustom org-display-custom-times nil
1597 "Non-nil means, overlay custom formats over all time stamps.
1598 The formats are defined through the variable `org-time-stamp-custom-formats'.
1599 To turn this on on a per-file basis, insert anywhere in the file:
1600 #+STARTUP: customtime"
1601 :group 'org-time
1602 :set 'set-default
1603 :type 'sexp)
1604 (make-variable-buffer-local 'org-display-custom-times)
1606 (defcustom org-time-stamp-custom-formats
1607 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1608 "Custom formats for time stamps. See `format-time-string' for the syntax.
1609 These are overlayed over the default ISO format if the variable
1610 `org-display-custom-times' is set. Time like %H:%M should be at the
1611 end of the second format."
1612 :group 'org-time
1613 :type 'sexp)
1615 (defun org-time-stamp-format (&optional long inactive)
1616 "Get the right format for a time string."
1617 (let ((f (if long (cdr org-time-stamp-formats)
1618 (car org-time-stamp-formats))))
1619 (if inactive
1620 (concat "[" (substring f 1 -1) "]")
1621 f)))
1623 (defcustom org-time-clocksum-format "%d:%02d"
1624 "The format string used when creating CLOCKSUM lines, or when
1625 org-mode generates a time duration."
1626 :group 'org-time
1627 :type 'string)
1629 (defcustom org-deadline-warning-days 14
1630 "No. of days before expiration during which a deadline becomes active.
1631 This variable governs the display in sparse trees and in the agenda.
1632 When 0 or negative, it means use this number (the absolute value of it)
1633 even if a deadline has a different individual lead time specified."
1634 :group 'org-time
1635 :group 'org-agenda-daily/weekly
1636 :type 'number)
1638 (defcustom org-read-date-prefer-future t
1639 "Non-nil means, assume future for incomplete date input from user.
1640 This affects the following situations:
1641 1. The user gives a day, but no month.
1642 For example, if today is the 15th, and you enter \"3\", Org-mode will
1643 read this as the third of *next* month. However, if you enter \"17\",
1644 it will be considered as *this* month.
1645 2. The user gives a month but not a year.
1646 For example, if it is april and you enter \"feb 2\", this will be read
1647 as feb 2, *next* year. \"May 5\", however, will be this year.
1649 Currently this does not work for ISO week specifications.
1651 When this option is nil, the current month and year will always be used
1652 as defaults."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-display-live t
1657 "Non-nil means, display current interpretation of date prompt live.
1658 This display will be in an overlay, in the minibuffer."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defcustom org-read-date-popup-calendar t
1663 "Non-nil means, pop up a calendar when prompting for a date.
1664 In the calendar, the date can be selected with mouse-1. However, the
1665 minibuffer will also be active, and you can simply enter the date as well.
1666 When nil, only the minibuffer will be available."
1667 :group 'org-time
1668 :type 'boolean)
1669 (if (fboundp 'defvaralias)
1670 (defvaralias 'org-popup-calendar-for-date-prompt
1671 'org-read-date-popup-calendar))
1673 (defcustom org-extend-today-until 0
1674 "The hour when your day really ends.
1675 This has influence for the following applications:
1676 - When switching the agenda to \"today\". It it is still earlier than
1677 the time given here, the day recognized as TODAY is actually yesterday.
1678 - When a date is read from the user and it is still before the time given
1679 here, the current date and time will be assumed to be yesterday, 23:59.
1681 FIXME:
1682 IMPORTANT: This is still a very experimental feature, it may disappear
1683 again or it may be extended to mean more things."
1684 :group 'org-time
1685 :type 'number)
1687 (defcustom org-edit-timestamp-down-means-later nil
1688 "Non-nil means, S-down will increase the time in a time stamp.
1689 When nil, S-up will increase."
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-calendar-follow-timestamp-change t
1694 "Non-nil means, make the calendar window follow timestamp changes.
1695 When a timestamp is modified and the calendar window is visible, it will be
1696 moved to the new date."
1697 :group 'org-time
1698 :type 'boolean)
1700 (defgroup org-tags nil
1701 "Options concerning tags in Org-mode."
1702 :tag "Org Tags"
1703 :group 'org)
1705 (defcustom org-tag-alist nil
1706 "List of tags allowed in Org-mode files.
1707 When this list is nil, Org-mode will base TAG input on what is already in the
1708 buffer.
1709 The value of this variable is an alist, the car of each entry must be a
1710 keyword as a string, the cdr may be a character that is used to select
1711 that tag through the fast-tag-selection interface.
1712 See the manual for details."
1713 :group 'org-tags
1714 :type '(repeat
1715 (choice
1716 (cons (string :tag "Tag name")
1717 (character :tag "Access char"))
1718 (const :tag "Start radio group" (:startgroup))
1719 (const :tag "End radio group" (:endgroup)))))
1721 (defvar org-file-tags nil
1722 "List of tags that can be inherited by all entries in the file.
1723 The tags will be inherited if the variable `org-use-tag-inheritance'
1724 says they should be.
1725 This variable is populated from #+TAG lines.")
1727 (defcustom org-use-fast-tag-selection 'auto
1728 "Non-nil means, use fast tag selection scheme.
1729 This is a special interface to select and deselect tags with single keys.
1730 When nil, fast selection is never used.
1731 When the symbol `auto', fast selection is used if and only if selection
1732 characters for tags have been configured, either through the variable
1733 `org-tag-alist' or through a #+TAGS line in the buffer.
1734 When t, fast selection is always used and selection keys are assigned
1735 automatically if necessary."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Always" t)
1739 (const :tag "Never" nil)
1740 (const :tag "When selection characters are configured" 'auto)))
1742 (defcustom org-fast-tag-selection-single-key nil
1743 "Non-nil means, fast tag selection exits after first change.
1744 When nil, you have to press RET to exit it.
1745 During fast tag selection, you can toggle this flag with `C-c'.
1746 This variable can also have the value `expert'. In this case, the window
1747 displaying the tags menu is not even shown, until you press C-c again."
1748 :group 'org-tags
1749 :type '(choice
1750 (const :tag "No" nil)
1751 (const :tag "Yes" t)
1752 (const :tag "Expert" expert)))
1754 (defvar org-fast-tag-selection-include-todo nil
1755 "Non-nil means, fast tags selection interface will also offer TODO states.
1756 This is an undocumented feature, you should not rely on it.")
1758 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1759 "The column to which tags should be indented in a headline.
1760 If this number is positive, it specifies the column. If it is negative,
1761 it means that the tags should be flushright to that column. For example,
1762 -80 works well for a normal 80 character screen."
1763 :group 'org-tags
1764 :type 'integer)
1766 (defcustom org-auto-align-tags t
1767 "Non-nil means, realign tags after pro/demotion of TODO state change.
1768 These operations change the length of a headline and therefore shift
1769 the tags around. With this options turned on, after each such operation
1770 the tags are again aligned to `org-tags-column'."
1771 :group 'org-tags
1772 :type 'boolean)
1774 (defcustom org-use-tag-inheritance t
1775 "Non-nil means, tags in levels apply also for sublevels.
1776 When nil, only the tags directly given in a specific line apply there.
1777 If this option is t, a match early-on in a tree can lead to a large
1778 number of matches in the subtree. If you only want to see the first
1779 match in a tree during a search, check out the variable
1780 `org-tags-match-list-sublevels'.
1782 This may also be a list of tags that should be inherited, or a regexp that
1783 matches tags that should be inherited."
1784 :group 'org-tags
1785 :type '(choice
1786 (const :tag "Not" nil)
1787 (const :tag "Always" t)
1788 (repeat :tag "Specific tags" (string :tag "Tag"))
1789 (regexp :tag "Tags matched by regexp")))
1791 (defun org-tag-inherit-p (tag)
1792 "Check if TAG is one that should be inherited."
1793 (cond
1794 ((eq org-use-tag-inheritance t) t)
1795 ((not org-use-tag-inheritance) nil)
1796 ((stringp org-use-tag-inheritance)
1797 (string-match org-use-tag-inheritance tag))
1798 ((listp org-use-tag-inheritance)
1799 (member tag org-use-tag-inheritance))
1800 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1802 (defcustom org-tags-match-list-sublevels t
1803 "Non-nil means list also sublevels of headlines matching tag search.
1804 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1805 the sublevels of a headline matching a tag search often also match
1806 the same search. Listing all of them can create very long lists.
1807 Setting this variable to nil causes subtrees of a match to be skipped.
1808 This option is off by default, because inheritance in on. If you turn
1809 inheritance off, you very likely want to turn this option on.
1811 As a special case, if the tag search is restricted to TODO items, the
1812 value of this variable is ignored and sublevels are always checked, to
1813 make sure all corresponding TODO items find their way into the list."
1814 :group 'org-tags
1815 :type 'boolean)
1817 (defvar org-tags-history nil
1818 "History of minibuffer reads for tags.")
1819 (defvar org-last-tags-completion-table nil
1820 "The last used completion table for tags.")
1821 (defvar org-after-tags-change-hook nil
1822 "Hook that is run after the tags in a line have changed.")
1824 (defgroup org-properties nil
1825 "Options concerning properties in Org-mode."
1826 :tag "Org Properties"
1827 :group 'org)
1829 (defcustom org-property-format "%-10s %s"
1830 "How property key/value pairs should be formatted by `indent-line'.
1831 When `indent-line' hits a property definition, it will format the line
1832 according to this format, mainly to make sure that the values are
1833 lined-up with respect to each other."
1834 :group 'org-properties
1835 :type 'string)
1837 (defcustom org-use-property-inheritance nil
1838 "Non-nil means, properties apply also for sublevels.
1840 This setting is chiefly used during property searches. Turning it on can
1841 cause significant overhead when doing a search, which is why it is not
1842 on by default.
1844 When nil, only the properties directly given in the current entry count.
1845 When t, every property is inherited. The value may also be a list of
1846 properties that should have inheritance, or a regular expression matching
1847 properties that should be inherited.
1849 However, note that some special properties use inheritance under special
1850 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1851 and the properties ending in \"_ALL\" when they are used as descriptor
1852 for valid values of a property.
1854 Note for programmers:
1855 When querying an entry with `org-entry-get', you can control if inheritance
1856 should be used. By default, `org-entry-get' looks only at the local
1857 properties. You can request inheritance by setting the inherit argument
1858 to t (to force inheritance) or to `selective' (to respect the setting
1859 in this variable)."
1860 :group 'org-properties
1861 :type '(choice
1862 (const :tag "Not" nil)
1863 (const :tag "Always" t)
1864 (repeat :tag "Specific properties" (string :tag "Property"))
1865 (regexp :tag "Properties matched by regexp")))
1867 (defun org-property-inherit-p (property)
1868 "Check if PROPERTY is one that should be inherited."
1869 (cond
1870 ((eq org-use-property-inheritance t) t)
1871 ((not org-use-property-inheritance) nil)
1872 ((stringp org-use-property-inheritance)
1873 (string-match org-use-property-inheritance property))
1874 ((listp org-use-property-inheritance)
1875 (member property org-use-property-inheritance))
1876 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1878 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1879 "The default column format, if no other format has been defined.
1880 This variable can be set on the per-file basis by inserting a line
1882 #+COLUMNS: %25ITEM ....."
1883 :group 'org-properties
1884 :type 'string)
1886 (defcustom org-effort-property "Effort"
1887 "The property that is being used to keep track of effort estimates.
1888 Effort estimates given in this property need to have the format H:MM."
1889 :group 'org-properties
1890 :group 'org-progress
1891 :type '(string :tag "Property"))
1893 (defconst org-global-properties-fixed
1894 '(("VISIBILITY_ALL" . "folded children content all"))
1895 "List of property/value pairs that can be inherited by any entry.
1896 These are fixed values, for the preset properties.")
1899 (defcustom org-global-properties nil
1900 "List of property/value pairs that can be inherited by any entry.
1901 You can set buffer-local values for this by adding lines like
1903 #+PROPERTY: NAME VALUE"
1904 :group 'org-properties
1905 :type '(repeat
1906 (cons (string :tag "Property")
1907 (string :tag "Value"))))
1909 (defvar org-file-properties nil
1910 "List of property/value pairs that can be inherited by any entry.
1911 Valid for the current buffer.
1912 This variable is populated from #+PROPERTY lines.")
1914 (defgroup org-agenda nil
1915 "Options concerning agenda views in Org-mode."
1916 :tag "Org Agenda"
1917 :group 'org)
1919 (defvar org-category nil
1920 "Variable used by org files to set a category for agenda display.
1921 Such files should use a file variable to set it, for example
1923 # -*- mode: org; org-category: \"ELisp\"
1925 or contain a special line
1927 #+CATEGORY: ELisp
1929 If the file does not specify a category, then file's base name
1930 is used instead.")
1931 (make-variable-buffer-local 'org-category)
1933 (defcustom org-agenda-files nil
1934 "The files to be used for agenda display.
1935 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1936 \\[org-remove-file]. You can also use customize to edit the list.
1938 If an entry is a directory, all files in that directory that are matched by
1939 `org-agenda-file-regexp' will be part of the file list.
1941 If the value of the variable is not a list but a single file name, then
1942 the list of agenda files is actually stored and maintained in that file, one
1943 agenda file per line."
1944 :group 'org-agenda
1945 :type '(choice
1946 (repeat :tag "List of files and directories" file)
1947 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1949 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1950 "Regular expression to match files for `org-agenda-files'.
1951 If any element in the list in that variable contains a directory instead
1952 of a normal file, all files in that directory that are matched by this
1953 regular expression will be included."
1954 :group 'org-agenda
1955 :type 'regexp)
1957 (defcustom org-agenda-text-search-extra-files nil
1958 "List of extra files to be searched by text search commands.
1959 These files will be search in addition to the agenda files by the
1960 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1961 Note that these files will only be searched for text search commands,
1962 not for the other agenda views like todo lists, tag searches or the weekly
1963 agenda. This variable is intended to list notes and possibly archive files
1964 that should also be searched by these two commands.
1965 In fact, if the first element in the list is the symbol `agenda-archives',
1966 than all archive files of all agenda files will be added to the search
1967 scope."
1968 :group 'org-agenda
1969 :type '(set :greedy t
1970 (const :tag "Agenda Archives" agenda-archives)
1971 (repeat :inline t (file))))
1973 (if (fboundp 'defvaralias)
1974 (defvaralias 'org-agenda-multi-occur-extra-files
1975 'org-agenda-text-search-extra-files))
1977 (defcustom org-agenda-skip-unavailable-files nil
1978 "t means to just skip non-reachable files in `org-agenda-files'.
1979 Nil means to remove them, after a query, from the list."
1980 :group 'org-agenda
1981 :type 'boolean)
1983 (defcustom org-calendar-to-agenda-key [?c]
1984 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1985 The command `org-calendar-goto-agenda' will be bound to this key. The
1986 default is the character `c' because then `c' can be used to switch back and
1987 forth between agenda and calendar."
1988 :group 'org-agenda
1989 :type 'sexp)
1991 (eval-after-load "calendar"
1992 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1993 'org-calendar-goto-agenda))
1995 (defgroup org-latex nil
1996 "Options for embedding LaTeX code into Org-mode."
1997 :tag "Org LaTeX"
1998 :group 'org)
2000 (defcustom org-format-latex-options
2001 '(:foreground default :background default :scale 1.0
2002 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2003 :matchers ("begin" "$" "$$" "\\(" "\\["))
2004 "Options for creating images from LaTeX fragments.
2005 This is a property list with the following properties:
2006 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2007 `default' means use the foreground of the default face.
2008 :background the background color, or \"Transparent\".
2009 `default' means use the background of the default face.
2010 :scale a scaling factor for the size of the images.
2011 :html-foreground, :html-background, :html-scale
2012 the same numbers for HTML export.
2013 :matchers a list indicating which matchers should be used to
2014 find LaTeX fragments. Valid members of this list are:
2015 \"begin\" find environments
2016 \"$\" find math expressions surrounded by $...$
2017 \"$$\" find math expressions surrounded by $$....$$
2018 \"\\(\" find math expressions surrounded by \\(...\\)
2019 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2020 :group 'org-latex
2021 :type 'plist)
2023 (defcustom org-format-latex-header "\\documentclass{article}
2024 \\usepackage{fullpage} % do not remove
2025 \\usepackage{amssymb}
2026 \\usepackage[usenames]{color}
2027 \\usepackage{amsmath}
2028 \\usepackage{latexsym}
2029 \\usepackage[mathscr]{eucal}
2030 \\pagestyle{empty} % do not remove"
2031 "The document header used for processing LaTeX fragments."
2032 :group 'org-latex
2033 :type 'string)
2036 (defgroup org-font-lock nil
2037 "Font-lock settings for highlighting in Org-mode."
2038 :tag "Org Font Lock"
2039 :group 'org)
2041 (defcustom org-level-color-stars-only nil
2042 "Non-nil means fontify only the stars in each headline.
2043 When nil, the entire headline is fontified.
2044 Changing it requires restart of `font-lock-mode' to become effective
2045 also in regions already fontified."
2046 :group 'org-font-lock
2047 :type 'boolean)
2049 (defcustom org-hide-leading-stars nil
2050 "Non-nil means, hide the first N-1 stars in a headline.
2051 This works by using the face `org-hide' for these stars. This
2052 face is white for a light background, and black for a dark
2053 background. You may have to customize the face `org-hide' to
2054 make this work.
2055 Changing it requires restart of `font-lock-mode' to become effective
2056 also in regions already fontified.
2057 You may also set this on a per-file basis by adding one of the following
2058 lines to the buffer:
2060 #+STARTUP: hidestars
2061 #+STARTUP: showstars"
2062 :group 'org-font-lock
2063 :type 'boolean)
2065 (defcustom org-fontify-done-headline nil
2066 "Non-nil means, change the face of a headline if it is marked DONE.
2067 Normally, only the TODO/DONE keyword indicates the state of a headline.
2068 When this is non-nil, the headline after the keyword is set to the
2069 `org-headline-done' as an additional indication."
2070 :group 'org-font-lock
2071 :type 'boolean)
2073 (defcustom org-fontify-emphasized-text t
2074 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2075 Changing this variable requires a restart of Emacs to take effect."
2076 :group 'org-font-lock
2077 :type 'boolean)
2079 (defcustom org-highlight-latex-fragments-and-specials nil
2080 "Non-nil means, fontify what is treated specially by the exporters."
2081 :group 'org-font-lock
2082 :type 'boolean)
2084 (defcustom org-hide-emphasis-markers nil
2085 "Non-nil mean font-lock should hide the emphasis marker characters."
2086 :group 'org-font-lock
2087 :type 'boolean)
2089 (defvar org-emph-re nil
2090 "Regular expression for matching emphasis.")
2091 (defvar org-verbatim-re nil
2092 "Regular expression for matching verbatim text.")
2093 (defvar org-emphasis-regexp-components) ; defined just below
2094 (defvar org-emphasis-alist) ; defined just below
2095 (defun org-set-emph-re (var val)
2096 "Set variable and compute the emphasis regular expression."
2097 (set var val)
2098 (when (and (boundp 'org-emphasis-alist)
2099 (boundp 'org-emphasis-regexp-components)
2100 org-emphasis-alist org-emphasis-regexp-components)
2101 (let* ((e org-emphasis-regexp-components)
2102 (pre (car e))
2103 (post (nth 1 e))
2104 (border (nth 2 e))
2105 (body (nth 3 e))
2106 (nl (nth 4 e))
2107 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2108 (body1 (concat body "*?"))
2109 (markers (mapconcat 'car org-emphasis-alist ""))
2110 (vmarkers (mapconcat
2111 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2112 org-emphasis-alist "")))
2113 ;; make sure special characters appear at the right position in the class
2114 (if (string-match "\\^" markers)
2115 (setq markers (concat (replace-match "" t t markers) "^")))
2116 (if (string-match "-" markers)
2117 (setq markers (concat (replace-match "" t t markers) "-")))
2118 (if (string-match "\\^" vmarkers)
2119 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2120 (if (string-match "-" vmarkers)
2121 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2122 (if (> nl 0)
2123 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2124 (int-to-string nl) "\\}")))
2125 ;; Make the regexp
2126 (setq org-emph-re
2127 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2128 "\\("
2129 "\\([" markers "]\\)"
2130 "\\("
2131 "[^" border "]\\|"
2132 "[^" border (if (and nil stacked) markers) "]"
2133 body1
2134 "[^" border (if (and nil stacked) markers) "]"
2135 "\\)"
2136 "\\3\\)"
2137 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2138 (setq org-verbatim-re
2139 (concat "\\([" pre "]\\|^\\)"
2140 "\\("
2141 "\\([" vmarkers "]\\)"
2142 "\\("
2143 "[^" border "]\\|"
2144 "[^" border "]"
2145 body1
2146 "[^" border "]"
2147 "\\)"
2148 "\\3\\)"
2149 "\\([" post "]\\|$\\)")))))
2151 (defcustom org-emphasis-regexp-components
2152 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2153 "Components used to build the regular expression for emphasis.
2154 This is a list with 6 entries. Terminology: In an emphasis string
2155 like \" *strong word* \", we call the initial space PREMATCH, the final
2156 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2157 and \"trong wor\" is the body. The different components in this variable
2158 specify what is allowed/forbidden in each part:
2160 pre Chars allowed as prematch. Beginning of line will be allowed too.
2161 post Chars allowed as postmatch. End of line will be allowed too.
2162 border The chars *forbidden* as border characters.
2163 body-regexp A regexp like \".\" to match a body character. Don't use
2164 non-shy groups here, and don't allow newline here.
2165 newline The maximum number of newlines allowed in an emphasis exp.
2167 Use customize to modify this, or restart Emacs after changing it."
2168 :group 'org-font-lock
2169 :set 'org-set-emph-re
2170 :type '(list
2171 (sexp :tag "Allowed chars in pre ")
2172 (sexp :tag "Allowed chars in post ")
2173 (sexp :tag "Forbidden chars in border ")
2174 (sexp :tag "Regexp for body ")
2175 (integer :tag "number of newlines allowed")
2176 (option (boolean :tag "Stacking (DISABLED) "))))
2178 (defcustom org-emphasis-alist
2179 `(("*" bold "<b>" "</b>")
2180 ("/" italic "<i>" "</i>")
2181 ("_" underline "<u>" "</u>")
2182 ("=" org-code "<code>" "</code>" verbatim)
2183 ("~" org-verbatim "" "" verbatim)
2184 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2185 "<del>" "</del>")
2187 "Special syntax for emphasized text.
2188 Text starting and ending with a special character will be emphasized, for
2189 example *bold*, _underlined_ and /italic/. This variable sets the marker
2190 characters, the face to be used by font-lock for highlighting in Org-mode
2191 Emacs buffers, and the HTML tags to be used for this.
2192 Use customize to modify this, or restart Emacs after changing it."
2193 :group 'org-font-lock
2194 :set 'org-set-emph-re
2195 :type '(repeat
2196 (list
2197 (string :tag "Marker character")
2198 (choice
2199 (face :tag "Font-lock-face")
2200 (plist :tag "Face property list"))
2201 (string :tag "HTML start tag")
2202 (string :tag "HTML end tag")
2203 (option (const verbatim)))))
2205 ;;; Miscellaneous options
2207 (defgroup org-completion nil
2208 "Completion in Org-mode."
2209 :tag "Org Completion"
2210 :group 'org)
2212 (defcustom org-completion-fallback-command 'hippie-expand
2213 "The expansion command called by \\[org-complete] in normal context.
2214 Normal means, no org-mode-specific context."
2215 :group 'org-completion
2216 :type 'function)
2218 ;;; Functions and variables from ther packages
2219 ;; Declared here to avoid compiler warnings
2221 ;; XEmacs only
2222 (defvar outline-mode-menu-heading)
2223 (defvar outline-mode-menu-show)
2224 (defvar outline-mode-menu-hide)
2225 (defvar zmacs-regions) ; XEmacs regions
2227 ;; Emacs only
2228 (defvar mark-active)
2230 ;; Various packages
2231 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2232 (declare-function calendar-forward-day "cal-move" (arg))
2233 (declare-function calendar-goto-date "cal-move" (date))
2234 (declare-function calendar-goto-today "cal-move" ())
2235 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2236 (defvar calc-embedded-close-formula)
2237 (defvar calc-embedded-open-formula)
2238 (declare-function cdlatex-tab "ext:cdlatex" ())
2239 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2240 (defvar font-lock-unfontify-region-function)
2241 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2242 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2243 (defvar iswitchb-temp-buflist)
2244 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2245 (declare-function org-agenda-skip "org-agenda" ())
2246 (declare-function org-format-agenda-item "org-agenda"
2247 (extra txt &optional category tags dotime noprefix remove-re))
2248 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2249 (declare-function org-agenda-change-all-lines "org-agenda"
2250 (newhead hdmarker &optional fixface))
2251 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2252 (declare-function org-agenda-maybe-redo "org-agenda" ())
2253 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2254 (beg end))
2255 (declare-function parse-time-string "parse-time" (string))
2256 (declare-function remember "remember" (&optional initial))
2257 (declare-function remember-buffer-desc "remember" ())
2258 (declare-function remember-finalize "remember" ())
2259 (defvar remember-save-after-remembering)
2260 (defvar remember-data-file)
2261 (defvar remember-register)
2262 (defvar remember-buffer)
2263 (defvar remember-handler-functions)
2264 (defvar remember-annotation-functions)
2265 (defvar texmathp-why)
2266 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2267 (declare-function table--at-cell-p "table" (position &optional object at-column))
2269 (defvar w3m-current-url)
2270 (defvar w3m-current-title)
2272 (defvar org-latex-regexps)
2274 ;;; Autoload and prepare some org modules
2276 ;; Some table stuff that needs to be defined here, because it is used
2277 ;; by the functions setting up org-mode or checking for table context.
2279 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2280 "Detects an org-type or table-type table.")
2281 (defconst org-table-line-regexp "^[ \t]*|"
2282 "Detects an org-type table line.")
2283 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2284 "Detects an org-type table line.")
2285 (defconst org-table-hline-regexp "^[ \t]*|-"
2286 "Detects an org-type table hline.")
2287 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2288 "Detects a table-type table hline.")
2289 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2290 "Searching from within a table (any type) this finds the first line
2291 outside the table.")
2293 ;; Autoload the functions in org-table.el that are needed by functions here.
2295 (eval-and-compile
2296 (org-autoload "org-table"
2297 '(org-table-align org-table-begin org-table-blank-field
2298 org-table-convert org-table-convert-region org-table-copy-down
2299 org-table-copy-region org-table-create
2300 org-table-create-or-convert-from-region
2301 org-table-create-with-table.el org-table-current-dline
2302 org-table-cut-region org-table-delete-column org-table-edit-field
2303 org-table-edit-formulas org-table-end org-table-eval-formula
2304 org-table-export org-table-field-info
2305 org-table-get-stored-formulas org-table-goto-column
2306 org-table-hline-and-move org-table-import org-table-insert-column
2307 org-table-insert-hline org-table-insert-row org-table-iterate
2308 org-table-justify-field-maybe org-table-kill-row
2309 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2310 org-table-move-column org-table-move-column-left
2311 org-table-move-column-right org-table-move-row
2312 org-table-move-row-down org-table-move-row-up
2313 org-table-next-field org-table-next-row org-table-paste-rectangle
2314 org-table-previous-field org-table-recalculate
2315 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2316 org-table-toggle-coordinate-overlays
2317 org-table-toggle-formula-debugger org-table-wrap-region
2318 orgtbl-mode turn-on-orgtbl)))
2320 (defun org-at-table-p (&optional table-type)
2321 "Return t if the cursor is inside an org-type table.
2322 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2323 (if org-enable-table-editor
2324 (save-excursion
2325 (beginning-of-line 1)
2326 (looking-at (if table-type org-table-any-line-regexp
2327 org-table-line-regexp)))
2328 nil))
2329 (defsubst org-table-p () (org-at-table-p))
2331 (defun org-at-table.el-p ()
2332 "Return t if and only if we are at a table.el table."
2333 (and (org-at-table-p 'any)
2334 (save-excursion
2335 (goto-char (org-table-begin 'any))
2336 (looking-at org-table1-hline-regexp))))
2337 (defun org-table-recognize-table.el ()
2338 "If there is a table.el table nearby, recognize it and move into it."
2339 (if org-table-tab-recognizes-table.el
2340 (if (org-at-table.el-p)
2341 (progn
2342 (beginning-of-line 1)
2343 (if (looking-at org-table-dataline-regexp)
2345 (if (looking-at org-table1-hline-regexp)
2346 (progn
2347 (beginning-of-line 2)
2348 (if (looking-at org-table-any-border-regexp)
2349 (beginning-of-line -1)))))
2350 (if (re-search-forward "|" (org-table-end t) t)
2351 (progn
2352 (require 'table)
2353 (if (table--at-cell-p (point))
2355 (message "recognizing table.el table...")
2356 (table-recognize-table)
2357 (message "recognizing table.el table...done")))
2358 (error "This should not happen..."))
2360 nil)
2361 nil))
2363 (defun org-at-table-hline-p ()
2364 "Return t if the cursor is inside a hline in a table."
2365 (if org-enable-table-editor
2366 (save-excursion
2367 (beginning-of-line 1)
2368 (looking-at org-table-hline-regexp))
2369 nil))
2371 (defvar org-table-clean-did-remove-column nil)
2373 (defun org-table-map-tables (function)
2374 "Apply FUNCTION to the start of all tables in the buffer."
2375 (save-excursion
2376 (save-restriction
2377 (widen)
2378 (goto-char (point-min))
2379 (while (re-search-forward org-table-any-line-regexp nil t)
2380 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2381 (beginning-of-line 1)
2382 (if (looking-at org-table-line-regexp)
2383 (save-excursion (funcall function)))
2384 (re-search-forward org-table-any-border-regexp nil 1))))
2385 (message "Mapping tables: done"))
2387 ;; Declare and autoload functions from org-exp.el
2389 (declare-function org-default-export-plist "org-exp")
2390 (declare-function org-infile-export-plist "org-exp")
2391 (declare-function org-get-current-options "org-exp")
2392 (eval-and-compile
2393 (org-autoload "org-exp"
2394 '(org-export org-export-as-ascii org-export-visible
2395 org-insert-export-options-template org-export-as-html-and-open
2396 org-export-as-html-batch org-export-as-html-to-buffer
2397 org-replace-region-by-html org-export-region-as-html
2398 org-export-as-html org-export-icalendar-this-file
2399 org-export-icalendar-all-agenda-files
2400 org-table-clean-before-export
2401 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2403 ;; Declare and autoload functions from org-exp.el
2405 (eval-and-compile
2406 (org-autoload "org-exp"
2407 '(org-agenda org-agenda-list org-search-view
2408 org-todo-list org-tags-view org-agenda-list-stuck-projects
2409 org-diary org-agenda-to-appt)))
2411 ;; Autoload org-remember
2413 (eval-and-compile
2414 (org-autoload "org-remember"
2415 '(org-remember-insinuate org-remember-annotation
2416 org-remember-apply-template org-remember org-remember-handler)))
2418 ;; Autoload org-clock.el
2421 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2422 (beg end))
2423 (declare-function org-update-mode-line "org-clock" ())
2424 (defvar org-clock-start-time)
2425 (defvar org-clock-marker (make-marker)
2426 "Marker recording the last clock-in.")
2428 (eval-and-compile
2429 (org-autoload
2430 "org-clock"
2431 '(org-clock-in org-clock-out org-clock-cancel
2432 org-clock-goto org-clock-sum org-clock-display
2433 org-remove-clock-overlays org-clock-report
2434 org-clocktable-shift org-dblock-write:clocktable
2435 org-get-clocktable)))
2437 (defun org-clock-update-time-maybe ()
2438 "If this is a CLOCK line, update it and return t.
2439 Otherwise, return nil."
2440 (interactive)
2441 (save-excursion
2442 (beginning-of-line 1)
2443 (skip-chars-forward " \t")
2444 (when (looking-at org-clock-string)
2445 (let ((re (concat "[ \t]*" org-clock-string
2446 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2447 "\\([ \t]*=>.*\\)?\\)?"))
2448 ts te h m s)
2449 (cond
2450 ((not (looking-at re))
2451 nil)
2452 ((not (match-end 2))
2453 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2454 (> org-clock-marker (point))
2455 (<= org-clock-marker (point-at-eol)))
2456 ;; The clock is running here
2457 (setq org-clock-start-time
2458 (apply 'encode-time
2459 (org-parse-time-string (match-string 1))))
2460 (org-update-mode-line)))
2462 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2463 (end-of-line 1)
2464 (setq ts (match-string 1)
2465 te (match-string 3))
2466 (setq s (- (time-to-seconds
2467 (apply 'encode-time (org-parse-time-string te)))
2468 (time-to-seconds
2469 (apply 'encode-time (org-parse-time-string ts))))
2470 h (floor (/ s 3600))
2471 s (- s (* 3600 h))
2472 m (floor (/ s 60))
2473 s (- s (* 60 s)))
2474 (insert " => " (format "%2d:%02d" h m))
2475 t))))))
2477 (defun org-check-running-clock ()
2478 "Check if the current buffer contains the running clock.
2479 If yes, offer to stop it and to save the buffer with the changes."
2480 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2481 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2482 (buffer-name))))
2483 (org-clock-out)
2484 (when (y-or-n-p "Save changed buffer?")
2485 (save-buffer))))
2487 (defun org-clocktable-try-shift (dir n)
2488 "Check if this line starts a clock table, if yes, shift the time block."
2489 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2490 (org-clocktable-shift dir n)))
2492 ;; Autoload archiving code
2493 ;; The stuff that is needed for cycling and tags has to be defined here.
2495 (defgroup org-archive nil
2496 "Options concerning archiving in Org-mode."
2497 :tag "Org Archive"
2498 :group 'org-structure)
2500 (defcustom org-archive-location "%s_archive::"
2501 "The location where subtrees should be archived.
2503 Otherwise, the value of this variable is a string, consisting of two
2504 parts, separated by a double-colon.
2506 The first part is a file name - when omitted, archiving happens in the same
2507 file. %s will be replaced by the current file name (without directory part).
2508 Archiving to a different file is useful to keep archived entries from
2509 contributing to the Org-mode Agenda.
2511 The part after the double colon is a headline. The archived entries will be
2512 filed under that headline. When omitted, the subtrees are simply filed away
2513 at the end of the file, as top-level entries.
2515 Here are a few examples:
2516 \"%s_archive::\"
2517 If the current file is Projects.org, archive in file
2518 Projects.org_archive, as top-level trees. This is the default.
2520 \"::* Archived Tasks\"
2521 Archive in the current file, under the top-level headline
2522 \"* Archived Tasks\".
2524 \"~/org/archive.org::\"
2525 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2527 \"basement::** Finished Tasks\"
2528 Archive in file ./basement (relative path), as level 3 trees
2529 below the level 2 heading \"** Finished Tasks\".
2531 You may set this option on a per-file basis by adding to the buffer a
2532 line like
2534 #+ARCHIVE: basement::** Finished Tasks
2536 You may also define it locally for a subtree by setting an ARCHIVE property
2537 in the entry. If such a property is found in an entry, or anywhere up
2538 the hierarchy, it will be used."
2539 :group 'org-archive
2540 :type 'string)
2542 (defcustom org-archive-tag "ARCHIVE"
2543 "The tag that marks a subtree as archived.
2544 An archived subtree does not open during visibility cycling, and does
2545 not contribute to the agenda listings.
2546 After changing this, font-lock must be restarted in the relevant buffers to
2547 get the proper fontification."
2548 :group 'org-archive
2549 :group 'org-keywords
2550 :type 'string)
2552 (defcustom org-agenda-skip-archived-trees t
2553 "Non-nil means, the agenda will skip any items located in archived trees.
2554 An archived tree is a tree marked with the tag ARCHIVE."
2555 :group 'org-archive
2556 :group 'org-agenda-skip
2557 :type 'boolean)
2559 (defcustom org-cycle-open-archived-trees nil
2560 "Non-nil means, `org-cycle' will open archived trees.
2561 An archived tree is a tree marked with the tag ARCHIVE.
2562 When nil, archived trees will stay folded. You can still open them with
2563 normal outline commands like `show-all', but not with the cycling commands."
2564 :group 'org-archive
2565 :group 'org-cycle
2566 :type 'boolean)
2568 (defcustom org-sparse-tree-open-archived-trees nil
2569 "Non-nil means sparse tree construction shows matches in archived trees.
2570 When nil, matches in these trees are highlighted, but the trees are kept in
2571 collapsed state."
2572 :group 'org-archive
2573 :group 'org-sparse-trees
2574 :type 'boolean)
2576 (defun org-cycle-hide-archived-subtrees (state)
2577 "Re-hide all archived subtrees after a visibility state change."
2578 (when (and (not org-cycle-open-archived-trees)
2579 (not (memq state '(overview folded))))
2580 (save-excursion
2581 (let* ((globalp (memq state '(contents all)))
2582 (beg (if globalp (point-min) (point)))
2583 (end (if globalp (point-max) (org-end-of-subtree t))))
2584 (org-hide-archived-subtrees beg end)
2585 (goto-char beg)
2586 (if (looking-at (concat ".*:" org-archive-tag ":"))
2587 (message "%s" (substitute-command-keys
2588 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2590 (defun org-force-cycle-archived ()
2591 "Cycle subtree even if it is archived."
2592 (interactive)
2593 (setq this-command 'org-cycle)
2594 (let ((org-cycle-open-archived-trees t))
2595 (call-interactively 'org-cycle)))
2597 (defun org-hide-archived-subtrees (beg end)
2598 "Re-hide all archived subtrees after a visibility state change."
2599 (save-excursion
2600 (let* ((re (concat ":" org-archive-tag ":")))
2601 (goto-char beg)
2602 (while (re-search-forward re end t)
2603 (and (org-on-heading-p) (hide-subtree))
2604 (org-end-of-subtree t)))))
2606 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2608 (eval-and-compile
2609 (org-autoload "org-archive"
2610 '(org-add-archive-files org-archive-subtree
2611 org-archive-to-archive-sibling org-toggle-archive-tag)))
2613 ;; Autoload Column View Code
2615 (declare-function org-columns-number-to-string "org-colview")
2616 (declare-function org-columns-get-format-and-top-level "org-colview")
2617 (declare-function org-columns-compute "org-colview")
2619 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2620 '(org-columns-number-to-string org-columns-get-format-and-top-level
2621 org-columns-compute org-agenda-columns org-columns-remove-overlays
2622 org-columns org-insert-columns-dblock))
2624 ;; Autoload ID code
2626 (org-autoload "org-id"
2627 '(org-id-get-create org-id-new org-id-copy org-id-get
2628 org-id-get-with-outline-path-completion
2629 org-id-get-with-outline-drilling
2630 org-id-goto org-id-find))
2632 ;;; Variables for pre-computed regular expressions, all buffer local
2634 (defvar org-drawer-regexp nil
2635 "Matches first line of a hidden block.")
2636 (make-variable-buffer-local 'org-drawer-regexp)
2637 (defvar org-todo-regexp nil
2638 "Matches any of the TODO state keywords.")
2639 (make-variable-buffer-local 'org-todo-regexp)
2640 (defvar org-not-done-regexp nil
2641 "Matches any of the TODO state keywords except the last one.")
2642 (make-variable-buffer-local 'org-not-done-regexp)
2643 (defvar org-todo-line-regexp nil
2644 "Matches a headline and puts TODO state into group 2 if present.")
2645 (make-variable-buffer-local 'org-todo-line-regexp)
2646 (defvar org-complex-heading-regexp nil
2647 "Matches a headline and puts everything into groups:
2648 group 1: the stars
2649 group 2: The todo keyword, maybe
2650 group 3: Priority cookie
2651 group 4: True headline
2652 group 5: Tags")
2653 (make-variable-buffer-local 'org-complex-heading-regexp)
2654 (defvar org-todo-line-tags-regexp nil
2655 "Matches a headline and puts TODO state into group 2 if present.
2656 Also put tags into group 4 if tags are present.")
2657 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2658 (defvar org-nl-done-regexp nil
2659 "Matches newline followed by a headline with the DONE keyword.")
2660 (make-variable-buffer-local 'org-nl-done-regexp)
2661 (defvar org-looking-at-done-regexp nil
2662 "Matches the DONE keyword a point.")
2663 (make-variable-buffer-local 'org-looking-at-done-regexp)
2664 (defvar org-ds-keyword-length 12
2665 "Maximum length of the Deadline and SCHEDULED keywords.")
2666 (make-variable-buffer-local 'org-ds-keyword-length)
2667 (defvar org-deadline-regexp nil
2668 "Matches the DEADLINE keyword.")
2669 (make-variable-buffer-local 'org-deadline-regexp)
2670 (defvar org-deadline-time-regexp nil
2671 "Matches the DEADLINE keyword together with a time stamp.")
2672 (make-variable-buffer-local 'org-deadline-time-regexp)
2673 (defvar org-deadline-line-regexp nil
2674 "Matches the DEADLINE keyword and the rest of the line.")
2675 (make-variable-buffer-local 'org-deadline-line-regexp)
2676 (defvar org-scheduled-regexp nil
2677 "Matches the SCHEDULED keyword.")
2678 (make-variable-buffer-local 'org-scheduled-regexp)
2679 (defvar org-scheduled-time-regexp nil
2680 "Matches the SCHEDULED keyword together with a time stamp.")
2681 (make-variable-buffer-local 'org-scheduled-time-regexp)
2682 (defvar org-closed-time-regexp nil
2683 "Matches the CLOSED keyword together with a time stamp.")
2684 (make-variable-buffer-local 'org-closed-time-regexp)
2686 (defvar org-keyword-time-regexp nil
2687 "Matches any of the 4 keywords, together with the time stamp.")
2688 (make-variable-buffer-local 'org-keyword-time-regexp)
2689 (defvar org-keyword-time-not-clock-regexp nil
2690 "Matches any of the 3 keywords, together with the time stamp.")
2691 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2692 (defvar org-maybe-keyword-time-regexp nil
2693 "Matches a timestamp, possibly preceeded by a keyword.")
2694 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2695 (defvar org-planning-or-clock-line-re nil
2696 "Matches a line with planning or clock info.")
2697 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2699 (defconst org-plain-time-of-day-regexp
2700 (concat
2701 "\\(\\<[012]?[0-9]"
2702 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2703 "\\(--?"
2704 "\\(\\<[012]?[0-9]"
2705 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2706 "\\)?")
2707 "Regular expression to match a plain time or time range.
2708 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2709 groups carry important information:
2710 0 the full match
2711 1 the first time, range or not
2712 8 the second time, if it is a range.")
2714 (defconst org-plain-time-extension-regexp
2715 (concat
2716 "\\(\\<[012]?[0-9]"
2717 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2718 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2719 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2720 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2721 groups carry important information:
2722 0 the full match
2723 7 hours of duration
2724 9 minutes of duration")
2726 (defconst org-stamp-time-of-day-regexp
2727 (concat
2728 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2729 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2730 "\\(--?"
2731 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2732 "Regular expression to match a timestamp time or time range.
2733 After a match, the following groups carry important information:
2734 0 the full match
2735 1 date plus weekday, for backreferencing to make sure both times on same day
2736 2 the first time, range or not
2737 4 the second time, if it is a range.")
2739 (defconst org-startup-options
2740 '(("fold" org-startup-folded t)
2741 ("overview" org-startup-folded t)
2742 ("nofold" org-startup-folded nil)
2743 ("showall" org-startup-folded nil)
2744 ("content" org-startup-folded content)
2745 ("hidestars" org-hide-leading-stars t)
2746 ("showstars" org-hide-leading-stars nil)
2747 ("odd" org-odd-levels-only t)
2748 ("oddeven" org-odd-levels-only nil)
2749 ("align" org-startup-align-all-tables t)
2750 ("noalign" org-startup-align-all-tables nil)
2751 ("customtime" org-display-custom-times t)
2752 ("logdone" org-log-done time)
2753 ("lognotedone" org-log-done note)
2754 ("nologdone" org-log-done nil)
2755 ("lognoteclock-out" org-log-note-clock-out t)
2756 ("nolognoteclock-out" org-log-note-clock-out nil)
2757 ("logrepeat" org-log-repeat state)
2758 ("lognoterepeat" org-log-repeat note)
2759 ("nologrepeat" org-log-repeat nil)
2760 ("constcgs" constants-unit-system cgs)
2761 ("constSI" constants-unit-system SI))
2762 "Variable associated with STARTUP options for org-mode.
2763 Each element is a list of three items: The startup options as written
2764 in the #+STARTUP line, the corresponding variable, and the value to
2765 set this variable to if the option is found. An optional forth element PUSH
2766 means to push this value onto the list in the variable.")
2768 (defun org-set-regexps-and-options ()
2769 "Precompute regular expressions for current buffer."
2770 (when (org-mode-p)
2771 (org-set-local 'org-todo-kwd-alist nil)
2772 (org-set-local 'org-todo-key-alist nil)
2773 (org-set-local 'org-todo-key-trigger nil)
2774 (org-set-local 'org-todo-keywords-1 nil)
2775 (org-set-local 'org-done-keywords nil)
2776 (org-set-local 'org-todo-heads nil)
2777 (org-set-local 'org-todo-sets nil)
2778 (org-set-local 'org-todo-log-states nil)
2779 (let ((re (org-make-options-regexp
2780 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2781 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2782 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2783 (splitre "[ \t]+")
2784 kwds kws0 kwsa key log value cat arch tags const links hw dws
2785 tail sep kws1 prio props ftags drawers
2786 ext-setup-or-nil setup-contents (start 0))
2787 (save-excursion
2788 (save-restriction
2789 (widen)
2790 (goto-char (point-min))
2791 (while (or (and ext-setup-or-nil
2792 (string-match re ext-setup-or-nil start)
2793 (setq start (match-end 0)))
2794 (and (setq ext-setup-or-nil nil start 0)
2795 (re-search-forward re nil t)))
2796 (setq key (upcase (match-string 1 ext-setup-or-nil))
2797 value (org-match-string-no-properties 2 ext-setup-or-nil))
2798 (cond
2799 ((equal key "CATEGORY")
2800 (if (string-match "[ \t]+$" value)
2801 (setq value (replace-match "" t t value)))
2802 (setq cat value))
2803 ((member key '("SEQ_TODO" "TODO"))
2804 (push (cons 'sequence (org-split-string value splitre)) kwds))
2805 ((equal key "TYP_TODO")
2806 (push (cons 'type (org-split-string value splitre)) kwds))
2807 ((equal key "TAGS")
2808 (setq tags (append tags (org-split-string value splitre))))
2809 ((equal key "COLUMNS")
2810 (org-set-local 'org-columns-default-format value))
2811 ((equal key "LINK")
2812 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2813 (push (cons (match-string 1 value)
2814 (org-trim (match-string 2 value)))
2815 links)))
2816 ((equal key "PRIORITIES")
2817 (setq prio (org-split-string value " +")))
2818 ((equal key "PROPERTY")
2819 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2820 (push (cons (match-string 1 value) (match-string 2 value))
2821 props)))
2822 ((equal key "FILETAGS")
2823 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2824 (setq ftags
2825 (append
2826 ftags
2827 (apply 'append
2828 (mapcar (lambda (x) (org-split-string x ":"))
2829 (org-split-string value)))))))
2830 ((equal key "DRAWERS")
2831 (setq drawers (org-split-string value splitre)))
2832 ((equal key "CONSTANTS")
2833 (setq const (append const (org-split-string value splitre))))
2834 ((equal key "STARTUP")
2835 (let ((opts (org-split-string value splitre))
2836 l var val)
2837 (while (setq l (pop opts))
2838 (when (setq l (assoc l org-startup-options))
2839 (setq var (nth 1 l) val (nth 2 l))
2840 (if (not (nth 3 l))
2841 (set (make-local-variable var) val)
2842 (if (not (listp (symbol-value var)))
2843 (set (make-local-variable var) nil))
2844 (set (make-local-variable var) (symbol-value var))
2845 (add-to-list var val))))))
2846 ((equal key "ARCHIVE")
2847 (string-match " *$" value)
2848 (setq arch (replace-match "" t t value))
2849 (remove-text-properties 0 (length arch)
2850 '(face t fontified t) arch))
2851 ((equal key "SETUPFILE")
2852 (setq setup-contents (org-file-contents
2853 (expand-file-name
2854 (org-remove-double-quotes value))
2855 'noerror))
2856 (if (not ext-setup-or-nil)
2857 (setq ext-setup-or-nil setup-contents start 0)
2858 (setq ext-setup-or-nil
2859 (concat (substring ext-setup-or-nil 0 start)
2860 "\n" setup-contents "\n"
2861 (substring ext-setup-or-nil start)))))
2862 ))))
2863 (when cat
2864 (org-set-local 'org-category (intern cat))
2865 (push (cons "CATEGORY" cat) props))
2866 (when prio
2867 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2868 (setq prio (mapcar 'string-to-char prio))
2869 (org-set-local 'org-highest-priority (nth 0 prio))
2870 (org-set-local 'org-lowest-priority (nth 1 prio))
2871 (org-set-local 'org-default-priority (nth 2 prio)))
2872 (and props (org-set-local 'org-file-properties (nreverse props)))
2873 (and ftags (org-set-local 'org-file-tags ftags))
2874 (and drawers (org-set-local 'org-drawers drawers))
2875 (and arch (org-set-local 'org-archive-location arch))
2876 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2877 ;; Process the TODO keywords
2878 (unless kwds
2879 ;; Use the global values as if they had been given locally.
2880 (setq kwds (default-value 'org-todo-keywords))
2881 (if (stringp (car kwds))
2882 (setq kwds (list (cons org-todo-interpretation
2883 (default-value 'org-todo-keywords)))))
2884 (setq kwds (reverse kwds)))
2885 (setq kwds (nreverse kwds))
2886 (let (inter kws kw)
2887 (while (setq kws (pop kwds))
2888 (setq inter (pop kws) sep (member "|" kws)
2889 kws0 (delete "|" (copy-sequence kws))
2890 kwsa nil
2891 kws1 (mapcar
2892 (lambda (x)
2893 ;; 1 2
2894 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2895 (progn
2896 (setq kw (match-string 1 x)
2897 key (and (match-end 2) (match-string 2 x))
2898 log (org-extract-log-state-settings x))
2899 (push (cons kw (and key (string-to-char key))) kwsa)
2900 (and log (push log org-todo-log-states))
2902 (error "Invalid TODO keyword %s" x)))
2903 kws0)
2904 kwsa (if kwsa (append '((:startgroup))
2905 (nreverse kwsa)
2906 '((:endgroup))))
2907 hw (car kws1)
2908 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2909 tail (list inter hw (car dws) (org-last dws)))
2910 (add-to-list 'org-todo-heads hw 'append)
2911 (push kws1 org-todo-sets)
2912 (setq org-done-keywords (append org-done-keywords dws nil))
2913 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2914 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2915 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2916 (setq org-todo-sets (nreverse org-todo-sets)
2917 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2918 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2919 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2920 ;; Process the constants
2921 (when const
2922 (let (e cst)
2923 (while (setq e (pop const))
2924 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2925 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2926 (setq org-table-formula-constants-local cst)))
2928 ;; Process the tags.
2929 (when tags
2930 (let (e tgs)
2931 (while (setq e (pop tags))
2932 (cond
2933 ((equal e "{") (push '(:startgroup) tgs))
2934 ((equal e "}") (push '(:endgroup) tgs))
2935 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2936 (push (cons (match-string 1 e)
2937 (string-to-char (match-string 2 e)))
2938 tgs))
2939 (t (push (list e) tgs))))
2940 (org-set-local 'org-tag-alist nil)
2941 (while (setq e (pop tgs))
2942 (or (and (stringp (car e))
2943 (assoc (car e) org-tag-alist))
2944 (push e org-tag-alist)))))
2946 ;; Compute the regular expressions and other local variables
2947 (if (not org-done-keywords)
2948 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2949 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2950 (length org-scheduled-string)
2951 (length org-clock-string)
2952 (length org-closed-string)))
2953 org-drawer-regexp
2954 (concat "^[ \t]*:\\("
2955 (mapconcat 'regexp-quote org-drawers "\\|")
2956 "\\):[ \t]*$")
2957 org-not-done-keywords
2958 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2959 org-todo-regexp
2960 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2961 "\\|") "\\)\\>")
2962 org-not-done-regexp
2963 (concat "\\<\\("
2964 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2965 "\\)\\>")
2966 org-todo-line-regexp
2967 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2968 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2969 "\\)\\>\\)?[ \t]*\\(.*\\)")
2970 org-complex-heading-regexp
2971 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2972 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2973 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2974 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2975 org-nl-done-regexp
2976 (concat "\n\\*+[ \t]+"
2977 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2978 "\\)" "\\>")
2979 org-todo-line-tags-regexp
2980 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2981 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2982 (org-re
2983 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2984 org-looking-at-done-regexp
2985 (concat "^" "\\(?:"
2986 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2987 "\\>")
2988 org-deadline-regexp (concat "\\<" org-deadline-string)
2989 org-deadline-time-regexp
2990 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2991 org-deadline-line-regexp
2992 (concat "\\<\\(" org-deadline-string "\\).*")
2993 org-scheduled-regexp
2994 (concat "\\<" org-scheduled-string)
2995 org-scheduled-time-regexp
2996 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2997 org-closed-time-regexp
2998 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2999 org-keyword-time-regexp
3000 (concat "\\<\\(" org-scheduled-string
3001 "\\|" org-deadline-string
3002 "\\|" org-closed-string
3003 "\\|" org-clock-string "\\)"
3004 " *[[<]\\([^]>]+\\)[]>]")
3005 org-keyword-time-not-clock-regexp
3006 (concat "\\<\\(" org-scheduled-string
3007 "\\|" org-deadline-string
3008 "\\|" org-closed-string
3009 "\\)"
3010 " *[[<]\\([^]>]+\\)[]>]")
3011 org-maybe-keyword-time-regexp
3012 (concat "\\(\\<\\(" org-scheduled-string
3013 "\\|" org-deadline-string
3014 "\\|" org-closed-string
3015 "\\|" org-clock-string "\\)\\)?"
3016 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3017 org-planning-or-clock-line-re
3018 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3019 "\\|" org-deadline-string
3020 "\\|" org-closed-string "\\|" org-clock-string
3021 "\\)\\>\\)")
3023 (org-compute-latex-and-specials-regexp)
3024 (org-set-font-lock-defaults))))
3026 (defun org-file-contents (file &optional noerror)
3027 "Return the contents of FILE, as a string."
3028 (if (or (not file)
3029 (not (file-readable-p file)))
3030 (if noerror
3031 (progn
3032 (message "Cannot read file %s" file)
3033 (ding) (sit-for 2)
3035 (error "Cannot read file %s" file))
3036 (with-temp-buffer
3037 (insert-file-contents file)
3038 (buffer-string))))
3040 (defun org-extract-log-state-settings (x)
3041 "Extract the log state setting from a TODO keyword string.
3042 This will extract info from a string like \"WAIT(w@/!)\"."
3043 (let (kw key log1 log2)
3044 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3045 (setq kw (match-string 1 x)
3046 key (and (match-end 2) (match-string 2 x))
3047 log1 (and (match-end 3) (match-string 3 x))
3048 log2 (and (match-end 4) (match-string 4 x)))
3049 (and (or log1 log2)
3050 (list kw
3051 (and log1 (if (equal log1 "!") 'time 'note))
3052 (and log2 (if (equal log2 "!") 'time 'note)))))))
3054 (defun org-remove-keyword-keys (list)
3055 "Remove a pair of parenthesis at the end of each string in LIST."
3056 (mapcar (lambda (x)
3057 (if (string-match "(.*)$" x)
3058 (substring x 0 (match-beginning 0))
3060 list))
3062 ;; FIXME: this could be done much better, using second characters etc.
3063 (defun org-assign-fast-keys (alist)
3064 "Assign fast keys to a keyword-key alist.
3065 Respect keys that are already there."
3066 (let (new e k c c1 c2 (char ?a))
3067 (while (setq e (pop alist))
3068 (cond
3069 ((equal e '(:startgroup)) (push e new))
3070 ((equal e '(:endgroup)) (push e new))
3072 (setq k (car e) c2 nil)
3073 (if (cdr e)
3074 (setq c (cdr e))
3075 ;; automatically assign a character.
3076 (setq c1 (string-to-char
3077 (downcase (substring
3078 k (if (= (string-to-char k) ?@) 1 0)))))
3079 (if (or (rassoc c1 new) (rassoc c1 alist))
3080 (while (or (rassoc char new) (rassoc char alist))
3081 (setq char (1+ char)))
3082 (setq c2 c1))
3083 (setq c (or c2 char)))
3084 (push (cons k c) new))))
3085 (nreverse new)))
3087 ;;; Some variables used in various places
3089 (defvar org-window-configuration nil
3090 "Used in various places to store a window configuration.")
3091 (defvar org-finish-function nil
3092 "Function to be called when `C-c C-c' is used.
3093 This is for getting out of special buffers like remember.")
3096 ;; FIXME: Occasionally check by commenting these, to make sure
3097 ;; no other functions uses these, forgetting to let-bind them.
3098 (defvar entry)
3099 (defvar state)
3100 (defvar last-state)
3101 (defvar date)
3102 (defvar description)
3104 ;; Defined somewhere in this file, but used before definition.
3105 (defvar org-html-entities)
3106 (defvar org-struct-menu)
3107 (defvar org-org-menu)
3108 (defvar org-tbl-menu)
3109 (defvar org-agenda-keymap)
3111 ;;;; Define the Org-mode
3113 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3114 (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."))
3117 ;; We use a before-change function to check if a table might need
3118 ;; an update.
3119 (defvar org-table-may-need-update t
3120 "Indicates that a table might need an update.
3121 This variable is set by `org-before-change-function'.
3122 `org-table-align' sets it back to nil.")
3123 (defun org-before-change-function (beg end)
3124 "Every change indicates that a table might need an update."
3125 (setq org-table-may-need-update t))
3126 (defvar org-mode-map)
3127 (defvar org-mode-hook nil)
3128 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3129 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3130 (defvar org-table-buffer-is-an nil)
3131 (defconst org-outline-regexp "\\*+ ")
3133 ;;;###autoload
3134 (define-derived-mode org-mode outline-mode "Org"
3135 "Outline-based notes management and organizer, alias
3136 \"Carsten's outline-mode for keeping track of everything.\"
3138 Org-mode develops organizational tasks around a NOTES file which
3139 contains information about projects as plain text. Org-mode is
3140 implemented on top of outline-mode, which is ideal to keep the content
3141 of large files well structured. It supports ToDo items, deadlines and
3142 time stamps, which magically appear in the diary listing of the Emacs
3143 calendar. Tables are easily created with a built-in table editor.
3144 Plain text URL-like links connect to websites, emails (VM), Usenet
3145 messages (Gnus), BBDB entries, and any files related to the project.
3146 For printing and sharing of notes, an Org-mode file (or a part of it)
3147 can be exported as a structured ASCII or HTML file.
3149 The following commands are available:
3151 \\{org-mode-map}"
3153 ;; Get rid of Outline menus, they are not needed
3154 ;; Need to do this here because define-derived-mode sets up
3155 ;; the keymap so late. Still, it is a waste to call this each time
3156 ;; we switch another buffer into org-mode.
3157 (if (featurep 'xemacs)
3158 (when (boundp 'outline-mode-menu-heading)
3159 ;; Assume this is Greg's port, it used easymenu
3160 (easy-menu-remove outline-mode-menu-heading)
3161 (easy-menu-remove outline-mode-menu-show)
3162 (easy-menu-remove outline-mode-menu-hide))
3163 (define-key org-mode-map [menu-bar headings] 'undefined)
3164 (define-key org-mode-map [menu-bar hide] 'undefined)
3165 (define-key org-mode-map [menu-bar show] 'undefined))
3167 (org-load-modules-maybe)
3168 (easy-menu-add org-org-menu)
3169 (easy-menu-add org-tbl-menu)
3170 (org-install-agenda-files-menu)
3171 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3172 (org-add-to-invisibility-spec '(org-cwidth))
3173 (when (featurep 'xemacs)
3174 (org-set-local 'line-move-ignore-invisible t))
3175 (org-set-local 'outline-regexp org-outline-regexp)
3176 (org-set-local 'outline-level 'org-outline-level)
3177 (when (and org-ellipsis
3178 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3179 (fboundp 'make-glyph-code))
3180 (unless org-display-table
3181 (setq org-display-table (make-display-table)))
3182 (set-display-table-slot
3183 org-display-table 4
3184 (vconcat (mapcar
3185 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3186 org-ellipsis)))
3187 (if (stringp org-ellipsis) org-ellipsis "..."))))
3188 (setq buffer-display-table org-display-table))
3189 (org-set-regexps-and-options)
3190 ;; Calc embedded
3191 (org-set-local 'calc-embedded-open-mode "# ")
3192 (modify-syntax-entry ?# "<")
3193 (modify-syntax-entry ?@ "w")
3194 (if org-startup-truncated (setq truncate-lines t))
3195 (org-set-local 'font-lock-unfontify-region-function
3196 'org-unfontify-region)
3197 ;; Activate before-change-function
3198 (org-set-local 'org-table-may-need-update t)
3199 (org-add-hook 'before-change-functions 'org-before-change-function nil
3200 'local)
3201 ;; Check for running clock before killing a buffer
3202 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3203 ;; Paragraphs and auto-filling
3204 (org-set-autofill-regexps)
3205 (setq indent-line-function 'org-indent-line-function)
3206 (org-update-radio-target-regexp)
3208 ;; Comment characters
3209 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3210 (org-set-local 'comment-padding " ")
3212 ;; Align options lines
3213 (org-set-local
3214 'align-mode-rules-list
3215 '((org-in-buffer-settings
3216 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3217 (modes . '(org-mode)))))
3219 ;; Imenu
3220 (org-set-local 'imenu-create-index-function
3221 'org-imenu-get-tree)
3223 ;; Make isearch reveal context
3224 (if (or (featurep 'xemacs)
3225 (not (boundp 'outline-isearch-open-invisible-function)))
3226 ;; Emacs 21 and XEmacs make use of the hook
3227 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3228 ;; Emacs 22 deals with this through a special variable
3229 (org-set-local 'outline-isearch-open-invisible-function
3230 (lambda (&rest ignore) (org-show-context 'isearch))))
3232 ;; If empty file that did not turn on org-mode automatically, make it to.
3233 (if (and org-insert-mode-line-in-empty-file
3234 (interactive-p)
3235 (= (point-min) (point-max)))
3236 (insert "# -*- mode: org -*-\n\n"))
3238 (unless org-inhibit-startup
3239 (when org-startup-align-all-tables
3240 (let ((bmp (buffer-modified-p)))
3241 (org-table-map-tables 'org-table-align)
3242 (set-buffer-modified-p bmp)))
3243 (org-set-startup-visibility)))
3245 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3247 (defun org-current-time ()
3248 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3249 (if (> (car org-time-stamp-rounding-minutes) 1)
3250 (let ((r (car org-time-stamp-rounding-minutes))
3251 (time (decode-time)))
3252 (apply 'encode-time
3253 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3254 (nthcdr 2 time))))
3255 (current-time)))
3257 ;;;; Font-Lock stuff, including the activators
3259 (defvar org-mouse-map (make-sparse-keymap))
3260 (org-defkey org-mouse-map
3261 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3262 (org-defkey org-mouse-map
3263 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3264 (when org-mouse-1-follows-link
3265 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3266 (when org-tab-follows-link
3267 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3268 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3269 (when org-return-follows-link
3270 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3271 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3273 (require 'font-lock)
3275 (defconst org-non-link-chars "]\t\n\r<>")
3276 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3277 "shell" "elisp"))
3278 (defvar org-link-types-re nil
3279 "Matches a link that has a url-like prefix like \"http:\"")
3280 (defvar org-link-re-with-space nil
3281 "Matches a link with spaces, optional angular brackets around it.")
3282 (defvar org-link-re-with-space2 nil
3283 "Matches a link with spaces, optional angular brackets around it.")
3284 (defvar org-angle-link-re nil
3285 "Matches link with angular brackets, spaces are allowed.")
3286 (defvar org-plain-link-re nil
3287 "Matches plain link, without spaces.")
3288 (defvar org-bracket-link-regexp nil
3289 "Matches a link in double brackets.")
3290 (defvar org-bracket-link-analytic-regexp nil
3291 "Regular expression used to analyze links.
3292 Here is what the match groups contain after a match:
3293 1: http:
3294 2: http
3295 3: path
3296 4: [desc]
3297 5: desc")
3298 (defvar org-any-link-re nil
3299 "Regular expression matching any link.")
3301 (defun org-make-link-regexps ()
3302 "Update the link regular expressions.
3303 This should be called after the variable `org-link-types' has changed."
3304 (setq org-link-types-re
3305 (concat
3306 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3307 org-link-re-with-space
3308 (concat
3309 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3310 "\\([^" org-non-link-chars " ]"
3311 "[^" org-non-link-chars "]*"
3312 "[^" org-non-link-chars " ]\\)>?")
3313 org-link-re-with-space2
3314 (concat
3315 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3316 "\\([^" org-non-link-chars " ]"
3317 "[^]\t\n\r]*"
3318 "[^" org-non-link-chars " ]\\)>?")
3319 org-angle-link-re
3320 (concat
3321 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3322 "\\([^" org-non-link-chars " ]"
3323 "[^" org-non-link-chars "]*"
3324 "\\)>")
3325 org-plain-link-re
3326 (concat
3327 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3328 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3329 org-bracket-link-regexp
3330 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3331 org-bracket-link-analytic-regexp
3332 (concat
3333 "\\[\\["
3334 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3335 "\\([^]]+\\)"
3336 "\\]"
3337 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3338 "\\]")
3339 org-any-link-re
3340 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3341 org-angle-link-re "\\)\\|\\("
3342 org-plain-link-re "\\)")))
3344 (org-make-link-regexps)
3346 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3347 "Regular expression for fast time stamp matching.")
3348 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3349 "Regular expression for fast time stamp matching.")
3350 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3351 "Regular expression matching time strings for analysis.
3352 This one does not require the space after the date, so it can be used
3353 on a string that terminates immediately after the date.")
3354 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3355 "Regular expression matching time strings for analysis.")
3356 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3357 "Regular expression matching time stamps, with groups.")
3358 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3359 "Regular expression matching time stamps (also [..]), with groups.")
3360 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3361 "Regular expression matching a time stamp range.")
3362 (defconst org-tr-regexp-both
3363 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3364 "Regular expression matching a time stamp range.")
3365 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3366 org-ts-regexp "\\)?")
3367 "Regular expression matching a time stamp or time stamp range.")
3368 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3369 org-ts-regexp-both "\\)?")
3370 "Regular expression matching a time stamp or time stamp range.
3371 The time stamps may be either active or inactive.")
3373 (defvar org-emph-face nil)
3375 (defun org-do-emphasis-faces (limit)
3376 "Run through the buffer and add overlays to links."
3377 (let (rtn)
3378 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3379 (if (not (= (char-after (match-beginning 3))
3380 (char-after (match-beginning 4))))
3381 (progn
3382 (setq rtn t)
3383 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3384 'face
3385 (nth 1 (assoc (match-string 3)
3386 org-emphasis-alist)))
3387 (add-text-properties (match-beginning 2) (match-end 2)
3388 '(font-lock-multiline t))
3389 (when org-hide-emphasis-markers
3390 (add-text-properties (match-end 4) (match-beginning 5)
3391 '(invisible org-link))
3392 (add-text-properties (match-beginning 3) (match-end 3)
3393 '(invisible org-link)))))
3394 (backward-char 1))
3395 rtn))
3397 (defun org-emphasize (&optional char)
3398 "Insert or change an emphasis, i.e. a font like bold or italic.
3399 If there is an active region, change that region to a new emphasis.
3400 If there is no region, just insert the marker characters and position
3401 the cursor between them.
3402 CHAR should be either the marker character, or the first character of the
3403 HTML tag associated with that emphasis. If CHAR is a space, the means
3404 to remove the emphasis of the selected region.
3405 If char is not given (for example in an interactive call) it
3406 will be prompted for."
3407 (interactive)
3408 (let ((eal org-emphasis-alist) e det
3409 (erc org-emphasis-regexp-components)
3410 (prompt "")
3411 (string "") beg end move tag c s)
3412 (if (org-region-active-p)
3413 (setq beg (region-beginning) end (region-end)
3414 string (buffer-substring beg end))
3415 (setq move t))
3417 (while (setq e (pop eal))
3418 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3419 c (aref tag 0))
3420 (push (cons c (string-to-char (car e))) det)
3421 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3422 (substring tag 1)))))
3423 (unless char
3424 (message "%s" (concat "Emphasis marker or tag:" prompt))
3425 (setq char (read-char-exclusive)))
3426 (setq char (or (cdr (assoc char det)) char))
3427 (if (equal char ?\ )
3428 (setq s "" move nil)
3429 (unless (assoc (char-to-string char) org-emphasis-alist)
3430 (error "No such emphasis marker: \"%c\"" char))
3431 (setq s (char-to-string char)))
3432 (while (and (> (length string) 1)
3433 (equal (substring string 0 1) (substring string -1))
3434 (assoc (substring string 0 1) org-emphasis-alist))
3435 (setq string (substring string 1 -1)))
3436 (setq string (concat s string s))
3437 (if beg (delete-region beg end))
3438 (unless (or (bolp)
3439 (string-match (concat "[" (nth 0 erc) "\n]")
3440 (char-to-string (char-before (point)))))
3441 (insert " "))
3442 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3443 (char-to-string (char-after (point))))
3444 (insert " ") (backward-char 1))
3445 (insert string)
3446 (and move (backward-char 1))))
3448 (defconst org-nonsticky-props
3449 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3452 (defun org-activate-plain-links (limit)
3453 "Run through the buffer and add overlays to links."
3454 (catch 'exit
3455 (let (f)
3456 (while (re-search-forward org-plain-link-re limit t)
3457 (setq f (get-text-property (match-beginning 0) 'face))
3458 (if (or (eq f 'org-tag)
3459 (and (listp f) (memq 'org-tag f)))
3461 (add-text-properties (match-beginning 0) (match-end 0)
3462 (list 'mouse-face 'highlight
3463 'rear-nonsticky org-nonsticky-props
3464 'keymap org-mouse-map
3466 (throw 'exit t))))))
3468 (defun org-activate-code (limit)
3469 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3470 (unless (get-text-property (match-beginning 1) 'face)
3471 (remove-text-properties (match-beginning 0) (match-end 0)
3472 '(display t invisible t intangible t))
3473 t)))
3475 (defun org-activate-angle-links (limit)
3476 "Run through the buffer and add overlays to links."
3477 (if (re-search-forward org-angle-link-re limit t)
3478 (progn
3479 (add-text-properties (match-beginning 0) (match-end 0)
3480 (list 'mouse-face 'highlight
3481 'rear-nonsticky org-nonsticky-props
3482 'keymap org-mouse-map
3484 t)))
3486 (defun org-activate-bracket-links (limit)
3487 "Run through the buffer and add overlays to bracketed links."
3488 (if (re-search-forward org-bracket-link-regexp limit t)
3489 (let* ((help (concat "LINK: "
3490 (org-match-string-no-properties 1)))
3491 ;; FIXME: above we should remove the escapes.
3492 ;; but that requires another match, protecting match data,
3493 ;; a lot of overhead for font-lock.
3494 (ip (org-maybe-intangible
3495 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3496 'keymap org-mouse-map 'mouse-face 'highlight
3497 'font-lock-multiline t 'help-echo help)))
3498 (vp (list 'rear-nonsticky org-nonsticky-props
3499 'keymap org-mouse-map 'mouse-face 'highlight
3500 ' font-lock-multiline t 'help-echo help)))
3501 ;; We need to remove the invisible property here. Table narrowing
3502 ;; may have made some of this invisible.
3503 (remove-text-properties (match-beginning 0) (match-end 0)
3504 '(invisible nil))
3505 (if (match-end 3)
3506 (progn
3507 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3508 (add-text-properties (match-beginning 3) (match-end 3) vp)
3509 (add-text-properties (match-end 3) (match-end 0) ip))
3510 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3511 (add-text-properties (match-beginning 1) (match-end 1) vp)
3512 (add-text-properties (match-end 1) (match-end 0) ip))
3513 t)))
3515 (defun org-activate-dates (limit)
3516 "Run through the buffer and add overlays to dates."
3517 (if (re-search-forward org-tsr-regexp-both limit t)
3518 (progn
3519 (add-text-properties (match-beginning 0) (match-end 0)
3520 (list 'mouse-face 'highlight
3521 'rear-nonsticky org-nonsticky-props
3522 'keymap org-mouse-map))
3523 (when org-display-custom-times
3524 (if (match-end 3)
3525 (org-display-custom-time (match-beginning 3) (match-end 3)))
3526 (org-display-custom-time (match-beginning 1) (match-end 1)))
3527 t)))
3529 (defvar org-target-link-regexp nil
3530 "Regular expression matching radio targets in plain text.")
3531 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3532 "Regular expression matching a link target.")
3533 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3534 "Regular expression matching a radio target.")
3535 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3536 "Regular expression matching any target.")
3538 (defun org-activate-target-links (limit)
3539 "Run through the buffer and add overlays to target matches."
3540 (when org-target-link-regexp
3541 (let ((case-fold-search t))
3542 (if (re-search-forward org-target-link-regexp limit t)
3543 (progn
3544 (add-text-properties (match-beginning 0) (match-end 0)
3545 (list 'mouse-face 'highlight
3546 'rear-nonsticky org-nonsticky-props
3547 'keymap org-mouse-map
3548 'help-echo "Radio target link"
3549 'org-linked-text t))
3550 t)))))
3552 (defun org-update-radio-target-regexp ()
3553 "Find all radio targets in this file and update the regular expression."
3554 (interactive)
3555 (when (memq 'radio org-activate-links)
3556 (setq org-target-link-regexp
3557 (org-make-target-link-regexp (org-all-targets 'radio)))
3558 (org-restart-font-lock)))
3560 (defun org-hide-wide-columns (limit)
3561 (let (s e)
3562 (setq s (text-property-any (point) (or limit (point-max))
3563 'org-cwidth t))
3564 (when s
3565 (setq e (next-single-property-change s 'org-cwidth))
3566 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3567 (goto-char e)
3568 t)))
3570 (defvar org-latex-and-specials-regexp nil
3571 "Regular expression for highlighting export special stuff.")
3572 (defvar org-match-substring-regexp)
3573 (defvar org-match-substring-with-braces-regexp)
3574 (defvar org-export-html-special-string-regexps)
3576 (defun org-compute-latex-and-specials-regexp ()
3577 "Compute regular expression for stuff treated specially by exporters."
3578 (if (not org-highlight-latex-fragments-and-specials)
3579 (org-set-local 'org-latex-and-specials-regexp nil)
3580 (require 'org-exp)
3581 (let*
3582 ((matchers (plist-get org-format-latex-options :matchers))
3583 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3584 org-latex-regexps)))
3585 (options (org-combine-plists (org-default-export-plist)
3586 (org-infile-export-plist)))
3587 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3588 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3589 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3590 (org-export-html-expand (plist-get options :expand-quoted-html))
3591 (org-export-with-special-strings (plist-get options :special-strings))
3592 (re-sub
3593 (cond
3594 ((equal org-export-with-sub-superscripts '{})
3595 (list org-match-substring-with-braces-regexp))
3596 (org-export-with-sub-superscripts
3597 (list org-match-substring-regexp))
3598 (t nil)))
3599 (re-latex
3600 (if org-export-with-LaTeX-fragments
3601 (mapcar (lambda (x) (nth 1 x)) latexs)))
3602 (re-macros
3603 (if org-export-with-TeX-macros
3604 (list (concat "\\\\"
3605 (regexp-opt
3606 (append (mapcar 'car org-html-entities)
3607 (if (boundp 'org-latex-entities)
3608 org-latex-entities nil))
3609 'words))) ; FIXME
3611 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3612 (re-special (if org-export-with-special-strings
3613 (mapcar (lambda (x) (car x))
3614 org-export-html-special-string-regexps)))
3615 (re-rest
3616 (delq nil
3617 (list
3618 (if org-export-html-expand "@<[^>\n]+>")
3619 ))))
3620 (org-set-local
3621 'org-latex-and-specials-regexp
3622 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3623 re-rest) "\\|")))))
3625 (defun org-do-latex-and-special-faces (limit)
3626 "Run through the buffer and add overlays to links."
3627 (when org-latex-and-specials-regexp
3628 (let (rtn d)
3629 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3630 limit t))
3631 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3632 'face))
3633 '(org-code org-verbatim underline)))
3634 (progn
3635 (setq rtn t
3636 d (cond ((member (char-after (1+ (match-beginning 0)))
3637 '(?_ ?^)) 1)
3638 (t 0)))
3639 (font-lock-prepend-text-property
3640 (+ d (match-beginning 0)) (match-end 0)
3641 'face 'org-latex-and-export-specials)
3642 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3643 '(font-lock-multiline t)))))
3644 rtn)))
3646 (defun org-restart-font-lock ()
3647 "Restart font-lock-mode, to force refontification."
3648 (when (and (boundp 'font-lock-mode) font-lock-mode)
3649 (font-lock-mode -1)
3650 (font-lock-mode 1)))
3652 (defun org-all-targets (&optional radio)
3653 "Return a list of all targets in this file.
3654 With optional argument RADIO, only find radio targets."
3655 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3656 rtn)
3657 (save-excursion
3658 (goto-char (point-min))
3659 (while (re-search-forward re nil t)
3660 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3661 rtn)))
3663 (defun org-make-target-link-regexp (targets)
3664 "Make regular expression matching all strings in TARGETS.
3665 The regular expression finds the targets also if there is a line break
3666 between words."
3667 (and targets
3668 (concat
3669 "\\<\\("
3670 (mapconcat
3671 (lambda (x)
3672 (while (string-match " +" x)
3673 (setq x (replace-match "\\s-+" t t x)))
3675 targets
3676 "\\|")
3677 "\\)\\>")))
3679 (defun org-activate-tags (limit)
3680 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3681 (progn
3682 (add-text-properties (match-beginning 1) (match-end 1)
3683 (list 'mouse-face 'highlight
3684 'rear-nonsticky org-nonsticky-props
3685 'keymap org-mouse-map))
3686 t)))
3688 (defun org-outline-level ()
3689 (save-excursion
3690 (looking-at outline-regexp)
3691 (if (match-beginning 1)
3692 (+ (org-get-string-indentation (match-string 1)) 1000)
3693 (1- (- (match-end 0) (match-beginning 0))))))
3695 (defvar org-font-lock-keywords nil)
3697 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3698 "Regular expression matching a property line.")
3700 (defvar org-font-lock-hook nil
3701 "Functions to be called for special font lock stuff.")
3703 (defun org-font-lock-hook (limit)
3704 (run-hook-with-args 'org-font-lock-hook limit))
3706 (defun org-set-font-lock-defaults ()
3707 (let* ((em org-fontify-emphasized-text)
3708 (lk org-activate-links)
3709 (org-font-lock-extra-keywords
3710 (list
3711 ;; Call the hook
3712 '(org-font-lock-hook)
3713 ;; Headlines
3714 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3715 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3716 ;; Table lines
3717 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3718 (1 'org-table t))
3719 ;; Table internals
3720 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3721 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3722 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3723 ;; Drawers
3724 (list org-drawer-regexp '(0 'org-special-keyword t))
3725 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3726 ;; Properties
3727 (list org-property-re
3728 '(1 'org-special-keyword t)
3729 '(3 'org-property-value t))
3730 (if org-format-transports-properties-p
3731 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3732 ;; Links
3733 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3734 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3735 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3736 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3737 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3738 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3739 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3740 '(org-hide-wide-columns (0 nil append))
3741 ;; TODO lines
3742 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3743 '(1 (org-get-todo-face 1) t))
3744 ;; DONE
3745 (if org-fontify-done-headline
3746 (list (concat "^[*]+ +\\<\\("
3747 (mapconcat 'regexp-quote org-done-keywords "\\|")
3748 "\\)\\(.*\\)")
3749 '(2 'org-headline-done t))
3750 nil)
3751 ;; Priorities
3752 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3753 ;; Special keywords
3754 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3755 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3756 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3757 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3758 ;; Emphasis
3759 (if em
3760 (if (featurep 'xemacs)
3761 '(org-do-emphasis-faces (0 nil append))
3762 '(org-do-emphasis-faces)))
3763 ;; Checkboxes
3764 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3765 2 'bold prepend)
3766 (if org-provide-checkbox-statistics
3767 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3768 (0 (org-get-checkbox-statistics-face) t)))
3769 ;; Description list items
3770 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3771 2 'bold prepend)
3772 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3773 '(1 'org-archived prepend))
3774 ;; Specials
3775 '(org-do-latex-and-special-faces)
3776 ;; Code
3777 '(org-activate-code (1 'org-code t))
3778 ;; COMMENT
3779 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3780 "\\|" org-quote-string "\\)\\>")
3781 '(1 'org-special-keyword t))
3782 '("^#.*" (0 'font-lock-comment-face t))
3784 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3785 ;; Now set the full font-lock-keywords
3786 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3787 (org-set-local 'font-lock-defaults
3788 '(org-font-lock-keywords t nil nil backward-paragraph))
3789 (kill-local-variable 'font-lock-keywords) nil))
3791 (defvar org-m nil)
3792 (defvar org-l nil)
3793 (defvar org-f nil)
3794 (defun org-get-level-face (n)
3795 "Get the right face for match N in font-lock matching of healdines."
3796 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3797 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3798 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3799 (cond
3800 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3801 ((eq n 2) org-f)
3802 (t (if org-level-color-stars-only nil org-f))))
3804 (defun org-get-todo-face (kwd)
3805 "Get the right face for a TODO keyword KWD.
3806 If KWD is a number, get the corresponding match group."
3807 (if (numberp kwd) (setq kwd (match-string kwd)))
3808 (or (cdr (assoc kwd org-todo-keyword-faces))
3809 (and (member kwd org-done-keywords) 'org-done)
3810 'org-todo))
3812 (defun org-unfontify-region (beg end &optional maybe_loudly)
3813 "Remove fontification and activation overlays from links."
3814 (font-lock-default-unfontify-region beg end)
3815 (let* ((buffer-undo-list t)
3816 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3817 (inhibit-modification-hooks t)
3818 deactivate-mark buffer-file-name buffer-file-truename)
3819 (remove-text-properties beg end
3820 '(mouse-face t keymap t org-linked-text t
3821 invisible t intangible t))))
3823 ;;;; Visibility cycling, including org-goto and indirect buffer
3825 ;;; Cycling
3827 (defvar org-cycle-global-status nil)
3828 (make-variable-buffer-local 'org-cycle-global-status)
3829 (defvar org-cycle-subtree-status nil)
3830 (make-variable-buffer-local 'org-cycle-subtree-status)
3832 ;;;###autoload
3833 (defun org-cycle (&optional arg)
3834 "Visibility cycling for Org-mode.
3836 - When this function is called with a prefix argument, rotate the entire
3837 buffer through 3 states (global cycling)
3838 1. OVERVIEW: Show only top-level headlines.
3839 2. CONTENTS: Show all headlines of all levels, but no body text.
3840 3. SHOW ALL: Show everything.
3841 When called with two C-c C-u prefixes, switch to the startup visibility,
3842 determined by the variable `org-startup-folded', and by any VISIBILITY
3843 properties in the buffer.
3845 - When point is at the beginning of a headline, rotate the subtree started
3846 by this line through 3 different states (local cycling)
3847 1. FOLDED: Only the main headline is shown.
3848 2. CHILDREN: The main headline and the direct children are shown.
3849 From this state, you can move to one of the children
3850 and zoom in further.
3851 3. SUBTREE: Show the entire subtree, including body text.
3853 - When there is a numeric prefix, go up to a heading with level ARG, do
3854 a `show-subtree' and return to the previous cursor position. If ARG
3855 is negative, go up that many levels.
3857 - When point is not at the beginning of a headline, execute the global
3858 binding for TAB, which is re-indenting the line. See the option
3859 `org-cycle-emulate-tab' for details.
3861 - Special case: if point is at the beginning of the buffer and there is
3862 no headline in line 1, this function will act as if called with prefix arg.
3863 But only if also the variable `org-cycle-global-at-bob' is t."
3864 (interactive "P")
3865 (org-load-modules-maybe)
3866 (let* ((outline-regexp
3867 (if (and (org-mode-p) org-cycle-include-plain-lists)
3868 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3869 outline-regexp))
3870 (bob-special (and org-cycle-global-at-bob (bobp)
3871 (not (looking-at outline-regexp))))
3872 (org-cycle-hook
3873 (if bob-special
3874 (delq 'org-optimize-window-after-visibility-change
3875 (copy-sequence org-cycle-hook))
3876 org-cycle-hook))
3877 (pos (point)))
3879 (if (or bob-special (equal arg '(4)))
3880 ;; special case: use global cycling
3881 (setq arg t))
3883 (cond
3885 ((equal arg '(16))
3886 (org-set-startup-visibility)
3887 (message "Startup visibility, plus VISIBILITY properties."))
3889 ((org-at-table-p 'any)
3890 ;; Enter the table or move to the next field in the table
3891 (or (org-table-recognize-table.el)
3892 (progn
3893 (if arg (org-table-edit-field t)
3894 (org-table-justify-field-maybe)
3895 (call-interactively 'org-table-next-field)))))
3897 ((eq arg t) ;; Global cycling
3899 (cond
3900 ((and (eq last-command this-command)
3901 (eq org-cycle-global-status 'overview))
3902 ;; We just created the overview - now do table of contents
3903 ;; This can be slow in very large buffers, so indicate action
3904 (message "CONTENTS...")
3905 (org-content)
3906 (message "CONTENTS...done")
3907 (setq org-cycle-global-status 'contents)
3908 (run-hook-with-args 'org-cycle-hook 'contents))
3910 ((and (eq last-command this-command)
3911 (eq org-cycle-global-status 'contents))
3912 ;; We just showed the table of contents - now show everything
3913 (show-all)
3914 (message "SHOW ALL")
3915 (setq org-cycle-global-status 'all)
3916 (run-hook-with-args 'org-cycle-hook 'all))
3919 ;; Default action: go to overview
3920 (org-overview)
3921 (message "OVERVIEW")
3922 (setq org-cycle-global-status 'overview)
3923 (run-hook-with-args 'org-cycle-hook 'overview))))
3925 ((and org-drawers org-drawer-regexp
3926 (save-excursion
3927 (beginning-of-line 1)
3928 (looking-at org-drawer-regexp)))
3929 ;; Toggle block visibility
3930 (org-flag-drawer
3931 (not (get-char-property (match-end 0) 'invisible))))
3933 ((integerp arg)
3934 ;; Show-subtree, ARG levels up from here.
3935 (save-excursion
3936 (org-back-to-heading)
3937 (outline-up-heading (if (< arg 0) (- arg)
3938 (- (funcall outline-level) arg)))
3939 (org-show-subtree)))
3941 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3942 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3943 ;; At a heading: rotate between three different views
3944 (org-back-to-heading)
3945 (let ((goal-column 0) eoh eol eos)
3946 ;; First, some boundaries
3947 (save-excursion
3948 (org-back-to-heading)
3949 (save-excursion
3950 (beginning-of-line 2)
3951 (while (and (not (eobp)) ;; this is like `next-line'
3952 (get-char-property (1- (point)) 'invisible))
3953 (beginning-of-line 2)) (setq eol (point)))
3954 (outline-end-of-heading) (setq eoh (point))
3955 (org-end-of-subtree t)
3956 (unless (eobp)
3957 (skip-chars-forward " \t\n")
3958 (beginning-of-line 1) ; in case this is an item
3960 (setq eos (1- (point))))
3961 ;; Find out what to do next and set `this-command'
3962 (cond
3963 ((= eos eoh)
3964 ;; Nothing is hidden behind this heading
3965 (message "EMPTY ENTRY")
3966 (setq org-cycle-subtree-status nil)
3967 (save-excursion
3968 (goto-char eos)
3969 (outline-next-heading)
3970 (if (org-invisible-p) (org-flag-heading nil))))
3971 ((or (>= eol eos)
3972 (not (string-match "\\S-" (buffer-substring eol eos))))
3973 ;; Entire subtree is hidden in one line: open it
3974 (org-show-entry)
3975 (show-children)
3976 (message "CHILDREN")
3977 (save-excursion
3978 (goto-char eos)
3979 (outline-next-heading)
3980 (if (org-invisible-p) (org-flag-heading nil)))
3981 (setq org-cycle-subtree-status 'children)
3982 (run-hook-with-args 'org-cycle-hook 'children))
3983 ((and (eq last-command this-command)
3984 (eq org-cycle-subtree-status 'children))
3985 ;; We just showed the children, now show everything.
3986 (org-show-subtree)
3987 (message "SUBTREE")
3988 (setq org-cycle-subtree-status 'subtree)
3989 (run-hook-with-args 'org-cycle-hook 'subtree))
3991 ;; Default action: hide the subtree.
3992 (hide-subtree)
3993 (message "FOLDED")
3994 (setq org-cycle-subtree-status 'folded)
3995 (run-hook-with-args 'org-cycle-hook 'folded)))))
3997 ;; TAB emulation and template completion
3998 (buffer-read-only (org-back-to-heading))
4000 ((org-try-structure-completion))
4002 ((org-try-cdlatex-tab))
4004 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4005 (or (not (bolp))
4006 (not (looking-at outline-regexp))))
4007 (call-interactively (global-key-binding "\t")))
4009 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4010 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4011 (or (and (eq org-cycle-emulate-tab 'white)
4012 (= (match-end 0) (point-at-eol)))
4013 (and (eq org-cycle-emulate-tab 'whitestart)
4014 (>= (match-end 0) pos))))
4016 (eq org-cycle-emulate-tab t))
4017 (call-interactively (global-key-binding "\t")))
4019 (t (save-excursion
4020 (org-back-to-heading)
4021 (org-cycle))))))
4023 ;;;###autoload
4024 (defun org-global-cycle (&optional arg)
4025 "Cycle the global visibility. For details see `org-cycle'.
4026 With C-u prefix arg, switch to startup visibility.
4027 With a numeric prefix, show all headlines up to that level."
4028 (interactive "P")
4029 (let ((org-cycle-include-plain-lists
4030 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4031 (cond
4032 ((integerp arg)
4033 (show-all)
4034 (hide-sublevels arg)
4035 (setq org-cycle-global-status 'contents))
4036 ((equal arg '(4))
4037 (org-set-startup-visibility)
4038 (message "Startup visibility, plus VISIBILITY properties."))
4040 (org-cycle '(4))))))
4042 (defun org-set-startup-visibility ()
4043 "Set the visibility required by startup options and properties."
4044 (cond
4045 ((eq org-startup-folded t)
4046 (org-cycle '(4)))
4047 ((eq org-startup-folded 'content)
4048 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4049 (org-cycle '(4)) (org-cycle '(4)))))
4050 (org-set-visibility-according-to-property 'no-cleanup)
4051 (org-cycle-hide-archived-subtrees 'all)
4052 (org-cycle-hide-drawers 'all)
4053 (org-cycle-show-empty-lines 'all))
4055 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4056 "Switch subtree visibilities according to :VISIBILITY: property."
4057 (interactive)
4058 (let (state)
4059 (save-excursion
4060 (goto-char (point-min))
4061 (while (re-search-forward
4062 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4063 nil t)
4064 (setq state (match-string 1))
4065 (save-excursion
4066 (org-back-to-heading t)
4067 (hide-subtree)
4068 (org-reveal)
4069 (cond
4070 ((equal state '("fold" "folded"))
4071 (hide-subtree))
4072 ((equal state "children")
4073 (org-show-hidden-entry)
4074 (show-children))
4075 ((equal state "content")
4076 (save-excursion
4077 (save-restriction
4078 (org-narrow-to-subtree)
4079 (org-content))))
4080 ((member state '("all" "showall"))
4081 (show-subtree)))))
4082 (unless no-cleanup
4083 (org-cycle-hide-archived-subtrees 'all)
4084 (org-cycle-hide-drawers 'all)
4085 (org-cycle-show-empty-lines 'all)))))
4087 (defun org-overview ()
4088 "Switch to overview mode, shoing only top-level headlines.
4089 Really, this shows all headlines with level equal or greater than the level
4090 of the first headline in the buffer. This is important, because if the
4091 first headline is not level one, then (hide-sublevels 1) gives confusing
4092 results."
4093 (interactive)
4094 (let ((level (save-excursion
4095 (goto-char (point-min))
4096 (if (re-search-forward (concat "^" outline-regexp) nil t)
4097 (progn
4098 (goto-char (match-beginning 0))
4099 (funcall outline-level))))))
4100 (and level (hide-sublevels level))))
4102 (defun org-content (&optional arg)
4103 "Show all headlines in the buffer, like a table of contents.
4104 With numerical argument N, show content up to level N."
4105 (interactive "P")
4106 (save-excursion
4107 ;; Visit all headings and show their offspring
4108 (and (integerp arg) (org-overview))
4109 (goto-char (point-max))
4110 (catch 'exit
4111 (while (and (progn (condition-case nil
4112 (outline-previous-visible-heading 1)
4113 (error (goto-char (point-min))))
4115 (looking-at outline-regexp))
4116 (if (integerp arg)
4117 (show-children (1- arg))
4118 (show-branches))
4119 (if (bobp) (throw 'exit nil))))))
4122 (defun org-optimize-window-after-visibility-change (state)
4123 "Adjust the window after a change in outline visibility.
4124 This function is the default value of the hook `org-cycle-hook'."
4125 (when (get-buffer-window (current-buffer))
4126 (cond
4127 ; ((eq state 'overview) (org-first-headline-recenter 1))
4128 ; ((eq state 'overview) (org-beginning-of-line))
4129 ((eq state 'content) nil)
4130 ((eq state 'all) nil)
4131 ((eq state 'folded) nil)
4132 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4133 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4135 (defun org-compact-display-after-subtree-move ()
4136 (let (beg end)
4137 (save-excursion
4138 (if (org-up-heading-safe)
4139 (progn
4140 (hide-subtree)
4141 (show-entry)
4142 (show-children)
4143 (org-cycle-show-empty-lines 'children)
4144 (org-cycle-hide-drawers 'children))
4145 (org-overview)))))
4147 (defun org-cycle-show-empty-lines (state)
4148 "Show empty lines above all visible headlines.
4149 The region to be covered depends on STATE when called through
4150 `org-cycle-hook'. Lisp program can use t for STATE to get the
4151 entire buffer covered. Note that an empty line is only shown if there
4152 are at least `org-cycle-separator-lines' empty lines before the headeline."
4153 (when (> org-cycle-separator-lines 0)
4154 (save-excursion
4155 (let* ((n org-cycle-separator-lines)
4156 (re (cond
4157 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4158 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4159 (t (let ((ns (number-to-string (- n 2))))
4160 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4161 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4162 beg end)
4163 (cond
4164 ((memq state '(overview contents t))
4165 (setq beg (point-min) end (point-max)))
4166 ((memq state '(children folded))
4167 (setq beg (point) end (progn (org-end-of-subtree t t)
4168 (beginning-of-line 2)
4169 (point)))))
4170 (when beg
4171 (goto-char beg)
4172 (while (re-search-forward re end t)
4173 (if (not (get-char-property (match-end 1) 'invisible))
4174 (outline-flag-region
4175 (match-beginning 1) (match-end 1) nil)))))))
4176 ;; Never hide empty lines at the end of the file.
4177 (save-excursion
4178 (goto-char (point-max))
4179 (outline-previous-heading)
4180 (outline-end-of-heading)
4181 (if (and (looking-at "[ \t\n]+")
4182 (= (match-end 0) (point-max)))
4183 (outline-flag-region (point) (match-end 0) nil))))
4185 (defun org-cycle-hide-drawers (state)
4186 "Re-hide all drawers after a visibility state change."
4187 (when (and (org-mode-p)
4188 (not (memq state '(overview folded))))
4189 (save-excursion
4190 (let* ((globalp (memq state '(contents all)))
4191 (beg (if globalp (point-min) (point)))
4192 (end (if globalp (point-max) (org-end-of-subtree t))))
4193 (goto-char beg)
4194 (while (re-search-forward org-drawer-regexp end t)
4195 (org-flag-drawer t))))))
4197 (defun org-flag-drawer (flag)
4198 (save-excursion
4199 (beginning-of-line 1)
4200 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4201 (let ((b (match-end 0))
4202 (outline-regexp org-outline-regexp))
4203 (if (re-search-forward
4204 "^[ \t]*:END:"
4205 (save-excursion (outline-next-heading) (point)) t)
4206 (outline-flag-region b (point-at-eol) flag)
4207 (error ":END: line missing"))))))
4209 (defun org-subtree-end-visible-p ()
4210 "Is the end of the current subtree visible?"
4211 (pos-visible-in-window-p
4212 (save-excursion (org-end-of-subtree t) (point))))
4214 (defun org-first-headline-recenter (&optional N)
4215 "Move cursor to the first headline and recenter the headline.
4216 Optional argument N means, put the headline into the Nth line of the window."
4217 (goto-char (point-min))
4218 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4219 (beginning-of-line)
4220 (recenter (prefix-numeric-value N))))
4222 ;;; Org-goto
4224 (defvar org-goto-window-configuration nil)
4225 (defvar org-goto-marker nil)
4226 (defvar org-goto-map
4227 (let ((map (make-sparse-keymap)))
4228 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4229 (while (setq cmd (pop cmds))
4230 (substitute-key-definition cmd cmd map global-map)))
4231 (suppress-keymap map)
4232 (org-defkey map "\C-m" 'org-goto-ret)
4233 (org-defkey map [(return)] 'org-goto-ret)
4234 (org-defkey map [(left)] 'org-goto-left)
4235 (org-defkey map [(right)] 'org-goto-right)
4236 (org-defkey map [(control ?g)] 'org-goto-quit)
4237 (org-defkey map "\C-i" 'org-cycle)
4238 (org-defkey map [(tab)] 'org-cycle)
4239 (org-defkey map [(down)] 'outline-next-visible-heading)
4240 (org-defkey map [(up)] 'outline-previous-visible-heading)
4241 (if org-goto-auto-isearch
4242 (if (fboundp 'define-key-after)
4243 (define-key-after map [t] 'org-goto-local-auto-isearch)
4244 nil)
4245 (org-defkey map "q" 'org-goto-quit)
4246 (org-defkey map "n" 'outline-next-visible-heading)
4247 (org-defkey map "p" 'outline-previous-visible-heading)
4248 (org-defkey map "f" 'outline-forward-same-level)
4249 (org-defkey map "b" 'outline-backward-same-level)
4250 (org-defkey map "u" 'outline-up-heading))
4251 (org-defkey map "/" 'org-occur)
4252 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4253 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4254 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4255 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4256 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4257 map))
4259 (defconst org-goto-help
4260 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4261 RET=jump to location [Q]uit and return to previous location
4262 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4264 (defvar org-goto-start-pos) ; dynamically scoped parameter
4266 ;; FIXME: Docstring doe not mention both interfaces
4267 (defun org-goto (&optional alternative-interface)
4268 "Look up a different location in the current file, keeping current visibility.
4270 When you want look-up or go to a different location in a document, the
4271 fastest way is often to fold the entire buffer and then dive into the tree.
4272 This method has the disadvantage, that the previous location will be folded,
4273 which may not be what you want.
4275 This command works around this by showing a copy of the current buffer
4276 in an indirect buffer, in overview mode. You can dive into the tree in
4277 that copy, use org-occur and incremental search to find a location.
4278 When pressing RET or `Q', the command returns to the original buffer in
4279 which the visibility is still unchanged. After RET is will also jump to
4280 the location selected in the indirect buffer and expose the
4281 the headline hierarchy above."
4282 (interactive "P")
4283 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4284 (org-refile-use-outline-path t)
4285 (interface
4286 (if (not alternative-interface)
4287 org-goto-interface
4288 (if (eq org-goto-interface 'outline)
4289 'outline-path-completion
4290 'outline)))
4291 (org-goto-start-pos (point))
4292 (selected-point
4293 (if (eq interface 'outline)
4294 (car (org-get-location (current-buffer) org-goto-help))
4295 (nth 3 (org-refile-get-location "Goto: ")))))
4296 (if selected-point
4297 (progn
4298 (org-mark-ring-push org-goto-start-pos)
4299 (goto-char selected-point)
4300 (if (or (org-invisible-p) (org-invisible-p2))
4301 (org-show-context 'org-goto)))
4302 (message "Quit"))))
4304 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4305 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4306 (defvar org-goto-local-auto-isearch-map) ; defined below
4308 (defun org-get-location (buf help)
4309 "Let the user select a location in the Org-mode buffer BUF.
4310 This function uses a recursive edit. It returns the selected position
4311 or nil."
4312 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4313 (isearch-hide-immediately nil)
4314 (isearch-search-fun-function
4315 (lambda () 'org-goto-local-search-forward-headings))
4316 (org-goto-selected-point org-goto-exit-command))
4317 (save-excursion
4318 (save-window-excursion
4319 (delete-other-windows)
4320 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4321 (switch-to-buffer
4322 (condition-case nil
4323 (make-indirect-buffer (current-buffer) "*org-goto*")
4324 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4325 (with-output-to-temp-buffer "*Help*"
4326 (princ help))
4327 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4328 (setq buffer-read-only nil)
4329 (let ((org-startup-truncated t)
4330 (org-startup-folded nil)
4331 (org-startup-align-all-tables nil))
4332 (org-mode)
4333 (org-overview))
4334 (setq buffer-read-only t)
4335 (if (and (boundp 'org-goto-start-pos)
4336 (integer-or-marker-p org-goto-start-pos))
4337 (let ((org-show-hierarchy-above t)
4338 (org-show-siblings t)
4339 (org-show-following-heading t))
4340 (goto-char org-goto-start-pos)
4341 (and (org-invisible-p) (org-show-context)))
4342 (goto-char (point-min)))
4343 (org-beginning-of-line)
4344 (message "Select location and press RET")
4345 (use-local-map org-goto-map)
4346 (recursive-edit)
4348 (kill-buffer "*org-goto*")
4349 (cons org-goto-selected-point org-goto-exit-command)))
4351 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4352 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4353 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4354 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4356 (defun org-goto-local-search-forward-headings (string bound noerror)
4357 "Search and make sure that anu matches are in headlines."
4358 (catch 'return
4359 (while (search-forward string bound noerror)
4360 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4361 (and (member :headline context)
4362 (not (member :tags context))))
4363 (throw 'return (point))))))
4365 (defun org-goto-local-auto-isearch ()
4366 "Start isearch."
4367 (interactive)
4368 (goto-char (point-min))
4369 (let ((keys (this-command-keys)))
4370 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4371 (isearch-mode t)
4372 (isearch-process-search-char (string-to-char keys)))))
4374 (defun org-goto-ret (&optional arg)
4375 "Finish `org-goto' by going to the new location."
4376 (interactive "P")
4377 (setq org-goto-selected-point (point)
4378 org-goto-exit-command 'return)
4379 (throw 'exit nil))
4381 (defun org-goto-left ()
4382 "Finish `org-goto' by going to the new location."
4383 (interactive)
4384 (if (org-on-heading-p)
4385 (progn
4386 (beginning-of-line 1)
4387 (setq org-goto-selected-point (point)
4388 org-goto-exit-command 'left)
4389 (throw 'exit nil))
4390 (error "Not on a heading")))
4392 (defun org-goto-right ()
4393 "Finish `org-goto' by going to the new location."
4394 (interactive)
4395 (if (org-on-heading-p)
4396 (progn
4397 (setq org-goto-selected-point (point)
4398 org-goto-exit-command 'right)
4399 (throw 'exit nil))
4400 (error "Not on a heading")))
4402 (defun org-goto-quit ()
4403 "Finish `org-goto' without cursor motion."
4404 (interactive)
4405 (setq org-goto-selected-point nil)
4406 (setq org-goto-exit-command 'quit)
4407 (throw 'exit nil))
4409 ;;; Indirect buffer display of subtrees
4411 (defvar org-indirect-dedicated-frame nil
4412 "This is the frame being used for indirect tree display.")
4413 (defvar org-last-indirect-buffer nil)
4415 (defun org-tree-to-indirect-buffer (&optional arg)
4416 "Create indirect buffer and narrow it to current subtree.
4417 With numerical prefix ARG, go up to this level and then take that tree.
4418 If ARG is negative, go up that many levels.
4419 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4420 indirect buffer previously made with this command, to avoid proliferation of
4421 indirect buffers. However, when you call the command with a `C-u' prefix, or
4422 when `org-indirect-buffer-display' is `new-frame', the last buffer
4423 is kept so that you can work with several indirect buffers at the same time.
4424 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4425 requests that a new frame be made for the new buffer, so that the dedicated
4426 frame is not changed."
4427 (interactive "P")
4428 (let ((cbuf (current-buffer))
4429 (cwin (selected-window))
4430 (pos (point))
4431 beg end level heading ibuf)
4432 (save-excursion
4433 (org-back-to-heading t)
4434 (when (numberp arg)
4435 (setq level (org-outline-level))
4436 (if (< arg 0) (setq arg (+ level arg)))
4437 (while (> (setq level (org-outline-level)) arg)
4438 (outline-up-heading 1 t)))
4439 (setq beg (point)
4440 heading (org-get-heading))
4441 (org-end-of-subtree t) (setq end (point)))
4442 (if (and (buffer-live-p org-last-indirect-buffer)
4443 (not (eq org-indirect-buffer-display 'new-frame))
4444 (not arg))
4445 (kill-buffer org-last-indirect-buffer))
4446 (setq ibuf (org-get-indirect-buffer cbuf)
4447 org-last-indirect-buffer ibuf)
4448 (cond
4449 ((or (eq org-indirect-buffer-display 'new-frame)
4450 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4451 (select-frame (make-frame))
4452 (delete-other-windows)
4453 (switch-to-buffer ibuf)
4454 (org-set-frame-title heading))
4455 ((eq org-indirect-buffer-display 'dedicated-frame)
4456 (raise-frame
4457 (select-frame (or (and org-indirect-dedicated-frame
4458 (frame-live-p org-indirect-dedicated-frame)
4459 org-indirect-dedicated-frame)
4460 (setq org-indirect-dedicated-frame (make-frame)))))
4461 (delete-other-windows)
4462 (switch-to-buffer ibuf)
4463 (org-set-frame-title (concat "Indirect: " heading)))
4464 ((eq org-indirect-buffer-display 'current-window)
4465 (switch-to-buffer ibuf))
4466 ((eq org-indirect-buffer-display 'other-window)
4467 (pop-to-buffer ibuf))
4468 (t (error "Invalid value.")))
4469 (if (featurep 'xemacs)
4470 (save-excursion (org-mode) (turn-on-font-lock)))
4471 (narrow-to-region beg end)
4472 (show-all)
4473 (goto-char pos)
4474 (and (window-live-p cwin) (select-window cwin))))
4476 (defun org-get-indirect-buffer (&optional buffer)
4477 (setq buffer (or buffer (current-buffer)))
4478 (let ((n 1) (base (buffer-name buffer)) bname)
4479 (while (buffer-live-p
4480 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4481 (setq n (1+ n)))
4482 (condition-case nil
4483 (make-indirect-buffer buffer bname 'clone)
4484 (error (make-indirect-buffer buffer bname)))))
4486 (defun org-set-frame-title (title)
4487 "Set the title of the current frame to the string TITLE."
4488 ;; FIXME: how to name a single frame in XEmacs???
4489 (unless (featurep 'xemacs)
4490 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4492 ;;;; Structure editing
4494 ;;; Inserting headlines
4496 (defun org-insert-heading (&optional force-heading)
4497 "Insert a new heading or item with same depth at point.
4498 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4499 If point is at the beginning of a headline, insert a sibling before the
4500 current headline. If point is not at the beginning, do not split the line,
4501 but create the new hedline after the current line."
4502 (interactive "P")
4503 (if (= (buffer-size) 0)
4504 (insert "\n* ")
4505 (when (or force-heading (not (org-insert-item)))
4506 (let* ((head (save-excursion
4507 (condition-case nil
4508 (progn
4509 (org-back-to-heading)
4510 (match-string 0))
4511 (error "*"))))
4512 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4513 pos)
4514 (cond
4515 ((and (org-on-heading-p) (bolp)
4516 (or (bobp)
4517 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4518 ;; insert before the current line
4519 (open-line (if blank 2 1)))
4520 ((and (bolp)
4521 (or (bobp)
4522 (save-excursion
4523 (backward-char 1) (not (org-invisible-p)))))
4524 ;; insert right here
4525 nil)
4527 ;; in the middle of the line
4528 (org-show-entry)
4529 (let ((split
4530 (org-get-alist-option org-M-RET-may-split-line 'headline))
4531 tags pos)
4532 (if (org-on-heading-p)
4533 (progn
4534 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4535 (setq tags (and (match-end 2) (match-string 2)))
4536 (and (match-end 1)
4537 (delete-region (match-beginning 1) (match-end 1)))
4538 (setq pos (point-at-bol))
4539 (or split (end-of-line 1))
4540 (delete-horizontal-space)
4541 (newline (if blank 2 1))
4542 (when tags
4543 (save-excursion
4544 (goto-char pos)
4545 (end-of-line 1)
4546 (insert " " tags)
4547 (org-set-tags nil 'align))))
4548 (or split (end-of-line 1))
4549 (newline (if blank 2 1))))))
4550 (insert head) (just-one-space)
4551 (setq pos (point))
4552 (end-of-line 1)
4553 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4554 (run-hooks 'org-insert-heading-hook)))))
4556 (defun org-get-heading (&optional no-tags)
4557 "Return the heading of the current entry, without the stars."
4558 (save-excursion
4559 (org-back-to-heading t)
4560 (if (looking-at
4561 (if no-tags
4562 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4563 "\\*+[ \t]+\\([^\r\n]*\\)"))
4564 (match-string 1) "")))
4566 (defun org-insert-heading-after-current ()
4567 "Insert a new heading with same level as current, after current subtree."
4568 (interactive)
4569 (org-back-to-heading)
4570 (org-insert-heading)
4571 (org-move-subtree-down)
4572 (end-of-line 1))
4574 (defun org-insert-todo-heading (arg)
4575 "Insert a new heading with the same level and TODO state as current heading.
4576 If the heading has no TODO state, or if the state is DONE, use the first
4577 state (TODO by default). Also with prefix arg, force first state."
4578 (interactive "P")
4579 (when (not (org-insert-item 'checkbox))
4580 (org-insert-heading)
4581 (save-excursion
4582 (org-back-to-heading)
4583 (outline-previous-heading)
4584 (looking-at org-todo-line-regexp))
4585 (if (or arg
4586 (not (match-beginning 2))
4587 (member (match-string 2) org-done-keywords))
4588 (insert (car org-todo-keywords-1) " ")
4589 (insert (match-string 2) " "))
4590 (when org-provide-todo-statistics
4591 (org-update-parent-todo-statistics))))
4593 (defun org-insert-subheading (arg)
4594 "Insert a new subheading and demote it.
4595 Works for outline headings and for plain lists alike."
4596 (interactive "P")
4597 (org-insert-heading arg)
4598 (cond
4599 ((org-on-heading-p) (org-do-demote))
4600 ((org-at-item-p) (org-indent-item 1))))
4602 (defun org-insert-todo-subheading (arg)
4603 "Insert a new subheading with TODO keyword or checkbox and demote it.
4604 Works for outline headings and for plain lists alike."
4605 (interactive "P")
4606 (org-insert-todo-heading arg)
4607 (cond
4608 ((org-on-heading-p) (org-do-demote))
4609 ((org-at-item-p) (org-indent-item 1))))
4611 ;;; Promotion and Demotion
4613 (defun org-promote-subtree ()
4614 "Promote the entire subtree.
4615 See also `org-promote'."
4616 (interactive)
4617 (save-excursion
4618 (org-map-tree 'org-promote))
4619 (org-fix-position-after-promote))
4621 (defun org-demote-subtree ()
4622 "Demote the entire subtree. See `org-demote'.
4623 See also `org-promote'."
4624 (interactive)
4625 (save-excursion
4626 (org-map-tree 'org-demote))
4627 (org-fix-position-after-promote))
4630 (defun org-do-promote ()
4631 "Promote the current heading higher up the tree.
4632 If the region is active in `transient-mark-mode', promote all headings
4633 in the region."
4634 (interactive)
4635 (save-excursion
4636 (if (org-region-active-p)
4637 (org-map-region 'org-promote (region-beginning) (region-end))
4638 (org-promote)))
4639 (org-fix-position-after-promote))
4641 (defun org-do-demote ()
4642 "Demote the current heading lower down the tree.
4643 If the region is active in `transient-mark-mode', demote all headings
4644 in the region."
4645 (interactive)
4646 (save-excursion
4647 (if (org-region-active-p)
4648 (org-map-region 'org-demote (region-beginning) (region-end))
4649 (org-demote)))
4650 (org-fix-position-after-promote))
4652 (defun org-fix-position-after-promote ()
4653 "Make sure that after pro/demotion cursor position is right."
4654 (let ((pos (point)))
4655 (when (save-excursion
4656 (beginning-of-line 1)
4657 (looking-at org-todo-line-regexp)
4658 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4659 (cond ((eobp) (insert " "))
4660 ((eolp) (insert " "))
4661 ((equal (char-after) ?\ ) (forward-char 1))))))
4663 (defun org-reduced-level (l)
4664 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4666 (defun org-get-valid-level (level &optional change)
4667 "Rectify a level change under the influence of `org-odd-levels-only'
4668 LEVEL is a current level, CHANGE is by how much the level should be
4669 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4670 even level numbers will become the next higher odd number."
4671 (if org-odd-levels-only
4672 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4673 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4674 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4675 (max 1 (+ level change))))
4677 (if (boundp 'define-obsolete-function-alias)
4678 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4679 (define-obsolete-function-alias 'org-get-legal-level
4680 'org-get-valid-level)
4681 (define-obsolete-function-alias 'org-get-legal-level
4682 'org-get-valid-level "23.1")))
4684 (defun org-promote ()
4685 "Promote the current heading higher up the tree.
4686 If the region is active in `transient-mark-mode', promote all headings
4687 in the region."
4688 (org-back-to-heading t)
4689 (let* ((level (save-match-data (funcall outline-level)))
4690 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4691 (diff (abs (- level (length up-head) -1))))
4692 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4693 (replace-match up-head nil t)
4694 ;; Fixup tag positioning
4695 (and org-auto-align-tags (org-set-tags nil t))
4696 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4698 (defun org-demote ()
4699 "Demote the current heading lower down the tree.
4700 If the region is active in `transient-mark-mode', demote all headings
4701 in the region."
4702 (org-back-to-heading t)
4703 (let* ((level (save-match-data (funcall outline-level)))
4704 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4705 (diff (abs (- level (length down-head) -1))))
4706 (replace-match down-head nil t)
4707 ;; Fixup tag positioning
4708 (and org-auto-align-tags (org-set-tags nil t))
4709 (if org-adapt-indentation (org-fixup-indentation diff))))
4711 (defun org-map-tree (fun)
4712 "Call FUN for every heading underneath the current one."
4713 (org-back-to-heading)
4714 (let ((level (funcall outline-level)))
4715 (save-excursion
4716 (funcall fun)
4717 (while (and (progn
4718 (outline-next-heading)
4719 (> (funcall outline-level) level))
4720 (not (eobp)))
4721 (funcall fun)))))
4723 (defun org-map-region (fun beg end)
4724 "Call FUN for every heading between BEG and END."
4725 (let ((org-ignore-region t))
4726 (save-excursion
4727 (setq end (copy-marker end))
4728 (goto-char beg)
4729 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4730 (< (point) end))
4731 (funcall fun))
4732 (while (and (progn
4733 (outline-next-heading)
4734 (< (point) end))
4735 (not (eobp)))
4736 (funcall fun)))))
4738 (defun org-fixup-indentation (diff)
4739 "Change the indentation in the current entry by DIFF
4740 However, if any line in the current entry has no indentation, or if it
4741 would end up with no indentation after the change, nothing at all is done."
4742 (save-excursion
4743 (let ((end (save-excursion (outline-next-heading)
4744 (point-marker)))
4745 (prohibit (if (> diff 0)
4746 "^\\S-"
4747 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4748 col)
4749 (unless (save-excursion (end-of-line 1)
4750 (re-search-forward prohibit end t))
4751 (while (and (< (point) end)
4752 (re-search-forward "^[ \t]+" end t))
4753 (goto-char (match-end 0))
4754 (setq col (current-column))
4755 (if (< diff 0) (replace-match ""))
4756 (indent-to (+ diff col))))
4757 (move-marker end nil))))
4759 (defun org-convert-to-odd-levels ()
4760 "Convert an org-mode file with all levels allowed to one with odd levels.
4761 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4762 level 5 etc."
4763 (interactive)
4764 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4765 (let ((org-odd-levels-only nil) n)
4766 (save-excursion
4767 (goto-char (point-min))
4768 (while (re-search-forward "^\\*\\*+ " nil t)
4769 (setq n (- (length (match-string 0)) 2))
4770 (while (>= (setq n (1- n)) 0)
4771 (org-demote))
4772 (end-of-line 1))))))
4775 (defun org-convert-to-oddeven-levels ()
4776 "Convert an org-mode file with only odd levels to one with odd and even levels.
4777 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4778 section with an even level, conversion would destroy the structure of the file. An error
4779 is signaled in this case."
4780 (interactive)
4781 (goto-char (point-min))
4782 ;; First check if there are no even levels
4783 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4784 (org-show-context t)
4785 (error "Not all levels are odd in this file. Conversion not possible."))
4786 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4787 (let ((org-odd-levels-only nil) n)
4788 (save-excursion
4789 (goto-char (point-min))
4790 (while (re-search-forward "^\\*\\*+ " nil t)
4791 (setq n (/ (1- (length (match-string 0))) 2))
4792 (while (>= (setq n (1- n)) 0)
4793 (org-promote))
4794 (end-of-line 1))))))
4796 (defun org-tr-level (n)
4797 "Make N odd if required."
4798 (if org-odd-levels-only (1+ (/ n 2)) n))
4800 ;;; Vertical tree motion, cutting and pasting of subtrees
4802 (defun org-move-subtree-up (&optional arg)
4803 "Move the current subtree up past ARG headlines of the same level."
4804 (interactive "p")
4805 (org-move-subtree-down (- (prefix-numeric-value arg))))
4807 (defun org-move-subtree-down (&optional arg)
4808 "Move the current subtree down past ARG headlines of the same level."
4809 (interactive "p")
4810 (setq arg (prefix-numeric-value arg))
4811 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4812 'outline-get-last-sibling))
4813 (ins-point (make-marker))
4814 (cnt (abs arg))
4815 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4816 ;; Select the tree
4817 (org-back-to-heading)
4818 (setq beg0 (point))
4819 (save-excursion
4820 (setq ne-beg (org-back-over-empty-lines))
4821 (setq beg (point)))
4822 (save-match-data
4823 (save-excursion (outline-end-of-heading)
4824 (setq folded (org-invisible-p)))
4825 (outline-end-of-subtree))
4826 (outline-next-heading)
4827 (setq ne-end (org-back-over-empty-lines))
4828 (setq end (point))
4829 (goto-char beg0)
4830 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4831 ;; include less whitespace
4832 (save-excursion
4833 (goto-char beg)
4834 (forward-line (- ne-beg ne-end))
4835 (setq beg (point))))
4836 ;; Find insertion point, with error handling
4837 (while (> cnt 0)
4838 (or (and (funcall movfunc) (looking-at outline-regexp))
4839 (progn (goto-char beg0)
4840 (error "Cannot move past superior level or buffer limit")))
4841 (setq cnt (1- cnt)))
4842 (if (> arg 0)
4843 ;; Moving forward - still need to move over subtree
4844 (progn (org-end-of-subtree t t)
4845 (save-excursion
4846 (org-back-over-empty-lines)
4847 (or (bolp) (newline)))))
4848 (setq ne-ins (org-back-over-empty-lines))
4849 (move-marker ins-point (point))
4850 (setq txt (buffer-substring beg end))
4851 (org-save-markers-in-region beg end)
4852 (delete-region beg end)
4853 (outline-flag-region (1- beg) beg nil)
4854 (outline-flag-region (1- (point)) (point) nil)
4855 (let ((bbb (point)))
4856 (insert-before-markers txt)
4857 (org-reinstall-markers-in-region bbb)
4858 (move-marker ins-point bbb))
4859 (or (bolp) (insert "\n"))
4860 (setq ins-end (point))
4861 (goto-char ins-point)
4862 (org-skip-whitespace)
4863 (when (and (< arg 0)
4864 (org-first-sibling-p)
4865 (> ne-ins ne-beg))
4866 ;; Move whitespace back to beginning
4867 (save-excursion
4868 (goto-char ins-end)
4869 (let ((kill-whole-line t))
4870 (kill-line (- ne-ins ne-beg)) (point)))
4871 (insert (make-string (- ne-ins ne-beg) ?\n)))
4872 (move-marker ins-point nil)
4873 (org-compact-display-after-subtree-move)
4874 (unless folded
4875 (org-show-entry)
4876 (show-children)
4877 (org-cycle-hide-drawers 'children))))
4879 (defvar org-subtree-clip ""
4880 "Clipboard for cut and paste of subtrees.
4881 This is actually only a copy of the kill, because we use the normal kill
4882 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4884 (defvar org-subtree-clip-folded nil
4885 "Was the last copied subtree folded?
4886 This is used to fold the tree back after pasting.")
4888 (defun org-cut-subtree (&optional n)
4889 "Cut the current subtree into the clipboard.
4890 With prefix arg N, cut this many sequential subtrees.
4891 This is a short-hand for marking the subtree and then cutting it."
4892 (interactive "p")
4893 (org-copy-subtree n 'cut))
4895 (defun org-copy-subtree (&optional n cut force-store-markers)
4896 "Cut the current subtree into the clipboard.
4897 With prefix arg N, cut this many sequential subtrees.
4898 This is a short-hand for marking the subtree and then copying it.
4899 If CUT is non-nil, actually cut the subtree.
4900 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4901 of some markers in the region, even if CUT is non-nil. This is
4902 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4903 (interactive "p")
4904 (let (beg end folded (beg0 (point)))
4905 (if (interactive-p)
4906 (org-back-to-heading nil) ; take what looks like a subtree
4907 (org-back-to-heading t)) ; take what is really there
4908 (org-back-over-empty-lines)
4909 (setq beg (point))
4910 (skip-chars-forward " \t\r\n")
4911 (save-match-data
4912 (save-excursion (outline-end-of-heading)
4913 (setq folded (org-invisible-p)))
4914 (condition-case nil
4915 (outline-forward-same-level (1- n))
4916 (error nil))
4917 (org-end-of-subtree t t))
4918 (org-back-over-empty-lines)
4919 (setq end (point))
4920 (goto-char beg0)
4921 (when (> end beg)
4922 (setq org-subtree-clip-folded folded)
4923 (when (or cut force-store-markers)
4924 (org-save-markers-in-region beg end))
4925 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4926 (setq org-subtree-clip (current-kill 0))
4927 (message "%s: Subtree(s) with %d characters"
4928 (if cut "Cut" "Copied")
4929 (length org-subtree-clip)))))
4931 (defun org-paste-subtree (&optional level tree)
4932 "Paste the clipboard as a subtree, with modification of headline level.
4933 The entire subtree is promoted or demoted in order to match a new headline
4934 level. By default, the new level is derived from the visible headings
4935 before and after the insertion point, and taken to be the inferior headline
4936 level of the two. So if the previous visible heading is level 3 and the
4937 next is level 4 (or vice versa), level 4 will be used for insertion.
4938 This makes sure that the subtree remains an independent subtree and does
4939 not swallow low level entries.
4941 You can also force a different level, either by using a numeric prefix
4942 argument, or by inserting the heading marker by hand. For example, if the
4943 cursor is after \"*****\", then the tree will be shifted to level 5.
4945 If you want to insert the tree as is, just use \\[yank].
4947 If optional TREE is given, use this text instead of the kill ring."
4948 (interactive "P")
4949 (unless (org-kill-is-subtree-p tree)
4950 (error "%s"
4951 (substitute-command-keys
4952 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4953 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4954 (^re (concat "^\\(" outline-regexp "\\)"))
4955 (re (concat "\\(" outline-regexp "\\)"))
4956 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4958 (old-level (if (string-match ^re txt)
4959 (- (match-end 0) (match-beginning 0) 1)
4960 -1))
4961 (force-level (cond (level (prefix-numeric-value level))
4962 ((string-match
4963 ^re_ (buffer-substring (point-at-bol) (point)))
4964 (- (match-end 1) (match-beginning 1)))
4965 (t nil)))
4966 (previous-level (save-excursion
4967 (condition-case nil
4968 (progn
4969 (outline-previous-visible-heading 1)
4970 (if (looking-at re)
4971 (- (match-end 0) (match-beginning 0) 1)
4973 (error 1))))
4974 (next-level (save-excursion
4975 (condition-case nil
4976 (progn
4977 (or (looking-at outline-regexp)
4978 (outline-next-visible-heading 1))
4979 (if (looking-at re)
4980 (- (match-end 0) (match-beginning 0) 1)
4982 (error 1))))
4983 (new-level (or force-level (max previous-level next-level)))
4984 (shift (if (or (= old-level -1)
4985 (= new-level -1)
4986 (= old-level new-level))
4988 (- new-level old-level)))
4989 (delta (if (> shift 0) -1 1))
4990 (func (if (> shift 0) 'org-demote 'org-promote))
4991 (org-odd-levels-only nil)
4992 beg end)
4993 ;; Remove the forced level indicator
4994 (if force-level
4995 (delete-region (point-at-bol) (point)))
4996 ;; Paste
4997 (beginning-of-line 1)
4998 (org-back-over-empty-lines)
4999 (setq beg (point))
5000 (insert-before-markers txt)
5001 (unless (string-match "\n\\'" txt) (insert "\n"))
5002 (org-reinstall-markers-in-region beg)
5003 (setq end (point))
5004 (goto-char beg)
5005 (skip-chars-forward " \t\n\r")
5006 (setq beg (point))
5007 ;; Shift if necessary
5008 (unless (= shift 0)
5009 (save-restriction
5010 (narrow-to-region beg end)
5011 (while (not (= shift 0))
5012 (org-map-region func (point-min) (point-max))
5013 (setq shift (+ delta shift)))
5014 (goto-char (point-min))))
5015 (when (interactive-p)
5016 (message "Clipboard pasted as level %d subtree" new-level))
5017 (if (and kill-ring
5018 (eq org-subtree-clip (current-kill 0))
5019 org-subtree-clip-folded)
5020 ;; The tree was folded before it was killed/copied
5021 (hide-subtree))))
5023 (defun org-kill-is-subtree-p (&optional txt)
5024 "Check if the current kill is an outline subtree, or a set of trees.
5025 Returns nil if kill does not start with a headline, or if the first
5026 headline level is not the largest headline level in the tree.
5027 So this will actually accept several entries of equal levels as well,
5028 which is OK for `org-paste-subtree'.
5029 If optional TXT is given, check this string instead of the current kill."
5030 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5031 (start-level (and kill
5032 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5033 org-outline-regexp "\\)")
5034 kill)
5035 (- (match-end 2) (match-beginning 2) 1)))
5036 (re (concat "^" org-outline-regexp))
5037 (start (1+ (match-beginning 2))))
5038 (if (not start-level)
5039 (progn
5040 nil) ;; does not even start with a heading
5041 (catch 'exit
5042 (while (setq start (string-match re kill (1+ start)))
5043 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5044 (throw 'exit nil)))
5045 t))))
5047 (defvar org-markers-to-move nil
5048 "Markers that should be moved with a cut-and-paste operation.
5049 Those markers are stored together with their positions relative to
5050 the start of the region.")
5052 (defun org-save-markers-in-region (beg end)
5053 "Check markers in region.
5054 If these markers are between BEG and END, record their position relative
5055 to BEG, so that after moving the block of text, we can put the markers back
5056 into place.
5057 This function gets called just before an entry or tree gets cut from the
5058 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5059 called immediately, to move the markers with the entries."
5060 (setq org-markers-to-move nil)
5061 (when (featurep 'org-clock)
5062 (org-clock-save-markers-for-cut-and-paste beg end))
5063 (when (featurep 'org-agenda)
5064 (org-agenda-save-markers-for-cut-and-paste beg end)))
5066 (defun org-check-and-save-marker (marker beg end)
5067 "Check if MARKER is between BEG and END.
5068 If yes, remember the marker and the distance to BEG."
5069 (when (and (marker-buffer marker)
5070 (equal (marker-buffer marker) (current-buffer)))
5071 (if (and (>= marker beg) (< marker end))
5072 (push (cons marker (- marker beg)) org-markers-to-move))))
5074 (defun org-reinstall-markers-in-region (beg)
5075 "Move all remembered markers to their position relative to BEG."
5076 (mapc (lambda (x)
5077 (move-marker (car x) (+ beg (cdr x))))
5078 org-markers-to-move)
5079 (setq org-markers-to-move nil))
5081 (defun org-narrow-to-subtree ()
5082 "Narrow buffer to the current subtree."
5083 (interactive)
5084 (save-excursion
5085 (save-match-data
5086 (narrow-to-region
5087 (progn (org-back-to-heading) (point))
5088 (progn (org-end-of-subtree t t) (point))))))
5091 ;;; Outline Sorting
5093 (defun org-sort (with-case)
5094 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5095 Optional argument WITH-CASE means sort case-sensitively."
5096 (interactive "P")
5097 (if (org-at-table-p)
5098 (org-call-with-arg 'org-table-sort-lines with-case)
5099 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5101 (defun org-sort-remove-invisible (s)
5102 (remove-text-properties 0 (length s) org-rm-props s)
5103 (while (string-match org-bracket-link-regexp s)
5104 (setq s (replace-match (if (match-end 2)
5105 (match-string 3 s)
5106 (match-string 1 s)) t t s)))
5109 (defvar org-priority-regexp) ; defined later in the file
5111 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5112 "Sort entries on a certain level of an outline tree.
5113 If there is an active region, the entries in the region are sorted.
5114 Else, if the cursor is before the first entry, sort the top-level items.
5115 Else, the children of the entry at point are sorted.
5117 Sorting can be alphabetically, numerically, and by date/time as given by
5118 the first time stamp in the entry. The command prompts for the sorting
5119 type unless it has been given to the function through the SORTING-TYPE
5120 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5121 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5122 called with point at the beginning of the record. It must return either
5123 a string or a number that should serve as the sorting key for that record.
5125 Comparing entries ignores case by default. However, with an optional argument
5126 WITH-CASE, the sorting considers case as well."
5127 (interactive "P")
5128 (let ((case-func (if with-case 'identity 'downcase))
5129 start beg end stars re re2
5130 txt what tmp plain-list-p)
5131 ;; Find beginning and end of region to sort
5132 (cond
5133 ((org-region-active-p)
5134 ;; we will sort the region
5135 (setq end (region-end)
5136 what "region")
5137 (goto-char (region-beginning))
5138 (if (not (org-on-heading-p)) (outline-next-heading))
5139 (setq start (point)))
5140 ((org-at-item-p)
5141 ;; we will sort this plain list
5142 (org-beginning-of-item-list) (setq start (point))
5143 (org-end-of-item-list) (setq end (point))
5144 (goto-char start)
5145 (setq plain-list-p t
5146 what "plain list"))
5147 ((or (org-on-heading-p)
5148 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5149 ;; we will sort the children of the current headline
5150 (org-back-to-heading)
5151 (setq start (point)
5152 end (progn (org-end-of-subtree t t)
5153 (org-back-over-empty-lines)
5154 (point))
5155 what "children")
5156 (goto-char start)
5157 (show-subtree)
5158 (outline-next-heading))
5160 ;; we will sort the top-level entries in this file
5161 (goto-char (point-min))
5162 (or (org-on-heading-p) (outline-next-heading))
5163 (setq start (point) end (point-max) what "top-level")
5164 (goto-char start)
5165 (show-all)))
5167 (setq beg (point))
5168 (if (>= beg end) (error "Nothing to sort"))
5170 (unless plain-list-p
5171 (looking-at "\\(\\*+\\)")
5172 (setq stars (match-string 1)
5173 re (concat "^" (regexp-quote stars) " +")
5174 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5175 txt (buffer-substring beg end))
5176 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5177 (if (and (not (equal stars "*")) (string-match re2 txt))
5178 (error "Region to sort contains a level above the first entry")))
5180 (unless sorting-type
5181 (message
5182 (if plain-list-p
5183 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5184 "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:")
5185 what)
5186 (setq sorting-type (read-char-exclusive))
5188 (and (= (downcase sorting-type) ?f)
5189 (setq getkey-func
5190 (completing-read "Sort using function: "
5191 obarray 'fboundp t nil nil))
5192 (setq getkey-func (intern getkey-func)))
5194 (and (= (downcase sorting-type) ?r)
5195 (setq property
5196 (completing-read "Property: "
5197 (mapcar 'list (org-buffer-property-keys t))
5198 nil t))))
5200 (message "Sorting entries...")
5202 (save-restriction
5203 (narrow-to-region start end)
5205 (let ((dcst (downcase sorting-type))
5206 (now (current-time)))
5207 (sort-subr
5208 (/= dcst sorting-type)
5209 ;; This function moves to the beginning character of the "record" to
5210 ;; be sorted.
5211 (if plain-list-p
5212 (lambda nil
5213 (if (org-at-item-p) t (goto-char (point-max))))
5214 (lambda nil
5215 (if (re-search-forward re nil t)
5216 (goto-char (match-beginning 0))
5217 (goto-char (point-max)))))
5218 ;; This function moves to the last character of the "record" being
5219 ;; sorted.
5220 (if plain-list-p
5221 'org-end-of-item
5222 (lambda nil
5223 (save-match-data
5224 (condition-case nil
5225 (outline-forward-same-level 1)
5226 (error
5227 (goto-char (point-max)))))))
5229 ;; This function returns the value that gets sorted against.
5230 (if plain-list-p
5231 (lambda nil
5232 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5233 (cond
5234 ((= dcst ?n)
5235 (string-to-number (buffer-substring (match-end 0)
5236 (point-at-eol))))
5237 ((= dcst ?a)
5238 (buffer-substring (match-end 0) (point-at-eol)))
5239 ((= dcst ?t)
5240 (if (re-search-forward org-ts-regexp
5241 (point-at-eol) t)
5242 (org-time-string-to-time (match-string 0))
5243 now))
5244 ((= dcst ?f)
5245 (if getkey-func
5246 (progn
5247 (setq tmp (funcall getkey-func))
5248 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5249 tmp)
5250 (error "Invalid key function `%s'" getkey-func)))
5251 (t (error "Invalid sorting type `%c'" sorting-type)))))
5252 (lambda nil
5253 (cond
5254 ((= dcst ?n)
5255 (if (looking-at outline-regexp)
5256 (string-to-number (buffer-substring (match-end 0)
5257 (point-at-eol)))
5258 nil))
5259 ((= dcst ?a)
5260 (funcall case-func (buffer-substring (point-at-bol)
5261 (point-at-eol))))
5262 ((= dcst ?t)
5263 (if (re-search-forward org-ts-regexp
5264 (save-excursion
5265 (forward-line 2)
5266 (point)) t)
5267 (org-time-string-to-time (match-string 0))
5268 now))
5269 ((= dcst ?p)
5270 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5271 (string-to-char (match-string 2))
5272 org-default-priority))
5273 ((= dcst ?r)
5274 (or (org-entry-get nil property) ""))
5275 ((= dcst ?o)
5276 (if (looking-at org-complex-heading-regexp)
5277 (- 9999 (length (member (match-string 2)
5278 org-todo-keywords-1)))))
5279 ((= dcst ?f)
5280 (if getkey-func
5281 (progn
5282 (setq tmp (funcall getkey-func))
5283 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5284 tmp)
5285 (error "Invalid key function `%s'" getkey-func)))
5286 (t (error "Invalid sorting type `%c'" sorting-type)))))
5288 (cond
5289 ((= dcst ?a) 'string<)
5290 ((= dcst ?t) 'time-less-p)
5291 (t nil)))))
5292 (message "Sorting entries...done")))
5294 (defun org-do-sort (table what &optional with-case sorting-type)
5295 "Sort TABLE of WHAT according to SORTING-TYPE.
5296 The user will be prompted for the SORTING-TYPE if the call to this
5297 function does not specify it. WHAT is only for the prompt, to indicate
5298 what is being sorted. The sorting key will be extracted from
5299 the car of the elements of the table.
5300 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5301 (unless sorting-type
5302 (message
5303 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5304 what)
5305 (setq sorting-type (read-char-exclusive)))
5306 (let ((dcst (downcase sorting-type))
5307 extractfun comparefun)
5308 ;; Define the appropriate functions
5309 (cond
5310 ((= dcst ?n)
5311 (setq extractfun 'string-to-number
5312 comparefun (if (= dcst sorting-type) '< '>)))
5313 ((= dcst ?a)
5314 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5315 (lambda(x) (downcase (org-sort-remove-invisible x))))
5316 comparefun (if (= dcst sorting-type)
5317 'string<
5318 (lambda (a b) (and (not (string< a b))
5319 (not (string= a b)))))))
5320 ((= dcst ?t)
5321 (setq extractfun
5322 (lambda (x)
5323 (if (string-match org-ts-regexp x)
5324 (time-to-seconds
5325 (org-time-string-to-time (match-string 0 x)))
5327 comparefun (if (= dcst sorting-type) '< '>)))
5328 (t (error "Invalid sorting type `%c'" sorting-type)))
5330 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5331 table)
5332 (lambda (a b) (funcall comparefun (car a) (car b))))))
5334 ;;; Editing source examples
5336 (defun org-edit-src-example ()
5337 "Edit the source code example at point.
5338 An indirect buffer is created, and that buffer is then narrowed to the
5339 example at point and switched to the correct language mode. When done,
5340 exit by killing the buffer with \\[kill-buffer]. It is important to exit
5341 in this way because some Org quoting of the example will take place."
5342 (interactive)
5343 (let ((line (org-current-line))
5344 (case-fold-search t)
5345 (msg (substitute-command-keys
5346 "Edit, then kill this indirect buffer with \\[kill-buffer]"))
5347 beg end)
5348 (if (not (org-find-src-example-start))
5349 ;; not at an example
5351 (if (not (save-excursion
5352 (goto-char (point-at-bol))
5353 (or (looking-at "#\\+begin_src[ \t]+\\([^ \t\n]+\\)")
5354 (looking-at "[ \t]*<src .*?lang=\"\\(.*?\\)\""))))
5355 (error "This should not happen"))
5356 (setq beg (point-at-bol 2)
5357 lang (match-string 1)
5358 lang-f (intern (concat lang "-mode")))
5359 (unless (functionp lang-f)
5360 "No such language mode: %s" lang-f)
5361 (unless (re-search-forward "^\\(#\\+end_src\\|[ \t]*</src>\\)" nil t)
5362 (error "Cannot find end of src"))
5363 (setq end (match-beginning 0))
5364 (goto-line line)
5365 (if (get-buffer "*Org Edit Src Example*")
5366 (kill-buffer "*Org Edit Src Example*"))
5367 (switch-to-buffer (make-indirect-buffer (current-buffer)
5368 "*Org Edit Src Example*"))
5369 (narrow-to-region beg end)
5370 (funcall lang-f)
5371 (goto-char (point-min))
5372 (while (re-search-forward "^," nil t)
5373 (replace-match ""))
5374 (goto-char (point-min))
5375 (goto-line line)
5376 (org-add-hook 'kill-buffer-hook 'org-protect-source-example nil 'loc)
5377 (org-set-local 'header-line-format msg)
5378 (message "%s" msg)
5379 t)))
5381 (defun org-find-src-example-start ()
5382 "If point is in a src example, move to the beginning of it.
5383 If not, just return nil."
5384 (let ((re "^\\(#\\+begin_src\\|[ \t]*<src\\)")
5385 (pos (point))
5387 (beginning-of-line 1)
5388 (if (looking-at re)
5389 (point)
5390 (if (and (setq p1 (re-search-backward re nil t))
5391 (re-search-forward "^\\(#\\+end_src\\|[ \t]*</src\\)" nil t)
5392 (>= (point-at-eol) pos))
5393 (goto-char p1)
5394 (goto-char pos)
5395 nil))))
5397 (defun org-protect-source-example ()
5398 "Protect example lines with Org syntax."
5399 (unless (> (point-min) 1)
5400 (error "This buffer is not narrowed, something is wrong..."))
5401 (goto-char (point-min))
5402 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5403 (replace-match ",\\1")))
5405 ;;;; Plain list items, including checkboxes
5407 ;;; Plain list items
5409 (defun org-at-item-p ()
5410 "Is point in a line starting a hand-formatted item?"
5411 (let ((llt org-plain-list-ordered-item-terminator))
5412 (save-excursion
5413 (goto-char (point-at-bol))
5414 (looking-at
5415 (cond
5416 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5417 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5418 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5419 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5421 (defun org-in-item-p ()
5422 "It the cursor inside a plain list item.
5423 Does not have to be the first line."
5424 (save-excursion
5425 (condition-case nil
5426 (progn
5427 (org-beginning-of-item)
5428 (org-at-item-p)
5430 (error nil))))
5432 (defun org-insert-item (&optional checkbox)
5433 "Insert a new item at the current level.
5434 Return t when things worked, nil when we are not in an item."
5435 (when (save-excursion
5436 (condition-case nil
5437 (progn
5438 (org-beginning-of-item)
5439 (org-at-item-p)
5440 (if (org-invisible-p) (error "Invisible item"))
5442 (error nil)))
5443 (let* ((bul (match-string 0))
5444 (descp (save-excursion (goto-char (match-beginning 0))
5445 (beginning-of-line 1)
5446 (save-match-data
5447 (looking-at "[ \t]*.*? ::"))))
5448 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5449 (match-end 0)))
5450 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5451 pos)
5452 (if descp (setq checkbox nil))
5453 (cond
5454 ((and (org-at-item-p) (<= (point) eow))
5455 ;; before the bullet
5456 (beginning-of-line 1)
5457 (open-line (if blank 2 1)))
5458 ((<= (point) eow)
5459 (beginning-of-line 1))
5461 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5462 (end-of-line 1)
5463 (delete-horizontal-space))
5464 (newline (if blank 2 1))))
5465 (insert bul
5466 (if checkbox "[ ]" "")
5467 (if descp (concat (if checkbox " " "")
5468 (read-string "Term: ") " :: ") ""))
5469 (just-one-space)
5470 (setq pos (point))
5471 (end-of-line 1)
5472 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5473 (org-maybe-renumber-ordered-list)
5474 (and checkbox (org-update-checkbox-count-maybe))
5477 ;;; Checkboxes
5479 (defun org-at-item-checkbox-p ()
5480 "Is point at a line starting a plain-list item with a checklet?"
5481 (and (org-at-item-p)
5482 (save-excursion
5483 (goto-char (match-end 0))
5484 (skip-chars-forward " \t")
5485 (looking-at "\\[[- X]\\]"))))
5487 (defun org-toggle-checkbox (&optional arg)
5488 "Toggle the checkbox in the current line."
5489 (interactive "P")
5490 (catch 'exit
5491 (let (beg end status (firstnew 'unknown))
5492 (cond
5493 ((org-region-active-p)
5494 (setq beg (region-beginning) end (region-end)))
5495 ((org-on-heading-p)
5496 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5497 ((org-at-item-checkbox-p)
5498 (let ((pos (point)))
5499 (replace-match
5500 (cond (arg "[-]")
5501 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5502 (t "[ ]"))
5503 t t)
5504 (goto-char pos))
5505 (throw 'exit t))
5506 (t (error "Not at a checkbox or heading, and no active region")))
5507 (save-excursion
5508 (goto-char beg)
5509 (while (< (point) end)
5510 (when (org-at-item-checkbox-p)
5511 (setq status (equal (match-string 0) "[X]"))
5512 (when (eq firstnew 'unknown)
5513 (setq firstnew (not status)))
5514 (replace-match
5515 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5516 (beginning-of-line 2)))))
5517 (org-update-checkbox-count-maybe))
5519 (defun org-update-checkbox-count-maybe ()
5520 "Update checkbox statistics unless turned off by user."
5521 (when org-provide-checkbox-statistics
5522 (org-update-checkbox-count)))
5524 (defun org-update-checkbox-count (&optional all)
5525 "Update the checkbox statistics in the current section.
5526 This will find all statistic cookies like [57%] and [6/12] and update them
5527 with the current numbers. With optional prefix argument ALL, do this for
5528 the whole buffer."
5529 (interactive "P")
5530 (save-excursion
5531 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5532 (beg (condition-case nil
5533 (progn (outline-back-to-heading) (point))
5534 (error (point-min))))
5535 (end (move-marker (make-marker)
5536 (progn (outline-next-heading) (point))))
5537 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5538 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5539 (re-find (concat re "\\|" re-box))
5540 beg-cookie end-cookie is-percent c-on c-off lim
5541 eline curr-ind next-ind continue-from startsearch
5542 (cstat 0)
5544 (when all
5545 (goto-char (point-min))
5546 (outline-next-heading)
5547 (setq beg (point) end (point-max)))
5548 (goto-char end)
5549 ;; find each statistic cookie
5550 (while (re-search-backward re-find beg t)
5551 (setq beg-cookie (match-beginning 1)
5552 end-cookie (match-end 1)
5553 cstat (+ cstat (if end-cookie 1 0))
5554 startsearch (point-at-eol)
5555 continue-from (point-at-bol)
5556 is-percent (match-beginning 2)
5557 lim (cond
5558 ((org-on-heading-p) (outline-next-heading) (point))
5559 ((org-at-item-p) (org-end-of-item) (point))
5560 (t nil))
5561 c-on 0
5562 c-off 0)
5563 (when lim
5564 ;; find first checkbox for this cookie and gather
5565 ;; statistics from all that are at this indentation level
5566 (goto-char startsearch)
5567 (if (re-search-forward re-box lim t)
5568 (progn
5569 (org-beginning-of-item)
5570 (setq curr-ind (org-get-indentation))
5571 (setq next-ind curr-ind)
5572 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5573 (save-excursion (end-of-line) (setq eline (point)))
5574 (if (re-search-forward re-box eline t)
5575 (if (member (match-string 2) '("[ ]" "[-]"))
5576 (setq c-off (1+ c-off))
5577 (setq c-on (1+ c-on))
5580 (org-end-of-item)
5581 (setq next-ind (org-get-indentation))
5583 (goto-char continue-from)
5584 ;; update cookie
5585 (when end-cookie
5586 (delete-region beg-cookie end-cookie)
5587 (goto-char beg-cookie)
5588 (insert
5589 (if is-percent
5590 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5591 (format "[%d/%d]" c-on (+ c-on c-off)))))
5592 ;; update items checkbox if it has one
5593 (when (org-at-item-p)
5594 (org-beginning-of-item)
5595 (when (and (> (+ c-on c-off) 0)
5596 (re-search-forward re-box (point-at-eol) t))
5597 (setq beg-cookie (match-beginning 2)
5598 end-cookie (match-end 2))
5599 (delete-region beg-cookie end-cookie)
5600 (goto-char beg-cookie)
5601 (cond ((= c-off 0) (insert "[X]"))
5602 ((= c-on 0) (insert "[ ]"))
5603 (t (insert "[-]")))
5605 (goto-char continue-from))
5606 (when (interactive-p)
5607 (message "Checkbox satistics updated %s (%d places)"
5608 (if all "in entire file" "in current outline entry") cstat)))))
5610 (defun org-get-checkbox-statistics-face ()
5611 "Select the face for checkbox statistics.
5612 The face will be `org-done' when all relevant boxes are checked. Otherwise
5613 it will be `org-todo'."
5614 (if (match-end 1)
5615 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5616 (if (and (> (match-end 2) (match-beginning 2))
5617 (equal (match-string 2) (match-string 3)))
5618 'org-done
5619 'org-todo)))
5621 (defun org-get-indentation (&optional line)
5622 "Get the indentation of the current line, interpreting tabs.
5623 When LINE is given, assume it represents a line and compute its indentation."
5624 (if line
5625 (if (string-match "^ *" (org-remove-tabs line))
5626 (match-end 0))
5627 (save-excursion
5628 (beginning-of-line 1)
5629 (skip-chars-forward " \t")
5630 (current-column))))
5632 (defun org-remove-tabs (s &optional width)
5633 "Replace tabulators in S with spaces.
5634 Assumes that s is a single line, starting in column 0."
5635 (setq width (or width tab-width))
5636 (while (string-match "\t" s)
5637 (setq s (replace-match
5638 (make-string
5639 (- (* width (/ (+ (match-beginning 0) width) width))
5640 (match-beginning 0)) ?\ )
5641 t t s)))
5644 (defun org-fix-indentation (line ind)
5645 "Fix indentation in LINE.
5646 IND is a cons cell with target and minimum indentation.
5647 If the current indenation in LINE is smaller than the minimum,
5648 leave it alone. If it is larger than ind, set it to the target."
5649 (let* ((l (org-remove-tabs line))
5650 (i (org-get-indentation l))
5651 (i1 (car ind)) (i2 (cdr ind)))
5652 (if (>= i i2) (setq l (substring line i2)))
5653 (if (> i1 0)
5654 (concat (make-string i1 ?\ ) l)
5655 l)))
5657 (defun org-beginning-of-item ()
5658 "Go to the beginning of the current hand-formatted item.
5659 If the cursor is not in an item, throw an error."
5660 (interactive)
5661 (let ((pos (point))
5662 (limit (save-excursion
5663 (condition-case nil
5664 (progn
5665 (org-back-to-heading)
5666 (beginning-of-line 2) (point))
5667 (error (point-min)))))
5668 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5669 ind ind1)
5670 (if (org-at-item-p)
5671 (beginning-of-line 1)
5672 (beginning-of-line 1)
5673 (skip-chars-forward " \t")
5674 (setq ind (current-column))
5675 (if (catch 'exit
5676 (while t
5677 (beginning-of-line 0)
5678 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5680 (if (looking-at "[ \t]*$")
5681 (setq ind1 ind-empty)
5682 (skip-chars-forward " \t")
5683 (setq ind1 (current-column)))
5684 (if (< ind1 ind)
5685 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5687 (goto-char pos)
5688 (error "Not in an item")))))
5690 (defun org-end-of-item ()
5691 "Go to the end of the current hand-formatted item.
5692 If the cursor is not in an item, throw an error."
5693 (interactive)
5694 (let* ((pos (point))
5695 ind1
5696 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5697 (limit (save-excursion (outline-next-heading) (point)))
5698 (ind (save-excursion
5699 (org-beginning-of-item)
5700 (skip-chars-forward " \t")
5701 (current-column)))
5702 (end (catch 'exit
5703 (while t
5704 (beginning-of-line 2)
5705 (if (eobp) (throw 'exit (point)))
5706 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5707 (if (looking-at "[ \t]*$")
5708 (setq ind1 ind-empty)
5709 (skip-chars-forward " \t")
5710 (setq ind1 (current-column)))
5711 (if (<= ind1 ind)
5712 (throw 'exit (point-at-bol)))))))
5713 (if end
5714 (goto-char end)
5715 (goto-char pos)
5716 (error "Not in an item"))))
5718 (defun org-next-item ()
5719 "Move to the beginning of the next item in the current plain list.
5720 Error if not at a plain list, or if this is the last item in the list."
5721 (interactive)
5722 (let (ind ind1 (pos (point)))
5723 (org-beginning-of-item)
5724 (setq ind (org-get-indentation))
5725 (org-end-of-item)
5726 (setq ind1 (org-get-indentation))
5727 (unless (and (org-at-item-p) (= ind ind1))
5728 (goto-char pos)
5729 (error "On last item"))))
5731 (defun org-previous-item ()
5732 "Move to the beginning of the previous item in the current plain list.
5733 Error if not at a plain list, or if this is the first item in the list."
5734 (interactive)
5735 (let (beg ind ind1 (pos (point)))
5736 (org-beginning-of-item)
5737 (setq beg (point))
5738 (setq ind (org-get-indentation))
5739 (goto-char beg)
5740 (catch 'exit
5741 (while t
5742 (beginning-of-line 0)
5743 (if (looking-at "[ \t]*$")
5745 (if (<= (setq ind1 (org-get-indentation)) ind)
5746 (throw 'exit t)))))
5747 (condition-case nil
5748 (if (or (not (org-at-item-p))
5749 (< ind1 (1- ind)))
5750 (error "")
5751 (org-beginning-of-item))
5752 (error (goto-char pos)
5753 (error "On first item")))))
5755 (defun org-first-list-item-p ()
5756 "Is this heading the item in a plain list?"
5757 (unless (org-at-item-p)
5758 (error "Not at a plain list item"))
5759 (org-beginning-of-item)
5760 (= (point) (save-excursion (org-beginning-of-item-list))))
5762 (defun org-move-item-down ()
5763 "Move the plain list item at point down, i.e. swap with following item.
5764 Subitems (items with larger indentation) are considered part of the item,
5765 so this really moves item trees."
5766 (interactive)
5767 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5768 (org-beginning-of-item)
5769 (setq beg0 (point))
5770 (save-excursion
5771 (setq ne-beg (org-back-over-empty-lines))
5772 (setq beg (point)))
5773 (goto-char beg0)
5774 (setq ind (org-get-indentation))
5775 (org-end-of-item)
5776 (setq end0 (point))
5777 (setq ind1 (org-get-indentation))
5778 (setq ne-end (org-back-over-empty-lines))
5779 (setq end (point))
5780 (goto-char beg0)
5781 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5782 ;; include less whitespace
5783 (save-excursion
5784 (goto-char beg)
5785 (forward-line (- ne-beg ne-end))
5786 (setq beg (point))))
5787 (goto-char end0)
5788 (if (and (org-at-item-p) (= ind ind1))
5789 (progn
5790 (org-end-of-item)
5791 (org-back-over-empty-lines)
5792 (setq txt (buffer-substring beg end))
5793 (save-excursion
5794 (delete-region beg end))
5795 (setq pos (point))
5796 (insert txt)
5797 (goto-char pos) (org-skip-whitespace)
5798 (org-maybe-renumber-ordered-list))
5799 (goto-char pos)
5800 (error "Cannot move this item further down"))))
5802 (defun org-move-item-up (arg)
5803 "Move the plain list item at point up, i.e. swap with previous item.
5804 Subitems (items with larger indentation) are considered part of the item,
5805 so this really moves item trees."
5806 (interactive "p")
5807 (let (beg beg0 end ind ind1 (pos (point)) txt
5808 ne-beg ne-ins ins-end)
5809 (org-beginning-of-item)
5810 (setq beg0 (point))
5811 (setq ind (org-get-indentation))
5812 (save-excursion
5813 (setq ne-beg (org-back-over-empty-lines))
5814 (setq beg (point)))
5815 (goto-char beg0)
5816 (org-end-of-item)
5817 (setq end (point))
5818 (goto-char beg0)
5819 (catch 'exit
5820 (while t
5821 (beginning-of-line 0)
5822 (if (looking-at "[ \t]*$")
5823 (if org-empty-line-terminates-plain-lists
5824 (progn
5825 (goto-char pos)
5826 (error "Cannot move this item further up"))
5827 nil)
5828 (if (<= (setq ind1 (org-get-indentation)) ind)
5829 (throw 'exit t)))))
5830 (condition-case nil
5831 (org-beginning-of-item)
5832 (error (goto-char beg)
5833 (error "Cannot move this item further up")))
5834 (setq ind1 (org-get-indentation))
5835 (if (and (org-at-item-p) (= ind ind1))
5836 (progn
5837 (setq ne-ins (org-back-over-empty-lines))
5838 (setq txt (buffer-substring beg end))
5839 (save-excursion
5840 (delete-region beg end))
5841 (setq pos (point))
5842 (insert txt)
5843 (setq ins-end (point))
5844 (goto-char pos) (org-skip-whitespace)
5846 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5847 ;; Move whitespace back to beginning
5848 (save-excursion
5849 (goto-char ins-end)
5850 (let ((kill-whole-line t))
5851 (kill-line (- ne-ins ne-beg)) (point)))
5852 (insert (make-string (- ne-ins ne-beg) ?\n)))
5854 (org-maybe-renumber-ordered-list))
5855 (goto-char pos)
5856 (error "Cannot move this item further up"))))
5858 (defun org-maybe-renumber-ordered-list ()
5859 "Renumber the ordered list at point if setup allows it.
5860 This tests the user option `org-auto-renumber-ordered-lists' before
5861 doing the renumbering."
5862 (interactive)
5863 (when (and org-auto-renumber-ordered-lists
5864 (org-at-item-p))
5865 (if (match-beginning 3)
5866 (org-renumber-ordered-list 1)
5867 (org-fix-bullet-type))))
5869 (defun org-maybe-renumber-ordered-list-safe ()
5870 (condition-case nil
5871 (save-excursion
5872 (org-maybe-renumber-ordered-list))
5873 (error nil)))
5875 (defun org-cycle-list-bullet (&optional which)
5876 "Cycle through the different itemize/enumerate bullets.
5877 This cycle the entire list level through the sequence:
5879 `-' -> `+' -> `*' -> `1.' -> `1)'
5881 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5882 0 meand `-', 1 means `+' etc."
5883 (interactive "P")
5884 (org-preserve-lc
5885 (org-beginning-of-item-list)
5886 (org-at-item-p)
5887 (beginning-of-line 1)
5888 (let ((current (match-string 0))
5889 (prevp (eq which 'previous))
5890 new)
5891 (setq new (cond
5892 ((and (numberp which)
5893 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5894 ((string-match "-" current) (if prevp "1)" "+"))
5895 ((string-match "\\+" current)
5896 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5897 ((string-match "\\*" current) (if prevp "+" "1."))
5898 ((string-match "\\." current) (if prevp "*" "1)"))
5899 ((string-match ")" current) (if prevp "1." "-"))
5900 (t (error "This should not happen"))))
5901 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5902 (org-fix-bullet-type)
5903 (org-maybe-renumber-ordered-list))))
5905 (defun org-get-string-indentation (s)
5906 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5907 (let ((n -1) (i 0) (w tab-width) c)
5908 (catch 'exit
5909 (while (< (setq n (1+ n)) (length s))
5910 (setq c (aref s n))
5911 (cond ((= c ?\ ) (setq i (1+ i)))
5912 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5913 (t (throw 'exit t)))))
5916 (defun org-renumber-ordered-list (arg)
5917 "Renumber an ordered plain list.
5918 Cursor needs to be in the first line of an item, the line that starts
5919 with something like \"1.\" or \"2)\"."
5920 (interactive "p")
5921 (unless (and (org-at-item-p)
5922 (match-beginning 3))
5923 (error "This is not an ordered list"))
5924 (let ((line (org-current-line))
5925 (col (current-column))
5926 (ind (org-get-string-indentation
5927 (buffer-substring (point-at-bol) (match-beginning 3))))
5928 ;; (term (substring (match-string 3) -1))
5929 ind1 (n (1- arg))
5930 fmt)
5931 ;; find where this list begins
5932 (org-beginning-of-item-list)
5933 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5934 (setq fmt (concat "%d" (match-string 1)))
5935 (beginning-of-line 0)
5936 ;; walk forward and replace these numbers
5937 (catch 'exit
5938 (while t
5939 (catch 'next
5940 (beginning-of-line 2)
5941 (if (eobp) (throw 'exit nil))
5942 (if (looking-at "[ \t]*$") (throw 'next nil))
5943 (skip-chars-forward " \t") (setq ind1 (current-column))
5944 (if (> ind1 ind) (throw 'next t))
5945 (if (< ind1 ind) (throw 'exit t))
5946 (if (not (org-at-item-p)) (throw 'exit nil))
5947 (delete-region (match-beginning 2) (match-end 2))
5948 (goto-char (match-beginning 2))
5949 (insert (format fmt (setq n (1+ n)))))))
5950 (goto-line line)
5951 (org-move-to-column col)))
5953 (defun org-fix-bullet-type ()
5954 "Make sure all items in this list have the same bullet as the firsst item."
5955 (interactive)
5956 (unless (org-at-item-p) (error "This is not a list"))
5957 (let ((line (org-current-line))
5958 (col (current-column))
5959 (ind (current-indentation))
5960 ind1 bullet)
5961 ;; find where this list begins
5962 (org-beginning-of-item-list)
5963 (beginning-of-line 1)
5964 ;; find out what the bullet type is
5965 (looking-at "[ \t]*\\(\\S-+\\)")
5966 (setq bullet (match-string 1))
5967 ;; walk forward and replace these numbers
5968 (beginning-of-line 0)
5969 (catch 'exit
5970 (while t
5971 (catch 'next
5972 (beginning-of-line 2)
5973 (if (eobp) (throw 'exit nil))
5974 (if (looking-at "[ \t]*$") (throw 'next nil))
5975 (skip-chars-forward " \t") (setq ind1 (current-column))
5976 (if (> ind1 ind) (throw 'next t))
5977 (if (< ind1 ind) (throw 'exit t))
5978 (if (not (org-at-item-p)) (throw 'exit nil))
5979 (skip-chars-forward " \t")
5980 (looking-at "\\S-+")
5981 (replace-match bullet))))
5982 (goto-line line)
5983 (org-move-to-column col)
5984 (if (string-match "[0-9]" bullet)
5985 (org-renumber-ordered-list 1))))
5987 (defun org-beginning-of-item-list ()
5988 "Go to the beginning of the current item list.
5989 I.e. to the first item in this list."
5990 (interactive)
5991 (org-beginning-of-item)
5992 (let ((pos (point-at-bol))
5993 (ind (org-get-indentation))
5994 ind1)
5995 ;; find where this list begins
5996 (catch 'exit
5997 (while t
5998 (catch 'next
5999 (beginning-of-line 0)
6000 (if (looking-at "[ \t]*$")
6001 (throw (if (bobp) 'exit 'next) t))
6002 (skip-chars-forward " \t") (setq ind1 (current-column))
6003 (if (or (< ind1 ind)
6004 (and (= ind1 ind)
6005 (not (org-at-item-p)))
6006 (bobp))
6007 (throw 'exit t)
6008 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6009 (goto-char pos)))
6012 (defun org-end-of-item-list ()
6013 "Go to the end of the current item list.
6014 I.e. to the text after the last item."
6015 (interactive)
6016 (org-beginning-of-item)
6017 (let ((pos (point-at-bol))
6018 (ind (org-get-indentation))
6019 ind1)
6020 ;; find where this list begins
6021 (catch 'exit
6022 (while t
6023 (catch 'next
6024 (beginning-of-line 2)
6025 (if (looking-at "[ \t]*$")
6026 (throw (if (eobp) 'exit 'next) t))
6027 (skip-chars-forward " \t") (setq ind1 (current-column))
6028 (if (or (< ind1 ind)
6029 (and (= ind1 ind)
6030 (not (org-at-item-p)))
6031 (eobp))
6032 (progn
6033 (setq pos (point-at-bol))
6034 (throw 'exit t))))))
6035 (goto-char pos)))
6038 (defvar org-last-indent-begin-marker (make-marker))
6039 (defvar org-last-indent-end-marker (make-marker))
6041 (defun org-outdent-item (arg)
6042 "Outdent a local list item."
6043 (interactive "p")
6044 (org-indent-item (- arg)))
6046 (defun org-indent-item (arg)
6047 "Indent a local list item."
6048 (interactive "p")
6049 (unless (org-at-item-p)
6050 (error "Not on an item"))
6051 (save-excursion
6052 (let (beg end ind ind1 tmp delta ind-down ind-up)
6053 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6054 (setq beg org-last-indent-begin-marker
6055 end org-last-indent-end-marker)
6056 (org-beginning-of-item)
6057 (setq beg (move-marker org-last-indent-begin-marker (point)))
6058 (org-end-of-item)
6059 (setq end (move-marker org-last-indent-end-marker (point))))
6060 (goto-char beg)
6061 (setq tmp (org-item-indent-positions)
6062 ind (car tmp)
6063 ind-down (nth 2 tmp)
6064 ind-up (nth 1 tmp)
6065 delta (if (> arg 0)
6066 (if ind-down (- ind-down ind) 2)
6067 (if ind-up (- ind-up ind) -2)))
6068 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6069 (while (< (point) end)
6070 (beginning-of-line 1)
6071 (skip-chars-forward " \t") (setq ind1 (current-column))
6072 (delete-region (point-at-bol) (point))
6073 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6074 (beginning-of-line 2))))
6075 (org-fix-bullet-type)
6076 (org-maybe-renumber-ordered-list-safe)
6077 (save-excursion
6078 (beginning-of-line 0)
6079 (condition-case nil (org-beginning-of-item) (error nil))
6080 (org-maybe-renumber-ordered-list-safe)))
6082 (defun org-item-indent-positions ()
6083 "Return indentation for plain list items.
6084 This returns a list with three values: The current indentation, the
6085 parent indentation and the indentation a child should habe.
6086 Assumes cursor in item line."
6087 (let* ((bolpos (point-at-bol))
6088 (ind (org-get-indentation))
6089 ind-down ind-up pos)
6090 (save-excursion
6091 (org-beginning-of-item-list)
6092 (skip-chars-backward "\n\r \t")
6093 (when (org-in-item-p)
6094 (org-beginning-of-item)
6095 (setq ind-up (org-get-indentation))))
6096 (setq pos (point))
6097 (save-excursion
6098 (cond
6099 ((and (condition-case nil (progn (org-previous-item) t)
6100 (error nil))
6101 (or (forward-char 1) t)
6102 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6103 (setq ind-down (org-get-indentation)))
6104 ((and (goto-char pos)
6105 (org-at-item-p))
6106 (goto-char (match-end 0))
6107 (skip-chars-forward " \t")
6108 (setq ind-down (current-column)))))
6109 (list ind ind-up ind-down)))
6111 ;;; The orgstruct minor mode
6113 ;; Define a minor mode which can be used in other modes in order to
6114 ;; integrate the org-mode structure editing commands.
6116 ;; This is really a hack, because the org-mode structure commands use
6117 ;; keys which normally belong to the major mode. Here is how it
6118 ;; works: The minor mode defines all the keys necessary to operate the
6119 ;; structure commands, but wraps the commands into a function which
6120 ;; tests if the cursor is currently at a headline or a plain list
6121 ;; item. If that is the case, the structure command is used,
6122 ;; temporarily setting many Org-mode variables like regular
6123 ;; expressions for filling etc. However, when any of those keys is
6124 ;; used at a different location, function uses `key-binding' to look
6125 ;; up if the key has an associated command in another currently active
6126 ;; keymap (minor modes, major mode, global), and executes that
6127 ;; command. There might be problems if any of the keys is otherwise
6128 ;; used as a prefix key.
6130 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6131 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6132 ;; addresses this by checking explicitly for both bindings.
6134 (defvar orgstruct-mode-map (make-sparse-keymap)
6135 "Keymap for the minor `orgstruct-mode'.")
6137 (defvar org-local-vars nil
6138 "List of local variables, for use by `orgstruct-mode'")
6140 ;;;###autoload
6141 (define-minor-mode orgstruct-mode
6142 "Toggle the minor more `orgstruct-mode'.
6143 This mode is for using Org-mode structure commands in other modes.
6144 The following key behave as if Org-mode was active, if the cursor
6145 is on a headline, or on a plain list item (both in the definition
6146 of Org-mode).
6148 M-up Move entry/item up
6149 M-down Move entry/item down
6150 M-left Promote
6151 M-right Demote
6152 M-S-up Move entry/item up
6153 M-S-down Move entry/item down
6154 M-S-left Promote subtree
6155 M-S-right Demote subtree
6156 M-q Fill paragraph and items like in Org-mode
6157 C-c ^ Sort entries
6158 C-c - Cycle list bullet
6159 TAB Cycle item visibility
6160 M-RET Insert new heading/item
6161 S-M-RET Insert new TODO heading / Chekbox item
6162 C-c C-c Set tags / toggle checkbox"
6163 nil " OrgStruct" nil
6164 (org-load-modules-maybe)
6165 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6167 ;;;###autoload
6168 (defun turn-on-orgstruct ()
6169 "Unconditionally turn on `orgstruct-mode'."
6170 (orgstruct-mode 1))
6172 ;;;###autoload
6173 (defun turn-on-orgstruct++ ()
6174 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6175 In addition to setting orgstruct-mode, this also exports all indentation and
6176 autofilling variables from org-mode into the buffer. Note that turning
6177 off orgstruct-mode will *not* remove these additional settings."
6178 (orgstruct-mode 1)
6179 (let (var val)
6180 (mapc
6181 (lambda (x)
6182 (when (string-match
6183 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6184 (symbol-name (car x)))
6185 (setq var (car x) val (nth 1 x))
6186 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6187 org-local-vars)))
6189 (defun orgstruct-error ()
6190 "Error when there is no default binding for a structure key."
6191 (interactive)
6192 (error "This key has no function outside structure elements"))
6194 (defun orgstruct-setup ()
6195 "Setup orgstruct keymaps."
6196 (let ((nfunc 0)
6197 (bindings
6198 (list
6199 '([(meta up)] org-metaup)
6200 '([(meta down)] org-metadown)
6201 '([(meta left)] org-metaleft)
6202 '([(meta right)] org-metaright)
6203 '([(meta shift up)] org-shiftmetaup)
6204 '([(meta shift down)] org-shiftmetadown)
6205 '([(meta shift left)] org-shiftmetaleft)
6206 '([(meta shift right)] org-shiftmetaright)
6207 '([(shift up)] org-shiftup)
6208 '([(shift down)] org-shiftdown)
6209 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6210 '("\M-q" fill-paragraph)
6211 '("\C-c^" org-sort)
6212 '("\C-c-" org-cycle-list-bullet)))
6213 elt key fun cmd)
6214 (while (setq elt (pop bindings))
6215 (setq nfunc (1+ nfunc))
6216 (setq key (org-key (car elt))
6217 fun (nth 1 elt)
6218 cmd (orgstruct-make-binding fun nfunc key))
6219 (org-defkey orgstruct-mode-map key cmd))
6221 ;; Special treatment needed for TAB and RET
6222 (org-defkey orgstruct-mode-map [(tab)]
6223 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6224 (org-defkey orgstruct-mode-map "\C-i"
6225 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6227 (org-defkey orgstruct-mode-map "\M-\C-m"
6228 (orgstruct-make-binding 'org-insert-heading 105
6229 "\M-\C-m" [(meta return)]))
6230 (org-defkey orgstruct-mode-map [(meta return)]
6231 (orgstruct-make-binding 'org-insert-heading 106
6232 [(meta return)] "\M-\C-m"))
6234 (org-defkey orgstruct-mode-map [(shift meta return)]
6235 (orgstruct-make-binding 'org-insert-todo-heading 107
6236 [(meta return)] "\M-\C-m"))
6238 (unless org-local-vars
6239 (setq org-local-vars (org-get-local-variables)))
6243 (defun orgstruct-make-binding (fun n &rest keys)
6244 "Create a function for binding in the structure minor mode.
6245 FUN is the command to call inside a table. N is used to create a unique
6246 command name. KEYS are keys that should be checked in for a command
6247 to execute outside of tables."
6248 (eval
6249 (list 'defun
6250 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6251 '(arg)
6252 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6253 "Outside of structure, run the binding of `"
6254 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6255 "'.")
6256 '(interactive "p")
6257 (list 'if
6258 '(org-context-p 'headline 'item)
6259 (list 'org-run-like-in-org-mode (list 'quote fun))
6260 (list 'let '(orgstruct-mode)
6261 (list 'call-interactively
6262 (append '(or)
6263 (mapcar (lambda (k)
6264 (list 'key-binding k))
6265 keys)
6266 '('orgstruct-error))))))))
6268 (defun org-context-p (&rest contexts)
6269 "Check if local context is and of CONTEXTS.
6270 Possible values in the list of contexts are `table', `headline', and `item'."
6271 (let ((pos (point)))
6272 (goto-char (point-at-bol))
6273 (prog1 (or (and (memq 'table contexts)
6274 (looking-at "[ \t]*|"))
6275 (and (memq 'headline contexts)
6276 (looking-at "\\*+"))
6277 (and (memq 'item contexts)
6278 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6279 (goto-char pos))))
6281 (defun org-get-local-variables ()
6282 "Return a list of all local variables in an org-mode buffer."
6283 (let (varlist)
6284 (with-current-buffer (get-buffer-create "*Org tmp*")
6285 (erase-buffer)
6286 (org-mode)
6287 (setq varlist (buffer-local-variables)))
6288 (kill-buffer "*Org tmp*")
6289 (delq nil
6290 (mapcar
6291 (lambda (x)
6292 (setq x
6293 (if (symbolp x)
6294 (list x)
6295 (list (car x) (list 'quote (cdr x)))))
6296 (if (string-match
6297 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6298 (symbol-name (car x)))
6299 x nil))
6300 varlist))))
6302 ;;;###autoload
6303 (defun org-run-like-in-org-mode (cmd)
6304 (org-load-modules-maybe)
6305 (unless org-local-vars
6306 (setq org-local-vars (org-get-local-variables)))
6307 (eval (list 'let org-local-vars
6308 (list 'call-interactively (list 'quote cmd)))))
6310 ;;;; Archiving
6312 (defun org-get-category (&optional pos)
6313 "Get the category applying to position POS."
6314 (get-text-property (or pos (point)) 'org-category))
6316 (defun org-refresh-category-properties ()
6317 "Refresh category text properties in the buffer."
6318 (let ((def-cat (cond
6319 ((null org-category)
6320 (if buffer-file-name
6321 (file-name-sans-extension
6322 (file-name-nondirectory buffer-file-name))
6323 "???"))
6324 ((symbolp org-category) (symbol-name org-category))
6325 (t org-category)))
6326 beg end cat pos optionp)
6327 (org-unmodified
6328 (save-excursion
6329 (save-restriction
6330 (widen)
6331 (goto-char (point-min))
6332 (put-text-property (point) (point-max) 'org-category def-cat)
6333 (while (re-search-forward
6334 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6335 (setq pos (match-end 0)
6336 optionp (equal (char-after (match-beginning 0)) ?#)
6337 cat (org-trim (match-string 2)))
6338 (if optionp
6339 (setq beg (point-at-bol) end (point-max))
6340 (org-back-to-heading t)
6341 (setq beg (point) end (org-end-of-subtree t t)))
6342 (put-text-property beg end 'org-category cat)
6343 (goto-char pos)))))))
6346 ;;;; Link Stuff
6348 ;;; Link abbreviations
6350 (defun org-link-expand-abbrev (link)
6351 "Apply replacements as defined in `org-link-abbrev-alist."
6352 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6353 (let* ((key (match-string 1 link))
6354 (as (or (assoc key org-link-abbrev-alist-local)
6355 (assoc key org-link-abbrev-alist)))
6356 (tag (and (match-end 2) (match-string 3 link)))
6357 rpl)
6358 (if (not as)
6359 link
6360 (setq rpl (cdr as))
6361 (cond
6362 ((symbolp rpl) (funcall rpl tag))
6363 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6364 (t (concat rpl tag)))))
6365 link))
6367 ;;; Storing and inserting links
6369 (defvar org-insert-link-history nil
6370 "Minibuffer history for links inserted with `org-insert-link'.")
6372 (defvar org-stored-links nil
6373 "Contains the links stored with `org-store-link'.")
6375 (defvar org-store-link-plist nil
6376 "Plist with info about the most recently link created with `org-store-link'.")
6378 (defvar org-link-protocols nil
6379 "Link protocols added to Org-mode using `org-add-link-type'.")
6381 (defvar org-store-link-functions nil
6382 "List of functions that are called to create and store a link.
6383 Each function will be called in turn until one returns a non-nil
6384 value. Each function should check if it is responsible for creating
6385 this link (for example by looking at the major mode).
6386 If not, it must exit and return nil.
6387 If yes, it should return a non-nil value after a calling
6388 `org-store-link-props' with a list of properties and values.
6389 Special properties are:
6391 :type The link prefix. like \"http\". This must be given.
6392 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6393 This is obligatory as well.
6394 :description Optional default description for the second pair
6395 of brackets in an Org-mode link. The user can still change
6396 this when inserting this link into an Org-mode buffer.
6398 In addition to these, any additional properties can be specified
6399 and then used in remember templates.")
6401 (defun org-add-link-type (type &optional follow export)
6402 "Add TYPE to the list of `org-link-types'.
6403 Re-compute all regular expressions depending on `org-link-types'
6405 FOLLOW and EXPORT are two functions.
6407 FOLLOW should take the link path as the single argument and do whatever
6408 is necessary to follow the link, for example find a file or display
6409 a mail message.
6411 EXPORT should format the link path for export to one of the export formats.
6412 It should be a function accepting three arguments:
6414 path the path of the link, the text after the prefix (like \"http:\")
6415 desc the description of the link, if any, nil if there was no descripton
6416 format the export format, a symbol like `html' or `latex'.
6418 The function may use the FORMAT information to return different values
6419 depending on the format. The return value will be put literally into
6420 the exported file.
6421 Org-mode has a built-in default for exporting links. If you are happy with
6422 this default, there is no need to define an export function for the link
6423 type. For a simple example of an export function, see `org-bbdb.el'."
6424 (add-to-list 'org-link-types type t)
6425 (org-make-link-regexps)
6426 (if (assoc type org-link-protocols)
6427 (setcdr (assoc type org-link-protocols) (list follow export))
6428 (push (list type follow export) org-link-protocols)))
6431 ;;;###autoload
6432 (defun org-store-link (arg)
6433 "\\<org-mode-map>Store an org-link to the current location.
6434 This link is added to `org-stored-links' and can later be inserted
6435 into an org-buffer with \\[org-insert-link].
6437 For some link types, a prefix arg is interpreted:
6438 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6439 For file links, arg negates `org-context-in-file-links'."
6440 (interactive "P")
6441 (org-load-modules-maybe)
6442 (setq org-store-link-plist nil) ; reset
6443 (let (link cpltxt desc description search txt)
6444 (cond
6446 ((run-hook-with-args-until-success 'org-store-link-functions)
6447 (setq link (plist-get org-store-link-plist :link)
6448 desc (or (plist-get org-store-link-plist :description) link)))
6450 ((eq major-mode 'calendar-mode)
6451 (let ((cd (calendar-cursor-to-date)))
6452 (setq link
6453 (format-time-string
6454 (car org-time-stamp-formats)
6455 (apply 'encode-time
6456 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6457 nil nil nil))))
6458 (org-store-link-props :type "calendar" :date cd)))
6460 ((eq major-mode 'w3-mode)
6461 (setq cpltxt (url-view-url t)
6462 link (org-make-link cpltxt))
6463 (org-store-link-props :type "w3" :url (url-view-url t)))
6465 ((eq major-mode 'w3m-mode)
6466 (setq cpltxt (or w3m-current-title w3m-current-url)
6467 link (org-make-link w3m-current-url))
6468 (org-store-link-props :type "w3m" :url (url-view-url t)))
6470 ((setq search (run-hook-with-args-until-success
6471 'org-create-file-search-functions))
6472 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6473 "::" search))
6474 (setq cpltxt (or description link)))
6476 ((eq major-mode 'image-mode)
6477 (setq cpltxt (concat "file:"
6478 (abbreviate-file-name buffer-file-name))
6479 link (org-make-link cpltxt))
6480 (org-store-link-props :type "image" :file buffer-file-name))
6482 ((eq major-mode 'dired-mode)
6483 ;; link to the file in the current line
6484 (setq cpltxt (concat "file:"
6485 (abbreviate-file-name
6486 (expand-file-name
6487 (dired-get-filename nil t))))
6488 link (org-make-link cpltxt)))
6490 ((and buffer-file-name (org-mode-p))
6491 ;; Just link to current headline
6492 (setq cpltxt (concat "file:"
6493 (abbreviate-file-name buffer-file-name)))
6494 ;; Add a context search string
6495 (when (org-xor org-context-in-file-links arg)
6496 ;; Check if we are on a target
6497 (if (org-in-regexp "<<\\(.*?\\)>>")
6498 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6499 (setq txt (cond
6500 ((org-on-heading-p) nil)
6501 ((org-region-active-p)
6502 (buffer-substring (region-beginning) (region-end)))
6503 (t nil)))
6504 (when (or (null txt) (string-match "\\S-" txt))
6505 (setq cpltxt
6506 (concat cpltxt "::"
6507 (condition-case nil
6508 (org-make-org-heading-search-string txt)
6509 (error "")))
6510 desc "NONE"))))
6511 (if (string-match "::\\'" cpltxt)
6512 (setq cpltxt (substring cpltxt 0 -2)))
6513 (setq link (org-make-link cpltxt)))
6515 ((buffer-file-name (buffer-base-buffer))
6516 ;; Just link to this file here.
6517 (setq cpltxt (concat "file:"
6518 (abbreviate-file-name
6519 (buffer-file-name (buffer-base-buffer)))))
6520 ;; Add a context string
6521 (when (org-xor org-context-in-file-links arg)
6522 (setq txt (if (org-region-active-p)
6523 (buffer-substring (region-beginning) (region-end))
6524 (buffer-substring (point-at-bol) (point-at-eol))))
6525 ;; Only use search option if there is some text.
6526 (when (string-match "\\S-" txt)
6527 (setq cpltxt
6528 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6529 desc "NONE")))
6530 (setq link (org-make-link cpltxt)))
6532 ((interactive-p)
6533 (error "Cannot link to a buffer which is not visiting a file"))
6535 (t (setq link nil)))
6537 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6538 (setq link (or link cpltxt)
6539 desc (or desc cpltxt))
6540 (if (equal desc "NONE") (setq desc nil))
6542 (if (and (interactive-p) link)
6543 (progn
6544 (setq org-stored-links
6545 (cons (list link desc) org-stored-links))
6546 (message "Stored: %s" (or desc link)))
6547 (and link (org-make-link-string link desc)))))
6549 (defun org-store-link-props (&rest plist)
6550 "Store link properties, extract names and addresses."
6551 (let (x adr)
6552 (when (setq x (plist-get plist :from))
6553 (setq adr (mail-extract-address-components x))
6554 (plist-put plist :fromname (car adr))
6555 (plist-put plist :fromaddress (nth 1 adr)))
6556 (when (setq x (plist-get plist :to))
6557 (setq adr (mail-extract-address-components x))
6558 (plist-put plist :toname (car adr))
6559 (plist-put plist :toaddress (nth 1 adr))))
6560 (let ((from (plist-get plist :from))
6561 (to (plist-get plist :to)))
6562 (when (and from to org-from-is-user-regexp)
6563 (plist-put plist :fromto
6564 (if (string-match org-from-is-user-regexp from)
6565 (concat "to %t")
6566 (concat "from %f")))))
6567 (setq org-store-link-plist plist))
6569 (defun org-add-link-props (&rest plist)
6570 "Add these properties to the link property list."
6571 (let (key value)
6572 (while plist
6573 (setq key (pop plist) value (pop plist))
6574 (setq org-store-link-plist
6575 (plist-put org-store-link-plist key value)))))
6577 (defun org-email-link-description (&optional fmt)
6578 "Return the description part of an email link.
6579 This takes information from `org-store-link-plist' and formats it
6580 according to FMT (default from `org-email-link-description-format')."
6581 (setq fmt (or fmt org-email-link-description-format))
6582 (let* ((p org-store-link-plist)
6583 (to (plist-get p :toaddress))
6584 (from (plist-get p :fromaddress))
6585 (table
6586 (list
6587 (cons "%c" (plist-get p :fromto))
6588 (cons "%F" (plist-get p :from))
6589 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6590 (cons "%T" (plist-get p :to))
6591 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6592 (cons "%s" (plist-get p :subject))
6593 (cons "%m" (plist-get p :message-id)))))
6594 (when (string-match "%c" fmt)
6595 ;; Check if the user wrote this message
6596 (if (and org-from-is-user-regexp from to
6597 (save-match-data (string-match org-from-is-user-regexp from)))
6598 (setq fmt (replace-match "to %t" t t fmt))
6599 (setq fmt (replace-match "from %f" t t fmt))))
6600 (org-replace-escapes fmt table)))
6602 (defun org-make-org-heading-search-string (&optional string heading)
6603 "Make search string for STRING or current headline."
6604 (interactive)
6605 (let ((s (or string (org-get-heading))))
6606 (unless (and string (not heading))
6607 ;; We are using a headline, clean up garbage in there.
6608 (if (string-match org-todo-regexp s)
6609 (setq s (replace-match "" t t s)))
6610 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6611 (setq s (replace-match "" t t s)))
6612 (setq s (org-trim s))
6613 (if (string-match (concat "^\\(" org-quote-string "\\|"
6614 org-comment-string "\\)") s)
6615 (setq s (replace-match "" t t s)))
6616 (while (string-match org-ts-regexp s)
6617 (setq s (replace-match "" t t s))))
6618 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6619 (setq s (replace-match " " t t s)))
6620 (or string (setq s (concat "*" s))) ; Add * for headlines
6621 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6623 (defun org-make-link (&rest strings)
6624 "Concatenate STRINGS."
6625 (apply 'concat strings))
6627 (defun org-make-link-string (link &optional description)
6628 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6629 (unless (string-match "\\S-" link)
6630 (error "Empty link"))
6631 (when (stringp description)
6632 ;; Remove brackets from the description, they are fatal.
6633 (while (string-match "\\[" description)
6634 (setq description (replace-match "{" t t description)))
6635 (while (string-match "\\]" description)
6636 (setq description (replace-match "}" t t description))))
6637 (when (equal (org-link-escape link) description)
6638 ;; No description needed, it is identical
6639 (setq description nil))
6640 (when (and (not description)
6641 (not (equal link (org-link-escape link))))
6642 (setq description link))
6643 (concat "[[" (org-link-escape link) "]"
6644 (if description (concat "[" description "]") "")
6645 "]"))
6647 (defconst org-link-escape-chars
6648 '((?\ . "%20")
6649 (?\[ . "%5B")
6650 (?\] . "%5D")
6651 (?\340 . "%E0") ; `a
6652 (?\342 . "%E2") ; ^a
6653 (?\347 . "%E7") ; ,c
6654 (?\350 . "%E8") ; `e
6655 (?\351 . "%E9") ; 'e
6656 (?\352 . "%EA") ; ^e
6657 (?\356 . "%EE") ; ^i
6658 (?\364 . "%F4") ; ^o
6659 (?\371 . "%F9") ; `u
6660 (?\373 . "%FB") ; ^u
6661 (?\; . "%3B")
6662 (?? . "%3F")
6663 (?= . "%3D")
6664 (?+ . "%2B")
6666 "Association list of escapes for some characters problematic in links.
6667 This is the list that is used for internal purposes.")
6669 (defconst org-link-escape-chars-browser
6670 '((?\ . "%20")) ; 32 for the SPC char
6671 "Association list of escapes for some characters problematic in links.
6672 This is the list that is used before handing over to the browser.")
6674 (defun org-link-escape (text &optional table)
6675 "Escape charaters in TEXT that are problematic for links."
6676 (setq table (or table org-link-escape-chars))
6677 (when text
6678 (let ((re (mapconcat (lambda (x) (regexp-quote
6679 (char-to-string (car x))))
6680 table "\\|")))
6681 (while (string-match re text)
6682 (setq text
6683 (replace-match
6684 (cdr (assoc (string-to-char (match-string 0 text))
6685 table))
6686 t t text)))
6687 text)))
6689 (defun org-link-unescape (text &optional table)
6690 "Reverse the action of `org-link-escape'."
6691 (setq table (or table org-link-escape-chars))
6692 (when text
6693 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6694 table "\\|")))
6695 (while (string-match re text)
6696 (setq text
6697 (replace-match
6698 (char-to-string (car (rassoc (match-string 0 text) table)))
6699 t t text)))
6700 text)))
6702 (defun org-xor (a b)
6703 "Exclusive or."
6704 (if a (not b) b))
6706 (defun org-get-header (header)
6707 "Find a header field in the current buffer."
6708 (save-excursion
6709 (goto-char (point-min))
6710 (let ((case-fold-search t) s)
6711 (cond
6712 ((eq header 'from)
6713 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6714 (setq s (match-string 1)))
6715 (while (string-match "\"" s)
6716 (setq s (replace-match "" t t s)))
6717 (if (string-match "[<(].*" s)
6718 (setq s (replace-match "" t t s))))
6719 ((eq header 'message-id)
6720 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6721 (setq s (match-string 1))))
6722 ((eq header 'subject)
6723 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6724 (setq s (match-string 1)))))
6725 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6726 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6727 s)))
6730 (defun org-fixup-message-id-for-http (s)
6731 "Replace special characters in a message id, so it can be used in an http query."
6732 (while (string-match "<" s)
6733 (setq s (replace-match "%3C" t t s)))
6734 (while (string-match ">" s)
6735 (setq s (replace-match "%3E" t t s)))
6736 (while (string-match "@" s)
6737 (setq s (replace-match "%40" t t s)))
6740 ;;;###autoload
6741 (defun org-insert-link-global ()
6742 "Insert a link like Org-mode does.
6743 This command can be called in any mode to insert a link in Org-mode syntax."
6744 (interactive)
6745 (org-load-modules-maybe)
6746 (org-run-like-in-org-mode 'org-insert-link))
6748 (defun org-insert-link (&optional complete-file link-location)
6749 "Insert a link. At the prompt, enter the link.
6751 Completion can be used to select a link previously stored with
6752 `org-store-link'. When the empty string is entered (i.e. if you just
6753 press RET at the prompt), the link defaults to the most recently
6754 stored link. As SPC triggers completion in the minibuffer, you need to
6755 use M-SPC or C-q SPC to force the insertion of a space character.
6757 You will also be prompted for a description, and if one is given, it will
6758 be displayed in the buffer instead of the link.
6760 If there is already a link at point, this command will allow you to edit link
6761 and description parts.
6763 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6764 be selected using completion. The path to the file will be relative to the
6765 current directory if the file is in the current directory or a subdirectory.
6766 Otherwise, the link will be the absolute path as completed in the minibuffer
6767 \(i.e. normally ~/path/to/file).
6769 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6770 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6771 of `org-keep-stored-link-after-insertion'.
6773 If `org-make-link-description-function' is non-nil, this function will be
6774 called with the link target, and the result will be the default
6775 link description.
6777 If the LINK-LOCATION parameter is non-nil, this value will be
6778 used as the link location instead of reading one interactively."
6779 (interactive "P")
6780 (let* ((wcf (current-window-configuration))
6781 (region (if (org-region-active-p)
6782 (buffer-substring (region-beginning) (region-end))))
6783 (remove (and region (list (region-beginning) (region-end))))
6784 (desc region)
6785 tmphist ; byte-compile incorrectly complains about this
6786 (link link-location)
6787 entry file)
6788 (cond
6789 (link-location) ; specified by arg, just use it.
6790 ((org-in-regexp org-bracket-link-regexp 1)
6791 ;; We do have a link at point, and we are going to edit it.
6792 (setq remove (list (match-beginning 0) (match-end 0)))
6793 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6794 (setq link (read-string "Link: "
6795 (org-link-unescape
6796 (org-match-string-no-properties 1)))))
6797 ((or (org-in-regexp org-angle-link-re)
6798 (org-in-regexp org-plain-link-re))
6799 ;; Convert to bracket link
6800 (setq remove (list (match-beginning 0) (match-end 0))
6801 link (read-string "Link: "
6802 (org-remove-angle-brackets (match-string 0)))))
6803 ((equal complete-file '(4))
6804 ;; Completing read for file names.
6805 (setq file (read-file-name "File: "))
6806 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6807 (pwd1 (file-name-as-directory (abbreviate-file-name
6808 (expand-file-name ".")))))
6809 (cond
6810 ((equal complete-file '(16))
6811 (setq link (org-make-link
6812 "file:"
6813 (abbreviate-file-name (expand-file-name file)))))
6814 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6815 (setq link (org-make-link "file:" (match-string 1 file))))
6816 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6817 (expand-file-name file))
6818 (setq link (org-make-link
6819 "file:" (match-string 1 (expand-file-name file)))))
6820 (t (setq link (org-make-link "file:" file))))))
6822 ;; Read link, with completion for stored links.
6823 (with-output-to-temp-buffer "*Org Links*"
6824 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6825 (when org-stored-links
6826 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6827 (princ (mapconcat
6828 (lambda (x)
6829 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6830 (reverse org-stored-links) "\n"))))
6831 (let ((cw (selected-window)))
6832 (select-window (get-buffer-window "*Org Links*"))
6833 (shrink-window-if-larger-than-buffer)
6834 (setq truncate-lines t)
6835 (select-window cw))
6836 ;; Fake a link history, containing the stored links.
6837 (setq tmphist (append (mapcar 'car org-stored-links)
6838 org-insert-link-history))
6839 (unwind-protect
6840 (setq link (org-completing-read
6841 "Link: "
6842 (append
6843 (mapcar (lambda (x) (list (concat (car x) ":")))
6844 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6845 (mapcar (lambda (x) (list (concat x ":")))
6846 org-link-types))
6847 nil nil nil
6848 'tmphist
6849 (or (car (car org-stored-links)))))
6850 (set-window-configuration wcf)
6851 (kill-buffer "*Org Links*"))
6852 (setq entry (assoc link org-stored-links))
6853 (or entry (push link org-insert-link-history))
6854 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6855 (not org-keep-stored-link-after-insertion))
6856 (setq org-stored-links (delq (assoc link org-stored-links)
6857 org-stored-links)))
6858 (setq desc (or desc (nth 1 entry)))))
6860 (if (string-match org-plain-link-re link)
6861 ;; URL-like link, normalize the use of angular brackets.
6862 (setq link (org-make-link (org-remove-angle-brackets link))))
6864 ;; Check if we are linking to the current file with a search option
6865 ;; If yes, simplify the link by using only the search option.
6866 (when (and buffer-file-name
6867 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6868 (let* ((path (match-string 1 link))
6869 (case-fold-search nil)
6870 (search (match-string 2 link)))
6871 (save-match-data
6872 (if (equal (file-truename buffer-file-name) (file-truename path))
6873 ;; We are linking to this same file, with a search option
6874 (setq link search)))))
6876 ;; Check if we can/should use a relative path. If yes, simplify the link
6877 (when (string-match "\\<file:\\(.*\\)" link)
6878 (let* ((path (match-string 1 link))
6879 (origpath path)
6880 (case-fold-search nil))
6881 (cond
6882 ((eq org-link-file-path-type 'absolute)
6883 (setq path (abbreviate-file-name (expand-file-name path))))
6884 ((eq org-link-file-path-type 'noabbrev)
6885 (setq path (expand-file-name path)))
6886 ((eq org-link-file-path-type 'relative)
6887 (setq path (file-relative-name path)))
6889 (save-match-data
6890 (if (string-match (concat "^" (regexp-quote
6891 (file-name-as-directory
6892 (expand-file-name "."))))
6893 (expand-file-name path))
6894 ;; We are linking a file with relative path name.
6895 (setq path (substring (expand-file-name path)
6896 (match-end 0)))))))
6897 (setq link (concat "file:" path))
6898 (if (equal desc origpath)
6899 (setq desc path))))
6901 (if org-make-link-description-function
6902 (setq desc (funcall org-make-link-description-function link desc)))
6904 (setq desc (read-string "Description: " desc))
6905 (unless (string-match "\\S-" desc) (setq desc nil))
6906 (if remove (apply 'delete-region remove))
6907 (insert (org-make-link-string link desc))))
6909 (defun org-completing-read (&rest args)
6910 (let ((minibuffer-local-completion-map
6911 (copy-keymap minibuffer-local-completion-map)))
6912 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6913 (apply 'completing-read args)))
6915 ;;; Opening/following a link
6917 (defvar org-link-search-failed nil)
6919 (defun org-next-link ()
6920 "Move forward to the next link.
6921 If the link is in hidden text, expose it."
6922 (interactive)
6923 (when (and org-link-search-failed (eq this-command last-command))
6924 (goto-char (point-min))
6925 (message "Link search wrapped back to beginning of buffer"))
6926 (setq org-link-search-failed nil)
6927 (let* ((pos (point))
6928 (ct (org-context))
6929 (a (assoc :link ct)))
6930 (if a (goto-char (nth 2 a)))
6931 (if (re-search-forward org-any-link-re nil t)
6932 (progn
6933 (goto-char (match-beginning 0))
6934 (if (org-invisible-p) (org-show-context)))
6935 (goto-char pos)
6936 (setq org-link-search-failed t)
6937 (error "No further link found"))))
6939 (defun org-previous-link ()
6940 "Move backward to the previous link.
6941 If the link is in hidden text, expose it."
6942 (interactive)
6943 (when (and org-link-search-failed (eq this-command last-command))
6944 (goto-char (point-max))
6945 (message "Link search wrapped back to end of buffer"))
6946 (setq org-link-search-failed nil)
6947 (let* ((pos (point))
6948 (ct (org-context))
6949 (a (assoc :link ct)))
6950 (if a (goto-char (nth 1 a)))
6951 (if (re-search-backward org-any-link-re nil t)
6952 (progn
6953 (goto-char (match-beginning 0))
6954 (if (org-invisible-p) (org-show-context)))
6955 (goto-char pos)
6956 (setq org-link-search-failed t)
6957 (error "No further link found"))))
6959 (defun org-find-file-at-mouse (ev)
6960 "Open file link or URL at mouse."
6961 (interactive "e")
6962 (mouse-set-point ev)
6963 (org-open-at-point 'in-emacs))
6965 (defun org-open-at-mouse (ev)
6966 "Open file link or URL at mouse."
6967 (interactive "e")
6968 (mouse-set-point ev)
6969 (org-open-at-point))
6971 (defvar org-window-config-before-follow-link nil
6972 "The window configuration before following a link.
6973 This is saved in case the need arises to restore it.")
6975 (defvar org-open-link-marker (make-marker)
6976 "Marker pointing to the location where `org-open-at-point; was called.")
6978 ;;;###autoload
6979 (defun org-open-at-point-global ()
6980 "Follow a link like Org-mode does.
6981 This command can be called in any mode to follow a link that has
6982 Org-mode syntax."
6983 (interactive)
6984 (org-run-like-in-org-mode 'org-open-at-point))
6986 ;;;###autoload
6987 (defun org-open-link-from-string (s &optional arg)
6988 "Open a link in the string S, as if it was in Org-mode."
6989 (interactive "sLink: \nP")
6990 (with-temp-buffer
6991 (let ((org-inhibit-startup t))
6992 (org-mode)
6993 (insert s)
6994 (goto-char (point-min))
6995 (org-open-at-point arg))))
6997 (defun org-open-at-point (&optional in-emacs)
6998 "Open link at or after point.
6999 If there is no link at point, this function will search forward up to
7000 the end of the current subtree.
7001 Normally, files will be opened by an appropriate application. If the
7002 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7003 (interactive "P")
7004 (org-load-modules-maybe)
7005 (move-marker org-open-link-marker (point))
7006 (setq org-window-config-before-follow-link (current-window-configuration))
7007 (org-remove-occur-highlights nil nil t)
7008 (if (org-at-timestamp-p t)
7009 (org-follow-timestamp-link)
7010 (let (type path link line search (pos (point)))
7011 (catch 'match
7012 (save-excursion
7013 (skip-chars-forward "^]\n\r")
7014 (when (org-in-regexp org-bracket-link-regexp)
7015 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7016 (while (string-match " *\n *" link)
7017 (setq link (replace-match " " t t link)))
7018 (setq link (org-link-expand-abbrev link))
7019 (if (string-match org-link-re-with-space2 link)
7020 (setq type (match-string 1 link) path (match-string 2 link))
7021 (setq type "thisfile" path link))
7022 (throw 'match t)))
7024 (when (get-text-property (point) 'org-linked-text)
7025 (setq type "thisfile"
7026 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7027 (1+ (point)) (point))
7028 path (buffer-substring
7029 (previous-single-property-change pos 'org-linked-text)
7030 (next-single-property-change pos 'org-linked-text)))
7031 (throw 'match t))
7033 (save-excursion
7034 (when (or (org-in-regexp org-angle-link-re)
7035 (org-in-regexp org-plain-link-re))
7036 (setq type (match-string 1) path (match-string 2))
7037 (throw 'match t)))
7038 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7039 (setq type "tree-match"
7040 path (match-string 1))
7041 (throw 'match t))
7042 (save-excursion
7043 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7044 (setq type "tags"
7045 path (match-string 1))
7046 (while (string-match ":" path)
7047 (setq path (replace-match "+" t t path)))
7048 (throw 'match t))))
7049 (unless path
7050 (error "No link found"))
7051 ;; Remove any trailing spaces in path
7052 (if (string-match " +\\'" path)
7053 (setq path (replace-match "" t t path)))
7055 (cond
7057 ((assoc type org-link-protocols)
7058 (funcall (nth 1 (assoc type org-link-protocols)) path))
7060 ((equal type "mailto")
7061 (let ((cmd (car org-link-mailto-program))
7062 (args (cdr org-link-mailto-program)) args1
7063 (address path) (subject "") a)
7064 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7065 (setq address (match-string 1 path)
7066 subject (org-link-escape (match-string 2 path))))
7067 (while args
7068 (cond
7069 ((not (stringp (car args))) (push (pop args) args1))
7070 (t (setq a (pop args))
7071 (if (string-match "%a" a)
7072 (setq a (replace-match address t t a)))
7073 (if (string-match "%s" a)
7074 (setq a (replace-match subject t t a)))
7075 (push a args1))))
7076 (apply cmd (nreverse args1))))
7078 ((member type '("http" "https" "ftp" "news"))
7079 (browse-url (concat type ":" (org-link-escape
7080 path org-link-escape-chars-browser))))
7082 ((member type '("message"))
7083 (browse-url (concat type ":" path)))
7085 ((string= type "tags")
7086 (org-tags-view in-emacs path))
7087 ((string= type "thisfile")
7088 (if in-emacs
7089 (switch-to-buffer-other-window
7090 (org-get-buffer-for-internal-link (current-buffer)))
7091 (org-mark-ring-push))
7092 (let ((cmd `(org-link-search
7093 ,path
7094 ,(cond ((equal in-emacs '(4)) 'occur)
7095 ((equal in-emacs '(16)) 'org-occur)
7096 (t nil))
7097 ,pos)))
7098 (condition-case nil (eval cmd)
7099 (error (progn (widen) (eval cmd))))))
7101 ((string= type "tree-match")
7102 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7104 ((string= type "file")
7105 (if (string-match "::\\([0-9]+\\)\\'" path)
7106 (setq line (string-to-number (match-string 1 path))
7107 path (substring path 0 (match-beginning 0)))
7108 (if (string-match "::\\(.+\\)\\'" path)
7109 (setq search (match-string 1 path)
7110 path (substring path 0 (match-beginning 0)))))
7111 (if (string-match "[*?{]" (file-name-nondirectory path))
7112 (dired path)
7113 (org-open-file path in-emacs line search)))
7115 ((string= type "news")
7116 (require 'org-gnus)
7117 (org-gnus-follow-link path))
7119 ((string= type "shell")
7120 (let ((cmd path))
7121 (if (or (not org-confirm-shell-link-function)
7122 (funcall org-confirm-shell-link-function
7123 (format "Execute \"%s\" in shell? "
7124 (org-add-props cmd nil
7125 'face 'org-warning))))
7126 (progn
7127 (message "Executing %s" cmd)
7128 (shell-command cmd))
7129 (error "Abort"))))
7131 ((string= type "elisp")
7132 (let ((cmd path))
7133 (if (or (not org-confirm-elisp-link-function)
7134 (funcall org-confirm-elisp-link-function
7135 (format "Execute \"%s\" as elisp? "
7136 (org-add-props cmd nil
7137 'face 'org-warning))))
7138 (message "%s => %s" cmd (eval (read cmd)))
7139 (error "Abort"))))
7142 (browse-url-at-point)))))
7143 (move-marker org-open-link-marker nil)
7144 (run-hook-with-args 'org-follow-link-hook))
7146 ;;;; Time estimates
7148 (defun org-get-effort (&optional pom)
7149 "Get the effort estimate for the current entry."
7150 (org-entry-get pom org-effort-property))
7152 ;;; File search
7154 (defvar org-create-file-search-functions nil
7155 "List of functions to construct the right search string for a file link.
7156 These functions are called in turn with point at the location to
7157 which the link should point.
7159 A function in the hook should first test if it would like to
7160 handle this file type, for example by checking the major-mode or
7161 the file extension. If it decides not to handle this file, it
7162 should just return nil to give other functions a chance. If it
7163 does handle the file, it must return the search string to be used
7164 when following the link. The search string will be part of the
7165 file link, given after a double colon, and `org-open-at-point'
7166 will automatically search for it. If special measures must be
7167 taken to make the search successful, another function should be
7168 added to the companion hook `org-execute-file-search-functions',
7169 which see.
7171 A function in this hook may also use `setq' to set the variable
7172 `description' to provide a suggestion for the descriptive text to
7173 be used for this link when it gets inserted into an Org-mode
7174 buffer with \\[org-insert-link].")
7176 (defvar org-execute-file-search-functions nil
7177 "List of functions to execute a file search triggered by a link.
7179 Functions added to this hook must accept a single argument, the
7180 search string that was part of the file link, the part after the
7181 double colon. The function must first check if it would like to
7182 handle this search, for example by checking the major-mode or the
7183 file extension. If it decides not to handle this search, it
7184 should just return nil to give other functions a chance. If it
7185 does handle the search, it must return a non-nil value to keep
7186 other functions from trying.
7188 Each function can access the current prefix argument through the
7189 variable `current-prefix-argument'. Note that a single prefix is
7190 used to force opening a link in Emacs, so it may be good to only
7191 use a numeric or double prefix to guide the search function.
7193 In case this is needed, a function in this hook can also restore
7194 the window configuration before `org-open-at-point' was called using:
7196 (set-window-configuration org-window-config-before-follow-link)")
7198 (defun org-link-search (s &optional type avoid-pos)
7199 "Search for a link search option.
7200 If S is surrounded by forward slashes, it is interpreted as a
7201 regular expression. In org-mode files, this will create an `org-occur'
7202 sparse tree. In ordinary files, `occur' will be used to list matches.
7203 If the current buffer is in `dired-mode', grep will be used to search
7204 in all files. If AVOID-POS is given, ignore matches near that position."
7205 (let ((case-fold-search t)
7206 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7207 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7208 (append '(("") (" ") ("\t") ("\n"))
7209 org-emphasis-alist)
7210 "\\|") "\\)"))
7211 (pos (point))
7212 (pre nil) (post nil)
7213 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7214 (cond
7215 ;; First check if there are any special
7216 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7217 ;; Now try the builtin stuff
7218 ((save-excursion
7219 (goto-char (point-min))
7220 (and
7221 (re-search-forward
7222 (concat "<<" (regexp-quote s0) ">>") nil t)
7223 (setq type 'dedicated
7224 pos (match-beginning 0))))
7225 ;; There is an exact target for this
7226 (goto-char pos))
7227 ((string-match "^/\\(.*\\)/$" s)
7228 ;; A regular expression
7229 (cond
7230 ((org-mode-p)
7231 (org-occur (match-string 1 s)))
7232 ;;((eq major-mode 'dired-mode)
7233 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7234 (t (org-do-occur (match-string 1 s)))))
7236 ;; A normal search strings
7237 (when (equal (string-to-char s) ?*)
7238 ;; Anchor on headlines, post may include tags.
7239 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7240 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7241 s (substring s 1)))
7242 (remove-text-properties
7243 0 (length s)
7244 '(face nil mouse-face nil keymap nil fontified nil) s)
7245 ;; Make a series of regular expressions to find a match
7246 (setq words (org-split-string s "[ \n\r\t]+")
7248 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7249 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7250 "\\)" markers)
7251 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7252 re2a (concat "[ \t\r\n]" re2a_)
7253 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7254 re4 (concat "[^a-zA-Z_]" re4_)
7256 re1 (concat pre re2 post)
7257 re3 (concat pre (if pre re4_ re4) post)
7258 re5 (concat pre ".*" re4)
7259 re2 (concat pre re2)
7260 re2a (concat pre (if pre re2a_ re2a))
7261 re4 (concat pre (if pre re4_ re4))
7262 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7263 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7264 re5 "\\)"
7266 (cond
7267 ((eq type 'org-occur) (org-occur reall))
7268 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7269 (t (goto-char (point-min))
7270 (setq type 'fuzzy)
7271 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7272 (org-search-not-self 1 re1 nil t)
7273 (org-search-not-self 1 re2 nil t)
7274 (org-search-not-self 1 re2a nil t)
7275 (org-search-not-self 1 re3 nil t)
7276 (org-search-not-self 1 re4 nil t)
7277 (org-search-not-self 1 re5 nil t)
7279 (goto-char (match-beginning 1))
7280 (goto-char pos)
7281 (error "No match")))))
7283 ;; Normal string-search
7284 (goto-char (point-min))
7285 (if (search-forward s nil t)
7286 (goto-char (match-beginning 0))
7287 (error "No match"))))
7288 (and (org-mode-p) (org-show-context 'link-search))
7289 type))
7291 (defun org-search-not-self (group &rest args)
7292 "Execute `re-search-forward', but only accept matches that do not
7293 enclose the position of `org-open-link-marker'."
7294 (let ((m org-open-link-marker))
7295 (catch 'exit
7296 (while (apply 're-search-forward args)
7297 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7298 (goto-char (match-end group))
7299 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7300 (> (match-beginning 0) (marker-position m))
7301 (< (match-end 0) (marker-position m)))
7302 (save-match-data
7303 (or (not (org-in-regexp
7304 org-bracket-link-analytic-regexp 1))
7305 (not (match-end 4)) ; no description
7306 (and (<= (match-beginning 4) (point))
7307 (>= (match-end 4) (point))))))
7308 (throw 'exit (point))))))))
7310 (defun org-get-buffer-for-internal-link (buffer)
7311 "Return a buffer to be used for displaying the link target of internal links."
7312 (cond
7313 ((not org-display-internal-link-with-indirect-buffer)
7314 buffer)
7315 ((string-match "(Clone)$" (buffer-name buffer))
7316 (message "Buffer is already a clone, not making another one")
7317 ;; we also do not modify visibility in this case
7318 buffer)
7319 (t ; make a new indirect buffer for displaying the link
7320 (let* ((bn (buffer-name buffer))
7321 (ibn (concat bn "(Clone)"))
7322 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7323 (with-current-buffer ib (org-overview))
7324 ib))))
7326 (defun org-do-occur (regexp &optional cleanup)
7327 "Call the Emacs command `occur'.
7328 If CLEANUP is non-nil, remove the printout of the regular expression
7329 in the *Occur* buffer. This is useful if the regex is long and not useful
7330 to read."
7331 (occur regexp)
7332 (when cleanup
7333 (let ((cwin (selected-window)) win beg end)
7334 (when (setq win (get-buffer-window "*Occur*"))
7335 (select-window win))
7336 (goto-char (point-min))
7337 (when (re-search-forward "match[a-z]+" nil t)
7338 (setq beg (match-end 0))
7339 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7340 (setq end (1- (match-beginning 0)))))
7341 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7342 (goto-char (point-min))
7343 (select-window cwin))))
7345 ;;; The mark ring for links jumps
7347 (defvar org-mark-ring nil
7348 "Mark ring for positions before jumps in Org-mode.")
7349 (defvar org-mark-ring-last-goto nil
7350 "Last position in the mark ring used to go back.")
7351 ;; Fill and close the ring
7352 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7353 (loop for i from 1 to org-mark-ring-length do
7354 (push (make-marker) org-mark-ring))
7355 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7356 org-mark-ring)
7358 (defun org-mark-ring-push (&optional pos buffer)
7359 "Put the current position or POS into the mark ring and rotate it."
7360 (interactive)
7361 (setq pos (or pos (point)))
7362 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7363 (move-marker (car org-mark-ring)
7364 (or pos (point))
7365 (or buffer (current-buffer)))
7366 (message "%s"
7367 (substitute-command-keys
7368 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7370 (defun org-mark-ring-goto (&optional n)
7371 "Jump to the previous position in the mark ring.
7372 With prefix arg N, jump back that many stored positions. When
7373 called several times in succession, walk through the entire ring.
7374 Org-mode commands jumping to a different position in the current file,
7375 or to another Org-mode file, automatically push the old position
7376 onto the ring."
7377 (interactive "p")
7378 (let (p m)
7379 (if (eq last-command this-command)
7380 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7381 (setq p org-mark-ring))
7382 (setq org-mark-ring-last-goto p)
7383 (setq m (car p))
7384 (switch-to-buffer (marker-buffer m))
7385 (goto-char m)
7386 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7388 (defun org-remove-angle-brackets (s)
7389 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7390 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7392 (defun org-add-angle-brackets (s)
7393 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7394 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7396 (defun org-remove-double-quotes (s)
7397 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7398 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7401 ;;; Following specific links
7403 (defun org-follow-timestamp-link ()
7404 (cond
7405 ((org-at-date-range-p t)
7406 (let ((org-agenda-start-on-weekday)
7407 (t1 (match-string 1))
7408 (t2 (match-string 2)))
7409 (setq t1 (time-to-days (org-time-string-to-time t1))
7410 t2 (time-to-days (org-time-string-to-time t2)))
7411 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7412 ((org-at-timestamp-p t)
7413 (org-agenda-list nil (time-to-days (org-time-string-to-time
7414 (substring (match-string 1) 0 10)))
7416 (t (error "This should not happen"))))
7419 ;;; Following file links
7420 (defvar org-wait nil)
7421 (defun org-open-file (path &optional in-emacs line search)
7422 "Open the file at PATH.
7423 First, this expands any special file name abbreviations. Then the
7424 configuration variable `org-file-apps' is checked if it contains an
7425 entry for this file type, and if yes, the corresponding command is launched.
7426 If no application is found, Emacs simply visits the file.
7427 With optional argument IN-EMACS, Emacs will visit the file.
7428 Optional LINE specifies a line to go to, optional SEARCH a string to
7429 search for. If LINE or SEARCH is given, the file will always be
7430 opened in Emacs.
7431 If the file does not exist, an error is thrown."
7432 (setq in-emacs (or in-emacs line search))
7433 (let* ((file (if (equal path "")
7434 buffer-file-name
7435 (substitute-in-file-name (expand-file-name path))))
7436 (apps (append org-file-apps (org-default-apps)))
7437 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7438 (dirp (if remp nil (file-directory-p file)))
7439 (dfile (downcase file))
7440 (old-buffer (current-buffer))
7441 (old-pos (point))
7442 (old-mode major-mode)
7443 ext cmd)
7444 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7445 (setq ext (match-string 1 dfile))
7446 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7447 (setq ext (match-string 1 dfile))))
7448 (if in-emacs
7449 (setq cmd 'emacs)
7450 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7451 (and dirp (cdr (assoc 'directory apps)))
7452 (cdr (assoc ext apps))
7453 (cdr (assoc t apps)))))
7454 (when (eq cmd 'mailcap)
7455 (require 'mailcap)
7456 (mailcap-parse-mailcaps)
7457 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7458 (command (mailcap-mime-info mime-type)))
7459 (if (stringp command)
7460 (setq cmd command)
7461 (setq cmd 'emacs))))
7462 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7463 (not (file-exists-p file))
7464 (not org-open-non-existing-files))
7465 (error "No such file: %s" file))
7466 (cond
7467 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7468 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7469 (while (string-match "['\"]%s['\"]" cmd)
7470 (setq cmd (replace-match "%s" t t cmd)))
7471 (while (string-match "%s" cmd)
7472 (setq cmd (replace-match
7473 (save-match-data
7474 (shell-quote-argument
7475 (convert-standard-filename file)))
7476 t t cmd)))
7477 (save-window-excursion
7478 (start-process-shell-command cmd nil cmd)
7479 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7481 ((or (stringp cmd)
7482 (eq cmd 'emacs))
7483 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7484 (widen)
7485 (if line (goto-line line)
7486 (if search (org-link-search search))))
7487 ((consp cmd)
7488 (let ((file (convert-standard-filename file)))
7489 (eval cmd)))
7490 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7491 (and (org-mode-p) (eq old-mode 'org-mode)
7492 (or (not (equal old-buffer (current-buffer)))
7493 (not (equal old-pos (point))))
7494 (org-mark-ring-push old-pos old-buffer))))
7496 (defun org-default-apps ()
7497 "Return the default applications for this operating system."
7498 (cond
7499 ((eq system-type 'darwin)
7500 org-file-apps-defaults-macosx)
7501 ((eq system-type 'windows-nt)
7502 org-file-apps-defaults-windowsnt)
7503 (t org-file-apps-defaults-gnu)))
7505 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7506 (defun org-file-remote-p (file)
7507 "Test whether FILE specifies a location on a remote system.
7508 Return non-nil if the location is indeed remote.
7510 For example, the filename \"/user@host:/foo\" specifies a location
7511 on the system \"/user@host:\"."
7512 (cond ((fboundp 'file-remote-p)
7513 (file-remote-p file))
7514 ((fboundp 'tramp-handle-file-remote-p)
7515 (tramp-handle-file-remote-p file))
7516 ((and (boundp 'ange-ftp-name-format)
7517 (string-match (car ange-ftp-name-format) file))
7519 (t nil)))
7522 ;;;; Refiling
7524 (defun org-get-org-file ()
7525 "Read a filename, with default directory `org-directory'."
7526 (let ((default (or org-default-notes-file remember-data-file)))
7527 (read-file-name (format "File name [%s]: " default)
7528 (file-name-as-directory org-directory)
7529 default)))
7531 (defun org-notes-order-reversed-p ()
7532 "Check if the current file should receive notes in reversed order."
7533 (cond
7534 ((not org-reverse-note-order) nil)
7535 ((eq t org-reverse-note-order) t)
7536 ((not (listp org-reverse-note-order)) nil)
7537 (t (catch 'exit
7538 (let ((all org-reverse-note-order)
7539 entry)
7540 (while (setq entry (pop all))
7541 (if (string-match (car entry) buffer-file-name)
7542 (throw 'exit (cdr entry))))
7543 nil)))))
7545 (defvar org-refile-target-table nil
7546 "The list of refile targets, created by `org-refile'.")
7548 (defvar org-agenda-new-buffers nil
7549 "Buffers created to visit agenda files.")
7551 (defun org-get-refile-targets (&optional default-buffer)
7552 "Produce a table with refile targets."
7553 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7554 targets txt re files f desc descre)
7555 (with-current-buffer (or default-buffer (current-buffer))
7556 (while (setq entry (pop entries))
7557 (setq files (car entry) desc (cdr entry))
7558 (cond
7559 ((null files) (setq files (list (current-buffer))))
7560 ((eq files 'org-agenda-files)
7561 (setq files (org-agenda-files 'unrestricted)))
7562 ((and (symbolp files) (fboundp files))
7563 (setq files (funcall files)))
7564 ((and (symbolp files) (boundp files))
7565 (setq files (symbol-value files))))
7566 (if (stringp files) (setq files (list files)))
7567 (cond
7568 ((eq (car desc) :tag)
7569 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7570 ((eq (car desc) :todo)
7571 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7572 ((eq (car desc) :regexp)
7573 (setq descre (cdr desc)))
7574 ((eq (car desc) :level)
7575 (setq descre (concat "^\\*\\{" (number-to-string
7576 (if org-odd-levels-only
7577 (1- (* 2 (cdr desc)))
7578 (cdr desc)))
7579 "\\}[ \t]")))
7580 ((eq (car desc) :maxlevel)
7581 (setq descre (concat "^\\*\\{1," (number-to-string
7582 (if org-odd-levels-only
7583 (1- (* 2 (cdr desc)))
7584 (cdr desc)))
7585 "\\}[ \t]")))
7586 (t (error "Bad refiling target description %s" desc)))
7587 (while (setq f (pop files))
7588 (save-excursion
7589 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7590 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7591 (save-excursion
7592 (save-restriction
7593 (widen)
7594 (goto-char (point-min))
7595 (while (re-search-forward descre nil t)
7596 (goto-char (point-at-bol))
7597 (when (looking-at org-complex-heading-regexp)
7598 (setq txt (match-string 4)
7599 re (concat "^" (regexp-quote
7600 (buffer-substring (match-beginning 1)
7601 (match-end 4)))))
7602 (if (match-end 5) (setq re (concat re "[ \t]+"
7603 (regexp-quote
7604 (match-string 5)))))
7605 (setq re (concat re "[ \t]*$"))
7606 (when org-refile-use-outline-path
7607 (setq txt (mapconcat 'identity
7608 (append
7609 (if (eq org-refile-use-outline-path 'file)
7610 (list (file-name-nondirectory
7611 (buffer-file-name (buffer-base-buffer))))
7612 (if (eq org-refile-use-outline-path 'full-file-path)
7613 (list (buffer-file-name (buffer-base-buffer)))))
7614 (org-get-outline-path)
7615 (list txt))
7616 "/")))
7617 (push (list txt f re (point)) targets))
7618 (goto-char (point-at-eol))))))))
7619 (nreverse targets))))
7621 (defun org-get-outline-path ()
7622 "Return the outline path to the current entry, as a list."
7623 (let (rtn)
7624 (save-excursion
7625 (while (org-up-heading-safe)
7626 (when (looking-at org-complex-heading-regexp)
7627 (push (org-match-string-no-properties 4) rtn)))
7628 rtn)))
7630 (defvar org-refile-history nil
7631 "History for refiling operations.")
7633 (defun org-refile (&optional goto default-buffer)
7634 "Move the entry at point to another heading.
7635 The list of target headings is compiled using the information in
7636 `org-refile-targets', which see. This list is created before each use
7637 and will therefore always be up-to-date.
7639 At the target location, the entry is filed as a subitem of the target heading.
7640 Depending on `org-reverse-note-order', the new subitem will either be the
7641 first of the last subitem.
7643 With prefix arg GOTO, the command will only visit the target location,
7644 not actually move anything.
7645 With a double prefix `C-c C-c', go to the location where the last refiling
7646 operation has put the subtree."
7647 (interactive "P")
7648 (let* ((cbuf (current-buffer))
7649 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7650 pos it nbuf file re level reversed)
7651 (if (equal goto '(16))
7652 (org-refile-goto-last-stored)
7653 (when (setq it (org-refile-get-location
7654 (if goto "Goto: " "Refile to: ") default-buffer))
7655 (setq file (nth 1 it)
7656 re (nth 2 it)
7657 pos (nth 3 it))
7658 (setq nbuf (or (find-buffer-visiting file)
7659 (find-file-noselect file)))
7660 (if goto
7661 (progn
7662 (switch-to-buffer nbuf)
7663 (goto-char pos)
7664 (org-show-context 'org-goto))
7665 (org-copy-subtree 1 nil t)
7666 (save-excursion
7667 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7668 (find-file-noselect file))))
7669 (setq reversed (org-notes-order-reversed-p))
7670 (save-excursion
7671 (save-restriction
7672 (widen)
7673 (goto-char pos)
7674 (looking-at outline-regexp)
7675 (setq level (org-get-valid-level (funcall outline-level) 1))
7676 (goto-char
7677 (if reversed
7678 (outline-next-heading)
7679 (or (save-excursion (outline-get-next-sibling))
7680 (org-end-of-subtree t t)
7681 (point-max))))
7682 (bookmark-set "org-refile-last-stored")
7683 (org-paste-subtree level))))
7684 (org-cut-subtree)
7685 (setq org-markers-to-move nil)
7686 (message "Entry refiled to \"%s\"" (car it)))))))
7688 (defun org-refile-goto-last-stored ()
7689 "Go to the location where the last refile was stored."
7690 (interactive)
7691 (bookmark-jump "org-refile-last-stored")
7692 (message "This is the location of the last refile"))
7694 (defun org-refile-get-location (&optional prompt default-buffer)
7695 "Prompt the user for a refile location, using PROMPT."
7696 (let ((org-refile-targets org-refile-targets)
7697 (org-refile-use-outline-path org-refile-use-outline-path))
7698 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7699 (unless org-refile-target-table
7700 (error "No refile targets"))
7701 (let* ((cbuf (current-buffer))
7702 (cfunc (if org-refile-use-outline-path
7703 'org-olpath-completing-read
7704 'completing-read))
7705 (extra (if org-refile-use-outline-path "/" ""))
7706 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7707 (fname (and filename (file-truename filename)))
7708 (tbl (mapcar
7709 (lambda (x)
7710 (if (not (equal fname (file-truename (nth 1 x))))
7711 (cons (concat (car x) extra " ("
7712 (file-name-nondirectory (nth 1 x)) ")")
7713 (cdr x))
7714 (cons (concat (car x) extra) (cdr x))))
7715 org-refile-target-table))
7716 (completion-ignore-case t))
7717 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7718 tbl)))
7720 (defun org-olpath-completing-read (prompt collection &rest args)
7721 "Read an outline path like a file name."
7722 (let ((thetable collection))
7723 (apply
7724 'completing-read prompt
7725 (lambda (string predicate &optional flag)
7726 (let (rtn r s f (l (length string)))
7727 (cond
7728 ((eq flag nil)
7729 ;; try completion
7730 (try-completion string thetable))
7731 ((eq flag t)
7732 ;; all-completions
7733 (setq rtn (all-completions string thetable predicate))
7734 (mapcar
7735 (lambda (x)
7736 (setq r (substring x l))
7737 (if (string-match " ([^)]*)$" x)
7738 (setq f (match-string 0 x))
7739 (setq f ""))
7740 (if (string-match "/" r)
7741 (concat string (substring r 0 (match-end 0)) f)
7743 rtn))
7744 ((eq flag 'lambda)
7745 ;; exact match?
7746 (assoc string thetable)))
7748 args)))
7750 ;;;; Dynamic blocks
7752 (defun org-find-dblock (name)
7753 "Find the first dynamic block with name NAME in the buffer.
7754 If not found, stay at current position and return nil."
7755 (let (pos)
7756 (save-excursion
7757 (goto-char (point-min))
7758 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7759 nil t)
7760 (match-beginning 0))))
7761 (if pos (goto-char pos))
7762 pos))
7764 (defconst org-dblock-start-re
7765 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7766 "Matches the startline of a dynamic block, with parameters.")
7768 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7769 "Matches the end of a dyhamic block.")
7771 (defun org-create-dblock (plist)
7772 "Create a dynamic block section, with parameters taken from PLIST.
7773 PLIST must containe a :name entry which is used as name of the block."
7774 (unless (bolp) (newline))
7775 (let ((name (plist-get plist :name)))
7776 (insert "#+BEGIN: " name)
7777 (while plist
7778 (if (eq (car plist) :name)
7779 (setq plist (cddr plist))
7780 (insert " " (prin1-to-string (pop plist)))))
7781 (insert "\n\n#+END:\n")
7782 (beginning-of-line -2)))
7784 (defun org-prepare-dblock ()
7785 "Prepare dynamic block for refresh.
7786 This empties the block, puts the cursor at the insert position and returns
7787 the property list including an extra property :name with the block name."
7788 (unless (looking-at org-dblock-start-re)
7789 (error "Not at a dynamic block"))
7790 (let* ((begdel (1+ (match-end 0)))
7791 (name (org-no-properties (match-string 1)))
7792 (params (append (list :name name)
7793 (read (concat "(" (match-string 3) ")")))))
7794 (unless (re-search-forward org-dblock-end-re nil t)
7795 (error "Dynamic block not terminated"))
7796 (setq params
7797 (append params
7798 (list :content (buffer-substring
7799 begdel (match-beginning 0)))))
7800 (delete-region begdel (match-beginning 0))
7801 (goto-char begdel)
7802 (open-line 1)
7803 params))
7805 (defun org-map-dblocks (&optional command)
7806 "Apply COMMAND to all dynamic blocks in the current buffer.
7807 If COMMAND is not given, use `org-update-dblock'."
7808 (let ((cmd (or command 'org-update-dblock))
7809 pos)
7810 (save-excursion
7811 (goto-char (point-min))
7812 (while (re-search-forward org-dblock-start-re nil t)
7813 (goto-char (setq pos (match-beginning 0)))
7814 (condition-case nil
7815 (funcall cmd)
7816 (error (message "Error during update of dynamic block")))
7817 (goto-char pos)
7818 (unless (re-search-forward org-dblock-end-re nil t)
7819 (error "Dynamic block not terminated"))))))
7821 (defun org-dblock-update (&optional arg)
7822 "User command for updating dynamic blocks.
7823 Update the dynamic block at point. With prefix ARG, update all dynamic
7824 blocks in the buffer."
7825 (interactive "P")
7826 (if arg
7827 (org-update-all-dblocks)
7828 (or (looking-at org-dblock-start-re)
7829 (org-beginning-of-dblock))
7830 (org-update-dblock)))
7832 (defun org-update-dblock ()
7833 "Update the dynamic block at point
7834 This means to empty the block, parse for parameters and then call
7835 the correct writing function."
7836 (save-window-excursion
7837 (let* ((pos (point))
7838 (line (org-current-line))
7839 (params (org-prepare-dblock))
7840 (name (plist-get params :name))
7841 (cmd (intern (concat "org-dblock-write:" name))))
7842 (message "Updating dynamic block `%s' at line %d..." name line)
7843 (funcall cmd params)
7844 (message "Updating dynamic block `%s' at line %d...done" name line)
7845 (goto-char pos))))
7847 (defun org-beginning-of-dblock ()
7848 "Find the beginning of the dynamic block at point.
7849 Error if there is no scuh block at point."
7850 (let ((pos (point))
7851 beg)
7852 (end-of-line 1)
7853 (if (and (re-search-backward org-dblock-start-re nil t)
7854 (setq beg (match-beginning 0))
7855 (re-search-forward org-dblock-end-re nil t)
7856 (> (match-end 0) pos))
7857 (goto-char beg)
7858 (goto-char pos)
7859 (error "Not in a dynamic block"))))
7861 (defun org-update-all-dblocks ()
7862 "Update all dynamic blocks in the buffer.
7863 This function can be used in a hook."
7864 (when (org-mode-p)
7865 (org-map-dblocks 'org-update-dblock)))
7868 ;;;; Completion
7870 (defconst org-additional-option-like-keywords
7871 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7872 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7873 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7875 (defcustom org-structure-template-alist
7877 ("s" "#+begin_src ?\n\n#+end_src"
7878 "<src lang=\"?\">\n\n</src>")
7879 ("e" "#+begin_example\n?\n#+end_example"
7880 "<example>\n?\n</example>")
7881 ("q" "#+begin_quote\n?\n#+end_quote"
7882 "<quote>\n?\n</quote>")
7883 ("v" "#+begin_verse\n?\n#+end_verse"
7884 "<verse>\n?\n/verse>")
7885 ("l" "#+begin_latex\n?\n#+end_latex"
7886 "<literal style=\"latex\">\n?\n</literal>")
7887 ("L" "#+latex: "
7888 "<literal style=\"latex\">?</literal>")
7889 ("h" "#+begin_html\n?\n#+end_html"
7890 "<literal style=\"html\">\n?\n</literal>")
7891 ("H" "#+html: "
7892 "<literal style=\"html\">?</literal>")
7893 ("a" "#+begin_ascii\n?\n#+end_ascii")
7894 ("A" "#+ascii: ")
7895 ("i" "#+include %file ?"
7896 "<include file=%file markup=\"?\">")
7898 "Structure completion elements.
7899 This is a list of abbreviation keys and values. The value gets inserted
7900 it you type @samp{.} followed by the key and then the completion key,
7901 usually `M-TAB'. %file will be replaced by a file name after prompting
7902 for the file uning completion.
7903 There are two templates for each key, the first uses the original Org syntax,
7904 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7905 the default when the /org-mtags.el/ module has been loaded. See also the
7906 variable `org-mtags-prefere-muse-templates'.
7907 This is an experimental feature, it is undecided if it is going to stay in."
7908 :group 'org-completion
7909 :type '(repeat
7910 (string :tag "Key")
7911 (string :tag "Template")
7912 (string :tag "Muse Template")))
7914 (defun org-try-structure-completion ()
7915 "Try to complete a structure template before point.
7916 This looks for strings like \"<e\" on an otherwise empty line and
7917 expands them."
7918 (let ((l (buffer-substring (point-at-bol) (point)))
7920 (when (and (looking-at "[ \t]*$")
7921 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7922 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7923 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7924 (match-beginning 1)) a)
7925 t)))
7927 (defun org-complete-expand-structure-template (start cell)
7928 "Expand a structure template."
7929 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7930 (rpl (nth (if musep 2 1) cell)))
7931 (delete-region start (point))
7932 (when (string-match "\\`#\\+" rpl)
7933 (cond
7934 ((bolp))
7935 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7936 (delete-region (point-at-bol) (point)))
7937 (t (newline))))
7938 (setq start (point))
7939 (if (string-match "%file" rpl)
7940 (setq rpl (replace-match
7941 (concat
7942 "\""
7943 (save-match-data
7944 (abbreviate-file-name (read-file-name "Include file: ")))
7945 "\"")
7946 t t rpl)))
7947 (insert rpl)
7948 (if (re-search-backward "\\?" start t) (delete-char 1))))
7951 (defun org-complete (&optional arg)
7952 "Perform completion on word at point.
7953 At the beginning of a headline, this completes TODO keywords as given in
7954 `org-todo-keywords'.
7955 If the current word is preceded by a backslash, completes the TeX symbols
7956 that are supported for HTML support.
7957 If the current word is preceded by \"#+\", completes special words for
7958 setting file options.
7959 In the line after \"#+STARTUP:, complete valid keywords.\"
7960 At all other locations, this simply calls the value of
7961 `org-completion-fallback-command'."
7962 (interactive "P")
7963 (org-without-partial-completion
7964 (catch 'exit
7965 (let* ((a nil)
7966 (end (point))
7967 (beg1 (save-excursion
7968 (skip-chars-backward (org-re "[:alnum:]_@"))
7969 (point)))
7970 (beg (save-excursion
7971 (skip-chars-backward "a-zA-Z0-9_:$")
7972 (point)))
7973 (confirm (lambda (x) (stringp (car x))))
7974 (searchhead (equal (char-before beg) ?*))
7975 (struct
7976 (when (and (member (char-before beg1) '(?. ?<))
7977 (setq a (assoc (buffer-substring beg1 (point))
7978 org-structure-template-alist)))
7979 (org-complete-expand-structure-template (1- beg1) a)
7980 (throw 'exit t)))
7981 (tag (and (equal (char-before beg1) ?:)
7982 (equal (char-after (point-at-bol)) ?*)))
7983 (prop (and (equal (char-before beg1) ?:)
7984 (not (equal (char-after (point-at-bol)) ?*))))
7985 (texp (equal (char-before beg) ?\\))
7986 (link (equal (char-before beg) ?\[))
7987 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7988 beg)
7989 "#+"))
7990 (startup (string-match "^#\\+STARTUP:.*"
7991 (buffer-substring (point-at-bol) (point))))
7992 (completion-ignore-case opt)
7993 (type nil)
7994 (tbl nil)
7995 (table (cond
7996 (opt
7997 (setq type :opt)
7998 (require 'org-exp)
7999 (append
8000 (mapcar
8001 (lambda (x)
8002 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8003 (cons (match-string 2 x) (match-string 1 x)))
8004 (org-split-string (org-get-current-options) "\n"))
8005 (mapcar 'list org-additional-option-like-keywords)))
8006 (startup
8007 (setq type :startup)
8008 org-startup-options)
8009 (link (append org-link-abbrev-alist-local
8010 org-link-abbrev-alist))
8011 (texp
8012 (setq type :tex)
8013 org-html-entities)
8014 ((string-match "\\`\\*+[ \t]+\\'"
8015 (buffer-substring (point-at-bol) beg))
8016 (setq type :todo)
8017 (mapcar 'list org-todo-keywords-1))
8018 (searchhead
8019 (setq type :searchhead)
8020 (save-excursion
8021 (goto-char (point-min))
8022 (while (re-search-forward org-todo-line-regexp nil t)
8023 (push (list
8024 (org-make-org-heading-search-string
8025 (match-string 3) t))
8026 tbl)))
8027 tbl)
8028 (tag (setq type :tag beg beg1)
8029 (or org-tag-alist (org-get-buffer-tags)))
8030 (prop (setq type :prop beg beg1)
8031 (mapcar 'list (org-buffer-property-keys nil t t)))
8032 (t (progn
8033 (call-interactively org-completion-fallback-command)
8034 (throw 'exit nil)))))
8035 (pattern (buffer-substring-no-properties beg end))
8036 (completion (try-completion pattern table confirm)))
8037 (cond ((eq completion t)
8038 (if (not (assoc (upcase pattern) table))
8039 (message "Already complete")
8040 (if (and (equal type :opt)
8041 (not (member (car (assoc (upcase pattern) table))
8042 org-additional-option-like-keywords)))
8043 (insert (substring (cdr (assoc (upcase pattern) table))
8044 (length pattern)))
8045 (if (memq type '(:tag :prop)) (insert ":")))))
8046 ((null completion)
8047 (message "Can't find completion for \"%s\"" pattern)
8048 (ding))
8049 ((not (string= pattern completion))
8050 (delete-region beg end)
8051 (if (string-match " +$" completion)
8052 (setq completion (replace-match "" t t completion)))
8053 (insert completion)
8054 (if (get-buffer-window "*Completions*")
8055 (delete-window (get-buffer-window "*Completions*")))
8056 (if (assoc completion table)
8057 (if (eq type :todo) (insert " ")
8058 (if (memq type '(:tag :prop)) (insert ":"))))
8059 (if (and (equal type :opt) (assoc completion table))
8060 (message "%s" (substitute-command-keys
8061 "Press \\[org-complete] again to insert example settings"))))
8063 (message "Making completion list...")
8064 (let ((list (sort (all-completions pattern table confirm)
8065 'string<)))
8066 (with-output-to-temp-buffer "*Completions*"
8067 (condition-case nil
8068 ;; Protection needed for XEmacs and emacs 21
8069 (display-completion-list list pattern)
8070 (error (display-completion-list list)))))
8071 (message "Making completion list...%s" "done")))))))
8073 ;;;; TODO, DEADLINE, Comments
8075 (defun org-toggle-comment ()
8076 "Change the COMMENT state of an entry."
8077 (interactive)
8078 (save-excursion
8079 (org-back-to-heading)
8080 (let (case-fold-search)
8081 (if (looking-at (concat outline-regexp
8082 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8083 (replace-match "" t t nil 1)
8084 (if (looking-at outline-regexp)
8085 (progn
8086 (goto-char (match-end 0))
8087 (insert org-comment-string " ")))))))
8089 (defvar org-last-todo-state-is-todo nil
8090 "This is non-nil when the last TODO state change led to a TODO state.
8091 If the last change removed the TODO tag or switched to DONE, then
8092 this is nil.")
8094 (defvar org-setting-tags nil) ; dynamically skiped
8096 (defun org-parse-local-options (string var)
8097 "Parse STRING for startup setting relevant for variable VAR."
8098 (let ((rtn (symbol-value var))
8099 e opts)
8100 (save-match-data
8101 (if (or (not string) (not (string-match "\\S-" string)))
8103 (setq opts (delq nil (mapcar (lambda (x)
8104 (setq e (assoc x org-startup-options))
8105 (if (eq (nth 1 e) var) e nil))
8106 (org-split-string string "[ \t]+"))))
8107 (if (not opts)
8109 (setq rtn nil)
8110 (while (setq e (pop opts))
8111 (if (not (nth 3 e))
8112 (setq rtn (nth 2 e))
8113 (if (not (listp rtn)) (setq rtn nil))
8114 (push (nth 2 e) rtn)))
8115 rtn)))))
8117 (defvar org-blocker-hook nil
8118 "Hook for functions that are allowed to block a state change.
8120 Each function gets as its single argument a property list, see
8121 `org-trigger-hook' for more information about this list.
8123 If any of the functions in this hook returns nil, the state change
8124 is blocked.")
8126 (defvar org-trigger-hook nil
8127 "Hook for functions that are triggered by a state change.
8129 Each function gets as its single argument a property list with at least
8130 the following elements:
8132 (:type type-of-change :position pos-at-entry-start
8133 :from old-state :to new-state)
8135 Depending on the type, more properties may be present.
8137 This mechanism is currently implemented for:
8139 TODO state changes
8140 ------------------
8141 :type todo-state-change
8142 :from previous state (keyword as a string), or nil
8143 :to new state (keyword as a string), or nil")
8146 (defun org-todo (&optional arg)
8147 "Change the TODO state of an item.
8148 The state of an item is given by a keyword at the start of the heading,
8149 like
8150 *** TODO Write paper
8151 *** DONE Call mom
8153 The different keywords are specified in the variable `org-todo-keywords'.
8154 By default the available states are \"TODO\" and \"DONE\".
8155 So for this example: when the item starts with TODO, it is changed to DONE.
8156 When it starts with DONE, the DONE is removed. And when neither TODO nor
8157 DONE are present, add TODO at the beginning of the heading.
8159 With C-u prefix arg, use completion to determine the new state.
8160 With numeric prefix arg, switch to that state.
8162 For calling through lisp, arg is also interpreted in the following way:
8163 'none -> empty state
8164 \"\"(empty string) -> switch to empty state
8165 'done -> switch to DONE
8166 'nextset -> switch to the next set of keywords
8167 'previousset -> switch to the previous set of keywords
8168 \"WAITING\" -> switch to the specified keyword, but only if it
8169 really is a member of `org-todo-keywords'."
8170 (interactive "P")
8171 (save-excursion
8172 (catch 'exit
8173 (org-back-to-heading)
8174 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8175 (or (looking-at (concat " +" org-todo-regexp " *"))
8176 (looking-at " *"))
8177 (let* ((match-data (match-data))
8178 (startpos (point-at-bol))
8179 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8180 (org-log-done org-log-done)
8181 (org-log-repeat org-log-repeat)
8182 (org-todo-log-states org-todo-log-states)
8183 (this (match-string 1))
8184 (hl-pos (match-beginning 0))
8185 (head (org-get-todo-sequence-head this))
8186 (ass (assoc head org-todo-kwd-alist))
8187 (interpret (nth 1 ass))
8188 (done-word (nth 3 ass))
8189 (final-done-word (nth 4 ass))
8190 (last-state (or this ""))
8191 (completion-ignore-case t)
8192 (member (member this org-todo-keywords-1))
8193 (tail (cdr member))
8194 (state (cond
8195 ((and org-todo-key-trigger
8196 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8197 (and (not arg) org-use-fast-todo-selection
8198 (not (eq org-use-fast-todo-selection 'prefix)))))
8199 ;; Use fast selection
8200 (org-fast-todo-selection))
8201 ((and (equal arg '(4))
8202 (or (not org-use-fast-todo-selection)
8203 (not org-todo-key-trigger)))
8204 ;; Read a state with completion
8205 (completing-read "State: " (mapcar (lambda(x) (list x))
8206 org-todo-keywords-1)
8207 nil t))
8208 ((eq arg 'right)
8209 (if this
8210 (if tail (car tail) nil)
8211 (car org-todo-keywords-1)))
8212 ((eq arg 'left)
8213 (if (equal member org-todo-keywords-1)
8215 (if this
8216 (nth (- (length org-todo-keywords-1) (length tail) 2)
8217 org-todo-keywords-1)
8218 (org-last org-todo-keywords-1))))
8219 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8220 (setq arg nil))) ; hack to fall back to cycling
8221 (arg
8222 ;; user or caller requests a specific state
8223 (cond
8224 ((equal arg "") nil)
8225 ((eq arg 'none) nil)
8226 ((eq arg 'done) (or done-word (car org-done-keywords)))
8227 ((eq arg 'nextset)
8228 (or (car (cdr (member head org-todo-heads)))
8229 (car org-todo-heads)))
8230 ((eq arg 'previousset)
8231 (let ((org-todo-heads (reverse org-todo-heads)))
8232 (or (car (cdr (member head org-todo-heads)))
8233 (car org-todo-heads))))
8234 ((car (member arg org-todo-keywords-1)))
8235 ((nth (1- (prefix-numeric-value arg))
8236 org-todo-keywords-1))))
8237 ((null member) (or head (car org-todo-keywords-1)))
8238 ((equal this final-done-word) nil) ;; -> make empty
8239 ((null tail) nil) ;; -> first entry
8240 ((eq interpret 'sequence)
8241 (car tail))
8242 ((memq interpret '(type priority))
8243 (if (eq this-command last-command)
8244 (car tail)
8245 (if (> (length tail) 0)
8246 (or done-word (car org-done-keywords))
8247 nil)))
8248 (t nil)))
8249 (next (if state (concat " " state " ") " "))
8250 (change-plist (list :type 'todo-state-change :from this :to state
8251 :position startpos))
8252 dolog now-done-p)
8253 (when org-blocker-hook
8254 (unless (save-excursion
8255 (save-match-data
8256 (run-hook-with-args-until-failure
8257 'org-blocker-hook change-plist)))
8258 (if (interactive-p)
8259 (error "TODO state change from %s to %s blocked" this state)
8260 ;; fail silently
8261 (message "TODO state change from %s to %s blocked" this state)
8262 (throw 'exit nil))))
8263 (store-match-data match-data)
8264 (replace-match next t t)
8265 (unless (pos-visible-in-window-p hl-pos)
8266 (message "TODO state changed to %s" (org-trim next)))
8267 (unless head
8268 (setq head (org-get-todo-sequence-head state)
8269 ass (assoc head org-todo-kwd-alist)
8270 interpret (nth 1 ass)
8271 done-word (nth 3 ass)
8272 final-done-word (nth 4 ass)))
8273 (when (memq arg '(nextset previousset))
8274 (message "Keyword-Set %d/%d: %s"
8275 (- (length org-todo-sets) -1
8276 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8277 (length org-todo-sets)
8278 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8279 (setq org-last-todo-state-is-todo
8280 (not (member state org-done-keywords)))
8281 (setq now-done-p (and (member state org-done-keywords)
8282 (not (member this org-done-keywords))))
8283 (and logging (org-local-logging logging))
8284 (when (and (or org-todo-log-states org-log-done)
8285 (not (memq arg '(nextset previousset))))
8286 ;; we need to look at recording a time and note
8287 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8288 (nth 2 (assoc this org-todo-log-states))))
8289 (when (and state
8290 (member state org-not-done-keywords)
8291 (not (member this org-not-done-keywords)))
8292 ;; This is now a todo state and was not one before
8293 ;; If there was a CLOSED time stamp, get rid of it.
8294 (org-add-planning-info nil nil 'closed))
8295 (when (and now-done-p org-log-done)
8296 ;; It is now done, and it was not done before
8297 (org-add-planning-info 'closed (org-current-time))
8298 (if (and (not dolog) (eq 'note org-log-done))
8299 (org-add-log-setup 'done state 'findpos 'note)))
8300 (when (and state dolog)
8301 ;; This is a non-nil state, and we need to log it
8302 (org-add-log-setup 'state state 'findpos dolog)))
8303 ;; Fixup tag positioning
8304 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8305 (when org-provide-todo-statistics
8306 (org-update-parent-todo-statistics))
8307 (run-hooks 'org-after-todo-state-change-hook)
8308 (if (and arg (not (member state org-done-keywords)))
8309 (setq head (org-get-todo-sequence-head state)))
8310 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8311 ;; Do we need to trigger a repeat?
8312 (when now-done-p (org-auto-repeat-maybe state))
8313 ;; Fixup cursor location if close to the keyword
8314 (if (and (outline-on-heading-p)
8315 (not (bolp))
8316 (save-excursion (beginning-of-line 1)
8317 (looking-at org-todo-line-regexp))
8318 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8319 (progn
8320 (goto-char (or (match-end 2) (match-end 1)))
8321 (just-one-space)))
8322 (when org-trigger-hook
8323 (save-excursion
8324 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8326 (defun org-update-parent-todo-statistics ()
8327 "Update any statistics cookie in the parent of the current headline."
8328 (interactive)
8329 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8330 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8331 (catch 'exit
8332 (save-excursion
8333 (setq level (org-up-heading-safe))
8334 (unless (and level
8335 (re-search-forward box-re (point-at-eol) t))
8336 (throw 'exit nil))
8337 (setq is-percent (match-end 2))
8338 (save-match-data
8339 (unless (outline-next-heading) (throw 'exit nil))
8340 (while (looking-at org-todo-line-regexp)
8341 (setq kwd (match-string 2))
8342 (and kwd (setq cnt-all (1+ cnt-all)))
8343 (and (member kwd org-done-keywords)
8344 (setq cnt-done (1+ cnt-done)))
8345 (condition-case nil
8346 (outline-forward-same-level 1)
8347 (error (end-of-line 1)))))
8348 (replace-match
8349 (if is-percent
8350 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8351 (format "[%d/%d]" cnt-done cnt-all)))
8352 (run-hook-with-args 'org-after-todo-statistics-hook
8353 cnt-done (- cnt-all cnt-done))))))
8355 (defvar org-after-todo-statistics-hook nil
8356 "Hook that is called after a TODO statistics cookie has been updated.
8357 Each function is called with two arguments: the number of not-done entries
8358 and the number of done entries.
8360 For example, the following function, when added to this hook, will switch
8361 an entry to DONE when all children are done, and back to TODO when new
8362 entries are set to a TODO status. Note that this hook is only called
8363 when there is a statistics cookie in the headline!
8365 (defun org-summary-todo (n-done n-not-done)
8366 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8367 (let (org-log-done org-log-states) ; turn off logging
8368 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8371 (defun org-local-logging (value)
8372 "Get logging settings from a property VALUE."
8373 (let* (words w a)
8374 ;; directly set the variables, they are already local.
8375 (setq org-log-done nil
8376 org-log-repeat nil
8377 org-todo-log-states nil)
8378 (setq words (org-split-string value))
8379 (while (setq w (pop words))
8380 (cond
8381 ((setq a (assoc w org-startup-options))
8382 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8383 (set (nth 1 a) (nth 2 a))))
8384 ((setq a (org-extract-log-state-settings w))
8385 (and (member (car a) org-todo-keywords-1)
8386 (push a org-todo-log-states)))))))
8388 (defun org-get-todo-sequence-head (kwd)
8389 "Return the head of the TODO sequence to which KWD belongs.
8390 If KWD is not set, check if there is a text property remembering the
8391 right sequence."
8392 (let (p)
8393 (cond
8394 ((not kwd)
8395 (or (get-text-property (point-at-bol) 'org-todo-head)
8396 (progn
8397 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8398 nil (point-at-eol)))
8399 (get-text-property p 'org-todo-head))))
8400 ((not (member kwd org-todo-keywords-1))
8401 (car org-todo-keywords-1))
8402 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8404 (defun org-fast-todo-selection ()
8405 "Fast TODO keyword selection with single keys.
8406 Returns the new TODO keyword, or nil if no state change should occur."
8407 (let* ((fulltable org-todo-key-alist)
8408 (done-keywords org-done-keywords) ;; needed for the faces.
8409 (maxlen (apply 'max (mapcar
8410 (lambda (x)
8411 (if (stringp (car x)) (string-width (car x)) 0))
8412 fulltable)))
8413 (expert nil)
8414 (fwidth (+ maxlen 3 1 3))
8415 (ncol (/ (- (window-width) 4) fwidth))
8416 tg cnt e c tbl
8417 groups ingroup)
8418 (save-window-excursion
8419 (if expert
8420 (set-buffer (get-buffer-create " *Org todo*"))
8421 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8422 (erase-buffer)
8423 (org-set-local 'org-done-keywords done-keywords)
8424 (setq tbl fulltable cnt 0)
8425 (while (setq e (pop tbl))
8426 (cond
8427 ((equal e '(:startgroup))
8428 (push '() groups) (setq ingroup t)
8429 (when (not (= cnt 0))
8430 (setq cnt 0)
8431 (insert "\n"))
8432 (insert "{ "))
8433 ((equal e '(:endgroup))
8434 (setq ingroup nil cnt 0)
8435 (insert "}\n"))
8437 (setq tg (car e) c (cdr e))
8438 (if ingroup (push tg (car groups)))
8439 (setq tg (org-add-props tg nil 'face
8440 (org-get-todo-face tg)))
8441 (if (and (= cnt 0) (not ingroup)) (insert " "))
8442 (insert "[" c "] " tg (make-string
8443 (- fwidth 4 (length tg)) ?\ ))
8444 (when (= (setq cnt (1+ cnt)) ncol)
8445 (insert "\n")
8446 (if ingroup (insert " "))
8447 (setq cnt 0)))))
8448 (insert "\n")
8449 (goto-char (point-min))
8450 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8451 (fit-window-to-buffer))
8452 (message "[a-z..]:Set [SPC]:clear")
8453 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8454 (cond
8455 ((or (= c ?\C-g)
8456 (and (= c ?q) (not (rassoc c fulltable))))
8457 (setq quit-flag t))
8458 ((= c ?\ ) nil)
8459 ((setq e (rassoc c fulltable) tg (car e))
8461 (t (setq quit-flag t))))))
8463 (defun org-entry-is-todo-p ()
8464 (member (org-get-todo-state) org-not-done-keywords))
8466 (defun org-entry-is-done-p ()
8467 (member (org-get-todo-state) org-done-keywords))
8469 (defun org-get-todo-state ()
8470 (save-excursion
8471 (org-back-to-heading t)
8472 (and (looking-at org-todo-line-regexp)
8473 (match-end 2)
8474 (match-string 2))))
8476 (defun org-at-date-range-p (&optional inactive-ok)
8477 "Is the cursor inside a date range?"
8478 (interactive)
8479 (save-excursion
8480 (catch 'exit
8481 (let ((pos (point)))
8482 (skip-chars-backward "^[<\r\n")
8483 (skip-chars-backward "<[")
8484 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8485 (>= (match-end 0) pos)
8486 (throw 'exit t))
8487 (skip-chars-backward "^<[\r\n")
8488 (skip-chars-backward "<[")
8489 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8490 (>= (match-end 0) pos)
8491 (throw 'exit t)))
8492 nil)))
8494 (defun org-get-repeat ()
8495 "Check if tere is a deadline/schedule with repeater in this entry."
8496 (save-match-data
8497 (save-excursion
8498 (org-back-to-heading t)
8499 (if (re-search-forward
8500 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8501 (match-string 1)))))
8503 (defvar org-last-changed-timestamp)
8504 (defvar org-log-post-message)
8505 (defvar org-log-note-purpose)
8506 (defvar org-log-note-how)
8507 (defun org-auto-repeat-maybe (done-word)
8508 "Check if the current headline contains a repeated deadline/schedule.
8509 If yes, set TODO state back to what it was and change the base date
8510 of repeating deadline/scheduled time stamps to new date.
8511 This function is run automatically after each state change to a DONE state."
8512 ;; last-state is dynamically scoped into this function
8513 (let* ((repeat (org-get-repeat))
8514 (aa (assoc last-state org-todo-kwd-alist))
8515 (interpret (nth 1 aa))
8516 (head (nth 2 aa))
8517 (whata '(("d" . day) ("m" . month) ("y" . year)))
8518 (msg "Entry repeats: ")
8519 (org-log-done nil)
8520 (org-todo-log-states nil)
8521 (nshiftmax 10) (nshift 0)
8522 re type n what ts mb0 time)
8523 (when repeat
8524 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8525 (org-todo (if (eq interpret 'type) last-state head))
8526 (when org-log-repeat
8527 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8528 (memq 'org-add-log-note post-command-hook))
8529 ;; OK, we are already setup for some record
8530 (if (eq org-log-repeat 'note)
8531 ;; make sure we take a note, not only a time stamp
8532 (setq org-log-note-how 'note))
8533 ;; Set up for taking a record
8534 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8535 'findpos org-log-repeat)))
8536 (org-back-to-heading t)
8537 (org-add-planning-info nil nil 'closed)
8538 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8539 org-deadline-time-regexp "\\)\\|\\("
8540 org-ts-regexp "\\)"))
8541 (while (re-search-forward
8542 re (save-excursion (outline-next-heading) (point)) t)
8543 (setq type (if (match-end 1) org-scheduled-string
8544 (if (match-end 3) org-deadline-string "Plain:"))
8545 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8546 mb0 (match-beginning 0))
8547 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8548 (setq n (string-to-number (match-string 2 ts))
8549 what (match-string 3 ts))
8550 (if (equal what "w") (setq n (* n 7) what "d"))
8551 ;; Preparation, see if we need to modify the start date for the change
8552 (when (match-end 1)
8553 (setq time (save-match-data (org-time-string-to-time ts)))
8554 (cond
8555 ((equal (match-string 1 ts) ".")
8556 ;; Shift starting date to today
8557 (org-timestamp-change
8558 (- (time-to-days (current-time)) (time-to-days time))
8559 'day))
8560 ((equal (match-string 1 ts) "+")
8561 (while (or (= nshift 0)
8562 (<= (time-to-days time) (time-to-days (current-time))))
8563 (when (= (incf nshift) nshiftmax)
8564 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8565 (error "Abort")))
8566 (org-timestamp-change n (cdr (assoc what whata)))
8567 (org-at-timestamp-p t)
8568 (setq ts (match-string 1))
8569 (setq time (save-match-data (org-time-string-to-time ts))))
8570 (org-timestamp-change (- n) (cdr (assoc what whata)))
8571 ;; rematch, so that we have everything in place for the real shift
8572 (org-at-timestamp-p t)
8573 (setq ts (match-string 1))
8574 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8575 (org-timestamp-change n (cdr (assoc what whata)))
8576 (setq msg (concat msg type org-last-changed-timestamp " "))))
8577 (setq org-log-post-message msg)
8578 (message "%s" msg))))
8580 (defun org-show-todo-tree (arg)
8581 "Make a compact tree which shows all headlines marked with TODO.
8582 The tree will show the lines where the regexp matches, and all higher
8583 headlines above the match.
8584 With a \\[universal-argument] prefix, also show the DONE entries.
8585 With a numeric prefix N, construct a sparse tree for the Nth element
8586 of `org-todo-keywords-1'."
8587 (interactive "P")
8588 (let ((case-fold-search nil)
8589 (kwd-re
8590 (cond ((null arg) org-not-done-regexp)
8591 ((equal arg '(4))
8592 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8593 (mapcar 'list org-todo-keywords-1))))
8594 (concat "\\("
8595 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8596 "\\)\\>")))
8597 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8598 (regexp-quote (nth (1- (prefix-numeric-value arg))
8599 org-todo-keywords-1)))
8600 (t (error "Invalid prefix argument: %s" arg)))))
8601 (message "%d TODO entries found"
8602 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8604 (defun org-deadline (&optional remove)
8605 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8606 With argument REMOVE, remove any deadline from the item."
8607 (interactive "P")
8608 (if remove
8609 (progn
8610 (org-remove-timestamp-with-keyword org-deadline-string)
8611 (message "Item no longer has a deadline."))
8612 (org-add-planning-info 'deadline nil 'closed)))
8614 (defun org-schedule (&optional remove)
8615 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8616 With argument REMOVE, remove any scheduling date from the item."
8617 (interactive "P")
8618 (if remove
8619 (progn
8620 (org-remove-timestamp-with-keyword org-scheduled-string)
8621 (message "Item is no longer scheduled."))
8622 (org-add-planning-info 'scheduled nil 'closed)))
8624 (defun org-remove-timestamp-with-keyword (keyword)
8625 "Remove all time stamps with KEYWORD in the current entry."
8626 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8627 beg)
8628 (save-excursion
8629 (org-back-to-heading t)
8630 (setq beg (point))
8631 (org-end-of-subtree t t)
8632 (while (re-search-backward re beg t)
8633 (replace-match "")
8634 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8635 (equal (char-before) ?\ ))
8636 (backward-delete-char 1)
8637 (if (string-match "^[ \t]*$" (buffer-substring
8638 (point-at-bol) (point-at-eol)))
8639 (delete-region (point-at-bol)
8640 (min (point-max) (1+ (point-at-eol))))))))))
8642 (defun org-add-planning-info (what &optional time &rest remove)
8643 "Insert new timestamp with keyword in the line directly after the headline.
8644 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8645 If non is given, the user is prompted for a date.
8646 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8647 be removed."
8648 (interactive)
8649 (let (org-time-was-given org-end-time-was-given ts
8650 end default-time default-input)
8652 (when (and (not time) (memq what '(scheduled deadline)))
8653 ;; Try to get a default date/time from existing timestamp
8654 (save-excursion
8655 (org-back-to-heading t)
8656 (setq end (save-excursion (outline-next-heading) (point)))
8657 (when (re-search-forward (if (eq what 'scheduled)
8658 org-scheduled-time-regexp
8659 org-deadline-time-regexp)
8660 end t)
8661 (setq ts (match-string 1)
8662 default-time
8663 (apply 'encode-time (org-parse-time-string ts))
8664 default-input (and ts (org-get-compact-tod ts))))))
8665 (when what
8666 ;; If necessary, get the time from the user
8667 (setq time (or time (org-read-date nil 'to-time nil nil
8668 default-time default-input))))
8670 (when (and org-insert-labeled-timestamps-at-point
8671 (member what '(scheduled deadline)))
8672 (insert
8673 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8674 (org-insert-time-stamp time org-time-was-given
8675 nil nil nil (list org-end-time-was-given))
8676 (setq what nil))
8677 (save-excursion
8678 (save-restriction
8679 (let (col list elt ts buffer-invisibility-spec)
8680 (org-back-to-heading t)
8681 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8682 (goto-char (match-end 1))
8683 (setq col (current-column))
8684 (goto-char (match-end 0))
8685 (if (eobp) (insert "\n") (forward-char 1))
8686 (if (and (not (looking-at outline-regexp))
8687 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8688 "[^\r\n]*"))
8689 (not (equal (match-string 1) org-clock-string)))
8690 (narrow-to-region (match-beginning 0) (match-end 0))
8691 (insert-before-markers "\n")
8692 (backward-char 1)
8693 (narrow-to-region (point) (point))
8694 (and org-adapt-indentation (org-indent-to-column col)))
8695 ;; Check if we have to remove something.
8696 (setq list (cons what remove))
8697 (while list
8698 (setq elt (pop list))
8699 (goto-char (point-min))
8700 (when (or (and (eq elt 'scheduled)
8701 (re-search-forward org-scheduled-time-regexp nil t))
8702 (and (eq elt 'deadline)
8703 (re-search-forward org-deadline-time-regexp nil t))
8704 (and (eq elt 'closed)
8705 (re-search-forward org-closed-time-regexp nil t)))
8706 (replace-match "")
8707 (if (looking-at "--+<[^>]+>") (replace-match ""))
8708 (if (looking-at " +") (replace-match ""))))
8709 (goto-char (point-max))
8710 (when what
8711 (insert
8712 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8713 (cond ((eq what 'scheduled) org-scheduled-string)
8714 ((eq what 'deadline) org-deadline-string)
8715 ((eq what 'closed) org-closed-string))
8716 " ")
8717 (setq ts (org-insert-time-stamp
8718 time
8719 (or org-time-was-given
8720 (and (eq what 'closed) org-log-done-with-time))
8721 (eq what 'closed)
8722 nil nil (list org-end-time-was-given)))
8723 (end-of-line 1))
8724 (goto-char (point-min))
8725 (widen)
8726 (if (and (looking-at "[ \t]+\n")
8727 (equal (char-before) ?\n))
8728 (delete-region (1- (point)) (point-at-eol)))
8729 ts)))))
8731 (defvar org-log-note-marker (make-marker))
8732 (defvar org-log-note-purpose nil)
8733 (defvar org-log-note-state nil)
8734 (defvar org-log-note-how nil)
8735 (defvar org-log-note-window-configuration nil)
8736 (defvar org-log-note-return-to (make-marker))
8737 (defvar org-log-post-message nil
8738 "Message to be displayed after a log note has been stored.
8739 The auto-repeater uses this.")
8741 (defun org-add-note ()
8742 "Add a note to the current entry.
8743 This is done in the same way as adding a state change note."
8744 (interactive)
8745 (org-add-log-setup 'note nil t nil))
8747 (defun org-add-log-setup (&optional purpose state findpos how)
8748 "Set up the post command hook to take a note.
8749 If this is about to TODO state change, the new state is expected in STATE.
8750 When FINDPOS is non-nil, find the correct position for the note in
8751 the current entry. If not, assume that it can be inserted at point."
8752 (save-excursion
8753 (when findpos
8754 (org-back-to-heading t)
8755 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8756 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8757 "[^\r\n]*\\)?"))
8758 (goto-char (match-end 0))
8759 (unless org-log-states-order-reversed
8760 (and (= (char-after) ?\n) (forward-char 1))
8761 (org-skip-over-state-notes)
8762 (skip-chars-backward " \t\n\r")))
8763 (move-marker org-log-note-marker (point))
8764 (setq org-log-note-purpose purpose
8765 org-log-note-state state
8766 org-log-note-how how)
8767 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8769 (defun org-skip-over-state-notes ()
8770 "Skip past the list of State notes in an entry."
8771 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8772 (while (looking-at "[ \t]*- State")
8773 (condition-case nil
8774 (org-next-item)
8775 (error (org-end-of-item)))))
8777 (defun org-add-log-note (&optional purpose)
8778 "Pop up a window for taking a note, and add this note later at point."
8779 (remove-hook 'post-command-hook 'org-add-log-note)
8780 (setq org-log-note-window-configuration (current-window-configuration))
8781 (delete-other-windows)
8782 (move-marker org-log-note-return-to (point))
8783 (switch-to-buffer (marker-buffer org-log-note-marker))
8784 (goto-char org-log-note-marker)
8785 (org-switch-to-buffer-other-window "*Org Note*")
8786 (erase-buffer)
8787 (if (memq org-log-note-how '(time state))
8788 (org-store-log-note)
8789 (let ((org-inhibit-startup t)) (org-mode))
8790 (insert (format "# Insert note for %s.
8791 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8792 (cond
8793 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8794 ((eq org-log-note-purpose 'done) "closed todo item")
8795 ((eq org-log-note-purpose 'state)
8796 (format "state change to \"%s\"" org-log-note-state))
8797 ((eq org-log-note-purpose 'note)
8798 "this entry")
8799 (t (error "This should not happen")))))
8800 (org-set-local 'org-finish-function 'org-store-log-note)))
8802 (defvar org-note-abort nil) ; dynamically scoped
8803 (defun org-store-log-note ()
8804 "Finish taking a log note, and insert it to where it belongs."
8805 (let ((txt (buffer-string))
8806 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8807 lines ind)
8808 (kill-buffer (current-buffer))
8809 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8810 (setq txt (replace-match "" t t txt)))
8811 (if (string-match "\\s-+\\'" txt)
8812 (setq txt (replace-match "" t t txt)))
8813 (setq lines (org-split-string txt "\n"))
8814 (when (and note (string-match "\\S-" note))
8815 (setq note
8816 (org-replace-escapes
8817 note
8818 (list (cons "%u" (user-login-name))
8819 (cons "%U" user-full-name)
8820 (cons "%t" (format-time-string
8821 (org-time-stamp-format 'long 'inactive)
8822 (current-time)))
8823 (cons "%s" (if org-log-note-state
8824 (concat "\"" org-log-note-state "\"")
8825 "")))))
8826 (if lines (setq note (concat note " \\\\")))
8827 (push note lines))
8828 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8829 (when lines
8830 (save-excursion
8831 (set-buffer (marker-buffer org-log-note-marker))
8832 (save-excursion
8833 (goto-char org-log-note-marker)
8834 (move-marker org-log-note-marker nil)
8835 (end-of-line 1)
8836 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8837 (indent-relative nil)
8838 (insert "- " (pop lines))
8839 (org-indent-line-function)
8840 (beginning-of-line 1)
8841 (looking-at "[ \t]*")
8842 (setq ind (concat (match-string 0) " "))
8843 (end-of-line 1)
8844 (while lines (insert "\n" ind (pop lines)))))))
8845 (set-window-configuration org-log-note-window-configuration)
8846 (with-current-buffer (marker-buffer org-log-note-return-to)
8847 (goto-char org-log-note-return-to))
8848 (move-marker org-log-note-return-to nil)
8849 (and org-log-post-message (message "%s" org-log-post-message)))
8851 (defun org-sparse-tree (&optional arg)
8852 "Create a sparse tree, prompt for the details.
8853 This command can create sparse trees. You first need to select the type
8854 of match used to create the tree:
8856 t Show entries with a specific TODO keyword.
8857 T Show entries selected by a tags match.
8858 p Enter a property name and its value (both with completion on existing
8859 names/values) and show entries with that property.
8860 r Show entries matching a regular expression
8861 d Show deadlines due within `org-deadline-warning-days'."
8862 (interactive "P")
8863 (let (ans kwd value)
8864 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8865 (setq ans (read-char-exclusive))
8866 (cond
8867 ((equal ans ?d)
8868 (call-interactively 'org-check-deadlines))
8869 ((equal ans ?b)
8870 (call-interactively 'org-check-before-date))
8871 ((equal ans ?t)
8872 (org-show-todo-tree '(4)))
8873 ((equal ans ?T)
8874 (call-interactively 'org-tags-sparse-tree))
8875 ((member ans '(?p ?P))
8876 (setq kwd (completing-read "Property: "
8877 (mapcar 'list (org-buffer-property-keys))))
8878 (setq value (completing-read "Value: "
8879 (mapcar 'list (org-property-values kwd))))
8880 (unless (string-match "\\`{.*}\\'" value)
8881 (setq value (concat "\"" value "\"")))
8882 (org-tags-sparse-tree arg (concat kwd "=" value)))
8883 ((member ans '(?r ?R ?/))
8884 (call-interactively 'org-occur))
8885 (t (error "No such sparse tree command \"%c\"" ans)))))
8887 (defvar org-occur-highlights nil
8888 "List of overlays used for occur matches.")
8889 (make-variable-buffer-local 'org-occur-highlights)
8890 (defvar org-occur-parameters nil
8891 "Parameters of the active org-occur calls.
8892 This is a list, each call to org-occur pushes as cons cell,
8893 containing the regular expression and the callback, onto the list.
8894 The list can contain several entries if `org-occur' has been called
8895 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8896 will only contain one set of parameters. When the highlights are
8897 removed (for example with `C-c C-c', or with the next edit (depending
8898 on `org-remove-highlights-with-change'), this variable is emptied
8899 as well.")
8900 (make-variable-buffer-local 'org-occur-parameters)
8902 (defun org-occur (regexp &optional keep-previous callback)
8903 "Make a compact tree which shows all matches of REGEXP.
8904 The tree will show the lines where the regexp matches, and all higher
8905 headlines above the match. It will also show the heading after the match,
8906 to make sure editing the matching entry is easy.
8907 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8908 call to `org-occur' will be kept, to allow stacking of calls to this
8909 command.
8910 If CALLBACK is non-nil, it is a function which is called to confirm
8911 that the match should indeed be shown."
8912 (interactive "sRegexp: \nP")
8913 (unless keep-previous
8914 (org-remove-occur-highlights nil nil t))
8915 (push (cons regexp callback) org-occur-parameters)
8916 (let ((cnt 0))
8917 (save-excursion
8918 (goto-char (point-min))
8919 (if (or (not keep-previous) ; do not want to keep
8920 (not org-occur-highlights)) ; no previous matches
8921 ;; hide everything
8922 (org-overview))
8923 (while (re-search-forward regexp nil t)
8924 (when (or (not callback)
8925 (save-match-data (funcall callback)))
8926 (setq cnt (1+ cnt))
8927 (when org-highlight-sparse-tree-matches
8928 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8929 (org-show-context 'occur-tree))))
8930 (when org-remove-highlights-with-change
8931 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8932 nil 'local))
8933 (unless org-sparse-tree-open-archived-trees
8934 (org-hide-archived-subtrees (point-min) (point-max)))
8935 (run-hooks 'org-occur-hook)
8936 (if (interactive-p)
8937 (message "%d match(es) for regexp %s" cnt regexp))
8938 cnt))
8940 (defun org-show-context (&optional key)
8941 "Make sure point and context and visible.
8942 How much context is shown depends upon the variables
8943 `org-show-hierarchy-above', `org-show-following-heading'. and
8944 `org-show-siblings'."
8945 (let ((heading-p (org-on-heading-p t))
8946 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8947 (following-p (org-get-alist-option org-show-following-heading key))
8948 (entry-p (org-get-alist-option org-show-entry-below key))
8949 (siblings-p (org-get-alist-option org-show-siblings key)))
8950 (catch 'exit
8951 ;; Show heading or entry text
8952 (if (and heading-p (not entry-p))
8953 (org-flag-heading nil) ; only show the heading
8954 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8955 (org-show-hidden-entry))) ; show entire entry
8956 (when following-p
8957 ;; Show next sibling, or heading below text
8958 (save-excursion
8959 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8960 (org-flag-heading nil))))
8961 (when siblings-p (org-show-siblings))
8962 (when hierarchy-p
8963 ;; show all higher headings, possibly with siblings
8964 (save-excursion
8965 (while (and (condition-case nil
8966 (progn (org-up-heading-all 1) t)
8967 (error nil))
8968 (not (bobp)))
8969 (org-flag-heading nil)
8970 (when siblings-p (org-show-siblings))))))))
8972 (defun org-reveal (&optional siblings)
8973 "Show current entry, hierarchy above it, and the following headline.
8974 This can be used to show a consistent set of context around locations
8975 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8976 not t for the search context.
8978 With optional argument SIBLINGS, on each level of the hierarchy all
8979 siblings are shown. This repairs the tree structure to what it would
8980 look like when opened with hierarchical calls to `org-cycle'."
8981 (interactive "P")
8982 (let ((org-show-hierarchy-above t)
8983 (org-show-following-heading t)
8984 (org-show-siblings (if siblings t org-show-siblings)))
8985 (org-show-context nil)))
8987 (defun org-highlight-new-match (beg end)
8988 "Highlight from BEG to END and mark the highlight is an occur headline."
8989 (let ((ov (org-make-overlay beg end)))
8990 (org-overlay-put ov 'face 'secondary-selection)
8991 (push ov org-occur-highlights)))
8993 (defun org-remove-occur-highlights (&optional beg end noremove)
8994 "Remove the occur highlights from the buffer.
8995 BEG and END are ignored. If NOREMOVE is nil, remove this function
8996 from the `before-change-functions' in the current buffer."
8997 (interactive)
8998 (unless org-inhibit-highlight-removal
8999 (mapc 'org-delete-overlay org-occur-highlights)
9000 (setq org-occur-highlights nil)
9001 (setq org-occur-parameters nil)
9002 (unless noremove
9003 (remove-hook 'before-change-functions
9004 'org-remove-occur-highlights 'local))))
9006 ;;;; Priorities
9008 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9009 "Regular expression matching the priority indicator.")
9011 (defvar org-remove-priority-next-time nil)
9013 (defun org-priority-up ()
9014 "Increase the priority of the current item."
9015 (interactive)
9016 (org-priority 'up))
9018 (defun org-priority-down ()
9019 "Decrease the priority of the current item."
9020 (interactive)
9021 (org-priority 'down))
9023 (defun org-priority (&optional action)
9024 "Change the priority of an item by ARG.
9025 ACTION can be `set', `up', `down', or a character."
9026 (interactive)
9027 (setq action (or action 'set))
9028 (let (current new news have remove)
9029 (save-excursion
9030 (org-back-to-heading)
9031 (if (looking-at org-priority-regexp)
9032 (setq current (string-to-char (match-string 2))
9033 have t)
9034 (setq current org-default-priority))
9035 (cond
9036 ((or (eq action 'set)
9037 (if (featurep 'xemacs) (characterp action) (integerp action)))
9038 (if (not (eq action 'set))
9039 (setq new action)
9040 (message "Priority %c-%c, SPC to remove: "
9041 org-highest-priority org-lowest-priority)
9042 (setq new (read-char-exclusive)))
9043 (if (and (= (upcase org-highest-priority) org-highest-priority)
9044 (= (upcase org-lowest-priority) org-lowest-priority))
9045 (setq new (upcase new)))
9046 (cond ((equal new ?\ ) (setq remove t))
9047 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9048 (error "Priority must be between `%c' and `%c'"
9049 org-highest-priority org-lowest-priority))))
9050 ((eq action 'up)
9051 (if (and (not have) (eq last-command this-command))
9052 (setq new org-lowest-priority)
9053 (setq new (if (and org-priority-start-cycle-with-default (not have))
9054 org-default-priority (1- current)))))
9055 ((eq action 'down)
9056 (if (and (not have) (eq last-command this-command))
9057 (setq new org-highest-priority)
9058 (setq new (if (and org-priority-start-cycle-with-default (not have))
9059 org-default-priority (1+ current)))))
9060 (t (error "Invalid action")))
9061 (if (or (< (upcase new) org-highest-priority)
9062 (> (upcase new) org-lowest-priority))
9063 (setq remove t))
9064 (setq news (format "%c" new))
9065 (if have
9066 (if remove
9067 (replace-match "" t t nil 1)
9068 (replace-match news t t nil 2))
9069 (if remove
9070 (error "No priority cookie found in line")
9071 (looking-at org-todo-line-regexp)
9072 (if (match-end 2)
9073 (progn
9074 (goto-char (match-end 2))
9075 (insert " [#" news "]"))
9076 (goto-char (match-beginning 3))
9077 (insert "[#" news "] ")))))
9078 (org-preserve-lc (org-set-tags nil 'align))
9079 (if remove
9080 (message "Priority removed")
9081 (message "Priority of current item set to %s" news))))
9084 (defun org-get-priority (s)
9085 "Find priority cookie and return priority."
9086 (save-match-data
9087 (if (not (string-match org-priority-regexp s))
9088 (* 1000 (- org-lowest-priority org-default-priority))
9089 (* 1000 (- org-lowest-priority
9090 (string-to-char (match-string 2 s)))))))
9092 ;;;; Tags
9094 (defun org-scan-tags (action matcher &optional todo-only)
9095 "Scan headline tags with inheritance and produce output ACTION.
9096 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9097 evaluated, testing if a given set of tags qualifies a headline for
9098 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9099 are included in the output."
9100 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9101 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9102 (org-re
9103 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9104 (props (list 'face nil
9105 'done-face 'org-done
9106 'undone-face nil
9107 'mouse-face 'highlight
9108 'org-not-done-regexp org-not-done-regexp
9109 'org-todo-regexp org-todo-regexp
9110 'keymap org-agenda-keymap
9111 'help-echo
9112 (format "mouse-2 or RET jump to org file %s"
9113 (abbreviate-file-name
9114 (or (buffer-file-name (buffer-base-buffer))
9115 (buffer-name (buffer-base-buffer)))))))
9116 (case-fold-search nil)
9117 lspos tags tags-list
9118 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9119 (llast 0) rtn level category i txt
9120 todo marker entry priority)
9121 (save-excursion
9122 (goto-char (point-min))
9123 (when (eq action 'sparse-tree)
9124 (org-overview)
9125 (org-remove-occur-highlights))
9126 (while (re-search-forward re nil t)
9127 (catch :skip
9128 (setq todo (if (match-end 1) (match-string 2))
9129 tags (if (match-end 4) (match-string 4)))
9130 (goto-char (setq lspos (1+ (match-beginning 0))))
9131 (setq level (org-reduced-level (funcall outline-level))
9132 category (org-get-category))
9133 (setq i llast llast level)
9134 ;; remove tag lists from same and sublevels
9135 (while (>= i level)
9136 (when (setq entry (assoc i tags-alist))
9137 (setq tags-alist (delete entry tags-alist)))
9138 (setq i (1- i)))
9139 ;; add the next tags
9140 (when tags
9141 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9142 tags-alist
9143 (cons (cons level tags) tags-alist)))
9144 ;; compile tags for current headline
9145 (setq tags-list
9146 (if org-use-tag-inheritance
9147 (apply 'append (mapcar 'cdr tags-alist))
9148 tags))
9149 (when (and tags org-use-tag-inheritance
9150 (not (eq t org-use-tag-inheritance)))
9151 ;; selective inheritance, remove uninherited ones
9152 (setcdr (car tags-alist)
9153 (org-remove-uniherited-tags (cdar tags-alist))))
9154 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9155 (eval matcher)
9156 (or (not org-agenda-skip-archived-trees)
9157 (not (member org-archive-tag tags-list))))
9158 (and (eq action 'agenda) (org-agenda-skip))
9159 ;; list this headline
9161 (if (eq action 'sparse-tree)
9162 (progn
9163 (and org-highlight-sparse-tree-matches
9164 (org-get-heading) (match-end 0)
9165 (org-highlight-new-match
9166 (match-beginning 0) (match-beginning 1)))
9167 (org-show-context 'tags-tree))
9168 (setq txt (org-format-agenda-item
9170 (concat
9171 (if org-tags-match-list-sublevels
9172 (make-string (1- level) ?.) "")
9173 (org-get-heading))
9174 category tags-list)
9175 priority (org-get-priority txt))
9176 (goto-char lspos)
9177 (setq marker (org-agenda-new-marker))
9178 (org-add-props txt props
9179 'org-marker marker 'org-hd-marker marker 'org-category category
9180 'priority priority 'type "tagsmatch")
9181 (push txt rtn))
9182 ;; if we are to skip sublevels, jump to end of subtree
9183 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9184 (when (and (eq action 'sparse-tree)
9185 (not org-sparse-tree-open-archived-trees))
9186 (org-hide-archived-subtrees (point-min) (point-max)))
9187 (nreverse rtn)))
9189 (defun org-remove-uniherited-tags (tags)
9190 "Remove all tags that are not inherited from the list TAGS."
9191 (cond
9192 ((eq org-use-tag-inheritance t) tags)
9193 ((not org-use-tag-inheritance) nil)
9194 ((stringp org-use-tag-inheritance)
9195 (delq nil (mapcar
9196 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9197 tags)))
9198 ((listp org-use-tag-inheritance)
9199 (org-delete-all org-use-tag-inheritance tags))))
9201 (defvar todo-only) ;; dynamically scoped
9203 (defun org-tags-sparse-tree (&optional todo-only match)
9204 "Create a sparse tree according to tags string MATCH.
9205 MATCH can contain positive and negative selection of tags, like
9206 \"+WORK+URGENT-WITHBOSS\".
9207 If optional argument TODO_ONLY is non-nil, only select lines that are
9208 also TODO lines."
9209 (interactive "P")
9210 (org-prepare-agenda-buffers (list (current-buffer)))
9211 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9213 (defvar org-cached-props nil)
9214 (defun org-cached-entry-get (pom property)
9215 (if (or (eq t org-use-property-inheritance)
9216 (and (stringp org-use-property-inheritance)
9217 (string-match org-use-property-inheritance property))
9218 (and (listp org-use-property-inheritance)
9219 (member property org-use-property-inheritance)))
9220 ;; Caching is not possible, check it directly
9221 (org-entry-get pom property 'inherit)
9222 ;; Get all properties, so that we can do complicated checks easily
9223 (cdr (assoc property (or org-cached-props
9224 (setq org-cached-props
9225 (org-entry-properties pom)))))))
9227 (defun org-global-tags-completion-table (&optional files)
9228 "Return the list of all tags in all agenda buffer/files."
9229 (save-excursion
9230 (org-uniquify
9231 (delq nil
9232 (apply 'append
9233 (mapcar
9234 (lambda (file)
9235 (set-buffer (find-file-noselect file))
9236 (append (org-get-buffer-tags)
9237 (mapcar (lambda (x) (if (stringp (car-safe x))
9238 (list (car-safe x)) nil))
9239 org-tag-alist)))
9240 (if (and files (car files))
9241 files
9242 (org-agenda-files))))))))
9244 (defun org-make-tags-matcher (match)
9245 "Create the TAGS//TODO matcher form for the selection string MATCH."
9246 ;; todo-only is scoped dynamically into this function, and the function
9247 ;; may change it it the matcher asksk for it.
9248 (unless match
9249 ;; Get a new match request, with completion
9250 (let ((org-last-tags-completion-table
9251 (org-global-tags-completion-table)))
9252 (setq match (completing-read
9253 "Match: " 'org-tags-completion-function nil nil nil
9254 'org-tags-history))))
9256 ;; Parse the string and create a lisp form
9257 (let ((match0 match)
9258 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9259 minus tag mm
9260 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9261 orterms term orlist re-p str-p level-p level-op
9262 prop-p pn pv po cat-p gv)
9263 (if (string-match "/+" match)
9264 ;; match contains also a todo-matching request
9265 (progn
9266 (setq tagsmatch (substring match 0 (match-beginning 0))
9267 todomatch (substring match (match-end 0)))
9268 (if (string-match "^!" todomatch)
9269 (setq todo-only t todomatch (substring todomatch 1)))
9270 (if (string-match "^\\s-*$" todomatch)
9271 (setq todomatch nil)))
9272 ;; only matching tags
9273 (setq tagsmatch match todomatch nil))
9275 ;; Make the tags matcher
9276 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9277 (setq tagsmatcher t)
9278 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9279 (while (setq term (pop orterms))
9280 (while (and (equal (substring term -1) "\\") orterms)
9281 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9282 (while (string-match re term)
9283 (setq minus (and (match-end 1)
9284 (equal (match-string 1 term) "-"))
9285 tag (match-string 2 term)
9286 re-p (equal (string-to-char tag) ?{)
9287 level-p (match-end 4)
9288 prop-p (match-end 5)
9289 mm (cond
9290 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9291 (level-p
9292 (setq level-op (org-op-to-function (match-string 3 term)))
9293 `(,level-op level ,(string-to-number
9294 (match-string 4 term))))
9295 (prop-p
9296 (setq pn (match-string 5 term)
9297 po (match-string 6 term)
9298 pv (match-string 7 term)
9299 cat-p (equal pn "CATEGORY")
9300 re-p (equal (string-to-char pv) ?{)
9301 str-p (equal (string-to-char pv) ?\")
9302 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9303 (setq po (org-op-to-function po str-p))
9304 (if (equal pn "CATEGORY")
9305 (setq gv '(get-text-property (point) 'org-category))
9306 (setq gv `(org-cached-entry-get nil ,pn)))
9307 (if re-p
9308 (if (eq po 'org<>)
9309 `(not (string-match ,pv (or ,gv "")))
9310 `(string-match ,pv (or ,gv "")))
9311 (if str-p
9312 `(,po (or ,gv "") ,pv)
9313 `(,po (string-to-number (or ,gv ""))
9314 ,(string-to-number pv) ))))
9315 (t `(member ,(downcase tag) tags-list)))
9316 mm (if minus (list 'not mm) mm)
9317 term (substring term (match-end 0)))
9318 (push mm tagsmatcher))
9319 (push (if (> (length tagsmatcher) 1)
9320 (cons 'and tagsmatcher)
9321 (car tagsmatcher))
9322 orlist)
9323 (setq tagsmatcher nil))
9324 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9325 (setq tagsmatcher
9326 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9327 ;; Make the todo matcher
9328 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9329 (setq todomatcher t)
9330 (setq orterms (org-split-string todomatch "|") orlist nil)
9331 (while (setq term (pop orterms))
9332 (while (string-match re term)
9333 (setq minus (and (match-end 1)
9334 (equal (match-string 1 term) "-"))
9335 kwd (match-string 2 term)
9336 re-p (equal (string-to-char kwd) ?{)
9337 term (substring term (match-end 0))
9338 mm (if re-p
9339 `(string-match ,(substring kwd 1 -1) todo)
9340 (list 'equal 'todo kwd))
9341 mm (if minus (list 'not mm) mm))
9342 (push mm todomatcher))
9343 (push (if (> (length todomatcher) 1)
9344 (cons 'and todomatcher)
9345 (car todomatcher))
9346 orlist)
9347 (setq todomatcher nil))
9348 (setq todomatcher (if (> (length orlist) 1)
9349 (cons 'or orlist) (car orlist))))
9351 ;; Return the string and lisp forms of the matcher
9352 (setq matcher (if todomatcher
9353 (list 'and tagsmatcher todomatcher)
9354 tagsmatcher))
9355 (cons match0 matcher)))
9357 (defun org-op-to-function (op &optional stringp)
9358 (setq op
9359 (cond
9360 ((equal op "<" ) '(< string< ))
9361 ((equal op ">" ) '(> org-string> ))
9362 ((member op '("<=" "=<")) '(<= org-string<= ))
9363 ((member op '(">=" "=>")) '(>= org-string>= ))
9364 ((member op '("=" "==")) '(= string= ))
9365 ((member op '("<>" "!=")) '(org<> org-string<> ))))
9366 (nth (if stringp 1 0) op))
9368 (defun org<> (a b) (not (= a b)))
9369 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9370 (defun org-string>= (a b) (not (string< a b)))
9371 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9372 (defun org-string<> (a b) (not (string= a b)))
9374 (defun org-match-any-p (re list)
9375 "Does re match any element of list?"
9376 (setq list (mapcar (lambda (x) (string-match re x)) list))
9377 (delq nil list))
9379 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9380 (defvar org-tags-overlay (org-make-overlay 1 1))
9381 (org-detach-overlay org-tags-overlay)
9383 (defun org-get-tags-at (&optional pos)
9384 "Get a list of all headline tags applicable at POS.
9385 POS defaults to point. If tags are inherited, the list contains
9386 the targets in the same sequence as the headlines appear, i.e.
9387 sthe tags of the current headline come last."
9388 (interactive)
9389 (let (tags ltags lastpos parent)
9390 (save-excursion
9391 (save-restriction
9392 (widen)
9393 (goto-char (or pos (point)))
9394 (save-match-data
9395 (condition-case nil
9396 (progn
9397 (org-back-to-heading t)
9398 (while (not (equal lastpos (point)))
9399 (setq lastpos (point))
9400 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9401 (setq ltags (org-split-string
9402 (org-match-string-no-properties 1) ":"))
9403 (setq tags (append (org-remove-uniherited-tags ltags)
9404 tags)))
9405 (or org-use-tag-inheritance (error ""))
9406 (org-up-heading-all 1)
9407 (setq parent t)))
9408 (error nil))))
9409 tags)))
9411 (defun org-toggle-tag (tag &optional onoff)
9412 "Toggle the tag TAG for the current line.
9413 If ONOFF is `on' or `off', don't toggle but set to this state."
9414 (unless (org-on-heading-p t) (error "Not on headling"))
9415 (let (res current)
9416 (save-excursion
9417 (beginning-of-line)
9418 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9419 (point-at-eol) t)
9420 (progn
9421 (setq current (match-string 1))
9422 (replace-match ""))
9423 (setq current ""))
9424 (setq current (nreverse (org-split-string current ":")))
9425 (cond
9426 ((eq onoff 'on)
9427 (setq res t)
9428 (or (member tag current) (push tag current)))
9429 ((eq onoff 'off)
9430 (or (not (member tag current)) (setq current (delete tag current))))
9431 (t (if (member tag current)
9432 (setq current (delete tag current))
9433 (setq res t)
9434 (push tag current))))
9435 (end-of-line 1)
9436 (if current
9437 (progn
9438 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9439 (org-set-tags nil t))
9440 (delete-horizontal-space))
9441 (run-hooks 'org-after-tags-change-hook))
9442 res))
9444 (defun org-align-tags-here (to-col)
9445 ;; Assumes that this is a headline
9446 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9447 (beginning-of-line 1)
9448 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9449 (< pos (match-beginning 2)))
9450 (progn
9451 (setq tags-l (- (match-end 2) (match-beginning 2)))
9452 (goto-char (match-beginning 1))
9453 (insert " ")
9454 (delete-region (point) (1+ (match-beginning 2)))
9455 (setq ncol (max (1+ (current-column))
9456 (1+ col)
9457 (if (> to-col 0)
9458 to-col
9459 (- (abs to-col) tags-l))))
9460 (setq p (point))
9461 (insert (make-string (- ncol (current-column)) ?\ ))
9462 (setq ncol (current-column))
9463 (tabify p (point-at-eol))
9464 (org-move-to-column (min ncol col) t))
9465 (goto-char pos))))
9467 (defun org-set-tags (&optional arg just-align)
9468 "Set the tags for the current headline.
9469 With prefix ARG, realign all tags in headings in the current buffer."
9470 (interactive "P")
9471 (let* ((re (concat "^" outline-regexp))
9472 (current (org-get-tags-string))
9473 (col (current-column))
9474 (org-setting-tags t)
9475 table current-tags inherited-tags ; computed below when needed
9476 tags p0 c0 c1 rpl)
9477 (if arg
9478 (save-excursion
9479 (goto-char (point-min))
9480 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9481 (while (re-search-forward re nil t)
9482 (org-set-tags nil t)
9483 (end-of-line 1)))
9484 (message "All tags realigned to column %d" org-tags-column))
9485 (if just-align
9486 (setq tags current)
9487 ;; Get a new set of tags from the user
9488 (save-excursion
9489 (setq table (or org-tag-alist (org-get-buffer-tags))
9490 org-last-tags-completion-table table
9491 current-tags (org-split-string current ":")
9492 inherited-tags (nreverse
9493 (nthcdr (length current-tags)
9494 (nreverse (org-get-tags-at))))
9495 tags
9496 (if (or (eq t org-use-fast-tag-selection)
9497 (and org-use-fast-tag-selection
9498 (delq nil (mapcar 'cdr table))))
9499 (org-fast-tag-selection
9500 current-tags inherited-tags table
9501 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9502 (let ((org-add-colon-after-tag-completion t))
9503 (org-trim
9504 (org-without-partial-completion
9505 (completing-read "Tags: " 'org-tags-completion-function
9506 nil nil current 'org-tags-history)))))))
9507 (while (string-match "[-+&]+" tags)
9508 ;; No boolean logic, just a list
9509 (setq tags (replace-match ":" t t tags))))
9511 (if (string-match "\\`[\t ]*\\'" tags)
9512 (setq tags "")
9513 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9514 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9516 ;; Insert new tags at the correct column
9517 (beginning-of-line 1)
9518 (cond
9519 ((and (equal current "") (equal tags "")))
9520 ((re-search-forward
9521 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9522 (point-at-eol) t)
9523 (if (equal tags "")
9524 (setq rpl "")
9525 (goto-char (match-beginning 0))
9526 (setq c0 (current-column) p0 (point)
9527 c1 (max (1+ c0) (if (> org-tags-column 0)
9528 org-tags-column
9529 (- (- org-tags-column) (length tags))))
9530 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9531 (replace-match rpl t t)
9532 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9533 tags)
9534 (t (error "Tags alignment failed")))
9535 (org-move-to-column col)
9536 (unless just-align
9537 (run-hooks 'org-after-tags-change-hook)))))
9539 (defun org-change-tag-in-region (beg end tag off)
9540 "Add or remove TAG for each entry in the region.
9541 This works in the agenda, and also in an org-mode buffer."
9542 (interactive
9543 (list (region-beginning) (region-end)
9544 (let ((org-last-tags-completion-table
9545 (if (org-mode-p)
9546 (org-get-buffer-tags)
9547 (org-global-tags-completion-table))))
9548 (completing-read
9549 "Tag: " 'org-tags-completion-function nil nil nil
9550 'org-tags-history))
9551 (progn
9552 (message "[s]et or [r]emove? ")
9553 (equal (read-char-exclusive) ?r))))
9554 (if (fboundp 'deactivate-mark) (deactivate-mark))
9555 (let ((agendap (equal major-mode 'org-agenda-mode))
9556 l1 l2 m buf pos newhead (cnt 0))
9557 (goto-char end)
9558 (setq l2 (1- (org-current-line)))
9559 (goto-char beg)
9560 (setq l1 (org-current-line))
9561 (loop for l from l1 to l2 do
9562 (goto-line l)
9563 (setq m (get-text-property (point) 'org-hd-marker))
9564 (when (or (and (org-mode-p) (org-on-heading-p))
9565 (and agendap m))
9566 (setq buf (if agendap (marker-buffer m) (current-buffer))
9567 pos (if agendap m (point)))
9568 (with-current-buffer buf
9569 (save-excursion
9570 (save-restriction
9571 (goto-char pos)
9572 (setq cnt (1+ cnt))
9573 (org-toggle-tag tag (if off 'off 'on))
9574 (setq newhead (org-get-heading)))))
9575 (and agendap (org-agenda-change-all-lines newhead m))))
9576 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9578 (defun org-tags-completion-function (string predicate &optional flag)
9579 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9580 (confirm (lambda (x) (stringp (car x)))))
9581 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9582 (setq s1 (match-string 1 string)
9583 s2 (match-string 2 string))
9584 (setq s1 "" s2 string))
9585 (cond
9586 ((eq flag nil)
9587 ;; try completion
9588 (setq rtn (try-completion s2 ctable confirm))
9589 (if (stringp rtn)
9590 (setq rtn
9591 (concat s1 s2 (substring rtn (length s2))
9592 (if (and org-add-colon-after-tag-completion
9593 (assoc rtn ctable))
9594 ":" ""))))
9595 rtn)
9596 ((eq flag t)
9597 ;; all-completions
9598 (all-completions s2 ctable confirm)
9600 ((eq flag 'lambda)
9601 ;; exact match?
9602 (assoc s2 ctable)))
9605 (defun org-fast-tag-insert (kwd tags face &optional end)
9606 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9607 (insert (format "%-12s" (concat kwd ":"))
9608 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9609 (or end "")))
9611 (defun org-fast-tag-show-exit (flag)
9612 (save-excursion
9613 (goto-line 3)
9614 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9615 (replace-match ""))
9616 (when flag
9617 (end-of-line 1)
9618 (org-move-to-column (- (window-width) 19) t)
9619 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9621 (defun org-set-current-tags-overlay (current prefix)
9622 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9623 (if (featurep 'xemacs)
9624 (org-overlay-display org-tags-overlay (concat prefix s)
9625 'secondary-selection)
9626 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9627 (org-overlay-display org-tags-overlay (concat prefix s)))))
9629 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9630 "Fast tag selection with single keys.
9631 CURRENT is the current list of tags in the headline, INHERITED is the
9632 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9633 possibly with grouping information. TODO-TABLE is a similar table with
9634 TODO keywords, should these have keys assigned to them.
9635 If the keys are nil, a-z are automatically assigned.
9636 Returns the new tags string, or nil to not change the current settings."
9637 (let* ((fulltable (append table todo-table))
9638 (maxlen (apply 'max (mapcar
9639 (lambda (x)
9640 (if (stringp (car x)) (string-width (car x)) 0))
9641 fulltable)))
9642 (buf (current-buffer))
9643 (expert (eq org-fast-tag-selection-single-key 'expert))
9644 (buffer-tags nil)
9645 (fwidth (+ maxlen 3 1 3))
9646 (ncol (/ (- (window-width) 4) fwidth))
9647 (i-face 'org-done)
9648 (c-face 'org-todo)
9649 tg cnt e c char c1 c2 ntable tbl rtn
9650 ov-start ov-end ov-prefix
9651 (exit-after-next org-fast-tag-selection-single-key)
9652 (done-keywords org-done-keywords)
9653 groups ingroup)
9654 (save-excursion
9655 (beginning-of-line 1)
9656 (if (looking-at
9657 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9658 (setq ov-start (match-beginning 1)
9659 ov-end (match-end 1)
9660 ov-prefix "")
9661 (setq ov-start (1- (point-at-eol))
9662 ov-end (1+ ov-start))
9663 (skip-chars-forward "^\n\r")
9664 (setq ov-prefix
9665 (concat
9666 (buffer-substring (1- (point)) (point))
9667 (if (> (current-column) org-tags-column)
9669 (make-string (- org-tags-column (current-column)) ?\ ))))))
9670 (org-move-overlay org-tags-overlay ov-start ov-end)
9671 (save-window-excursion
9672 (if expert
9673 (set-buffer (get-buffer-create " *Org tags*"))
9674 (delete-other-windows)
9675 (split-window-vertically)
9676 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9677 (erase-buffer)
9678 (org-set-local 'org-done-keywords done-keywords)
9679 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9680 (org-fast-tag-insert "Current" current c-face "\n\n")
9681 (org-fast-tag-show-exit exit-after-next)
9682 (org-set-current-tags-overlay current ov-prefix)
9683 (setq tbl fulltable char ?a cnt 0)
9684 (while (setq e (pop tbl))
9685 (cond
9686 ((equal e '(:startgroup))
9687 (push '() groups) (setq ingroup t)
9688 (when (not (= cnt 0))
9689 (setq cnt 0)
9690 (insert "\n"))
9691 (insert "{ "))
9692 ((equal e '(:endgroup))
9693 (setq ingroup nil cnt 0)
9694 (insert "}\n"))
9696 (setq tg (car e) c2 nil)
9697 (if (cdr e)
9698 (setq c (cdr e))
9699 ;; automatically assign a character.
9700 (setq c1 (string-to-char
9701 (downcase (substring
9702 tg (if (= (string-to-char tg) ?@) 1 0)))))
9703 (if (or (rassoc c1 ntable) (rassoc c1 table))
9704 (while (or (rassoc char ntable) (rassoc char table))
9705 (setq char (1+ char)))
9706 (setq c2 c1))
9707 (setq c (or c2 char)))
9708 (if ingroup (push tg (car groups)))
9709 (setq tg (org-add-props tg nil 'face
9710 (cond
9711 ((not (assoc tg table))
9712 (org-get-todo-face tg))
9713 ((member tg current) c-face)
9714 ((member tg inherited) i-face)
9715 (t nil))))
9716 (if (and (= cnt 0) (not ingroup)) (insert " "))
9717 (insert "[" c "] " tg (make-string
9718 (- fwidth 4 (length tg)) ?\ ))
9719 (push (cons tg c) ntable)
9720 (when (= (setq cnt (1+ cnt)) ncol)
9721 (insert "\n")
9722 (if ingroup (insert " "))
9723 (setq cnt 0)))))
9724 (setq ntable (nreverse ntable))
9725 (insert "\n")
9726 (goto-char (point-min))
9727 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9728 (fit-window-to-buffer))
9729 (setq rtn
9730 (catch 'exit
9731 (while t
9732 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9733 (if groups " [!] no groups" " [!]groups")
9734 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9735 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9736 (cond
9737 ((= c ?\r) (throw 'exit t))
9738 ((= c ?!)
9739 (setq groups (not groups))
9740 (goto-char (point-min))
9741 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9742 ((= c ?\C-c)
9743 (if (not expert)
9744 (org-fast-tag-show-exit
9745 (setq exit-after-next (not exit-after-next)))
9746 (setq expert nil)
9747 (delete-other-windows)
9748 (split-window-vertically)
9749 (org-switch-to-buffer-other-window " *Org tags*")
9750 (and (fboundp 'fit-window-to-buffer)
9751 (fit-window-to-buffer))))
9752 ((or (= c ?\C-g)
9753 (and (= c ?q) (not (rassoc c ntable))))
9754 (org-detach-overlay org-tags-overlay)
9755 (setq quit-flag t))
9756 ((= c ?\ )
9757 (setq current nil)
9758 (if exit-after-next (setq exit-after-next 'now)))
9759 ((= c ?\t)
9760 (condition-case nil
9761 (setq tg (completing-read
9762 "Tag: "
9763 (or buffer-tags
9764 (with-current-buffer buf
9765 (org-get-buffer-tags)))))
9766 (quit (setq tg "")))
9767 (when (string-match "\\S-" tg)
9768 (add-to-list 'buffer-tags (list tg))
9769 (if (member tg current)
9770 (setq current (delete tg current))
9771 (push tg current)))
9772 (if exit-after-next (setq exit-after-next 'now)))
9773 ((setq e (rassoc c todo-table) tg (car e))
9774 (with-current-buffer buf
9775 (save-excursion (org-todo tg)))
9776 (if exit-after-next (setq exit-after-next 'now)))
9777 ((setq e (rassoc c ntable) tg (car e))
9778 (if (member tg current)
9779 (setq current (delete tg current))
9780 (loop for g in groups do
9781 (if (member tg g)
9782 (mapc (lambda (x)
9783 (setq current (delete x current)))
9784 g)))
9785 (push tg current))
9786 (if exit-after-next (setq exit-after-next 'now))))
9788 ;; Create a sorted list
9789 (setq current
9790 (sort current
9791 (lambda (a b)
9792 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9793 (if (eq exit-after-next 'now) (throw 'exit t))
9794 (goto-char (point-min))
9795 (beginning-of-line 2)
9796 (delete-region (point) (point-at-eol))
9797 (org-fast-tag-insert "Current" current c-face)
9798 (org-set-current-tags-overlay current ov-prefix)
9799 (while (re-search-forward
9800 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9801 (setq tg (match-string 1))
9802 (add-text-properties
9803 (match-beginning 1) (match-end 1)
9804 (list 'face
9805 (cond
9806 ((member tg current) c-face)
9807 ((member tg inherited) i-face)
9808 (t (get-text-property (match-beginning 1) 'face))))))
9809 (goto-char (point-min)))))
9810 (org-detach-overlay org-tags-overlay)
9811 (if rtn
9812 (mapconcat 'identity current ":")
9813 nil))))
9815 (defun org-get-tags-string ()
9816 "Get the TAGS string in the current headline."
9817 (unless (org-on-heading-p t)
9818 (error "Not on a heading"))
9819 (save-excursion
9820 (beginning-of-line 1)
9821 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9822 (org-match-string-no-properties 1)
9823 "")))
9825 (defun org-get-tags ()
9826 "Get the list of tags specified in the current headline."
9827 (org-split-string (org-get-tags-string) ":"))
9829 (defun org-get-buffer-tags ()
9830 "Get a table of all tags used in the buffer, for completion."
9831 (let (tags)
9832 (save-excursion
9833 (goto-char (point-min))
9834 (while (re-search-forward
9835 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9836 (when (equal (char-after (point-at-bol 0)) ?*)
9837 (mapc (lambda (x) (add-to-list 'tags x))
9838 (org-split-string (org-match-string-no-properties 1) ":")))))
9839 (mapcar 'list tags)))
9842 ;;;; Properties
9844 ;;; Setting and retrieving properties
9846 (defconst org-special-properties
9847 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9848 "TIMESTAMP" "TIMESTAMP_IA")
9849 "The special properties valid in Org-mode.
9851 These are properties that are not defined in the property drawer,
9852 but in some other way.")
9854 (defconst org-default-properties
9855 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9856 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9857 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9858 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9859 "Some properties that are used by Org-mode for various purposes.
9860 Being in this list makes sure that they are offered for completion.")
9862 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9863 "Regular expression matching the first line of a property drawer.")
9865 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9866 "Regular expression matching the first line of a property drawer.")
9868 (defun org-property-action ()
9869 "Do an action on properties."
9870 (interactive)
9871 (let (c)
9872 (org-at-property-p)
9873 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9874 (setq c (read-char-exclusive))
9875 (cond
9876 ((equal c ?s)
9877 (call-interactively 'org-set-property))
9878 ((equal c ?d)
9879 (call-interactively 'org-delete-property))
9880 ((equal c ?D)
9881 (call-interactively 'org-delete-property-globally))
9882 ((equal c ?c)
9883 (call-interactively 'org-compute-property-at-point))
9884 (t (error "No such property action %c" c)))))
9886 (defun org-at-property-p ()
9887 "Is the cursor in a property line?"
9888 ;; FIXME: Does not check if we are actually in the drawer.
9889 ;; FIXME: also returns true on any drawers.....
9890 ;; This is used by C-c C-c for property action.
9891 (save-excursion
9892 (beginning-of-line 1)
9893 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9895 (defun org-get-property-block (&optional beg end force)
9896 "Return the (beg . end) range of the body of the property drawer.
9897 BEG and END can be beginning and end of subtree, if not given
9898 they will be found.
9899 If the drawer does not exist and FORCE is non-nil, create the drawer."
9900 (catch 'exit
9901 (save-excursion
9902 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9903 (end (or end (progn (outline-next-heading) (point)))))
9904 (goto-char beg)
9905 (if (re-search-forward org-property-start-re end t)
9906 (setq beg (1+ (match-end 0)))
9907 (if force
9908 (save-excursion
9909 (org-insert-property-drawer)
9910 (setq end (progn (outline-next-heading) (point))))
9911 (throw 'exit nil))
9912 (goto-char beg)
9913 (if (re-search-forward org-property-start-re end t)
9914 (setq beg (1+ (match-end 0)))))
9915 (if (re-search-forward org-property-end-re end t)
9916 (setq end (match-beginning 0))
9917 (or force (throw 'exit nil))
9918 (goto-char beg)
9919 (setq end beg)
9920 (org-indent-line-function)
9921 (insert ":END:\n"))
9922 (cons beg end)))))
9924 (defun org-entry-properties (&optional pom which)
9925 "Get all properties of the entry at point-or-marker POM.
9926 This includes the TODO keyword, the tags, time strings for deadline,
9927 scheduled, and clocking, and any additional properties defined in the
9928 entry. The return value is an alist, keys may occur multiple times
9929 if the property key was used several times.
9930 POM may also be nil, in which case the current entry is used.
9931 If WHICH is nil or `all', get all properties. If WHICH is
9932 `special' or `standard', only get that subclass."
9933 (setq which (or which 'all))
9934 (org-with-point-at pom
9935 (let ((clockstr (substring org-clock-string 0 -1))
9936 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9937 beg end range props sum-props key value string clocksum)
9938 (save-excursion
9939 (when (condition-case nil (org-back-to-heading t) (error nil))
9940 (setq beg (point))
9941 (setq sum-props (get-text-property (point) 'org-summaries))
9942 (setq clocksum (get-text-property (point) :org-clock-minutes))
9943 (outline-next-heading)
9944 (setq end (point))
9945 (when (memq which '(all special))
9946 ;; Get the special properties, like TODO and tags
9947 (goto-char beg)
9948 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9949 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9950 (when (looking-at org-priority-regexp)
9951 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9952 (when (and (setq value (org-get-tags-string))
9953 (string-match "\\S-" value))
9954 (push (cons "TAGS" value) props))
9955 (when (setq value (org-get-tags-at))
9956 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9957 props))
9958 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9959 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9960 string (if (equal key clockstr)
9961 (org-no-properties
9962 (org-trim
9963 (buffer-substring
9964 (match-beginning 3) (goto-char (point-at-eol)))))
9965 (substring (org-match-string-no-properties 3) 1 -1)))
9966 (unless key
9967 (if (= (char-after (match-beginning 3)) ?\[)
9968 (setq key "TIMESTAMP_IA")
9969 (setq key "TIMESTAMP")))
9970 (when (or (equal key clockstr) (not (assoc key props)))
9971 (push (cons key string) props)))
9975 (when (memq which '(all standard))
9976 ;; Get the standard properties, like :PORP: ...
9977 (setq range (org-get-property-block beg end))
9978 (when range
9979 (goto-char (car range))
9980 (while (re-search-forward
9981 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9982 (cdr range) t)
9983 (setq key (org-match-string-no-properties 1)
9984 value (org-trim (or (org-match-string-no-properties 2) "")))
9985 (unless (member key excluded)
9986 (push (cons key (or value "")) props)))))
9987 (if clocksum
9988 (push (cons "CLOCKSUM"
9989 (org-columns-number-to-string (/ (float clocksum) 60.)
9990 'add_times))
9991 props))
9992 (append sum-props (nreverse props)))))))
9994 (defun org-entry-get (pom property &optional inherit)
9995 "Get value of PROPERTY for entry at point-or-marker POM.
9996 If INHERIT is non-nil and the entry does not have the property,
9997 then also check higher levels of the hierarchy.
9998 If INHERIT is the symbol `selective', use inheritance only if the setting
9999 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10000 If the property is present but empty, the return value is the empty string.
10001 If the property is not present at all, nil is returned."
10002 (org-with-point-at pom
10003 (if (and inherit (if (eq inherit 'selective)
10004 (org-property-inherit-p property)
10006 (org-entry-get-with-inheritance property)
10007 (if (member property org-special-properties)
10008 ;; We need a special property. Use brute force, get all properties.
10009 (cdr (assoc property (org-entry-properties nil 'special)))
10010 (let ((range (org-get-property-block)))
10011 (if (and range
10012 (goto-char (car range))
10013 (re-search-forward
10014 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10015 (cdr range) t))
10016 ;; Found the property, return it.
10017 (if (match-end 1)
10018 (org-match-string-no-properties 1)
10019 "")))))))
10021 (defun org-property-or-variable-value (var &optional inherit)
10022 "Check if there is a property fixing the value of VAR.
10023 If yes, return this value. If not, return the current value of the variable."
10024 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10025 (if (and prop (stringp prop) (string-match "\\S-" prop))
10026 (read prop)
10027 (symbol-value var))))
10029 (defun org-entry-delete (pom property)
10030 "Delete the property PROPERTY from entry at point-or-marker POM."
10031 (org-with-point-at pom
10032 (if (member property org-special-properties)
10033 nil ; cannot delete these properties.
10034 (let ((range (org-get-property-block)))
10035 (if (and range
10036 (goto-char (car range))
10037 (re-search-forward
10038 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10039 (cdr range) t))
10040 (progn
10041 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10043 nil)))))
10045 ;; Multi-values properties are properties that contain multiple values
10046 ;; These values are assumed to be single words, separated by whitespace.
10047 (defun org-entry-add-to-multivalued-property (pom property value)
10048 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10049 (let* ((old (org-entry-get pom property))
10050 (values (and old (org-split-string old "[ \t]"))))
10051 (unless (member value values)
10052 (setq values (cons value values))
10053 (org-entry-put pom property
10054 (mapconcat 'identity values " ")))))
10056 (defun org-entry-remove-from-multivalued-property (pom property value)
10057 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10058 (let* ((old (org-entry-get pom property))
10059 (values (and old (org-split-string old "[ \t]"))))
10060 (when (member value values)
10061 (setq values (delete value values))
10062 (org-entry-put pom property
10063 (mapconcat 'identity values " ")))))
10065 (defun org-entry-member-in-multivalued-property (pom property value)
10066 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10067 (let* ((old (org-entry-get pom property))
10068 (values (and old (org-split-string old "[ \t]"))))
10069 (member value values)))
10071 (defvar org-entry-property-inherited-from (make-marker))
10073 (defun org-entry-get-with-inheritance (property)
10074 "Get entry property, and search higher levels if not present."
10075 (let (tmp)
10076 (save-excursion
10077 (save-restriction
10078 (widen)
10079 (catch 'ex
10080 (while t
10081 (when (setq tmp (org-entry-get nil property))
10082 (org-back-to-heading t)
10083 (move-marker org-entry-property-inherited-from (point))
10084 (throw 'ex tmp))
10085 (or (org-up-heading-safe) (throw 'ex nil)))))
10086 (or tmp
10087 (cdr (assoc property org-file-properties))
10088 (cdr (assoc property org-global-properties))
10089 (cdr (assoc property org-global-properties-fixed))))))
10091 (defun org-entry-put (pom property value)
10092 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10093 (org-with-point-at pom
10094 (org-back-to-heading t)
10095 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10096 range)
10097 (cond
10098 ((equal property "TODO")
10099 (when (and (stringp value) (string-match "\\S-" value)
10100 (not (member value org-todo-keywords-1)))
10101 (error "\"%s\" is not a valid TODO state" value))
10102 (if (or (not value)
10103 (not (string-match "\\S-" value)))
10104 (setq value 'none))
10105 (org-todo value)
10106 (org-set-tags nil 'align))
10107 ((equal property "PRIORITY")
10108 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10109 (string-to-char value) ?\ ))
10110 (org-set-tags nil 'align))
10111 ((equal property "SCHEDULED")
10112 (if (re-search-forward org-scheduled-time-regexp end t)
10113 (cond
10114 ((eq value 'earlier) (org-timestamp-change -1 'day))
10115 ((eq value 'later) (org-timestamp-change 1 'day))
10116 (t (call-interactively 'org-schedule)))
10117 (call-interactively 'org-schedule)))
10118 ((equal property "DEADLINE")
10119 (if (re-search-forward org-deadline-time-regexp end t)
10120 (cond
10121 ((eq value 'earlier) (org-timestamp-change -1 'day))
10122 ((eq value 'later) (org-timestamp-change 1 'day))
10123 (t (call-interactively 'org-deadline)))
10124 (call-interactively 'org-deadline)))
10125 ((member property org-special-properties)
10126 (error "The %s property can not yet be set with `org-entry-put'"
10127 property))
10128 (t ; a non-special property
10129 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10130 (setq range (org-get-property-block beg end 'force))
10131 (goto-char (car range))
10132 (if (re-search-forward
10133 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10134 (progn
10135 (delete-region (match-beginning 1) (match-end 1))
10136 (goto-char (match-beginning 1)))
10137 (goto-char (cdr range))
10138 (insert "\n")
10139 (backward-char 1)
10140 (org-indent-line-function)
10141 (insert ":" property ":"))
10142 (and value (insert " " value))
10143 (org-indent-line-function)))))))
10145 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10146 "Get all property keys in the current buffer.
10147 With INCLUDE-SPECIALS, also list the special properties that relect things
10148 like tags and TODO state.
10149 With INCLUDE-DEFAULTS, also include properties that has special meaning
10150 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10151 With INCLUDE-COLUMNS, also include property names given in COLUMN
10152 formats in the current buffer."
10153 (let (rtn range cfmt cols s p)
10154 (save-excursion
10155 (save-restriction
10156 (widen)
10157 (goto-char (point-min))
10158 (while (re-search-forward org-property-start-re nil t)
10159 (setq range (org-get-property-block))
10160 (goto-char (car range))
10161 (while (re-search-forward
10162 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10163 (cdr range) t)
10164 (add-to-list 'rtn (org-match-string-no-properties 1)))
10165 (outline-next-heading))))
10167 (when include-specials
10168 (setq rtn (append org-special-properties rtn)))
10170 (when include-defaults
10171 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10173 (when include-columns
10174 (save-excursion
10175 (save-restriction
10176 (widen)
10177 (goto-char (point-min))
10178 (while (re-search-forward
10179 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10180 nil t)
10181 (setq cfmt (match-string 2) s 0)
10182 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10183 cfmt s)
10184 (setq s (match-end 0)
10185 p (match-string 1 cfmt))
10186 (unless (or (equal p "ITEM")
10187 (member p org-special-properties))
10188 (add-to-list 'rtn (match-string 1 cfmt))))))))
10190 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10192 (defun org-property-values (key)
10193 "Return a list of all values of property KEY."
10194 (save-excursion
10195 (save-restriction
10196 (widen)
10197 (goto-char (point-min))
10198 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10199 values)
10200 (while (re-search-forward re nil t)
10201 (add-to-list 'values (org-trim (match-string 1))))
10202 (delete "" values)))))
10204 (defun org-insert-property-drawer ()
10205 "Insert a property drawer into the current entry."
10206 (interactive)
10207 (org-back-to-heading t)
10208 (looking-at outline-regexp)
10209 (let ((indent (- (match-end 0)(match-beginning 0)))
10210 (beg (point))
10211 (re (concat "^[ \t]*" org-keyword-time-regexp))
10212 end hiddenp)
10213 (outline-next-heading)
10214 (setq end (point))
10215 (goto-char beg)
10216 (while (re-search-forward re end t))
10217 (setq hiddenp (org-invisible-p))
10218 (end-of-line 1)
10219 (and (equal (char-after) ?\n) (forward-char 1))
10220 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10221 (beginning-of-line 2))
10222 (org-skip-over-state-notes)
10223 (skip-chars-backward " \t\n\r")
10224 (if (eq (char-before) ?*) (forward-char 1))
10225 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10226 (beginning-of-line 0)
10227 (org-indent-to-column indent)
10228 (beginning-of-line 2)
10229 (org-indent-to-column indent)
10230 (beginning-of-line 0)
10231 (if hiddenp
10232 (save-excursion
10233 (org-back-to-heading t)
10234 (hide-entry))
10235 (org-flag-drawer t))))
10237 (defun org-set-property (property value)
10238 "In the current entry, set PROPERTY to VALUE.
10239 When called interactively, this will prompt for a property name, offering
10240 completion on existing and default properties. And then it will prompt
10241 for a value, offering competion either on allowed values (via an inherited
10242 xxx_ALL property) or on existing values in other instances of this property
10243 in the current file."
10244 (interactive
10245 (let* ((completion-ignore-case t)
10246 (keys (org-buffer-property-keys nil t t))
10247 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10248 (prop (if (member prop0 keys)
10249 prop0
10250 (or (cdr (assoc (downcase prop0)
10251 (mapcar (lambda (x) (cons (downcase x) x))
10252 keys)))
10253 prop0)))
10254 (cur (org-entry-get nil prop))
10255 (allowed (org-property-get-allowed-values nil prop 'table))
10256 (existing (mapcar 'list (org-property-values prop)))
10257 (val (if allowed
10258 (org-completing-read "Value: " allowed nil 'req-match)
10259 (org-completing-read
10260 (concat "Value" (if (and cur (string-match "\\S-" cur))
10261 (concat "[" cur "]") "")
10262 ": ")
10263 existing nil nil "" nil cur))))
10264 (list prop (if (equal val "") cur val))))
10265 (unless (equal (org-entry-get nil property) value)
10266 (org-entry-put nil property value)))
10268 (defun org-delete-property (property)
10269 "In the current entry, delete PROPERTY."
10270 (interactive
10271 (let* ((completion-ignore-case t)
10272 (prop (completing-read
10273 "Property: " (org-entry-properties nil 'standard))))
10274 (list prop)))
10275 (message "Property %s %s" property
10276 (if (org-entry-delete nil property)
10277 "deleted"
10278 "was not present in the entry")))
10280 (defun org-delete-property-globally (property)
10281 "Remove PROPERTY globally, from all entries."
10282 (interactive
10283 (let* ((completion-ignore-case t)
10284 (prop (completing-read
10285 "Globally remove property: "
10286 (mapcar 'list (org-buffer-property-keys)))))
10287 (list prop)))
10288 (save-excursion
10289 (save-restriction
10290 (widen)
10291 (goto-char (point-min))
10292 (let ((cnt 0))
10293 (while (re-search-forward
10294 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10295 nil t)
10296 (setq cnt (1+ cnt))
10297 (replace-match ""))
10298 (message "Property \"%s\" removed from %d entries" property cnt)))))
10300 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10302 (defun org-compute-property-at-point ()
10303 "Compute the property at point.
10304 This looks for an enclosing column format, extracts the operator and
10305 then applies it to the proerty in the column format's scope."
10306 (interactive)
10307 (unless (org-at-property-p)
10308 (error "Not at a property"))
10309 (let ((prop (org-match-string-no-properties 2)))
10310 (org-columns-get-format-and-top-level)
10311 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10312 (error "No operator defined for property %s" prop))
10313 (org-columns-compute prop)))
10315 (defun org-property-get-allowed-values (pom property &optional table)
10316 "Get allowed values for the property PROPERTY.
10317 When TABLE is non-nil, return an alist that can directly be used for
10318 completion."
10319 (let (vals)
10320 (cond
10321 ((equal property "TODO")
10322 (setq vals (org-with-point-at pom
10323 (append org-todo-keywords-1 '("")))))
10324 ((equal property "PRIORITY")
10325 (let ((n org-lowest-priority))
10326 (while (>= n org-highest-priority)
10327 (push (char-to-string n) vals)
10328 (setq n (1- n)))))
10329 ((member property org-special-properties))
10331 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10333 (when (and vals (string-match "\\S-" vals))
10334 (setq vals (car (read-from-string (concat "(" vals ")"))))
10335 (setq vals (mapcar (lambda (x)
10336 (cond ((stringp x) x)
10337 ((numberp x) (number-to-string x))
10338 ((symbolp x) (symbol-name x))
10339 (t "???")))
10340 vals)))))
10341 (if table (mapcar 'list vals) vals)))
10343 (defun org-property-previous-allowed-value (&optional previous)
10344 "Switch to the next allowed value for this property."
10345 (interactive)
10346 (org-property-next-allowed-value t))
10348 (defun org-property-next-allowed-value (&optional previous)
10349 "Switch to the next allowed value for this property."
10350 (interactive)
10351 (unless (org-at-property-p)
10352 (error "Not at a property"))
10353 (let* ((key (match-string 2))
10354 (value (match-string 3))
10355 (allowed (or (org-property-get-allowed-values (point) key)
10356 (and (member value '("[ ]" "[-]" "[X]"))
10357 '("[ ]" "[X]"))))
10358 nval)
10359 (unless allowed
10360 (error "Allowed values for this property have not been defined"))
10361 (if previous (setq allowed (reverse allowed)))
10362 (if (member value allowed)
10363 (setq nval (car (cdr (member value allowed)))))
10364 (setq nval (or nval (car allowed)))
10365 (if (equal nval value)
10366 (error "Only one allowed value for this property"))
10367 (org-at-property-p)
10368 (replace-match (concat " :" key ": " nval) t t)
10369 (org-indent-line-function)
10370 (beginning-of-line 1)
10371 (skip-chars-forward " \t")))
10373 (defun org-find-entry-with-id (ident)
10374 "Locate the entry that contains the ID property with exact value IDENT.
10375 IDENT can be a string, a symbol or a number, this function will search for
10376 the string representation of it.
10377 Return the position where this entry starts, or nil if there is no such entry."
10378 (let ((id (cond
10379 ((stringp ident) ident)
10380 ((symbol-name ident) (symbol-name ident))
10381 ((numberp ident) (number-to-string ident))
10382 (t (error "IDENT %s must be a string, symbol or number" ident))))
10383 (case-fold-search nil))
10384 (save-excursion
10385 (save-restriction
10386 (widen)
10387 (goto-char (point-min))
10388 (when (re-search-forward
10389 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10390 nil t)
10391 (org-back-to-heading)
10392 (point))))))
10394 ;;;; Timestamps
10396 (defvar org-last-changed-timestamp nil)
10397 (defvar org-time-was-given) ; dynamically scoped parameter
10398 (defvar org-end-time-was-given) ; dynamically scoped parameter
10399 (defvar org-ts-what) ; dynamically scoped parameter
10401 (defun org-time-stamp (arg)
10402 "Prompt for a date/time and insert a time stamp.
10403 If the user specifies a time like HH:MM, or if this command is called
10404 with a prefix argument, the time stamp will contain date and time.
10405 Otherwise, only the date will be included. All parts of a date not
10406 specified by the user will be filled in from the current date/time.
10407 So if you press just return without typing anything, the time stamp
10408 will represent the current date/time. If there is already a timestamp
10409 at the cursor, it will be modified."
10410 (interactive "P")
10411 (let* ((ts nil)
10412 (default-time
10413 ;; Default time is either today, or, when entering a range,
10414 ;; the range start.
10415 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10416 (save-excursion
10417 (re-search-backward
10418 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10419 (- (point) 20) t)))
10420 (apply 'encode-time (org-parse-time-string (match-string 1)))
10421 (current-time)))
10422 (default-input (and ts (org-get-compact-tod ts)))
10423 org-time-was-given org-end-time-was-given time)
10424 (cond
10425 ((and (org-at-timestamp-p)
10426 (eq last-command 'org-time-stamp)
10427 (eq this-command 'org-time-stamp))
10428 (insert "--")
10429 (setq time (let ((this-command this-command))
10430 (org-read-date arg 'totime nil nil default-time default-input)))
10431 (org-insert-time-stamp time (or org-time-was-given arg)))
10432 ((org-at-timestamp-p)
10433 (setq time (let ((this-command this-command))
10434 (org-read-date arg 'totime nil nil default-time default-input)))
10435 (when (org-at-timestamp-p) ; just to get the match data
10436 (replace-match "")
10437 (setq org-last-changed-timestamp
10438 (org-insert-time-stamp
10439 time (or org-time-was-given arg)
10440 nil nil nil (list org-end-time-was-given))))
10441 (message "Timestamp updated"))
10443 (setq time (let ((this-command this-command))
10444 (org-read-date arg 'totime nil nil default-time default-input)))
10445 (org-insert-time-stamp time (or org-time-was-given arg)
10446 nil nil nil (list org-end-time-was-given))))))
10448 ;; FIXME: can we use this for something else, like computing time differences?
10449 (defun org-get-compact-tod (s)
10450 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10451 (let* ((t1 (match-string 1 s))
10452 (h1 (string-to-number (match-string 2 s)))
10453 (m1 (string-to-number (match-string 3 s)))
10454 (t2 (and (match-end 4) (match-string 5 s)))
10455 (h2 (and t2 (string-to-number (match-string 6 s))))
10456 (m2 (and t2 (string-to-number (match-string 7 s))))
10457 dh dm)
10458 (if (not t2)
10460 (setq dh (- h2 h1) dm (- m2 m1))
10461 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10462 (concat t1 "+" (number-to-string dh)
10463 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10465 (defun org-time-stamp-inactive (&optional arg)
10466 "Insert an inactive time stamp.
10467 An inactive time stamp is enclosed in square brackets instead of angle
10468 brackets. It is inactive in the sense that it does not trigger agenda entries,
10469 does not link to the calendar and cannot be changed with the S-cursor keys.
10470 So these are more for recording a certain time/date."
10471 (interactive "P")
10472 (let (org-time-was-given org-end-time-was-given time)
10473 (setq time (org-read-date arg 'totime))
10474 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10475 nil nil (list org-end-time-was-given))))
10477 (defvar org-date-ovl (org-make-overlay 1 1))
10478 (org-overlay-put org-date-ovl 'face 'org-warning)
10479 (org-detach-overlay org-date-ovl)
10481 (defvar org-ans1) ; dynamically scoped parameter
10482 (defvar org-ans2) ; dynamically scoped parameter
10484 (defvar org-plain-time-of-day-regexp) ; defined below
10486 (defvar org-read-date-overlay nil)
10487 (defvar org-dcst nil) ; dynamically scoped
10489 (defun org-read-date (&optional with-time to-time from-string prompt
10490 default-time default-input)
10491 "Read a date, possibly a time, and make things smooth for the user.
10492 The prompt will suggest to enter an ISO date, but you can also enter anything
10493 which will at least partially be understood by `parse-time-string'.
10494 Unrecognized parts of the date will default to the current day, month, year,
10495 hour and minute. If this command is called to replace a timestamp at point,
10496 of to enter the second timestamp of a range, the default time is taken from the
10497 existing stamp. For example,
10498 3-2-5 --> 2003-02-05
10499 feb 15 --> currentyear-02-15
10500 sep 12 9 --> 2009-09-12
10501 12:45 --> today 12:45
10502 22 sept 0:34 --> currentyear-09-22 0:34
10503 12 --> currentyear-currentmonth-12
10504 Fri --> nearest Friday (today or later)
10505 etc.
10507 Furthermore you can specify a relative date by giving, as the *first* thing
10508 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10509 change in days weeks, months, years.
10510 With a single plus or minus, the date is relative to today. With a double
10511 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10512 +4d --> four days from today
10513 +4 --> same as above
10514 +2w --> two weeks from today
10515 ++5 --> five days from default date
10517 The function understands only English month and weekday abbreviations,
10518 but this can be configured with the variables `parse-time-months' and
10519 `parse-time-weekdays'.
10521 While prompting, a calendar is popped up - you can also select the
10522 date with the mouse (button 1). The calendar shows a period of three
10523 months. To scroll it to other months, use the keys `>' and `<'.
10524 If you don't like the calendar, turn it off with
10525 \(setq org-read-date-popup-calendar nil)
10527 With optional argument TO-TIME, the date will immediately be converted
10528 to an internal time.
10529 With an optional argument WITH-TIME, the prompt will suggest to also
10530 insert a time. Note that when WITH-TIME is not set, you can still
10531 enter a time, and this function will inform the calling routine about
10532 this change. The calling routine may then choose to change the format
10533 used to insert the time stamp into the buffer to include the time.
10534 With optional argument FROM-STRING, read from this string instead from
10535 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10536 the time/date that is used for everything that is not specified by the
10537 user."
10538 (require 'parse-time)
10539 (let* ((org-time-stamp-rounding-minutes
10540 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10541 (org-dcst org-display-custom-times)
10542 (ct (org-current-time))
10543 (def (or default-time ct))
10544 (defdecode (decode-time def))
10545 (dummy (progn
10546 (when (< (nth 2 defdecode) org-extend-today-until)
10547 (setcar (nthcdr 2 defdecode) -1)
10548 (setcar (nthcdr 1 defdecode) 59)
10549 (setq def (apply 'encode-time defdecode)
10550 defdecode (decode-time def)))))
10551 (calendar-move-hook nil)
10552 (calendar-view-diary-initially-flag nil)
10553 (view-diary-entries-initially nil)
10554 (calendar-view-holidays-initially-flag nil)
10555 (view-calendar-holidays-initially nil)
10556 (timestr (format-time-string
10557 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10558 (prompt (concat (if prompt (concat prompt " ") "")
10559 (format "Date+time [%s]: " timestr)))
10560 ans (org-ans0 "") org-ans1 org-ans2 final)
10562 (cond
10563 (from-string (setq ans from-string))
10564 (org-read-date-popup-calendar
10565 (save-excursion
10566 (save-window-excursion
10567 (calendar)
10568 (calendar-forward-day (- (time-to-days def)
10569 (calendar-absolute-from-gregorian
10570 (calendar-current-date))))
10571 (org-eval-in-calendar nil t)
10572 (let* ((old-map (current-local-map))
10573 (map (copy-keymap calendar-mode-map))
10574 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10575 (org-defkey map (kbd "RET") 'org-calendar-select)
10576 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10577 'org-calendar-select-mouse)
10578 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10579 'org-calendar-select-mouse)
10580 (org-defkey minibuffer-local-map [(meta shift left)]
10581 (lambda () (interactive)
10582 (org-eval-in-calendar '(calendar-backward-month 1))))
10583 (org-defkey minibuffer-local-map [(meta shift right)]
10584 (lambda () (interactive)
10585 (org-eval-in-calendar '(calendar-forward-month 1))))
10586 (org-defkey minibuffer-local-map [(meta shift up)]
10587 (lambda () (interactive)
10588 (org-eval-in-calendar '(calendar-backward-year 1))))
10589 (org-defkey minibuffer-local-map [(meta shift down)]
10590 (lambda () (interactive)
10591 (org-eval-in-calendar '(calendar-forward-year 1))))
10592 (org-defkey minibuffer-local-map [(shift up)]
10593 (lambda () (interactive)
10594 (org-eval-in-calendar '(calendar-backward-week 1))))
10595 (org-defkey minibuffer-local-map [(shift down)]
10596 (lambda () (interactive)
10597 (org-eval-in-calendar '(calendar-forward-week 1))))
10598 (org-defkey minibuffer-local-map [(shift left)]
10599 (lambda () (interactive)
10600 (org-eval-in-calendar '(calendar-backward-day 1))))
10601 (org-defkey minibuffer-local-map [(shift right)]
10602 (lambda () (interactive)
10603 (org-eval-in-calendar '(calendar-forward-day 1))))
10604 (org-defkey minibuffer-local-map ">"
10605 (lambda () (interactive)
10606 (org-eval-in-calendar '(scroll-calendar-left 1))))
10607 (org-defkey minibuffer-local-map "<"
10608 (lambda () (interactive)
10609 (org-eval-in-calendar '(scroll-calendar-right 1))))
10610 (unwind-protect
10611 (progn
10612 (use-local-map map)
10613 (add-hook 'post-command-hook 'org-read-date-display)
10614 (setq org-ans0 (read-string prompt default-input nil nil))
10615 ;; org-ans0: from prompt
10616 ;; org-ans1: from mouse click
10617 ;; org-ans2: from calendar motion
10618 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10619 (remove-hook 'post-command-hook 'org-read-date-display)
10620 (use-local-map old-map)
10621 (when org-read-date-overlay
10622 (org-delete-overlay org-read-date-overlay)
10623 (setq org-read-date-overlay nil)))))))
10625 (t ; Naked prompt only
10626 (unwind-protect
10627 (setq ans (read-string prompt default-input nil timestr))
10628 (when org-read-date-overlay
10629 (org-delete-overlay org-read-date-overlay)
10630 (setq org-read-date-overlay nil)))))
10632 (setq final (org-read-date-analyze ans def defdecode))
10634 (if to-time
10635 (apply 'encode-time final)
10636 (if (and (boundp 'org-time-was-given) org-time-was-given)
10637 (format "%04d-%02d-%02d %02d:%02d"
10638 (nth 5 final) (nth 4 final) (nth 3 final)
10639 (nth 2 final) (nth 1 final))
10640 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10641 (defvar def)
10642 (defvar defdecode)
10643 (defvar with-time)
10644 (defun org-read-date-display ()
10645 "Display the currrent date prompt interpretation in the minibuffer."
10646 (when org-read-date-display-live
10647 (when org-read-date-overlay
10648 (org-delete-overlay org-read-date-overlay))
10649 (let ((p (point)))
10650 (end-of-line 1)
10651 (while (not (equal (buffer-substring
10652 (max (point-min) (- (point) 4)) (point))
10653 " "))
10654 (insert " "))
10655 (goto-char p))
10656 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10657 " " (or org-ans1 org-ans2)))
10658 (org-end-time-was-given nil)
10659 (f (org-read-date-analyze ans def defdecode))
10660 (fmts (if org-dcst
10661 org-time-stamp-custom-formats
10662 org-time-stamp-formats))
10663 (fmt (if (or with-time
10664 (and (boundp 'org-time-was-given) org-time-was-given))
10665 (cdr fmts)
10666 (car fmts)))
10667 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10668 (when (and org-end-time-was-given
10669 (string-match org-plain-time-of-day-regexp txt))
10670 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10671 org-end-time-was-given
10672 (substring txt (match-end 0)))))
10673 (setq org-read-date-overlay
10674 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10675 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10677 (defun org-read-date-analyze (ans def defdecode)
10678 "Analyze the combined answer of the date prompt."
10679 ;; FIXME: cleanup and comment
10680 (let (delta deltan deltaw deltadef year month day
10681 hour minute second wday pm h2 m2 tl wday1
10682 iso-year iso-weekday iso-week iso-year iso-date)
10684 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10685 (setq ans "+0"))
10687 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10688 (setq ans (replace-match "" t t ans)
10689 deltan (car delta)
10690 deltaw (nth 1 delta)
10691 deltadef (nth 2 delta)))
10693 ;; Check if there is an iso week date in there
10694 ;; If yes, sore the info and ostpone interpreting it until the rest
10695 ;; of the parsing is done
10696 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10697 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10698 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10699 iso-week (string-to-number (match-string 2 ans)))
10700 (setq ans (replace-match "" t t ans)))
10702 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10703 (when (string-match
10704 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10705 (setq year (if (match-end 2)
10706 (string-to-number (match-string 2 ans))
10707 (string-to-number (format-time-string "%Y")))
10708 month (string-to-number (match-string 3 ans))
10709 day (string-to-number (match-string 4 ans)))
10710 (if (< year 100) (setq year (+ 2000 year)))
10711 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10712 t nil ans)))
10713 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10714 ;; If there is a time with am/pm, and *no* time without it, we convert
10715 ;; so that matching will be successful.
10716 (loop for i from 1 to 2 do ; twice, for end time as well
10717 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10718 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10719 (setq hour (string-to-number (match-string 1 ans))
10720 minute (if (match-end 3)
10721 (string-to-number (match-string 3 ans))
10723 pm (equal ?p
10724 (string-to-char (downcase (match-string 4 ans)))))
10725 (if (and (= hour 12) (not pm))
10726 (setq hour 0)
10727 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10728 (setq ans (replace-match (format "%02d:%02d" hour minute)
10729 t t ans))))
10731 ;; Check if a time range is given as a duration
10732 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10733 (setq hour (string-to-number (match-string 1 ans))
10734 h2 (+ hour (string-to-number (match-string 3 ans)))
10735 minute (string-to-number (match-string 2 ans))
10736 m2 (+ minute (if (match-end 5) (string-to-number
10737 (match-string 5 ans))0)))
10738 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10739 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10740 t t ans)))
10742 ;; Check if there is a time range
10743 (when (boundp 'org-end-time-was-given)
10744 (setq org-time-was-given nil)
10745 (when (and (string-match org-plain-time-of-day-regexp ans)
10746 (match-end 8))
10747 (setq org-end-time-was-given (match-string 8 ans))
10748 (setq ans (concat (substring ans 0 (match-beginning 7))
10749 (substring ans (match-end 7))))))
10751 (setq tl (parse-time-string ans)
10752 day (or (nth 3 tl) (nth 3 defdecode))
10753 month (or (nth 4 tl)
10754 (if (and org-read-date-prefer-future
10755 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10756 (1+ (nth 4 defdecode))
10757 (nth 4 defdecode)))
10758 year (or (nth 5 tl)
10759 (if (and org-read-date-prefer-future
10760 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10761 (1+ (nth 5 defdecode))
10762 (nth 5 defdecode)))
10763 hour (or (nth 2 tl) (nth 2 defdecode))
10764 minute (or (nth 1 tl) (nth 1 defdecode))
10765 second (or (nth 0 tl) 0)
10766 wday (nth 6 tl))
10768 ;; Special date definitions below
10769 (cond
10770 (iso-week
10771 ;; There was an iso week
10772 (setq year (or iso-year year)
10773 day (or iso-weekday wday 1)
10774 wday nil ; to make sure that the trigger below does not match
10775 iso-date (calendar-gregorian-from-absolute
10776 (calendar-absolute-from-iso
10777 (list iso-week day year))))
10778 ; FIXME: Should we also push ISO weeks into the future?
10779 ; (when (and org-read-date-prefer-future
10780 ; (not iso-year)
10781 ; (< (calendar-absolute-from-gregorian iso-date)
10782 ; (time-to-days (current-time))))
10783 ; (setq year (1+ year)
10784 ; iso-date (calendar-gregorian-from-absolute
10785 ; (calendar-absolute-from-iso
10786 ; (list iso-week day year)))))
10787 (setq month (car iso-date)
10788 year (nth 2 iso-date)
10789 day (nth 1 iso-date)))
10790 (deltan
10791 (unless deltadef
10792 (let ((now (decode-time (current-time))))
10793 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10794 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10795 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10796 ((equal deltaw "m") (setq month (+ month deltan)))
10797 ((equal deltaw "y") (setq year (+ year deltan)))))
10798 ((and wday (not (nth 3 tl)))
10799 ;; Weekday was given, but no day, so pick that day in the week
10800 ;; on or after the derived date.
10801 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10802 (unless (equal wday wday1)
10803 (setq day (+ day (% (- wday wday1 -7) 7))))))
10804 (if (and (boundp 'org-time-was-given)
10805 (nth 2 tl))
10806 (setq org-time-was-given t))
10807 (if (< year 100) (setq year (+ 2000 year)))
10808 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10809 (list second minute hour day month year)))
10811 (defvar parse-time-weekdays)
10813 (defun org-read-date-get-relative (s today default)
10814 "Check string S for special relative date string.
10815 TODAY and DEFAULT are internal times, for today and for a default.
10816 Return shift list (N what def-flag)
10817 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10818 N is the number of WHATs to shift.
10819 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10820 the DEFAULT date rather than TODAY."
10821 (when (and
10822 (string-match
10823 (concat
10824 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10825 "\\([0-9]+\\)?"
10826 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10827 "\\([ \t]\\|$\\)") s)
10828 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10829 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10830 (string-to-char (substring (match-string 1 s) -1))
10831 ?+))
10832 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10833 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10834 (what (if (match-end 3) (match-string 3 s) "d"))
10835 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10836 (date (if rel default today))
10837 (wday (nth 6 (decode-time date)))
10838 delta)
10839 (if wday1
10840 (progn
10841 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10842 (if (= dir ?-) (setq delta (- delta 7)))
10843 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10844 (list delta "d" rel))
10845 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10847 (defun org-eval-in-calendar (form &optional keepdate)
10848 "Eval FORM in the calendar window and return to current window.
10849 Also, store the cursor date in variable org-ans2."
10850 (let ((sw (selected-window)))
10851 (select-window (get-buffer-window "*Calendar*"))
10852 (eval form)
10853 (when (and (not keepdate) (calendar-cursor-to-date))
10854 (let* ((date (calendar-cursor-to-date))
10855 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10856 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10857 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10858 (select-window sw)))
10860 ; ;; Update the prompt to show new default date
10861 ; (save-excursion
10862 ; (goto-char (point-min))
10863 ; (when (and org-ans2
10864 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10865 ; (get-text-property (match-end 0) 'field))
10866 ; (let ((inhibit-read-only t))
10867 ; (replace-match (concat "[" org-ans2 "]") t t)
10868 ; (add-text-properties (point-min) (1+ (match-end 0))
10869 ; (text-properties-at (1+ (point-min)))))))))
10871 (defun org-calendar-select ()
10872 "Return to `org-read-date' with the date currently selected.
10873 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10874 (interactive)
10875 (when (calendar-cursor-to-date)
10876 (let* ((date (calendar-cursor-to-date))
10877 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10878 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10879 (if (active-minibuffer-window) (exit-minibuffer))))
10881 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10882 "Insert a date stamp for the date given by the internal TIME.
10883 WITH-HM means, use the stamp format that includes the time of the day.
10884 INACTIVE means use square brackets instead of angular ones, so that the
10885 stamp will not contribute to the agenda.
10886 PRE and POST are optional strings to be inserted before and after the
10887 stamp.
10888 The command returns the inserted time stamp."
10889 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10890 stamp)
10891 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10892 (insert-before-markers (or pre ""))
10893 (insert-before-markers (setq stamp (format-time-string fmt time)))
10894 (when (listp extra)
10895 (setq extra (car extra))
10896 (if (and (stringp extra)
10897 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10898 (setq extra (format "-%02d:%02d"
10899 (string-to-number (match-string 1 extra))
10900 (string-to-number (match-string 2 extra))))
10901 (setq extra nil)))
10902 (when extra
10903 (backward-char 1)
10904 (insert-before-markers extra)
10905 (forward-char 1))
10906 (insert-before-markers (or post ""))
10907 stamp))
10909 (defun org-toggle-time-stamp-overlays ()
10910 "Toggle the use of custom time stamp formats."
10911 (interactive)
10912 (setq org-display-custom-times (not org-display-custom-times))
10913 (unless org-display-custom-times
10914 (let ((p (point-min)) (bmp (buffer-modified-p)))
10915 (while (setq p (next-single-property-change p 'display))
10916 (if (and (get-text-property p 'display)
10917 (eq (get-text-property p 'face) 'org-date))
10918 (remove-text-properties
10919 p (setq p (next-single-property-change p 'display))
10920 '(display t))))
10921 (set-buffer-modified-p bmp)))
10922 (if (featurep 'xemacs)
10923 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10924 (org-restart-font-lock)
10925 (setq org-table-may-need-update t)
10926 (if org-display-custom-times
10927 (message "Time stamps are overlayed with custom format")
10928 (message "Time stamp overlays removed")))
10930 (defun org-display-custom-time (beg end)
10931 "Overlay modified time stamp format over timestamp between BEG and END."
10932 (let* ((ts (buffer-substring beg end))
10933 t1 w1 with-hm tf time str w2 (off 0))
10934 (save-match-data
10935 (setq t1 (org-parse-time-string ts t))
10936 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10937 (setq off (- (match-end 0) (match-beginning 0)))))
10938 (setq end (- end off))
10939 (setq w1 (- end beg)
10940 with-hm (and (nth 1 t1) (nth 2 t1))
10941 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10942 time (org-fix-decoded-time t1)
10943 str (org-add-props
10944 (format-time-string
10945 (substring tf 1 -1) (apply 'encode-time time))
10946 nil 'mouse-face 'highlight)
10947 w2 (length str))
10948 (if (not (= w2 w1))
10949 (add-text-properties (1+ beg) (+ 2 beg)
10950 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10951 (if (featurep 'xemacs)
10952 (progn
10953 (put-text-property beg end 'invisible t)
10954 (put-text-property beg end 'end-glyph (make-glyph str)))
10955 (put-text-property beg end 'display str))))
10957 (defun org-translate-time (string)
10958 "Translate all timestamps in STRING to custom format.
10959 But do this only if the variable `org-display-custom-times' is set."
10960 (when org-display-custom-times
10961 (save-match-data
10962 (let* ((start 0)
10963 (re org-ts-regexp-both)
10964 t1 with-hm inactive tf time str beg end)
10965 (while (setq start (string-match re string start))
10966 (setq beg (match-beginning 0)
10967 end (match-end 0)
10968 t1 (save-match-data
10969 (org-parse-time-string (substring string beg end) t))
10970 with-hm (and (nth 1 t1) (nth 2 t1))
10971 inactive (equal (substring string beg (1+ beg)) "[")
10972 tf (funcall (if with-hm 'cdr 'car)
10973 org-time-stamp-custom-formats)
10974 time (org-fix-decoded-time t1)
10975 str (format-time-string
10976 (concat
10977 (if inactive "[" "<") (substring tf 1 -1)
10978 (if inactive "]" ">"))
10979 (apply 'encode-time time))
10980 string (replace-match str t t string)
10981 start (+ start (length str)))))))
10982 string)
10984 (defun org-fix-decoded-time (time)
10985 "Set 0 instead of nil for the first 6 elements of time.
10986 Don't touch the rest."
10987 (let ((n 0))
10988 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10990 (defun org-days-to-time (timestamp-string)
10991 "Difference between TIMESTAMP-STRING and now in days."
10992 (- (time-to-days (org-time-string-to-time timestamp-string))
10993 (time-to-days (current-time))))
10995 (defun org-deadline-close (timestamp-string &optional ndays)
10996 "Is the time in TIMESTAMP-STRING close to the current date?"
10997 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10998 (and (< (org-days-to-time timestamp-string) ndays)
10999 (not (org-entry-is-done-p))))
11001 (defun org-get-wdays (ts)
11002 "Get the deadline lead time appropriate for timestring TS."
11003 (cond
11004 ((<= org-deadline-warning-days 0)
11005 ;; 0 or negative, enforce this value no matter what
11006 (- org-deadline-warning-days))
11007 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11008 ;; lead time is specified.
11009 (floor (* (string-to-number (match-string 1 ts))
11010 (cdr (assoc (match-string 2 ts)
11011 '(("d" . 1) ("w" . 7)
11012 ("m" . 30.4) ("y" . 365.25)))))))
11013 ;; go for the default.
11014 (t org-deadline-warning-days)))
11016 (defun org-calendar-select-mouse (ev)
11017 "Return to `org-read-date' with the date currently selected.
11018 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11019 (interactive "e")
11020 (mouse-set-point ev)
11021 (when (calendar-cursor-to-date)
11022 (let* ((date (calendar-cursor-to-date))
11023 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11024 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11025 (if (active-minibuffer-window) (exit-minibuffer))))
11027 (defun org-check-deadlines (ndays)
11028 "Check if there are any deadlines due or past due.
11029 A deadline is considered due if it happens within `org-deadline-warning-days'
11030 days from today's date. If the deadline appears in an entry marked DONE,
11031 it is not shown. The prefix arg NDAYS can be used to test that many
11032 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11033 (interactive "P")
11034 (let* ((org-warn-days
11035 (cond
11036 ((equal ndays '(4)) 100000)
11037 (ndays (prefix-numeric-value ndays))
11038 (t (abs org-deadline-warning-days))))
11039 (case-fold-search nil)
11040 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11041 (callback
11042 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11044 (message "%d deadlines past-due or due within %d days"
11045 (org-occur regexp nil callback)
11046 org-warn-days)))
11048 (defun org-check-before-date (date)
11049 "Check if there are deadlines or scheduled entries before DATE."
11050 (interactive (list (org-read-date)))
11051 (let ((case-fold-search nil)
11052 (regexp (concat "\\<\\(" org-deadline-string
11053 "\\|" org-scheduled-string
11054 "\\) *<\\([^>]+\\)>"))
11055 (callback
11056 (lambda () (time-less-p
11057 (org-time-string-to-time (match-string 2))
11058 (org-time-string-to-time date)))))
11059 (message "%d entries before %s"
11060 (org-occur regexp nil callback) date)))
11062 (defun org-evaluate-time-range (&optional to-buffer)
11063 "Evaluate a time range by computing the difference between start and end.
11064 Normally the result is just printed in the echo area, but with prefix arg
11065 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11066 If the time range is actually in a table, the result is inserted into the
11067 next column.
11068 For time difference computation, a year is assumed to be exactly 365
11069 days in order to avoid rounding problems."
11070 (interactive "P")
11072 (org-clock-update-time-maybe)
11073 (save-excursion
11074 (unless (org-at-date-range-p t)
11075 (goto-char (point-at-bol))
11076 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11077 (if (not (org-at-date-range-p t))
11078 (error "Not at a time-stamp range, and none found in current line")))
11079 (let* ((ts1 (match-string 1))
11080 (ts2 (match-string 2))
11081 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11082 (match-end (match-end 0))
11083 (time1 (org-time-string-to-time ts1))
11084 (time2 (org-time-string-to-time ts2))
11085 (t1 (time-to-seconds time1))
11086 (t2 (time-to-seconds time2))
11087 (diff (abs (- t2 t1)))
11088 (negative (< (- t2 t1) 0))
11089 ;; (ys (floor (* 365 24 60 60)))
11090 (ds (* 24 60 60))
11091 (hs (* 60 60))
11092 (fy "%dy %dd %02d:%02d")
11093 (fy1 "%dy %dd")
11094 (fd "%dd %02d:%02d")
11095 (fd1 "%dd")
11096 (fh "%02d:%02d")
11097 y d h m align)
11098 (if havetime
11099 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11101 d (floor (/ diff ds)) diff (mod diff ds)
11102 h (floor (/ diff hs)) diff (mod diff hs)
11103 m (floor (/ diff 60)))
11104 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11106 d (floor (+ (/ diff ds) 0.5))
11107 h 0 m 0))
11108 (if (not to-buffer)
11109 (message "%s" (org-make-tdiff-string y d h m))
11110 (if (org-at-table-p)
11111 (progn
11112 (goto-char match-end)
11113 (setq align t)
11114 (and (looking-at " *|") (goto-char (match-end 0))))
11115 (goto-char match-end))
11116 (if (looking-at
11117 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11118 (replace-match ""))
11119 (if negative (insert " -"))
11120 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11121 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11122 (insert " " (format fh h m))))
11123 (if align (org-table-align))
11124 (message "Time difference inserted")))))
11126 (defun org-make-tdiff-string (y d h m)
11127 (let ((fmt "")
11128 (l nil))
11129 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11130 l (push y l)))
11131 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11132 l (push d l)))
11133 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11134 l (push h l)))
11135 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11136 l (push m l)))
11137 (apply 'format fmt (nreverse l))))
11139 (defun org-time-string-to-time (s)
11140 (apply 'encode-time (org-parse-time-string s)))
11142 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11143 "Convert a time stamp to an absolute day number.
11144 If there is a specifyer for a cyclic time stamp, get the closest date to
11145 DAYNR.
11146 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11147 (cond
11148 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11149 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11150 daynr
11151 (+ daynr 1000)))
11152 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11153 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11154 (time-to-days (current-time))) (match-string 0 s)
11155 prefer show-all))
11156 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11158 (defun org-days-to-iso-week (days)
11159 "Return the iso week number."
11160 (require 'cal-iso)
11161 (car (calendar-iso-from-absolute days)))
11163 (defun org-small-year-to-year (year)
11164 "Convert 2-digit years into 4-digit years.
11165 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11166 The year 2000 cannot be abbreviated. Any year lager than 99
11167 is retrned unchanged."
11168 (if (< year 38)
11169 (setq year (+ 2000 year))
11170 (if (< year 100)
11171 (setq year (+ 1900 year))))
11172 year)
11174 (defun org-time-from-absolute (d)
11175 "Return the time corresponding to date D.
11176 D may be an absolute day number, or a calendar-type list (month day year)."
11177 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11178 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11180 (defun org-calendar-holiday ()
11181 "List of holidays, for Diary display in Org-mode."
11182 (require 'holidays)
11183 (let ((hl (funcall
11184 (if (fboundp 'calendar-check-holidays)
11185 'calendar-check-holidays 'check-calendar-holidays) date)))
11186 (if hl (mapconcat 'identity hl "; "))))
11188 (defun org-diary-sexp-entry (sexp entry date)
11189 "Process a SEXP diary ENTRY for DATE."
11190 (require 'diary-lib)
11191 (let ((result (if calendar-debug-sexp
11192 (let ((stack-trace-on-error t))
11193 (eval (car (read-from-string sexp))))
11194 (condition-case nil
11195 (eval (car (read-from-string sexp)))
11196 (error
11197 (beep)
11198 (message "Bad sexp at line %d in %s: %s"
11199 (org-current-line)
11200 (buffer-file-name) sexp)
11201 (sleep-for 2))))))
11202 (cond ((stringp result) result)
11203 ((and (consp result)
11204 (stringp (cdr result))) (cdr result))
11205 (result entry)
11206 (t nil))))
11208 (defun org-diary-to-ical-string (frombuf)
11209 "Get iCalendar entries from diary entries in buffer FROMBUF.
11210 This uses the icalendar.el library."
11211 (let* ((tmpdir (if (featurep 'xemacs)
11212 (temp-directory)
11213 temporary-file-directory))
11214 (tmpfile (make-temp-name
11215 (expand-file-name "orgics" tmpdir)))
11216 buf rtn b e)
11217 (save-excursion
11218 (set-buffer frombuf)
11219 (icalendar-export-region (point-min) (point-max) tmpfile)
11220 (setq buf (find-buffer-visiting tmpfile))
11221 (set-buffer buf)
11222 (goto-char (point-min))
11223 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11224 (setq b (match-beginning 0)))
11225 (goto-char (point-max))
11226 (if (re-search-backward "^END:VEVENT" nil t)
11227 (setq e (match-end 0)))
11228 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11229 (kill-buffer buf)
11230 (kill-buffer frombuf)
11231 (delete-file tmpfile)
11232 rtn))
11234 (defun org-closest-date (start current change prefer show-all)
11235 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11236 When PREFER is `past' return a date that is either CURRENT or past.
11237 When PREFER is `future', return a date that is either CURRENT or future.
11238 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11239 ;; Make the proper lists from the dates
11240 (catch 'exit
11241 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11242 dn dw sday cday n1 n2
11243 d m y y1 y2 date1 date2 nmonths nm ny m2)
11245 (setq start (org-date-to-gregorian start)
11246 current (org-date-to-gregorian
11247 (if show-all
11248 current
11249 (time-to-days (current-time))))
11250 sday (calendar-absolute-from-gregorian start)
11251 cday (calendar-absolute-from-gregorian current))
11253 (if (<= cday sday) (throw 'exit sday))
11255 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11256 (setq dn (string-to-number (match-string 1 change))
11257 dw (cdr (assoc (match-string 2 change) a1)))
11258 (error "Invalid change specifyer: %s" change))
11259 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11260 (cond
11261 ((eq dw 'day)
11262 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11263 n2 (+ n1 dn)))
11264 ((eq dw 'year)
11265 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11266 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11267 (setq date1 (list m d y1)
11268 n1 (calendar-absolute-from-gregorian date1)
11269 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11270 n2 (calendar-absolute-from-gregorian date2)))
11271 ((eq dw 'month)
11272 ;; approx number of month between the tow dates
11273 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11274 ;; How often does dn fit in there?
11275 (setq d (nth 1 start) m (car start) y (nth 2 start)
11276 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11277 m (+ m nm)
11278 ny (floor (/ m 12))
11279 y (+ y ny)
11280 m (- m (* ny 12)))
11281 (while (> m 12) (setq m (- m 12) y (1+ y)))
11282 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11283 (setq m2 (+ m dn) y2 y)
11284 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11285 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11286 (while (< n2 cday)
11287 (setq n1 n2 m m2 y y2)
11288 (setq m2 (+ m dn) y2 y)
11289 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11290 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11292 (if show-all
11293 (cond
11294 ((eq prefer 'past) n1)
11295 ((eq prefer 'future) (if (= cday n1) n1 n2))
11296 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11297 (cond
11298 ((eq prefer 'past) n1)
11299 ((eq prefer 'future) (if (= cday n1) n1 n2))
11300 (t (if (= cday n1) n1 n2)))))))
11302 (defun org-date-to-gregorian (date)
11303 "Turn any specification of DATE into a gregorian date for the calendar."
11304 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11305 ((and (listp date) (= (length date) 3)) date)
11306 ((stringp date)
11307 (setq date (org-parse-time-string date))
11308 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11309 ((listp date)
11310 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11312 (defun org-parse-time-string (s &optional nodefault)
11313 "Parse the standard Org-mode time string.
11314 This should be a lot faster than the normal `parse-time-string'.
11315 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11316 hour and minute fields will be nil if not given."
11317 (if (string-match org-ts-regexp0 s)
11318 (list 0
11319 (if (or (match-beginning 8) (not nodefault))
11320 (string-to-number (or (match-string 8 s) "0")))
11321 (if (or (match-beginning 7) (not nodefault))
11322 (string-to-number (or (match-string 7 s) "0")))
11323 (string-to-number (match-string 4 s))
11324 (string-to-number (match-string 3 s))
11325 (string-to-number (match-string 2 s))
11326 nil nil nil)
11327 (make-list 9 0)))
11329 (defun org-timestamp-up (&optional arg)
11330 "Increase the date item at the cursor by one.
11331 If the cursor is on the year, change the year. If it is on the month or
11332 the day, change that.
11333 With prefix ARG, change by that many units."
11334 (interactive "p")
11335 (org-timestamp-change (prefix-numeric-value arg)))
11337 (defun org-timestamp-down (&optional arg)
11338 "Decrease the date item at the cursor by one.
11339 If the cursor is on the year, change the year. If it is on the month or
11340 the day, change that.
11341 With prefix ARG, change by that many units."
11342 (interactive "p")
11343 (org-timestamp-change (- (prefix-numeric-value arg))))
11345 (defun org-timestamp-up-day (&optional arg)
11346 "Increase the date in the time stamp by one day.
11347 With prefix ARG, change that many days."
11348 (interactive "p")
11349 (if (and (not (org-at-timestamp-p t))
11350 (org-on-heading-p))
11351 (org-todo 'up)
11352 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11354 (defun org-timestamp-down-day (&optional arg)
11355 "Decrease the date in the time stamp by one day.
11356 With prefix ARG, change that many days."
11357 (interactive "p")
11358 (if (and (not (org-at-timestamp-p t))
11359 (org-on-heading-p))
11360 (org-todo 'down)
11361 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11363 (defun org-at-timestamp-p (&optional inactive-ok)
11364 "Determine if the cursor is in or at a timestamp."
11365 (interactive)
11366 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11367 (pos (point))
11368 (ans (or (looking-at tsr)
11369 (save-excursion
11370 (skip-chars-backward "^[<\n\r\t")
11371 (if (> (point) (point-min)) (backward-char 1))
11372 (and (looking-at tsr)
11373 (> (- (match-end 0) pos) -1))))))
11374 (and ans
11375 (boundp 'org-ts-what)
11376 (setq org-ts-what
11377 (cond
11378 ((= pos (match-beginning 0)) 'bracket)
11379 ((= pos (1- (match-end 0))) 'bracket)
11380 ((org-pos-in-match-range pos 2) 'year)
11381 ((org-pos-in-match-range pos 3) 'month)
11382 ((org-pos-in-match-range pos 7) 'hour)
11383 ((org-pos-in-match-range pos 8) 'minute)
11384 ((or (org-pos-in-match-range pos 4)
11385 (org-pos-in-match-range pos 5)) 'day)
11386 ((and (> pos (or (match-end 8) (match-end 5)))
11387 (< pos (match-end 0)))
11388 (- pos (or (match-end 8) (match-end 5))))
11389 (t 'day))))
11390 ans))
11392 (defun org-toggle-timestamp-type ()
11393 "Toggle the type (<active> or [inactive]) of a time stamp."
11394 (interactive)
11395 (when (org-at-timestamp-p t)
11396 (save-excursion
11397 (goto-char (match-beginning 0))
11398 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11399 (goto-char (1- (match-end 0)))
11400 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11401 (message "Timestamp is now %sactive"
11402 (if (equal (char-before) ?>) "in" ""))))
11404 (defun org-timestamp-change (n &optional what)
11405 "Change the date in the time stamp at point.
11406 The date will be changed by N times WHAT. WHAT can be `day', `month',
11407 `year', `minute', `second'. If WHAT is not given, the cursor position
11408 in the timestamp determines what will be changed."
11409 (let ((pos (point))
11410 with-hm inactive
11411 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11412 org-ts-what
11413 extra rem
11414 ts time time0)
11415 (if (not (org-at-timestamp-p t))
11416 (error "Not at a timestamp"))
11417 (if (and (not what) (eq org-ts-what 'bracket))
11418 (org-toggle-timestamp-type)
11419 (if (and (not what) (not (eq org-ts-what 'day))
11420 org-display-custom-times
11421 (get-text-property (point) 'display)
11422 (not (get-text-property (1- (point)) 'display)))
11423 (setq org-ts-what 'day))
11424 (setq org-ts-what (or what org-ts-what)
11425 inactive (= (char-after (match-beginning 0)) ?\[)
11426 ts (match-string 0))
11427 (replace-match "")
11428 (if (string-match
11429 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11431 (setq extra (match-string 1 ts)))
11432 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11433 (setq with-hm t))
11434 (setq time0 (org-parse-time-string ts))
11435 (when (and (eq org-ts-what 'minute)
11436 (eq current-prefix-arg nil))
11437 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11438 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11439 (setcar (cdr time0) (+ (nth 1 time0)
11440 (if (> n 0) (- rem) (- dm rem))))))
11441 (setq time
11442 (encode-time (or (car time0) 0)
11443 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11444 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11445 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11446 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11447 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11448 (nthcdr 6 time0)))
11449 (when (integerp org-ts-what)
11450 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11451 (if (eq what 'calendar)
11452 (let ((cal-date (org-get-date-from-calendar)))
11453 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11454 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11455 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11456 (setcar time0 (or (car time0) 0))
11457 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11458 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11459 (setq time (apply 'encode-time time0))))
11460 (setq org-last-changed-timestamp
11461 (org-insert-time-stamp time with-hm inactive nil nil extra))
11462 (org-clock-update-time-maybe)
11463 (goto-char pos)
11464 ;; Try to recenter the calendar window, if any
11465 (if (and org-calendar-follow-timestamp-change
11466 (get-buffer-window "*Calendar*" t)
11467 (memq org-ts-what '(day month year)))
11468 (org-recenter-calendar (time-to-days time))))))
11470 (defun org-modify-ts-extra (s pos n dm)
11471 "Change the different parts of the lead-time and repeat fields in timestamp."
11472 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11473 ng h m new rem)
11474 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11475 (cond
11476 ((or (org-pos-in-match-range pos 2)
11477 (org-pos-in-match-range pos 3))
11478 (setq m (string-to-number (match-string 3 s))
11479 h (string-to-number (match-string 2 s)))
11480 (if (org-pos-in-match-range pos 2)
11481 (setq h (+ h n))
11482 (setq n (* dm (org-no-warnings (signum n))))
11483 (when (not (= 0 (setq rem (% m dm))))
11484 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11485 (setq m (+ m n)))
11486 (if (< m 0) (setq m (+ m 60) h (1- h)))
11487 (if (> m 59) (setq m (- m 60) h (1+ h)))
11488 (setq h (min 24 (max 0 h)))
11489 (setq ng 1 new (format "-%02d:%02d" h m)))
11490 ((org-pos-in-match-range pos 6)
11491 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11492 ((org-pos-in-match-range pos 5)
11493 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11495 ((org-pos-in-match-range pos 9)
11496 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11497 ((org-pos-in-match-range pos 8)
11498 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11500 (when ng
11501 (setq s (concat
11502 (substring s 0 (match-beginning ng))
11504 (substring s (match-end ng))))))
11507 (defun org-recenter-calendar (date)
11508 "If the calendar is visible, recenter it to DATE."
11509 (let* ((win (selected-window))
11510 (cwin (get-buffer-window "*Calendar*" t))
11511 (calendar-move-hook nil))
11512 (when cwin
11513 (select-window cwin)
11514 (calendar-goto-date (if (listp date) date
11515 (calendar-gregorian-from-absolute date)))
11516 (select-window win))))
11518 (defun org-goto-calendar (&optional arg)
11519 "Go to the Emacs calendar at the current date.
11520 If there is a time stamp in the current line, go to that date.
11521 A prefix ARG can be used to force the current date."
11522 (interactive "P")
11523 (let ((tsr org-ts-regexp) diff
11524 (calendar-move-hook nil)
11525 (calendar-view-holidays-initially-flag nil)
11526 (view-calendar-holidays-initially nil)
11527 (calendar-view-diary-initially-flag nil)
11528 (view-diary-entries-initially nil))
11529 (if (or (org-at-timestamp-p)
11530 (save-excursion
11531 (beginning-of-line 1)
11532 (looking-at (concat ".*" tsr))))
11533 (let ((d1 (time-to-days (current-time)))
11534 (d2 (time-to-days
11535 (org-time-string-to-time (match-string 1)))))
11536 (setq diff (- d2 d1))))
11537 (calendar)
11538 (calendar-goto-today)
11539 (if (and diff (not arg)) (calendar-forward-day diff))))
11541 (defun org-get-date-from-calendar ()
11542 "Return a list (month day year) of date at point in calendar."
11543 (with-current-buffer "*Calendar*"
11544 (save-match-data
11545 (calendar-cursor-to-date))))
11547 (defun org-date-from-calendar ()
11548 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11549 If there is already a time stamp at the cursor position, update it."
11550 (interactive)
11551 (if (org-at-timestamp-p t)
11552 (org-timestamp-change 0 'calendar)
11553 (let ((cal-date (org-get-date-from-calendar)))
11554 (org-insert-time-stamp
11555 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11557 (defun org-minutes-to-hh:mm-string (m)
11558 "Compute H:MM from a number of minutes."
11559 (let ((h (/ m 60)))
11560 (setq m (- m (* 60 h)))
11561 (format org-time-clocksum-format h m)))
11563 (defun org-hh:mm-string-to-minutes (s)
11564 "Convert a string H:MM to a number of minutes."
11565 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11566 (+ (* (string-to-number (match-string 1 s)) 60)
11567 (string-to-number (match-string 2 s)))
11570 ;;;; Agenda files
11572 ;;;###autoload
11573 (defun org-iswitchb (&optional arg)
11574 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11575 With a prefix argument, restrict available to files.
11576 With two prefix arguments, restrict available buffers to agenda files.
11578 Due to some yet unresolved reason, global function
11579 `iswitchb-mode' needs to be active for this function to work."
11580 (interactive "P")
11581 (require 'iswitchb)
11582 (let ((enabled iswitchb-mode) blist)
11583 (or enabled (iswitchb-mode 1))
11584 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11585 ((equal arg '(16)) (org-buffer-list 'agenda))
11586 (t (org-buffer-list))))
11587 (unwind-protect
11588 (let ((iswitchb-make-buflist-hook
11589 (lambda ()
11590 (setq iswitchb-temp-buflist
11591 (mapcar 'buffer-name blist)))))
11592 (switch-to-buffer
11593 (iswitchb-read-buffer
11594 "Switch-to: " nil t))
11595 (or enabled (iswitchb-mode -1))))))
11597 (defun org-buffer-list (&optional predicate tmp)
11598 "Return a list of Org buffers.
11599 PREDICATE can be either 'export, 'files or 'agenda.
11601 'export restrict the list to Export buffers.
11602 'files restrict the list to buffers visiting Org files.
11603 'agenda restrict the list to buffers visiting agenda files.
11605 If TMP is non-nil, don't include temporary buffers."
11606 (let (filter blist)
11607 (setq filter
11608 (cond ((eq predicate 'files) "\.org$")
11609 ((eq predicate 'export) "\*Org .*Export")
11610 (t "\*Org \\|\.org$")))
11611 (setq blist
11612 (mapcar
11613 (lambda(b)
11614 (let ((bname (buffer-name b))
11615 (bfile (buffer-file-name b)))
11616 (if (and (string-match filter bname)
11617 (if (eq predicate 'agenda)
11618 (member bfile
11619 (mapcar (lambda(f) (file-truename f))
11620 org-agenda-files)) t)
11621 (if tmp (not (string-match "tmp" bname)) t)) b)))
11622 (buffer-list)))
11623 (delete nil blist)))
11625 (defun org-agenda-files (&optional unrestricted ext)
11626 "Get the list of agenda files.
11627 Optional UNRESTRICTED means return the full list even if a restriction
11628 is currently in place.
11629 When EXT is non-nil, try to add all files that are created by adding EXT
11630 to the file nemes. Basically, this is a way to add the archive files
11631 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11632 a string, \"_archive\" will be used."
11633 (let ((files
11634 (cond
11635 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11636 ((stringp org-agenda-files) (org-read-agenda-file-list))
11637 ((listp org-agenda-files) org-agenda-files)
11638 (t (error "Invalid value of `org-agenda-files'")))))
11639 (setq files (apply 'append
11640 (mapcar (lambda (f)
11641 (if (file-directory-p f)
11642 (directory-files
11643 f t org-agenda-file-regexp)
11644 (list f)))
11645 files)))
11646 (when org-agenda-skip-unavailable-files
11647 (setq files (delq nil
11648 (mapcar (function
11649 (lambda (file)
11650 (and (file-readable-p file) file)))
11651 files))))
11652 (when ext
11653 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11654 ext "_archive"))
11655 (setq files (apply 'append
11656 (mapcar
11657 (lambda (f)
11658 (if (file-exists-p (concat f ext))
11659 (list f (concat f ext))
11660 (list f)))
11661 files))))
11662 files))
11664 (defun org-edit-agenda-file-list ()
11665 "Edit the list of agenda files.
11666 Depending on setup, this either uses customize to edit the variable
11667 `org-agenda-files', or it visits the file that is holding the list. In the
11668 latter case, the buffer is set up in a way that saving it automatically kills
11669 the buffer and restores the previous window configuration."
11670 (interactive)
11671 (if (stringp org-agenda-files)
11672 (let ((cw (current-window-configuration)))
11673 (find-file org-agenda-files)
11674 (org-set-local 'org-window-configuration cw)
11675 (org-add-hook 'after-save-hook
11676 (lambda ()
11677 (set-window-configuration
11678 (prog1 org-window-configuration
11679 (kill-buffer (current-buffer))))
11680 (org-install-agenda-files-menu)
11681 (message "New agenda file list installed"))
11682 nil 'local)
11683 (message "%s" (substitute-command-keys
11684 "Edit list and finish with \\[save-buffer]")))
11685 (customize-variable 'org-agenda-files)))
11687 (defun org-store-new-agenda-file-list (list)
11688 "Set new value for the agenda file list and save it correcly."
11689 (if (stringp org-agenda-files)
11690 (let ((f org-agenda-files) b)
11691 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11692 (with-temp-file f
11693 (insert (mapconcat 'identity list "\n") "\n")))
11694 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11695 (setq org-agenda-files list)
11696 (customize-save-variable 'org-agenda-files org-agenda-files))))
11698 (defun org-read-agenda-file-list ()
11699 "Read the list of agenda files from a file."
11700 (when (file-directory-p org-agenda-files)
11701 (error "`org-agenda-files' cannot be a single directory"))
11702 (when (stringp org-agenda-files)
11703 (with-temp-buffer
11704 (insert-file-contents org-agenda-files)
11705 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11708 ;;;###autoload
11709 (defun org-cycle-agenda-files ()
11710 "Cycle through the files in `org-agenda-files'.
11711 If the current buffer visits an agenda file, find the next one in the list.
11712 If the current buffer does not, find the first agenda file."
11713 (interactive)
11714 (let* ((fs (org-agenda-files t))
11715 (files (append fs (list (car fs))))
11716 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11717 file)
11718 (unless files (error "No agenda files"))
11719 (catch 'exit
11720 (while (setq file (pop files))
11721 (if (equal (file-truename file) tcf)
11722 (when (car files)
11723 (find-file (car files))
11724 (throw 'exit t))))
11725 (find-file (car fs)))
11726 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11728 (defun org-agenda-file-to-front (&optional to-end)
11729 "Move/add the current file to the top of the agenda file list.
11730 If the file is not present in the list, it is added to the front. If it is
11731 present, it is moved there. With optional argument TO-END, add/move to the
11732 end of the list."
11733 (interactive "P")
11734 (let ((org-agenda-skip-unavailable-files nil)
11735 (file-alist (mapcar (lambda (x)
11736 (cons (file-truename x) x))
11737 (org-agenda-files t)))
11738 (ctf (file-truename buffer-file-name))
11739 x had)
11740 (setq x (assoc ctf file-alist) had x)
11742 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11743 (if to-end
11744 (setq file-alist (append (delq x file-alist) (list x)))
11745 (setq file-alist (cons x (delq x file-alist))))
11746 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11747 (org-install-agenda-files-menu)
11748 (message "File %s to %s of agenda file list"
11749 (if had "moved" "added") (if to-end "end" "front"))))
11751 (defun org-remove-file (&optional file)
11752 "Remove current file from the list of files in variable `org-agenda-files'.
11753 These are the files which are being checked for agenda entries.
11754 Optional argument FILE means, use this file instead of the current."
11755 (interactive)
11756 (let* ((org-agenda-skip-unavailable-files nil)
11757 (file (or file buffer-file-name))
11758 (true-file (file-truename file))
11759 (afile (abbreviate-file-name file))
11760 (files (delq nil (mapcar
11761 (lambda (x)
11762 (if (equal true-file
11763 (file-truename x))
11764 nil x))
11765 (org-agenda-files t)))))
11766 (if (not (= (length files) (length (org-agenda-files t))))
11767 (progn
11768 (org-store-new-agenda-file-list files)
11769 (org-install-agenda-files-menu)
11770 (message "Removed file: %s" afile))
11771 (message "File was not in list: %s (not removed)" afile))))
11773 (defun org-file-menu-entry (file)
11774 (vector file (list 'find-file file) t))
11776 (defun org-check-agenda-file (file)
11777 "Make sure FILE exists. If not, ask user what to do."
11778 (when (not (file-exists-p file))
11779 (message "non-existent file %s. [R]emove from list or [A]bort?"
11780 (abbreviate-file-name file))
11781 (let ((r (downcase (read-char-exclusive))))
11782 (cond
11783 ((equal r ?r)
11784 (org-remove-file file)
11785 (throw 'nextfile t))
11786 (t (error "Abort"))))))
11788 (defun org-get-agenda-file-buffer (file)
11789 "Get a buffer visiting FILE. If the buffer needs to be created, add
11790 it to the list of buffers which might be released later."
11791 (let ((buf (org-find-base-buffer-visiting file)))
11792 (if buf
11793 buf ; just return it
11794 ;; Make a new buffer and remember it
11795 (setq buf (find-file-noselect file))
11796 (if buf (push buf org-agenda-new-buffers))
11797 buf)))
11799 (defun org-release-buffers (blist)
11800 "Release all buffers in list, asking the user for confirmation when needed.
11801 When a buffer is unmodified, it is just killed. When modified, it is saved
11802 \(if the user agrees) and then killed."
11803 (let (buf file)
11804 (while (setq buf (pop blist))
11805 (setq file (buffer-file-name buf))
11806 (when (and (buffer-modified-p buf)
11807 file
11808 (y-or-n-p (format "Save file %s? " file)))
11809 (with-current-buffer buf (save-buffer)))
11810 (kill-buffer buf))))
11812 (defun org-prepare-agenda-buffers (files)
11813 "Create buffers for all agenda files, protect archived trees and comments."
11814 (interactive)
11815 (let ((pa '(:org-archived t))
11816 (pc '(:org-comment t))
11817 (pall '(:org-archived t :org-comment t))
11818 (inhibit-read-only t)
11819 (rea (concat ":" org-archive-tag ":"))
11820 bmp file re)
11821 (save-excursion
11822 (save-restriction
11823 (while (setq file (pop files))
11824 (if (bufferp file)
11825 (set-buffer file)
11826 (org-check-agenda-file file)
11827 (set-buffer (org-get-agenda-file-buffer file)))
11828 (widen)
11829 (setq bmp (buffer-modified-p))
11830 (org-refresh-category-properties)
11831 (setq org-todo-keywords-for-agenda
11832 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11833 (setq org-done-keywords-for-agenda
11834 (append org-done-keywords-for-agenda org-done-keywords))
11835 (save-excursion
11836 (remove-text-properties (point-min) (point-max) pall)
11837 (when org-agenda-skip-archived-trees
11838 (goto-char (point-min))
11839 (while (re-search-forward rea nil t)
11840 (if (org-on-heading-p t)
11841 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11842 (goto-char (point-min))
11843 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11844 (while (re-search-forward re nil t)
11845 (add-text-properties
11846 (match-beginning 0) (org-end-of-subtree t) pc)))
11847 (set-buffer-modified-p bmp))))))
11849 ;;;; Embedded LaTeX
11851 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11852 "Keymap for the minor `org-cdlatex-mode'.")
11854 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11855 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11856 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11857 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11858 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11860 (defvar org-cdlatex-texmathp-advice-is-done nil
11861 "Flag remembering if we have applied the advice to texmathp already.")
11863 (define-minor-mode org-cdlatex-mode
11864 "Toggle the minor `org-cdlatex-mode'.
11865 This mode supports entering LaTeX environment and math in LaTeX fragments
11866 in Org-mode.
11867 \\{org-cdlatex-mode-map}"
11868 nil " OCDL" nil
11869 (when org-cdlatex-mode (require 'cdlatex))
11870 (unless org-cdlatex-texmathp-advice-is-done
11871 (setq org-cdlatex-texmathp-advice-is-done t)
11872 (defadvice texmathp (around org-math-always-on activate)
11873 "Always return t in org-mode buffers.
11874 This is because we want to insert math symbols without dollars even outside
11875 the LaTeX math segments. If Orgmode thinks that point is actually inside
11876 en embedded LaTeX fragement, let texmathp do its job.
11877 \\[org-cdlatex-mode-map]"
11878 (interactive)
11879 (let (p)
11880 (cond
11881 ((not (org-mode-p)) ad-do-it)
11882 ((eq this-command 'cdlatex-math-symbol)
11883 (setq ad-return-value t
11884 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11886 (let ((p (org-inside-LaTeX-fragment-p)))
11887 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11888 (setq ad-return-value t
11889 texmathp-why '("Org-mode embedded math" . 0))
11890 (if p ad-do-it)))))))))
11892 (defun turn-on-org-cdlatex ()
11893 "Unconditionally turn on `org-cdlatex-mode'."
11894 (org-cdlatex-mode 1))
11896 (defun org-inside-LaTeX-fragment-p ()
11897 "Test if point is inside a LaTeX fragment.
11898 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11899 sequence appearing also before point.
11900 Even though the matchers for math are configurable, this function assumes
11901 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11902 delimiters are skipped when they have been removed by customization.
11903 The return value is nil, or a cons cell with the delimiter and
11904 and the position of this delimiter.
11906 This function does a reasonably good job, but can locally be fooled by
11907 for example currency specifications. For example it will assume being in
11908 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11909 fragments that are properly closed, but during editing, we have to live
11910 with the uncertainty caused by missing closing delimiters. This function
11911 looks only before point, not after."
11912 (catch 'exit
11913 (let ((pos (point))
11914 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11915 (lim (progn
11916 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11917 (point)))
11918 dd-on str (start 0) m re)
11919 (goto-char pos)
11920 (when dodollar
11921 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11922 re (nth 1 (assoc "$" org-latex-regexps)))
11923 (while (string-match re str start)
11924 (cond
11925 ((= (match-end 0) (length str))
11926 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11927 ((= (match-end 0) (- (length str) 5))
11928 (throw 'exit nil))
11929 (t (setq start (match-end 0))))))
11930 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11931 (goto-char pos)
11932 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11933 (and (match-beginning 2) (throw 'exit nil))
11934 ;; count $$
11935 (while (re-search-backward "\\$\\$" lim t)
11936 (setq dd-on (not dd-on)))
11937 (goto-char pos)
11938 (if dd-on (cons "$$" m))))))
11941 (defun org-try-cdlatex-tab ()
11942 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11943 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11944 - inside a LaTeX fragment, or
11945 - after the first word in a line, where an abbreviation expansion could
11946 insert a LaTeX environment."
11947 (when org-cdlatex-mode
11948 (cond
11949 ((save-excursion
11950 (skip-chars-backward "a-zA-Z0-9*")
11951 (skip-chars-backward " \t")
11952 (bolp))
11953 (cdlatex-tab) t)
11954 ((org-inside-LaTeX-fragment-p)
11955 (cdlatex-tab) t)
11956 (t nil))))
11958 (defun org-cdlatex-underscore-caret (&optional arg)
11959 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11960 Revert to the normal definition outside of these fragments."
11961 (interactive "P")
11962 (if (org-inside-LaTeX-fragment-p)
11963 (call-interactively 'cdlatex-sub-superscript)
11964 (let (org-cdlatex-mode)
11965 (call-interactively (key-binding (vector last-input-event))))))
11967 (defun org-cdlatex-math-modify (&optional arg)
11968 "Execute `cdlatex-math-modify' in LaTeX fragments.
11969 Revert to the normal definition outside of these fragments."
11970 (interactive "P")
11971 (if (org-inside-LaTeX-fragment-p)
11972 (call-interactively 'cdlatex-math-modify)
11973 (let (org-cdlatex-mode)
11974 (call-interactively (key-binding (vector last-input-event))))))
11976 (defvar org-latex-fragment-image-overlays nil
11977 "List of overlays carrying the images of latex fragments.")
11978 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11980 (defun org-remove-latex-fragment-image-overlays ()
11981 "Remove all overlays with LaTeX fragment images in current buffer."
11982 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11983 (setq org-latex-fragment-image-overlays nil))
11985 (defun org-preview-latex-fragment (&optional subtree)
11986 "Preview the LaTeX fragment at point, or all locally or globally.
11987 If the cursor is in a LaTeX fragment, create the image and overlay
11988 it over the source code. If there is no fragment at point, display
11989 all fragments in the current text, from one headline to the next. With
11990 prefix SUBTREE, display all fragments in the current subtree. With a
11991 double prefix `C-u C-u', or when the cursor is before the first headline,
11992 display all fragments in the buffer.
11993 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11994 (interactive "P")
11995 (org-remove-latex-fragment-image-overlays)
11996 (save-excursion
11997 (save-restriction
11998 (let (beg end at msg)
11999 (cond
12000 ((or (equal subtree '(16))
12001 (not (save-excursion
12002 (re-search-backward (concat "^" outline-regexp) nil t))))
12003 (setq beg (point-min) end (point-max)
12004 msg "Creating images for buffer...%s"))
12005 ((equal subtree '(4))
12006 (org-back-to-heading)
12007 (setq beg (point) end (org-end-of-subtree t)
12008 msg "Creating images for subtree...%s"))
12010 (if (setq at (org-inside-LaTeX-fragment-p))
12011 (goto-char (max (point-min) (- (cdr at) 2)))
12012 (org-back-to-heading))
12013 (setq beg (point) end (progn (outline-next-heading) (point))
12014 msg (if at "Creating image...%s"
12015 "Creating images for entry...%s"))))
12016 (message msg "")
12017 (narrow-to-region beg end)
12018 (goto-char beg)
12019 (org-format-latex
12020 (concat "ltxpng/" (file-name-sans-extension
12021 (file-name-nondirectory
12022 buffer-file-name)))
12023 default-directory 'overlays msg at 'forbuffer)
12024 (message msg "done. Use `C-c C-c' to remove images.")))))
12026 (defvar org-latex-regexps
12027 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12028 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12029 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12030 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12031 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12032 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12033 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12034 "Regular expressions for matching embedded LaTeX.")
12036 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12037 "Replace LaTeX fragments with links to an image, and produce images."
12038 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12039 (let* ((prefixnodir (file-name-nondirectory prefix))
12040 (absprefix (expand-file-name prefix dir))
12041 (todir (file-name-directory absprefix))
12042 (opt org-format-latex-options)
12043 (matchers (plist-get opt :matchers))
12044 (re-list org-latex-regexps)
12045 (cnt 0) txt link beg end re e checkdir
12046 m n block linkfile movefile ov)
12047 ;; Check if there are old images files with this prefix, and remove them
12048 (when (file-directory-p todir)
12049 (mapc 'delete-file
12050 (directory-files
12051 todir 'full
12052 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12053 ;; Check the different regular expressions
12054 (while (setq e (pop re-list))
12055 (setq m (car e) re (nth 1 e) n (nth 2 e)
12056 block (if (nth 3 e) "\n\n" ""))
12057 (when (member m matchers)
12058 (goto-char (point-min))
12059 (while (re-search-forward re nil t)
12060 (when (or (not at) (equal (cdr at) (match-beginning n)))
12061 (setq txt (match-string n)
12062 beg (match-beginning n) end (match-end n)
12063 cnt (1+ cnt)
12064 linkfile (format "%s_%04d.png" prefix cnt)
12065 movefile (format "%s_%04d.png" absprefix cnt)
12066 link (concat block "[[file:" linkfile "]]" block))
12067 (if msg (message msg cnt))
12068 (goto-char beg)
12069 (unless checkdir ; make sure the directory exists
12070 (setq checkdir t)
12071 (or (file-directory-p todir) (make-directory todir)))
12072 (org-create-formula-image
12073 txt movefile opt forbuffer)
12074 (if overlays
12075 (progn
12076 (setq ov (org-make-overlay beg end))
12077 (if (featurep 'xemacs)
12078 (progn
12079 (org-overlay-put ov 'invisible t)
12080 (org-overlay-put
12081 ov 'end-glyph
12082 (make-glyph (vector 'png :file movefile))))
12083 (org-overlay-put
12084 ov 'display
12085 (list 'image :type 'png :file movefile :ascent 'center)))
12086 (push ov org-latex-fragment-image-overlays)
12087 (goto-char end))
12088 (delete-region beg end)
12089 (insert link))))))))
12091 ;; This function borrows from Ganesh Swami's latex2png.el
12092 (defun org-create-formula-image (string tofile options buffer)
12093 (let* ((tmpdir (if (featurep 'xemacs)
12094 (temp-directory)
12095 temporary-file-directory))
12096 (texfilebase (make-temp-name
12097 (expand-file-name "orgtex" tmpdir)))
12098 (texfile (concat texfilebase ".tex"))
12099 (dvifile (concat texfilebase ".dvi"))
12100 (pngfile (concat texfilebase ".png"))
12101 (fnh (if (featurep 'xemacs)
12102 (font-height (get-face-font 'default))
12103 (face-attribute 'default :height nil)))
12104 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12105 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12106 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12107 "Black"))
12108 (bg (or (plist-get options (if buffer :background :html-background))
12109 "Transparent")))
12110 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12111 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12112 (with-temp-file texfile
12113 (insert org-format-latex-header
12114 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12115 (let ((dir default-directory))
12116 (condition-case nil
12117 (progn
12118 (cd tmpdir)
12119 (call-process "latex" nil nil nil texfile))
12120 (error nil))
12121 (cd dir))
12122 (if (not (file-exists-p dvifile))
12123 (progn (message "Failed to create dvi file from %s" texfile) nil)
12124 (call-process "dvipng" nil nil nil
12125 "-E" "-fg" fg "-bg" bg
12126 "-D" dpi
12127 ;;"-x" scale "-y" scale
12128 "-T" "tight"
12129 "-o" pngfile
12130 dvifile)
12131 (if (not (file-exists-p pngfile))
12132 (progn (message "Failed to create png file from %s" texfile) nil)
12133 ;; Use the requested file name and clean up
12134 (copy-file pngfile tofile 'replace)
12135 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12136 (delete-file (concat texfilebase e)))
12137 pngfile))))
12139 (defun org-dvipng-color (attr)
12140 "Return an rgb color specification for dvipng."
12141 (apply 'format "rgb %s %s %s"
12142 (mapcar 'org-normalize-color
12143 (color-values (face-attribute 'default attr nil)))))
12145 (defun org-normalize-color (value)
12146 "Return string to be used as color value for an RGB component."
12147 (format "%g" (/ value 65535.0)))
12150 ;;;; Key bindings
12152 ;; Make `C-c C-x' a prefix key
12153 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12155 ;; TAB key with modifiers
12156 (org-defkey org-mode-map "\C-i" 'org-cycle)
12157 (org-defkey org-mode-map [(tab)] 'org-cycle)
12158 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12159 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12160 (org-defkey org-mode-map "\M-\t" 'org-complete)
12161 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12162 ;; The following line is necessary under Suse GNU/Linux
12163 (unless (featurep 'xemacs)
12164 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12165 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12166 (define-key org-mode-map [backtab] 'org-shifttab)
12168 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12169 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12170 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12172 ;; Cursor keys with modifiers
12173 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12174 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12175 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12176 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12178 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12179 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12180 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12181 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12183 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12184 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12185 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12186 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12188 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12189 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12191 ;;; Extra keys for tty access.
12192 ;; We only set them when really needed because otherwise the
12193 ;; menus don't show the simple keys
12195 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12196 (not window-system))
12197 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12198 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12199 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12200 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12201 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12202 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12203 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12204 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12205 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12206 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12207 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12208 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12209 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12210 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12211 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12212 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12213 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12214 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12215 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12216 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12217 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12218 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12220 ;; All the other keys
12222 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12223 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12224 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
12225 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12226 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12227 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12228 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12229 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12230 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12231 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12232 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12233 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12234 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12235 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12236 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12237 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12238 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12239 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12240 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12241 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12242 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12243 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12244 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12245 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12246 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12247 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12248 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12249 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12250 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12251 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12252 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12253 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12254 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12255 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12256 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12257 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12258 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12259 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12260 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12261 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12262 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12263 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12264 (org-defkey org-mode-map "\C-c^" 'org-sort)
12265 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12266 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12267 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12268 (org-defkey org-mode-map "\C-m" 'org-return)
12269 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12270 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12271 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12272 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12273 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12274 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12275 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12276 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12277 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12278 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12279 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12280 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12281 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12282 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12283 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12284 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12286 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12287 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12288 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12289 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12291 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12292 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12293 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12294 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12295 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12296 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12297 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12298 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12299 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12300 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12301 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12302 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12304 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12306 (when (featurep 'xemacs)
12307 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12309 (defvar org-table-auto-blank-field) ; defined in org-table.el
12310 (defun org-self-insert-command (N)
12311 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12312 If the cursor is in a table looking at whitespace, the whitespace is
12313 overwritten, and the table is not marked as requiring realignment."
12314 (interactive "p")
12315 (if (and (org-table-p)
12316 (progn
12317 ;; check if we blank the field, and if that triggers align
12318 (and (featurep 'org-table) org-table-auto-blank-field
12319 (member last-command
12320 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12321 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12322 ;; got extra space, this field does not determine column width
12323 (let (org-table-may-need-update) (org-table-blank-field))
12324 ;; no extra space, this field may determine column width
12325 (org-table-blank-field)))
12327 (eq N 1)
12328 (looking-at "[^|\n]* |"))
12329 (let (org-table-may-need-update)
12330 (goto-char (1- (match-end 0)))
12331 (delete-backward-char 1)
12332 (goto-char (match-beginning 0))
12333 (self-insert-command N))
12334 (setq org-table-may-need-update t)
12335 (self-insert-command N)
12336 (org-fix-tags-on-the-fly)))
12338 (defun org-fix-tags-on-the-fly ()
12339 (when (and (equal (char-after (point-at-bol)) ?*)
12340 (org-on-heading-p))
12341 (org-align-tags-here org-tags-column)))
12343 (defun org-delete-backward-char (N)
12344 "Like `delete-backward-char', insert whitespace at field end in tables.
12345 When deleting backwards, in tables this function will insert whitespace in
12346 front of the next \"|\" separator, to keep the table aligned. The table will
12347 still be marked for re-alignment if the field did fill the entire column,
12348 because, in this case the deletion might narrow the column."
12349 (interactive "p")
12350 (if (and (org-table-p)
12351 (eq N 1)
12352 (string-match "|" (buffer-substring (point-at-bol) (point)))
12353 (looking-at ".*?|"))
12354 (let ((pos (point))
12355 (noalign (looking-at "[^|\n\r]* |"))
12356 (c org-table-may-need-update))
12357 (backward-delete-char N)
12358 (skip-chars-forward "^|")
12359 (insert " ")
12360 (goto-char (1- pos))
12361 ;; noalign: if there were two spaces at the end, this field
12362 ;; does not determine the width of the column.
12363 (if noalign (setq org-table-may-need-update c)))
12364 (backward-delete-char N)
12365 (org-fix-tags-on-the-fly)))
12367 (defun org-delete-char (N)
12368 "Like `delete-char', but insert whitespace at field end in tables.
12369 When deleting characters, in tables this function will insert whitespace in
12370 front of the next \"|\" separator, to keep the table aligned. The table will
12371 still be marked for re-alignment if the field did fill the entire column,
12372 because, in this case the deletion might narrow the column."
12373 (interactive "p")
12374 (if (and (org-table-p)
12375 (not (bolp))
12376 (not (= (char-after) ?|))
12377 (eq N 1))
12378 (if (looking-at ".*?|")
12379 (let ((pos (point))
12380 (noalign (looking-at "[^|\n\r]* |"))
12381 (c org-table-may-need-update))
12382 (replace-match (concat
12383 (substring (match-string 0) 1 -1)
12384 " |"))
12385 (goto-char pos)
12386 ;; noalign: if there were two spaces at the end, this field
12387 ;; does not determine the width of the column.
12388 (if noalign (setq org-table-may-need-update c)))
12389 (delete-char N))
12390 (delete-char N)
12391 (org-fix-tags-on-the-fly)))
12393 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12394 (put 'org-self-insert-command 'delete-selection t)
12395 (put 'orgtbl-self-insert-command 'delete-selection t)
12396 (put 'org-delete-char 'delete-selection 'supersede)
12397 (put 'org-delete-backward-char 'delete-selection 'supersede)
12399 ;; Make `flyspell-mode' delay after some commands
12400 (put 'org-self-insert-command 'flyspell-delayed t)
12401 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12402 (put 'org-delete-char 'flyspell-delayed t)
12403 (put 'org-delete-backward-char 'flyspell-delayed t)
12405 ;; Make pabbrev-mode expand after org-mode commands
12406 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12407 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12409 ;; How to do this: Measure non-white length of current string
12410 ;; If equal to column width, we should realign.
12412 (defun org-remap (map &rest commands)
12413 "In MAP, remap the functions given in COMMANDS.
12414 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12415 (let (new old)
12416 (while commands
12417 (setq old (pop commands) new (pop commands))
12418 (if (fboundp 'command-remapping)
12419 (org-defkey map (vector 'remap old) new)
12420 (substitute-key-definition old new map global-map)))))
12422 (when (eq org-enable-table-editor 'optimized)
12423 ;; If the user wants maximum table support, we need to hijack
12424 ;; some standard editing functions
12425 (org-remap org-mode-map
12426 'self-insert-command 'org-self-insert-command
12427 'delete-char 'org-delete-char
12428 'delete-backward-char 'org-delete-backward-char)
12429 (org-defkey org-mode-map "|" 'org-force-self-insert))
12431 (defun org-shiftcursor-error ()
12432 "Throw an error because Shift-Cursor command was applied in wrong context."
12433 (error "This command is active in special context like tables, headlines or timestamps"))
12435 (defun org-shifttab (&optional arg)
12436 "Global visibility cycling or move to previous table field.
12437 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12438 on context.
12439 See the individual commands for more information."
12440 (interactive "P")
12441 (cond
12442 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12443 ((integerp arg)
12444 (message "Content view to level: %d" arg)
12445 (org-content (prefix-numeric-value arg))
12446 (setq org-cycle-global-status 'overview))
12447 (t (call-interactively 'org-global-cycle))))
12449 (defun org-shiftmetaleft ()
12450 "Promote subtree or delete table column.
12451 Calls `org-promote-subtree', `org-outdent-item',
12452 or `org-table-delete-column', depending on context.
12453 See the individual commands for more information."
12454 (interactive)
12455 (cond
12456 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12457 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12458 ((org-at-item-p) (call-interactively 'org-outdent-item))
12459 (t (org-shiftcursor-error))))
12461 (defun org-shiftmetaright ()
12462 "Demote subtree or insert table column.
12463 Calls `org-demote-subtree', `org-indent-item',
12464 or `org-table-insert-column', depending on context.
12465 See the individual commands for more information."
12466 (interactive)
12467 (cond
12468 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12469 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12470 ((org-at-item-p) (call-interactively 'org-indent-item))
12471 (t (org-shiftcursor-error))))
12473 (defun org-shiftmetaup (&optional arg)
12474 "Move subtree up or kill table row.
12475 Calls `org-move-subtree-up' or `org-table-kill-row' or
12476 `org-move-item-up' depending on context. See the individual commands
12477 for more information."
12478 (interactive "P")
12479 (cond
12480 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12481 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12482 ((org-at-item-p) (call-interactively 'org-move-item-up))
12483 (t (org-shiftcursor-error))))
12484 (defun org-shiftmetadown (&optional arg)
12485 "Move subtree down or insert table row.
12486 Calls `org-move-subtree-down' or `org-table-insert-row' or
12487 `org-move-item-down', depending on context. See the individual
12488 commands for more information."
12489 (interactive "P")
12490 (cond
12491 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12492 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12493 ((org-at-item-p) (call-interactively 'org-move-item-down))
12494 (t (org-shiftcursor-error))))
12496 (defun org-metaleft (&optional arg)
12497 "Promote heading or move table column to left.
12498 Calls `org-do-promote' or `org-table-move-column', depending on context.
12499 With no specific context, calls the Emacs default `backward-word'.
12500 See the individual commands for more information."
12501 (interactive "P")
12502 (cond
12503 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12504 ((or (org-on-heading-p) (org-region-active-p))
12505 (call-interactively 'org-do-promote))
12506 ((org-at-item-p) (call-interactively 'org-outdent-item))
12507 (t (call-interactively 'backward-word))))
12509 (defun org-metaright (&optional arg)
12510 "Demote subtree or move table column to right.
12511 Calls `org-do-demote' or `org-table-move-column', depending on context.
12512 With no specific context, calls the Emacs default `forward-word'.
12513 See the individual commands for more information."
12514 (interactive "P")
12515 (cond
12516 ((org-at-table-p) (call-interactively 'org-table-move-column))
12517 ((or (org-on-heading-p) (org-region-active-p))
12518 (call-interactively 'org-do-demote))
12519 ((org-at-item-p) (call-interactively 'org-indent-item))
12520 (t (call-interactively 'forward-word))))
12522 (defun org-metaup (&optional arg)
12523 "Move subtree up or move table row up.
12524 Calls `org-move-subtree-up' or `org-table-move-row' or
12525 `org-move-item-up', depending on context. See the individual commands
12526 for more information."
12527 (interactive "P")
12528 (cond
12529 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12530 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12531 ((org-at-item-p) (call-interactively 'org-move-item-up))
12532 (t (transpose-lines 1) (beginning-of-line -1))))
12534 (defun org-metadown (&optional arg)
12535 "Move subtree down or move table row down.
12536 Calls `org-move-subtree-down' or `org-table-move-row' or
12537 `org-move-item-down', depending on context. See the individual
12538 commands for more information."
12539 (interactive "P")
12540 (cond
12541 ((org-at-table-p) (call-interactively 'org-table-move-row))
12542 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12543 ((org-at-item-p) (call-interactively 'org-move-item-down))
12544 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12546 (defun org-shiftup (&optional arg)
12547 "Increase item in timestamp or increase priority of current headline.
12548 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12549 depending on context. See the individual commands for more information."
12550 (interactive "P")
12551 (cond
12552 ((org-at-timestamp-p t)
12553 (call-interactively (if org-edit-timestamp-down-means-later
12554 'org-timestamp-down 'org-timestamp-up)))
12555 ((org-on-heading-p) (call-interactively 'org-priority-up))
12556 ((org-at-item-p) (call-interactively 'org-previous-item))
12557 ((org-clocktable-try-shift 'up arg))
12558 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12560 (defun org-shiftdown (&optional arg)
12561 "Decrease item in timestamp or decrease priority of current headline.
12562 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12563 depending on context. See the individual commands for more information."
12564 (interactive "P")
12565 (cond
12566 ((org-at-timestamp-p t)
12567 (call-interactively (if org-edit-timestamp-down-means-later
12568 'org-timestamp-up 'org-timestamp-down)))
12569 ((org-on-heading-p) (call-interactively 'org-priority-down))
12570 ((org-clocktable-try-shift 'down arg))
12571 (t (call-interactively 'org-next-item))))
12573 (defun org-shiftright (&optional arg)
12574 "Next TODO keyword or timestamp one day later, depending on context."
12575 (interactive "P")
12576 (cond
12577 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12578 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12579 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12580 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12581 ((org-clocktable-try-shift 'right arg))
12582 (t (org-shiftcursor-error))))
12584 (defun org-shiftleft (&optional arg)
12585 "Previous TODO keyword or timestamp one day earlier, depending on context."
12586 (interactive "P")
12587 (cond
12588 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12589 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12590 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12591 ((org-at-property-p)
12592 (call-interactively 'org-property-previous-allowed-value))
12593 ((org-clocktable-try-shift 'left arg))
12594 (t (org-shiftcursor-error))))
12596 (defun org-shiftcontrolright ()
12597 "Switch to next TODO set."
12598 (interactive)
12599 (cond
12600 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12601 (t (org-shiftcursor-error))))
12603 (defun org-shiftcontrolleft ()
12604 "Switch to previous TODO set."
12605 (interactive)
12606 (cond
12607 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12608 (t (org-shiftcursor-error))))
12610 (defun org-ctrl-c-ret ()
12611 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12612 (interactive)
12613 (cond
12614 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12615 (t (call-interactively 'org-insert-heading))))
12617 (defun org-copy-special ()
12618 "Copy region in table or copy current subtree.
12619 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12620 See the individual commands for more information."
12621 (interactive)
12622 (call-interactively
12623 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12625 (defun org-cut-special ()
12626 "Cut region in table or cut current subtree.
12627 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12628 See the individual commands for more information."
12629 (interactive)
12630 (call-interactively
12631 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12633 (defun org-paste-special (arg)
12634 "Paste rectangular region into table, or past subtree relative to level.
12635 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12636 See the individual commands for more information."
12637 (interactive "P")
12638 (if (org-at-table-p)
12639 (org-table-paste-rectangle)
12640 (org-paste-subtree arg)))
12642 (defun org-edit-special ()
12643 "Call a special editor for the stuff at point.
12644 When at a table, call the formula editor with `org-table-edit-formulas'.
12645 When at the first line of an src example, call `org-edit-src-example'."
12646 (interactive)
12647 (if (org-at-table-p)
12648 (call-interactively 'org-table-edit-formulas)
12649 (or (org-edit-src-example)
12650 (error "%s"
12651 (substitute-command-keys
12652 "\\[org-edit-special] can do nothing useful here.")))))
12654 (defun org-ctrl-c-ctrl-c (&optional arg)
12655 "Set tags in headline, or update according to changed information at point.
12657 This command does many different things, depending on context:
12659 - If the cursor is in a headline, prompt for tags and insert them
12660 into the current line, aligned to `org-tags-column'. When called
12661 with prefix arg, realign all tags in the current buffer.
12663 - If the cursor is in one of the special #+KEYWORD lines, this
12664 triggers scanning the buffer for these lines and updating the
12665 information.
12667 - If the cursor is inside a table, realign the table. This command
12668 works even if the automatic table editor has been turned off.
12670 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12671 the entire table.
12673 - If the cursor is a the beginning of a dynamic block, update it.
12675 - If the cursor is inside a table created by the table.el package,
12676 activate that table.
12678 - If the current buffer is a remember buffer, close note and file it.
12679 with a prefix argument, file it without further interaction to the default
12680 location.
12682 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12683 links in this buffer.
12685 - If the cursor is on a numbered item in a plain list, renumber the
12686 ordered list.
12688 - If the cursor is on a checkbox, toggle it."
12689 (interactive "P")
12690 (let ((org-enable-table-editor t))
12691 (cond
12692 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12693 org-occur-highlights
12694 org-latex-fragment-image-overlays)
12695 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12696 (org-remove-occur-highlights)
12697 (org-remove-latex-fragment-image-overlays)
12698 (message "Temporary highlights/overlays removed from current buffer"))
12699 ((and (local-variable-p 'org-finish-function (current-buffer))
12700 (fboundp org-finish-function))
12701 (funcall org-finish-function))
12702 ((org-at-property-p)
12703 (call-interactively 'org-property-action))
12704 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12705 ((org-on-heading-p) (call-interactively 'org-set-tags))
12706 ((org-at-table.el-p)
12707 (require 'table)
12708 (beginning-of-line 1)
12709 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12710 (call-interactively 'table-recognize-table))
12711 ((org-at-table-p)
12712 (org-table-maybe-eval-formula)
12713 (if arg
12714 (call-interactively 'org-table-recalculate)
12715 (org-table-maybe-recalculate-line))
12716 (call-interactively 'org-table-align))
12717 ((org-at-item-checkbox-p)
12718 (call-interactively 'org-toggle-checkbox))
12719 ((org-at-item-p)
12720 (call-interactively 'org-maybe-renumber-ordered-list))
12721 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12722 ;; Dynamic block
12723 (beginning-of-line 1)
12724 (org-update-dblock))
12725 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12726 (cond
12727 ((equal (match-string 1) "TBLFM")
12728 ;; Recalculate the table before this line
12729 (save-excursion
12730 (beginning-of-line 1)
12731 (skip-chars-backward " \r\n\t")
12732 (if (org-at-table-p)
12733 (org-call-with-arg 'org-table-recalculate t))))
12735 ; (org-set-regexps-and-options)
12736 ; (org-restart-font-lock)
12737 (let ((org-inhibit-startup t)) (org-mode-restart))
12738 (message "Local setup has been refreshed"))))
12739 (t (error "C-c C-c can do nothing useful at this location.")))))
12741 (defun org-mode-restart ()
12742 "Restart Org-mode, to scan again for special lines.
12743 Also updates the keyword regular expressions."
12744 (interactive)
12745 (org-mode)
12746 (message "Org-mode restarted"))
12748 (defun org-kill-note-or-show-branches ()
12749 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12750 (interactive)
12751 (if (not org-finish-function)
12752 (call-interactively 'show-branches)
12753 (let ((org-note-abort t))
12754 (funcall org-finish-function))))
12756 (defun org-return (&optional indent)
12757 "Goto next table row or insert a newline.
12758 Calls `org-table-next-row' or `newline', depending on context.
12759 See the individual commands for more information."
12760 (interactive)
12761 (cond
12762 ((bobp) (if indent (newline-and-indent) (newline)))
12763 ((and (org-at-heading-p)
12764 (looking-at
12765 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12766 (org-show-entry)
12767 (end-of-line 1)
12768 (newline))
12769 ((org-at-table-p)
12770 (org-table-justify-field-maybe)
12771 (call-interactively 'org-table-next-row))
12772 (t (if indent (newline-and-indent) (newline)))))
12774 (defun org-return-indent ()
12775 "Goto next table row or insert a newline and indent.
12776 Calls `org-table-next-row' or `newline-and-indent', depending on
12777 context. See the individual commands for more information."
12778 (interactive)
12779 (org-return t))
12781 (defun org-ctrl-c-star ()
12782 "Compute table, or change heading status of lines.
12783 Calls `org-table-recalculate' or `org-toggle-region-headings',
12784 depending on context. This will also turn a plain list item or a normal
12785 line into a subheading."
12786 (interactive)
12787 (cond
12788 ((org-at-table-p)
12789 (call-interactively 'org-table-recalculate))
12790 ((org-region-active-p)
12791 ;; Convert all lines in region to list items
12792 (call-interactively 'org-toggle-region-headings))
12793 ((org-on-heading-p)
12794 (org-toggle-region-headings (point-at-bol)
12795 (min (1+ (point-at-eol)) (point-max))))
12796 ((org-at-item-p)
12797 ;; Convert to heading
12798 (let ((level (save-match-data
12799 (save-excursion
12800 (condition-case nil
12801 (progn
12802 (org-back-to-heading t)
12803 (funcall outline-level))
12804 (error 0))))))
12805 (replace-match
12806 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12807 (t (org-toggle-region-headings (point-at-bol)
12808 (min (1+ (point-at-eol)) (point-max))))))
12810 (defun org-ctrl-c-minus ()
12811 "Insert separator line in table or modify bullet status of line.
12812 Also turns a plain line or a region of lines into list items.
12813 Calls `org-table-insert-hline', `org-toggle-region-items', or
12814 `org-cycle-list-bullet', depending on context."
12815 (interactive)
12816 (cond
12817 ((org-at-table-p)
12818 (call-interactively 'org-table-insert-hline))
12819 ((org-on-heading-p)
12820 ;; Convert to item
12821 (save-excursion
12822 (beginning-of-line 1)
12823 (if (looking-at "\\*+ ")
12824 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12825 ((org-region-active-p)
12826 ;; Convert all lines in region to list items
12827 (call-interactively 'org-toggle-region-items))
12828 ((org-in-item-p)
12829 (call-interactively 'org-cycle-list-bullet))
12830 (t (org-toggle-region-items (point-at-bol)
12831 (min (1+ (point-at-eol)) (point-max))))))
12833 (defun org-toggle-region-items (beg end)
12834 "Convert all lines in region to list items.
12835 If the first line is already an item, convert all list items in the region
12836 to normal lines."
12837 (interactive "r")
12838 (let (l2 l)
12839 (save-excursion
12840 (goto-char end)
12841 (setq l2 (org-current-line))
12842 (goto-char beg)
12843 (beginning-of-line 1)
12844 (setq l (1- (org-current-line)))
12845 (if (org-at-item-p)
12846 ;; We already have items, de-itemize
12847 (while (< (setq l (1+ l)) l2)
12848 (when (org-at-item-p)
12849 (goto-char (match-beginning 2))
12850 (delete-region (match-beginning 2) (match-end 2))
12851 (and (looking-at "[ \t]+") (replace-match "")))
12852 (beginning-of-line 2))
12853 (while (< (setq l (1+ l)) l2)
12854 (unless (org-at-item-p)
12855 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12856 (replace-match "\\1- \\2")))
12857 (beginning-of-line 2))))))
12859 (defun org-toggle-region-headings (beg end)
12860 "Convert all lines in region to list items.
12861 If the first line is already an item, convert all list items in the region
12862 to normal lines."
12863 (interactive "r")
12864 (let (l2 l)
12865 (save-excursion
12866 (goto-char end)
12867 (setq l2 (org-current-line))
12868 (goto-char beg)
12869 (beginning-of-line 1)
12870 (setq l (1- (org-current-line)))
12871 (if (org-on-heading-p)
12872 ;; We already have headlines, de-star them
12873 (while (< (setq l (1+ l)) l2)
12874 (when (org-on-heading-p t)
12875 (and (looking-at outline-regexp) (replace-match "")))
12876 (beginning-of-line 2))
12877 (let* ((stars (save-excursion
12878 (re-search-backward org-complex-heading-regexp nil t)
12879 (or (match-string 1) "*")))
12880 (add-stars (if org-odd-levels-only "**" "*"))
12881 (rpl (concat stars add-stars " \\2")))
12882 (while (< (setq l (1+ l)) l2)
12883 (unless (org-on-heading-p)
12884 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12885 (replace-match rpl)))
12886 (beginning-of-line 2)))))))
12888 (defun org-meta-return (&optional arg)
12889 "Insert a new heading or wrap a region in a table.
12890 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12891 See the individual commands for more information."
12892 (interactive "P")
12893 (cond
12894 ((org-at-table-p)
12895 (call-interactively 'org-table-wrap-region))
12896 (t (call-interactively 'org-insert-heading))))
12898 ;;; Menu entries
12900 ;; Define the Org-mode menus
12901 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12902 '("Tbl"
12903 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12904 ["Next Field" org-cycle (org-at-table-p)]
12905 ["Previous Field" org-shifttab (org-at-table-p)]
12906 ["Next Row" org-return (org-at-table-p)]
12907 "--"
12908 ["Blank Field" org-table-blank-field (org-at-table-p)]
12909 ["Edit Field" org-table-edit-field (org-at-table-p)]
12910 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12911 "--"
12912 ("Column"
12913 ["Move Column Left" org-metaleft (org-at-table-p)]
12914 ["Move Column Right" org-metaright (org-at-table-p)]
12915 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12916 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12917 ("Row"
12918 ["Move Row Up" org-metaup (org-at-table-p)]
12919 ["Move Row Down" org-metadown (org-at-table-p)]
12920 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12921 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12922 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12923 "--"
12924 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12925 ("Rectangle"
12926 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12927 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12928 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12929 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12930 "--"
12931 ("Calculate"
12932 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12933 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12934 ["Edit Formulas" org-edit-special (org-at-table-p)]
12935 "--"
12936 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12937 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12938 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12939 "--"
12940 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12941 "--"
12942 ["Sum Column/Rectangle" org-table-sum
12943 (or (org-at-table-p) (org-region-active-p))]
12944 ["Which Column?" org-table-current-column (org-at-table-p)])
12945 ["Debug Formulas"
12946 org-table-toggle-formula-debugger
12947 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12948 ["Show Col/Row Numbers"
12949 org-table-toggle-coordinate-overlays
12950 :style toggle
12951 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12952 "--"
12953 ["Create" org-table-create (and (not (org-at-table-p))
12954 org-enable-table-editor)]
12955 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12956 ["Import from File" org-table-import (not (org-at-table-p))]
12957 ["Export to File" org-table-export (org-at-table-p)]
12958 "--"
12959 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12961 (easy-menu-define org-org-menu org-mode-map "Org menu"
12962 '("Org"
12963 ("Show/Hide"
12964 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12965 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12966 ["Sparse Tree..." org-sparse-tree t]
12967 ["Reveal Context" org-reveal t]
12968 ["Show All" show-all t]
12969 "--"
12970 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12971 "--"
12972 ["New Heading" org-insert-heading t]
12973 ("Navigate Headings"
12974 ["Up" outline-up-heading t]
12975 ["Next" outline-next-visible-heading t]
12976 ["Previous" outline-previous-visible-heading t]
12977 ["Next Same Level" outline-forward-same-level t]
12978 ["Previous Same Level" outline-backward-same-level t]
12979 "--"
12980 ["Jump" org-goto t])
12981 ("Edit Structure"
12982 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12983 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12984 "--"
12985 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12986 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12987 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12988 "--"
12989 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12990 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12991 ["Demote Heading" org-metaright (not (org-at-table-p))]
12992 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12993 "--"
12994 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12995 "--"
12996 ["Convert to odd levels" org-convert-to-odd-levels t]
12997 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12998 ("Editing"
12999 ["Emphasis..." org-emphasize t]
13000 ["Edit Source Example" org-edit-special t])
13001 ("Archive"
13002 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13003 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13004 ; :active t :keys "C-u C-c C-x C-a"]
13005 ["Sparse trees open ARCHIVE trees"
13006 (setq org-sparse-tree-open-archived-trees
13007 (not org-sparse-tree-open-archived-trees))
13008 :style toggle :selected org-sparse-tree-open-archived-trees]
13009 ["Cycling opens ARCHIVE trees"
13010 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13011 :style toggle :selected org-cycle-open-archived-trees]
13012 ["Agenda includes ARCHIVE trees"
13013 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
13014 :style toggle :selected (not org-agenda-skip-archived-trees)]
13015 "--"
13016 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13017 ; ["Check and Move Children" (org-archive-subtree '(4))
13018 ; :active t :keys "C-u C-c C-x C-s"]
13020 "--"
13021 ("TODO Lists"
13022 ["TODO/DONE/-" org-todo t]
13023 ("Select keyword"
13024 ["Next keyword" org-shiftright (org-on-heading-p)]
13025 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13026 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13027 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13028 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13029 ["Show TODO Tree" org-show-todo-tree t]
13030 ["Global TODO list" org-todo-list t]
13031 "--"
13032 ["Set Priority" org-priority t]
13033 ["Priority Up" org-shiftup t]
13034 ["Priority Down" org-shiftdown t])
13035 ("TAGS and Properties"
13036 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13037 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13038 "--"
13039 ["Set property" 'org-set-property t]
13040 ["Column view of properties" org-columns t]
13041 ["Insert Column View DBlock" org-insert-columns-dblock t])
13042 ("Dates and Scheduling"
13043 ["Timestamp" org-time-stamp t]
13044 ["Timestamp (inactive)" org-time-stamp-inactive t]
13045 ("Change Date"
13046 ["1 Day Later" org-shiftright t]
13047 ["1 Day Earlier" org-shiftleft t]
13048 ["1 ... Later" org-shiftup t]
13049 ["1 ... Earlier" org-shiftdown t])
13050 ["Compute Time Range" org-evaluate-time-range t]
13051 ["Schedule Item" org-schedule t]
13052 ["Deadline" org-deadline t]
13053 "--"
13054 ["Custom time format" org-toggle-time-stamp-overlays
13055 :style radio :selected org-display-custom-times]
13056 "--"
13057 ["Goto Calendar" org-goto-calendar t]
13058 ["Date from Calendar" org-date-from-calendar t])
13059 ("Logging work"
13060 ["Clock in" org-clock-in t]
13061 ["Clock out" org-clock-out t]
13062 ["Clock cancel" org-clock-cancel t]
13063 ["Goto running clock" org-clock-goto t]
13064 ["Display times" org-clock-display t]
13065 ["Create clock table" org-clock-report t]
13066 "--"
13067 ["Record DONE time"
13068 (progn (setq org-log-done (not org-log-done))
13069 (message "Switching to %s will %s record a timestamp"
13070 (car org-done-keywords)
13071 (if org-log-done "automatically" "not")))
13072 :style toggle :selected org-log-done])
13073 "--"
13074 ["Agenda Command..." org-agenda t]
13075 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13076 ("File List for Agenda")
13077 ("Special views current file"
13078 ["TODO Tree" org-show-todo-tree t]
13079 ["Check Deadlines" org-check-deadlines t]
13080 ["Timeline" org-timeline t]
13081 ["Tags Tree" org-tags-sparse-tree t])
13082 "--"
13083 ("Hyperlinks"
13084 ["Store Link (Global)" org-store-link t]
13085 ["Insert Link" org-insert-link t]
13086 ["Follow Link" org-open-at-point t]
13087 "--"
13088 ["Next link" org-next-link t]
13089 ["Previous link" org-previous-link t]
13090 "--"
13091 ["Descriptive Links"
13092 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13093 :style radio
13094 :selected (member '(org-link) buffer-invisibility-spec)]
13095 ["Literal Links"
13096 (progn
13097 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13098 :style radio
13099 :selected (not (member '(org-link) buffer-invisibility-spec))])
13100 "--"
13101 ["Export/Publish..." org-export t]
13102 ("LaTeX"
13103 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13104 :selected org-cdlatex-mode]
13105 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13106 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13107 ["Modify math symbol" org-cdlatex-math-modify
13108 (org-inside-LaTeX-fragment-p)]
13109 ["Export LaTeX fragments as images"
13110 (if (featurep 'org-exp)
13111 (setq org-export-with-LaTeX-fragments
13112 (not org-export-with-LaTeX-fragments))
13113 (require 'org-exp))
13114 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13115 org-export-with-LaTeX-fragments)])
13116 "--"
13117 ("Documentation"
13118 ["Show Version" org-version t]
13119 ["Info Documentation" org-info t])
13120 ("Customize"
13121 ["Browse Org Group" org-customize t]
13122 "--"
13123 ["Expand This Menu" org-create-customize-menu
13124 (fboundp 'customize-menu-create)])
13125 "--"
13126 ["Refresh setup" org-mode-restart t]
13129 (defun org-info (&optional node)
13130 "Read documentation for Org-mode in the info system.
13131 With optional NODE, go directly to that node."
13132 (interactive)
13133 (info (format "(org)%s" (or node ""))))
13135 (defun org-install-agenda-files-menu ()
13136 (let ((bl (buffer-list)))
13137 (save-excursion
13138 (while bl
13139 (set-buffer (pop bl))
13140 (if (org-mode-p) (setq bl nil)))
13141 (when (org-mode-p)
13142 (easy-menu-change
13143 '("Org") "File List for Agenda"
13144 (append
13145 (list
13146 ["Edit File List" (org-edit-agenda-file-list) t]
13147 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13148 ["Remove Current File from List" org-remove-file t]
13149 ["Cycle through agenda files" org-cycle-agenda-files t]
13150 ["Occur in all agenda files" org-occur-in-agenda-files t]
13151 "--")
13152 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13154 ;;;; Documentation
13156 (defun org-require-autoloaded-modules ()
13157 (interactive)
13158 (mapc 'require
13159 '(org-agenda org-archive org-clock org-colview
13160 org-exp org-export-latex org-publish
13161 org-remember org-table)))
13163 (defun org-customize ()
13164 "Call the customize function with org as argument."
13165 (interactive)
13166 (org-load-modules-maybe)
13167 (org-require-autoloaded-modules)
13168 (customize-browse 'org))
13170 (defun org-create-customize-menu ()
13171 "Create a full customization menu for Org-mode, insert it into the menu."
13172 (interactive)
13173 (org-load-modules-maybe)
13174 (org-require-autoloaded-modules)
13175 (if (fboundp 'customize-menu-create)
13176 (progn
13177 (easy-menu-change
13178 '("Org") "Customize"
13179 `(["Browse Org group" org-customize t]
13180 "--"
13181 ,(customize-menu-create 'org)
13182 ["Set" Custom-set t]
13183 ["Save" Custom-save t]
13184 ["Reset to Current" Custom-reset-current t]
13185 ["Reset to Saved" Custom-reset-saved t]
13186 ["Reset to Standard Settings" Custom-reset-standard t]))
13187 (message "\"Org\"-menu now contains full customization menu"))
13188 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13190 ;;;; Miscellaneous stuff
13192 ;;; Generally useful functions
13194 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13195 "Display the given MESSAGE as a warning."
13196 (if (fboundp 'display-warning)
13197 (display-warning 'org message
13198 (if (featurep 'xemacs)
13199 'warning
13200 :warning))
13201 (let ((buf (get-buffer-create "*Org warnings*")))
13202 (with-current-buffer buf
13203 (goto-char (point-max))
13204 (insert "Warning (Org): " message)
13205 (unless (bolp)
13206 (newline)))
13207 (display-buffer buf)
13208 (sit-for 0))))
13210 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13211 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13212 (if (and marker (marker-buffer marker)
13213 (buffer-live-p (marker-buffer marker)))
13214 (progn
13215 (switch-to-buffer (marker-buffer marker))
13216 (if (or (> marker (point-max)) (< marker (point-min)))
13217 (widen))
13218 (goto-char marker))
13219 (if bookmark
13220 (bookmark-jump bookmark)
13221 (error "Cannot find location"))))
13223 (defun org-quote-csv-field (s)
13224 "Quote field for inclusion in CSV material."
13225 (if (string-match "[\",]" s)
13226 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13229 (defun org-plist-delete (plist property)
13230 "Delete PROPERTY from PLIST.
13231 This is in contrast to merely setting it to 0."
13232 (let (p)
13233 (while plist
13234 (if (not (eq property (car plist)))
13235 (setq p (plist-put p (car plist) (nth 1 plist))))
13236 (setq plist (cddr plist)))
13239 (defun org-force-self-insert (N)
13240 "Needed to enforce self-insert under remapping."
13241 (interactive "p")
13242 (self-insert-command N))
13244 (defun org-string-width (s)
13245 "Compute width of string, ignoring invisible characters.
13246 This ignores character with invisibility property `org-link', and also
13247 characters with property `org-cwidth', because these will become invisible
13248 upon the next fontification round."
13249 (let (b l)
13250 (when (or (eq t buffer-invisibility-spec)
13251 (assq 'org-link buffer-invisibility-spec))
13252 (while (setq b (text-property-any 0 (length s)
13253 'invisible 'org-link s))
13254 (setq s (concat (substring s 0 b)
13255 (substring s (or (next-single-property-change
13256 b 'invisible s) (length s)))))))
13257 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13258 (setq s (concat (substring s 0 b)
13259 (substring s (or (next-single-property-change
13260 b 'org-cwidth s) (length s))))))
13261 (setq l (string-width s) b -1)
13262 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13263 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13266 (defun org-base-buffer (buffer)
13267 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13268 (if (not buffer)
13269 buffer
13270 (or (buffer-base-buffer buffer)
13271 buffer)))
13273 (defun org-trim (s)
13274 "Remove whitespace at beginning and end of string."
13275 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13276 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13279 (defun org-wrap (string &optional width lines)
13280 "Wrap string to either a number of lines, or a width in characters.
13281 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13282 that costs. If there is a word longer than WIDTH, the text is actually
13283 wrapped to the length of that word.
13284 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13285 many lines, whatever width that takes.
13286 The return value is a list of lines, without newlines at the end."
13287 (let* ((words (org-split-string string "[ \t\n]+"))
13288 (maxword (apply 'max (mapcar 'org-string-width words)))
13289 w ll)
13290 (cond (width
13291 (org-do-wrap words (max maxword width)))
13292 (lines
13293 (setq w maxword)
13294 (setq ll (org-do-wrap words maxword))
13295 (if (<= (length ll) lines)
13297 (setq ll words)
13298 (while (> (length ll) lines)
13299 (setq w (1+ w))
13300 (setq ll (org-do-wrap words w)))
13301 ll))
13302 (t (error "Cannot wrap this")))))
13304 (defun org-do-wrap (words width)
13305 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13306 (let (lines line)
13307 (while words
13308 (setq line (pop words))
13309 (while (and words (< (+ (length line) (length (car words))) width))
13310 (setq line (concat line " " (pop words))))
13311 (setq lines (push line lines)))
13312 (nreverse lines)))
13314 (defun org-split-string (string &optional separators)
13315 "Splits STRING into substrings at SEPARATORS.
13316 No empty strings are returned if there are matches at the beginning
13317 and end of string."
13318 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13319 (start 0)
13320 notfirst
13321 (list nil))
13322 (while (and (string-match rexp string
13323 (if (and notfirst
13324 (= start (match-beginning 0))
13325 (< start (length string)))
13326 (1+ start) start))
13327 (< (match-beginning 0) (length string)))
13328 (setq notfirst t)
13329 (or (eq (match-beginning 0) 0)
13330 (and (eq (match-beginning 0) (match-end 0))
13331 (eq (match-beginning 0) start))
13332 (setq list
13333 (cons (substring string start (match-beginning 0))
13334 list)))
13335 (setq start (match-end 0)))
13336 (or (eq start (length string))
13337 (setq list
13338 (cons (substring string start)
13339 list)))
13340 (nreverse list)))
13342 (defun org-context ()
13343 "Return a list of contexts of the current cursor position.
13344 If several contexts apply, all are returned.
13345 Each context entry is a list with a symbol naming the context, and
13346 two positions indicating start and end of the context. Possible
13347 contexts are:
13349 :headline anywhere in a headline
13350 :headline-stars on the leading stars in a headline
13351 :todo-keyword on a TODO keyword (including DONE) in a headline
13352 :tags on the TAGS in a headline
13353 :priority on the priority cookie in a headline
13354 :item on the first line of a plain list item
13355 :item-bullet on the bullet/number of a plain list item
13356 :checkbox on the checkbox in a plain list item
13357 :table in an org-mode table
13358 :table-special on a special filed in a table
13359 :table-table in a table.el table
13360 :link on a hyperlink
13361 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13362 :target on a <<target>>
13363 :radio-target on a <<<radio-target>>>
13364 :latex-fragment on a LaTeX fragment
13365 :latex-preview on a LaTeX fragment with overlayed preview image
13367 This function expects the position to be visible because it uses font-lock
13368 faces as a help to recognize the following contexts: :table-special, :link,
13369 and :keyword."
13370 (let* ((f (get-text-property (point) 'face))
13371 (faces (if (listp f) f (list f)))
13372 (p (point)) clist o)
13373 ;; First the large context
13374 (cond
13375 ((org-on-heading-p t)
13376 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13377 (when (progn
13378 (beginning-of-line 1)
13379 (looking-at org-todo-line-tags-regexp))
13380 (push (org-point-in-group p 1 :headline-stars) clist)
13381 (push (org-point-in-group p 2 :todo-keyword) clist)
13382 (push (org-point-in-group p 4 :tags) clist))
13383 (goto-char p)
13384 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13385 (if (looking-at "\\[#[A-Z0-9]\\]")
13386 (push (org-point-in-group p 0 :priority) clist)))
13388 ((org-at-item-p)
13389 (push (org-point-in-group p 2 :item-bullet) clist)
13390 (push (list :item (point-at-bol)
13391 (save-excursion (org-end-of-item) (point)))
13392 clist)
13393 (and (org-at-item-checkbox-p)
13394 (push (org-point-in-group p 0 :checkbox) clist)))
13396 ((org-at-table-p)
13397 (push (list :table (org-table-begin) (org-table-end)) clist)
13398 (if (memq 'org-formula faces)
13399 (push (list :table-special
13400 (previous-single-property-change p 'face)
13401 (next-single-property-change p 'face)) clist)))
13402 ((org-at-table-p 'any)
13403 (push (list :table-table) clist)))
13404 (goto-char p)
13406 ;; Now the small context
13407 (cond
13408 ((org-at-timestamp-p)
13409 (push (org-point-in-group p 0 :timestamp) clist))
13410 ((memq 'org-link faces)
13411 (push (list :link
13412 (previous-single-property-change p 'face)
13413 (next-single-property-change p 'face)) clist))
13414 ((memq 'org-special-keyword faces)
13415 (push (list :keyword
13416 (previous-single-property-change p 'face)
13417 (next-single-property-change p 'face)) clist))
13418 ((org-on-target-p)
13419 (push (org-point-in-group p 0 :target) clist)
13420 (goto-char (1- (match-beginning 0)))
13421 (if (looking-at org-radio-target-regexp)
13422 (push (org-point-in-group p 0 :radio-target) clist))
13423 (goto-char p))
13424 ((setq o (car (delq nil
13425 (mapcar
13426 (lambda (x)
13427 (if (memq x org-latex-fragment-image-overlays) x))
13428 (org-overlays-at (point))))))
13429 (push (list :latex-fragment
13430 (org-overlay-start o) (org-overlay-end o)) clist)
13431 (push (list :latex-preview
13432 (org-overlay-start o) (org-overlay-end o)) clist))
13433 ((org-inside-LaTeX-fragment-p)
13434 ;; FIXME: positions wrong.
13435 (push (list :latex-fragment (point) (point)) clist)))
13437 (setq clist (nreverse (delq nil clist)))
13438 clist))
13440 ;; FIXME: Compare with at-regexp-p Do we need both?
13441 (defun org-in-regexp (re &optional nlines visually)
13442 "Check if point is inside a match of regexp.
13443 Normally only the current line is checked, but you can include NLINES extra
13444 lines both before and after point into the search.
13445 If VISUALLY is set, require that the cursor is not after the match but
13446 really on, so that the block visually is on the match."
13447 (catch 'exit
13448 (let ((pos (point))
13449 (eol (point-at-eol (+ 1 (or nlines 0))))
13450 (inc (if visually 1 0)))
13451 (save-excursion
13452 (beginning-of-line (- 1 (or nlines 0)))
13453 (while (re-search-forward re eol t)
13454 (if (and (<= (match-beginning 0) pos)
13455 (>= (+ inc (match-end 0)) pos))
13456 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13458 (defun org-at-regexp-p (regexp)
13459 "Is point inside a match of REGEXP in the current line?"
13460 (catch 'exit
13461 (save-excursion
13462 (let ((pos (point)) (end (point-at-eol)))
13463 (beginning-of-line 1)
13464 (while (re-search-forward regexp end t)
13465 (if (and (<= (match-beginning 0) pos)
13466 (>= (match-end 0) pos))
13467 (throw 'exit t)))
13468 nil))))
13470 (defun org-occur-in-agenda-files (regexp &optional nlines)
13471 "Call `multi-occur' with buffers for all agenda files."
13472 (interactive "sOrg-files matching: \np")
13473 (let* ((files (org-agenda-files))
13474 (tnames (mapcar 'file-truename files))
13475 (extra org-agenda-text-search-extra-files)
13477 (when (eq (car extra) 'agenda-archives)
13478 (setq extra (cdr extra))
13479 (setq files (org-add-archive-files files)))
13480 (while (setq f (pop extra))
13481 (unless (member (file-truename f) tnames)
13482 (add-to-list 'files f 'append)
13483 (add-to-list 'tnames (file-truename f) 'append)))
13484 (multi-occur
13485 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13486 regexp)))
13488 (if (boundp 'occur-mode-find-occurrence-hook)
13489 ;; Emacs 23
13490 (add-hook 'occur-mode-find-occurrence-hook
13491 (lambda ()
13492 (when (org-mode-p)
13493 (org-reveal))))
13494 ;; Emacs 22
13495 (defadvice occur-mode-goto-occurrence
13496 (after org-occur-reveal activate)
13497 (and (org-mode-p) (org-reveal)))
13498 (defadvice occur-mode-goto-occurrence-other-window
13499 (after org-occur-reveal activate)
13500 (and (org-mode-p) (org-reveal)))
13501 (defadvice occur-mode-display-occurrence
13502 (after org-occur-reveal activate)
13503 (when (org-mode-p)
13504 (let ((pos (occur-mode-find-occurrence)))
13505 (with-current-buffer (marker-buffer pos)
13506 (save-excursion
13507 (goto-char pos)
13508 (org-reveal)))))))
13510 (defun org-uniquify (list)
13511 "Remove duplicate elements from LIST."
13512 (let (res)
13513 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13514 res))
13516 (defun org-delete-all (elts list)
13517 "Remove all elements in ELTS from LIST."
13518 (while elts
13519 (setq list (delete (pop elts) list)))
13520 list)
13522 (defun org-back-over-empty-lines ()
13523 "Move backwards over witespace, to the beginning of the first empty line.
13524 Returns the number of empty lines passed."
13525 (let ((pos (point)))
13526 (skip-chars-backward " \t\n\r")
13527 (beginning-of-line 2)
13528 (goto-char (min (point) pos))
13529 (count-lines (point) pos)))
13531 (defun org-skip-whitespace ()
13532 (skip-chars-forward " \t\n\r"))
13534 (defun org-point-in-group (point group &optional context)
13535 "Check if POINT is in match-group GROUP.
13536 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13537 match. If the match group does ot exist or point is not inside it,
13538 return nil."
13539 (and (match-beginning group)
13540 (>= point (match-beginning group))
13541 (<= point (match-end group))
13542 (if context
13543 (list context (match-beginning group) (match-end group))
13544 t)))
13546 (defun org-switch-to-buffer-other-window (&rest args)
13547 "Switch to buffer in a second window on the current frame.
13548 In particular, do not allow pop-up frames."
13549 (let (pop-up-frames special-display-buffer-names special-display-regexps
13550 special-display-function)
13551 (apply 'switch-to-buffer-other-window args)))
13553 (defun org-combine-plists (&rest plists)
13554 "Create a single property list from all plists in PLISTS.
13555 The process starts by copying the first list, and then setting properties
13556 from the other lists. Settings in the last list are the most significant
13557 ones and overrule settings in the other lists."
13558 (let ((rtn (copy-sequence (pop plists)))
13559 p v ls)
13560 (while plists
13561 (setq ls (pop plists))
13562 (while ls
13563 (setq p (pop ls) v (pop ls))
13564 (setq rtn (plist-put rtn p v))))
13565 rtn))
13567 (defun org-move-line-down (arg)
13568 "Move the current line down. With prefix argument, move it past ARG lines."
13569 (interactive "p")
13570 (let ((col (current-column))
13571 beg end pos)
13572 (beginning-of-line 1) (setq beg (point))
13573 (beginning-of-line 2) (setq end (point))
13574 (beginning-of-line (+ 1 arg))
13575 (setq pos (move-marker (make-marker) (point)))
13576 (insert (delete-and-extract-region beg end))
13577 (goto-char pos)
13578 (org-move-to-column col)))
13580 (defun org-move-line-up (arg)
13581 "Move the current line up. With prefix argument, move it past ARG lines."
13582 (interactive "p")
13583 (let ((col (current-column))
13584 beg end pos)
13585 (beginning-of-line 1) (setq beg (point))
13586 (beginning-of-line 2) (setq end (point))
13587 (beginning-of-line (- arg))
13588 (setq pos (move-marker (make-marker) (point)))
13589 (insert (delete-and-extract-region beg end))
13590 (goto-char pos)
13591 (org-move-to-column col)))
13593 (defun org-replace-escapes (string table)
13594 "Replace %-escapes in STRING with values in TABLE.
13595 TABLE is an association list with keys like \"%a\" and string values.
13596 The sequences in STRING may contain normal field width and padding information,
13597 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13598 so values can contain further %-escapes if they are define later in TABLE."
13599 (let ((case-fold-search nil)
13600 e re rpl)
13601 (while (setq e (pop table))
13602 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13603 (while (string-match re string)
13604 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13605 (cdr e)))
13606 (setq string (replace-match rpl t t string))))
13607 string))
13610 (defun org-sublist (list start end)
13611 "Return a section of LIST, from START to END.
13612 Counting starts at 1."
13613 (let (rtn (c start))
13614 (setq list (nthcdr (1- start) list))
13615 (while (and list (<= c end))
13616 (push (pop list) rtn)
13617 (setq c (1+ c)))
13618 (nreverse rtn)))
13620 (defun org-find-base-buffer-visiting (file)
13621 "Like `find-buffer-visiting' but alway return the base buffer and
13622 not an indirect buffer."
13623 (let ((buf (find-buffer-visiting file)))
13624 (if buf
13625 (or (buffer-base-buffer buf) buf)
13626 nil)))
13628 (defun org-image-file-name-regexp ()
13629 "Return regexp matching the file names of images."
13630 (if (fboundp 'image-file-name-regexp)
13631 (image-file-name-regexp)
13632 (let ((image-file-name-extensions
13633 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13634 "xbm" "xpm" "pbm" "pgm" "ppm")))
13635 (concat "\\."
13636 (regexp-opt (nconc (mapcar 'upcase
13637 image-file-name-extensions)
13638 image-file-name-extensions)
13640 "\\'"))))
13642 (defun org-file-image-p (file)
13643 "Return non-nil if FILE is an image."
13644 (save-match-data
13645 (string-match (org-image-file-name-regexp) file)))
13647 ;;; Paragraph filling stuff.
13648 ;; We want this to be just right, so use the full arsenal.
13650 (defun org-indent-line-function ()
13651 "Indent line like previous, but further if previous was headline or item."
13652 (interactive)
13653 (let* ((pos (point))
13654 (itemp (org-at-item-p))
13655 column bpos bcol tpos tcol bullet btype bullet-type)
13656 ;; Find the previous relevant line
13657 (beginning-of-line 1)
13658 (cond
13659 ((looking-at "#") (setq column 0))
13660 ((looking-at "\\*+ ") (setq column 0))
13662 (beginning-of-line 0)
13663 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13664 (beginning-of-line 0))
13665 (cond
13666 ((looking-at "\\*+[ \t]+")
13667 (if (not org-adapt-indentation)
13668 (setq column 0)
13669 (goto-char (match-end 0))
13670 (setq column (current-column))))
13671 ((org-in-item-p)
13672 (org-beginning-of-item)
13673 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13674 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13675 (setq bpos (match-beginning 1) tpos (match-end 0)
13676 bcol (progn (goto-char bpos) (current-column))
13677 tcol (progn (goto-char tpos) (current-column))
13678 bullet (match-string 1)
13679 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13680 (if (> tcol (+ bcol org-description-max-indent))
13681 (setq tcol (+ bcol 5)))
13682 (if (not itemp)
13683 (setq column tcol)
13684 (goto-char pos)
13685 (beginning-of-line 1)
13686 (if (looking-at "\\S-")
13687 (progn
13688 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13689 (setq bullet (match-string 1)
13690 btype (if (string-match "[0-9]" bullet) "n" bullet))
13691 (setq column (if (equal btype bullet-type) bcol tcol)))
13692 (setq column (org-get-indentation)))))
13693 (t (setq column (org-get-indentation))))))
13694 (goto-char pos)
13695 (if (<= (current-column) (current-indentation))
13696 (org-indent-line-to column)
13697 (save-excursion (org-indent-line-to column)))
13698 (setq column (current-column))
13699 (beginning-of-line 1)
13700 (if (looking-at
13701 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13702 (replace-match (concat "\\1" (format org-property-format
13703 (match-string 2) (match-string 3)))
13704 t nil))
13705 (org-move-to-column column)))
13707 (defun org-set-autofill-regexps ()
13708 (interactive)
13709 ;; In the paragraph separator we include headlines, because filling
13710 ;; text in a line directly attached to a headline would otherwise
13711 ;; fill the headline as well.
13712 (org-set-local 'comment-start-skip "^#+[ \t]*")
13713 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13714 ;; The paragraph starter includes hand-formatted lists.
13715 (org-set-local 'paragraph-start
13716 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13717 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13718 ;; But only if the user has not turned off tables or fixed-width regions
13719 (org-set-local
13720 'auto-fill-inhibit-regexp
13721 (concat "\\*+ \\|#\\+"
13722 "\\|[ \t]*" org-keyword-time-regexp
13723 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13724 (concat
13725 "\\|[ \t]*["
13726 (if org-enable-table-editor "|" "")
13727 (if org-enable-fixed-width-editor ":" "")
13728 "]"))))
13729 ;; We use our own fill-paragraph function, to make sure that tables
13730 ;; and fixed-width regions are not wrapped. That function will pass
13731 ;; through to `fill-paragraph' when appropriate.
13732 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13733 ; Adaptive filling: To get full control, first make sure that
13734 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13735 (org-set-local 'adaptive-fill-regexp "\000")
13736 (org-set-local 'adaptive-fill-function
13737 'org-adaptive-fill-function)
13738 (org-set-local
13739 'align-mode-rules-list
13740 '((org-in-buffer-settings
13741 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13742 (modes . '(org-mode))))))
13744 (defun org-fill-paragraph (&optional justify)
13745 "Re-align a table, pass through to fill-paragraph if no table."
13746 (let ((table-p (org-at-table-p))
13747 (table.el-p (org-at-table.el-p)))
13748 (cond ((and (equal (char-after (point-at-bol)) ?*)
13749 (save-excursion (goto-char (point-at-bol))
13750 (looking-at outline-regexp)))
13751 t) ; skip headlines
13752 (table.el-p t) ; skip table.el tables
13753 (table-p (org-table-align) t) ; align org-mode tables
13754 (t nil)))) ; call paragraph-fill
13756 ;; For reference, this is the default value of adaptive-fill-regexp
13757 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13759 (defun org-adaptive-fill-function ()
13760 "Return a fill prefix for org-mode files.
13761 In particular, this makes sure hanging paragraphs for hand-formatted lists
13762 work correctly."
13763 (cond ((looking-at "#[ \t]+")
13764 (match-string 0))
13765 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13766 (save-excursion
13767 (if (> (match-end 1) (+ (match-beginning 1)
13768 org-description-max-indent))
13769 (goto-char (+ (match-beginning 1) 5))
13770 (goto-char (match-end 0)))
13771 (make-string (current-column) ?\ )))
13772 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13773 (save-excursion
13774 (goto-char (match-end 0))
13775 (make-string (current-column) ?\ )))
13776 (t nil)))
13778 ;;; Other stuff.
13780 (defun org-toggle-fixed-width-section (arg)
13781 "Toggle the fixed-width export.
13782 If there is no active region, the QUOTE keyword at the current headline is
13783 inserted or removed. When present, it causes the text between this headline
13784 and the next to be exported as fixed-width text, and unmodified.
13785 If there is an active region, this command adds or removes a colon as the
13786 first character of this line. If the first character of a line is a colon,
13787 this line is also exported in fixed-width font."
13788 (interactive "P")
13789 (let* ((cc 0)
13790 (regionp (org-region-active-p))
13791 (beg (if regionp (region-beginning) (point)))
13792 (end (if regionp (region-end)))
13793 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13794 (case-fold-search nil)
13795 (re "[ \t]*\\(:\\)")
13796 off)
13797 (if regionp
13798 (save-excursion
13799 (goto-char beg)
13800 (setq cc (current-column))
13801 (beginning-of-line 1)
13802 (setq off (looking-at re))
13803 (while (> nlines 0)
13804 (setq nlines (1- nlines))
13805 (beginning-of-line 1)
13806 (cond
13807 (arg
13808 (org-move-to-column cc t)
13809 (insert ":\n")
13810 (forward-line -1))
13811 ((and off (looking-at re))
13812 (replace-match "" t t nil 1))
13813 ((not off) (org-move-to-column cc t) (insert ":")))
13814 (forward-line 1)))
13815 (save-excursion
13816 (org-back-to-heading)
13817 (if (looking-at (concat outline-regexp
13818 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13819 (replace-match "" t t nil 1)
13820 (if (looking-at outline-regexp)
13821 (progn
13822 (goto-char (match-end 0))
13823 (insert org-quote-string " "))))))))
13825 ;;;; Functions extending outline functionality
13827 (defun org-beginning-of-line (&optional arg)
13828 "Go to the beginning of the current line. If that is invisible, continue
13829 to a visible line beginning. This makes the function of C-a more intuitive.
13830 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13831 first attempt, and only move to after the tags when the cursor is already
13832 beyond the end of the headline."
13833 (interactive "P")
13834 (let ((pos (point)))
13835 (beginning-of-line 1)
13836 (if (bobp)
13838 (backward-char 1)
13839 (if (org-invisible-p)
13840 (while (and (not (bobp)) (org-invisible-p))
13841 (backward-char 1)
13842 (beginning-of-line 1))
13843 (forward-char 1)))
13844 (when org-special-ctrl-a/e
13845 (cond
13846 ((and (looking-at org-todo-line-regexp)
13847 (= (char-after (match-end 1)) ?\ ))
13848 (goto-char
13849 (if (eq org-special-ctrl-a/e t)
13850 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13851 ((= pos (point)) (match-beginning 3))
13852 (t (point)))
13853 (cond ((> pos (point)) (point))
13854 ((not (eq last-command this-command)) (point))
13855 (t (match-beginning 3))))))
13856 ((org-at-item-p)
13857 (goto-char
13858 (if (eq org-special-ctrl-a/e t)
13859 (cond ((> pos (match-end 4)) (match-end 4))
13860 ((= pos (point)) (match-end 4))
13861 (t (point)))
13862 (cond ((> pos (point)) (point))
13863 ((not (eq last-command this-command)) (point))
13864 (t (match-end 4))))))))))
13866 (defun org-end-of-line (&optional arg)
13867 "Go to the end of the line.
13868 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13869 first attempt, and only move to after the tags when the cursor is already
13870 beyond the end of the headline."
13871 (interactive "P")
13872 (if (or (not org-special-ctrl-a/e)
13873 (not (org-on-heading-p)))
13874 (end-of-line arg)
13875 (let ((pos (point)))
13876 (beginning-of-line 1)
13877 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13878 (if (eq org-special-ctrl-a/e t)
13879 (if (or (< pos (match-beginning 1))
13880 (= pos (match-end 0)))
13881 (goto-char (match-beginning 1))
13882 (goto-char (match-end 0)))
13883 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13884 (goto-char (match-end 0))
13885 (goto-char (match-beginning 1))))
13886 (end-of-line arg)))))
13888 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13889 (define-key org-mode-map "\C-e" 'org-end-of-line)
13891 (defun org-kill-line (&optional arg)
13892 "Kill line, to tags or end of line."
13893 (interactive "P")
13894 (cond
13895 ((or (not org-special-ctrl-k)
13896 (bolp)
13897 (not (org-on-heading-p)))
13898 (call-interactively 'kill-line))
13899 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13900 (kill-region (point) (match-beginning 1))
13901 (org-set-tags nil t))
13902 (t (kill-region (point) (point-at-eol)))))
13904 (define-key org-mode-map "\C-k" 'org-kill-line)
13906 (defun org-invisible-p ()
13907 "Check if point is at a character currently not visible."
13908 ;; Early versions of noutline don't have `outline-invisible-p'.
13909 (if (fboundp 'outline-invisible-p)
13910 (outline-invisible-p)
13911 (get-char-property (point) 'invisible)))
13913 (defun org-invisible-p2 ()
13914 "Check if point is at a character currently not visible."
13915 (save-excursion
13916 (if (and (eolp) (not (bobp))) (backward-char 1))
13917 ;; Early versions of noutline don't have `outline-invisible-p'.
13918 (if (fboundp 'outline-invisible-p)
13919 (outline-invisible-p)
13920 (get-char-property (point) 'invisible))))
13922 (defalias 'org-back-to-heading 'outline-back-to-heading)
13923 (defalias 'org-on-heading-p 'outline-on-heading-p)
13924 (defalias 'org-at-heading-p 'outline-on-heading-p)
13925 (defun org-at-heading-or-item-p ()
13926 (or (org-on-heading-p) (org-at-item-p)))
13928 (defun org-on-target-p ()
13929 (or (org-in-regexp org-radio-target-regexp)
13930 (org-in-regexp org-target-regexp)))
13932 (defun org-up-heading-all (arg)
13933 "Move to the heading line of which the present line is a subheading.
13934 This function considers both visible and invisible heading lines.
13935 With argument, move up ARG levels."
13936 (if (fboundp 'outline-up-heading-all)
13937 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13938 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13940 (defun org-up-heading-safe ()
13941 "Move to the heading line of which the present line is a subheading.
13942 This version will not throw an error. It will return the level of the
13943 headline found, or nil if no higher level is found."
13944 (let ((pos (point)) start-level level
13945 (re (concat "^" outline-regexp)))
13946 (catch 'exit
13947 (outline-back-to-heading t)
13948 (setq start-level (funcall outline-level))
13949 (if (equal start-level 1) (throw 'exit nil))
13950 (while (re-search-backward re nil t)
13951 (setq level (funcall outline-level))
13952 (if (< level start-level) (throw 'exit level)))
13953 nil)))
13955 (defun org-first-sibling-p ()
13956 "Is this heading the first child of its parents?"
13957 (interactive)
13958 (let ((re (concat "^" outline-regexp))
13959 level l)
13960 (unless (org-at-heading-p t)
13961 (error "Not at a heading"))
13962 (setq level (funcall outline-level))
13963 (save-excursion
13964 (if (not (re-search-backward re nil t))
13966 (setq l (funcall outline-level))
13967 (< l level)))))
13969 (defun org-goto-sibling (&optional previous)
13970 "Goto the next sibling, even if it is invisible.
13971 When PREVIOUS is set, go to the previous sibling instead. Returns t
13972 when a sibling was found. When none is found, return nil and don't
13973 move point."
13974 (let ((fun (if previous 're-search-backward 're-search-forward))
13975 (pos (point))
13976 (re (concat "^" outline-regexp))
13977 level l)
13978 (when (condition-case nil (org-back-to-heading t) (error nil))
13979 (setq level (funcall outline-level))
13980 (catch 'exit
13981 (or previous (forward-char 1))
13982 (while (funcall fun re nil t)
13983 (setq l (funcall outline-level))
13984 (when (< l level) (goto-char pos) (throw 'exit nil))
13985 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13986 (goto-char pos)
13987 nil))))
13989 (defun org-show-siblings ()
13990 "Show all siblings of the current headline."
13991 (save-excursion
13992 (while (org-goto-sibling) (org-flag-heading nil)))
13993 (save-excursion
13994 (while (org-goto-sibling 'previous)
13995 (org-flag-heading nil))))
13997 (defun org-show-hidden-entry ()
13998 "Show an entry where even the heading is hidden."
13999 (save-excursion
14000 (org-show-entry)))
14002 (defun org-flag-heading (flag &optional entry)
14003 "Flag the current heading. FLAG non-nil means make invisible.
14004 When ENTRY is non-nil, show the entire entry."
14005 (save-excursion
14006 (org-back-to-heading t)
14007 ;; Check if we should show the entire entry
14008 (if entry
14009 (progn
14010 (org-show-entry)
14011 (save-excursion
14012 (and (outline-next-heading)
14013 (org-flag-heading nil))))
14014 (outline-flag-region (max (point-min) (1- (point)))
14015 (save-excursion (outline-end-of-heading) (point))
14016 flag))))
14018 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14019 ;; This is an exact copy of the original function, but it uses
14020 ;; `org-back-to-heading', to make it work also in invisible
14021 ;; trees. And is uses an invisible-OK argument.
14022 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14023 (org-back-to-heading invisible-OK)
14024 (let ((first t)
14025 (level (funcall outline-level)))
14026 (while (and (not (eobp))
14027 (or first (> (funcall outline-level) level)))
14028 (setq first nil)
14029 (outline-next-heading))
14030 (unless to-heading
14031 (if (memq (preceding-char) '(?\n ?\^M))
14032 (progn
14033 ;; Go to end of line before heading
14034 (forward-char -1)
14035 (if (memq (preceding-char) '(?\n ?\^M))
14036 ;; leave blank line before heading
14037 (forward-char -1))))))
14038 (point))
14040 (defun org-show-subtree ()
14041 "Show everything after this heading at deeper levels."
14042 (outline-flag-region
14043 (point)
14044 (save-excursion
14045 (outline-end-of-subtree) (outline-next-heading) (point))
14046 nil))
14048 (defun org-show-entry ()
14049 "Show the body directly following this heading.
14050 Show the heading too, if it is currently invisible."
14051 (interactive)
14052 (save-excursion
14053 (condition-case nil
14054 (progn
14055 (org-back-to-heading t)
14056 (outline-flag-region
14057 (max (point-min) (1- (point)))
14058 (save-excursion
14059 (re-search-forward
14060 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14061 (or (match-beginning 1) (point-max)))
14062 nil))
14063 (error nil))))
14065 (defun org-make-options-regexp (kwds)
14066 "Make a regular expression for keyword lines."
14067 (concat
14069 "#?[ \t]*\\+\\("
14070 (mapconcat 'regexp-quote kwds "\\|")
14071 "\\):[ \t]*"
14072 "\\(.+\\)"))
14074 ;; Make isearch reveal the necessary context
14075 (defun org-isearch-end ()
14076 "Reveal context after isearch exits."
14077 (when isearch-success ; only if search was successful
14078 (if (featurep 'xemacs)
14079 ;; Under XEmacs, the hook is run in the correct place,
14080 ;; we directly show the context.
14081 (org-show-context 'isearch)
14082 ;; In Emacs the hook runs *before* restoring the overlays.
14083 ;; So we have to use a one-time post-command-hook to do this.
14084 ;; (Emacs 22 has a special variable, see function `org-mode')
14085 (unless (and (boundp 'isearch-mode-end-hook-quit)
14086 isearch-mode-end-hook-quit)
14087 ;; Only when the isearch was not quitted.
14088 (org-add-hook 'post-command-hook 'org-isearch-post-command
14089 'append 'local)))))
14091 (defun org-isearch-post-command ()
14092 "Remove self from hook, and show context."
14093 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14094 (org-show-context 'isearch))
14097 ;;;; Integration with and fixes for other packages
14099 ;;; Imenu support
14101 (defvar org-imenu-markers nil
14102 "All markers currently used by Imenu.")
14103 (make-variable-buffer-local 'org-imenu-markers)
14105 (defun org-imenu-new-marker (&optional pos)
14106 "Return a new marker for use by Imenu, and remember the marker."
14107 (let ((m (make-marker)))
14108 (move-marker m (or pos (point)))
14109 (push m org-imenu-markers)
14112 (defun org-imenu-get-tree ()
14113 "Produce the index for Imenu."
14114 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14115 (setq org-imenu-markers nil)
14116 (let* ((n org-imenu-depth)
14117 (re (concat "^" outline-regexp))
14118 (subs (make-vector (1+ n) nil))
14119 (last-level 0)
14120 m tree level head)
14121 (save-excursion
14122 (save-restriction
14123 (widen)
14124 (goto-char (point-max))
14125 (while (re-search-backward re nil t)
14126 (setq level (org-reduced-level (funcall outline-level)))
14127 (when (<= level n)
14128 (looking-at org-complex-heading-regexp)
14129 (setq head (org-match-string-no-properties 4)
14130 m (org-imenu-new-marker))
14131 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14132 (if (>= level last-level)
14133 (push (cons head m) (aref subs level))
14134 (push (cons head (aref subs (1+ level))) (aref subs level))
14135 (loop for i from (1+ level) to n do (aset subs i nil)))
14136 (setq last-level level)))))
14137 (aref subs 1)))
14139 (eval-after-load "imenu"
14140 '(progn
14141 (add-hook 'imenu-after-jump-hook
14142 (lambda () (org-show-context 'org-goto)))))
14144 ;; Speedbar support
14146 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14147 "Overlay marking the agenda restriction line in speedbar.")
14148 (org-overlay-put org-speedbar-restriction-lock-overlay
14149 'face 'org-agenda-restriction-lock)
14150 (org-overlay-put org-speedbar-restriction-lock-overlay
14151 'help-echo "Agendas are currently limited to this item.")
14152 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14154 (defun org-speedbar-set-agenda-restriction ()
14155 "Restrict future agenda commands to the location at point in speedbar.
14156 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14157 (interactive)
14158 (require 'org-agenda)
14159 (let (p m tp np dir txt w)
14160 (cond
14161 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14162 'org-imenu t))
14163 (setq m (get-text-property p 'org-imenu-marker))
14164 (save-excursion
14165 (save-restriction
14166 (set-buffer (marker-buffer m))
14167 (goto-char m)
14168 (org-agenda-set-restriction-lock 'subtree))))
14169 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14170 'speedbar-function 'speedbar-find-file))
14171 (setq tp (previous-single-property-change
14172 (1+ p) 'speedbar-function)
14173 np (next-single-property-change
14174 tp 'speedbar-function)
14175 dir (speedbar-line-directory)
14176 txt (buffer-substring-no-properties (or tp (point-min))
14177 (or np (point-max))))
14178 (save-excursion
14179 (save-restriction
14180 (set-buffer (find-file-noselect
14181 (let ((default-directory dir))
14182 (expand-file-name txt))))
14183 (unless (org-mode-p)
14184 (error "Cannot restrict to non-Org-mode file"))
14185 (org-agenda-set-restriction-lock 'file))))
14186 (t (error "Don't know how to restrict Org-mode's agenda")))
14187 (org-move-overlay org-speedbar-restriction-lock-overlay
14188 (point-at-bol) (point-at-eol))
14189 (setq current-prefix-arg nil)
14190 (org-agenda-maybe-redo)))
14192 (eval-after-load "speedbar"
14193 '(progn
14194 (speedbar-add-supported-extension ".org")
14195 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14196 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14197 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14198 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14199 (add-hook 'speedbar-visiting-tag-hook
14200 (lambda () (org-show-context 'org-goto)))))
14203 ;;; Fixes and Hacks for problems with other packages
14205 ;; Make flyspell not check words in links, to not mess up our keymap
14206 (defun org-mode-flyspell-verify ()
14207 "Don't let flyspell put overlays at active buttons."
14208 (not (get-text-property (point) 'keymap)))
14210 ;; Make `bookmark-jump' show the jump location if it was hidden.
14211 (eval-after-load "bookmark"
14212 '(if (boundp 'bookmark-after-jump-hook)
14213 ;; We can use the hook
14214 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14215 ;; Hook not available, use advice
14216 (defadvice bookmark-jump (after org-make-visible activate)
14217 "Make the position visible."
14218 (org-bookmark-jump-unhide))))
14220 (defun org-bookmark-jump-unhide ()
14221 "Unhide the current position, to show the bookmark location."
14222 (and (org-mode-p)
14223 (or (org-invisible-p)
14224 (save-excursion (goto-char (max (point-min) (1- (point))))
14225 (org-invisible-p)))
14226 (org-show-context 'bookmark-jump)))
14228 ;; Make session.el ignore our circular variable
14229 (eval-after-load "session"
14230 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14232 ;;;; Experimental code
14234 (defun org-closed-in-range ()
14235 "Sparse tree of items closed in a certain time range.
14236 Still experimental, may disappear in the future."
14237 (interactive)
14238 ;; Get the time interval from the user.
14239 (let* ((time1 (time-to-seconds
14240 (org-read-date nil 'to-time nil "Starting date: ")))
14241 (time2 (time-to-seconds
14242 (org-read-date nil 'to-time nil "End date:")))
14243 ;; callback function
14244 (callback (lambda ()
14245 (let ((time
14246 (time-to-seconds
14247 (apply 'encode-time
14248 (org-parse-time-string
14249 (match-string 1))))))
14250 ;; check if time in interval
14251 (and (>= time time1) (<= time time2))))))
14252 ;; make tree, check each match with the callback
14253 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14256 ;;;; Finish up
14258 (provide 'org)
14260 (run-hooks 'org-load-hook)
14262 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14264 ;;; org.el ends here