Minor documentation fixes.
[org-mode.git] / lisp / org.el
blob02a947703e0244f7d8aca22dde0a25ea22e56475
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.06b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.06b"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " id: Global id's for identifying entries" org-id)
165 (const :tag " info: Links to Info nodes" org-info)
166 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
167 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
168 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
169 (const :tag " mew Links to Mew folders/messages" org-mew)
170 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
171 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
172 (const :tag " vm: Links to VM folders/messages" org-vm)
173 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
174 (const :tag " mouse: Additional mouse support" org-mouse)
176 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
177 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
178 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
179 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
180 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
181 (const :tag "C eval: Include command output as text" org-eval)
182 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
183 (const :tag "C id: Global id's for identifying entries" org-id)
184 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
185 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
186 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
187 (const :tag "C mtags: Support for muse-like tags" org-mtags)
188 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
189 (const :tag "C registry: A registry for Org links" org-registry)
190 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
191 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
192 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
193 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
194 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
197 (defgroup org-startup nil
198 "Options concerning startup of Org-mode."
199 :tag "Org Startup"
200 :group 'org)
202 (defcustom org-startup-folded t
203 "Non-nil means, entering Org-mode will switch to OVERVIEW.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
207 #+STARTUP: fold
208 #+STARTUP: nofold
209 #+STARTUP: content"
210 :group 'org-startup
211 :type '(choice
212 (const :tag "nofold: show all" nil)
213 (const :tag "fold: overview" t)
214 (const :tag "content: all headlines" content)))
216 (defcustom org-startup-truncated t
217 "Non-nil means, entering Org-mode will set `truncate-lines'.
218 This is useful since some lines containing links can be very long and
219 uninteresting. Also tables look terrible when wrapped."
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-startup-align-all-tables nil
224 "Non-nil means, align all tables when visiting a file.
225 This is useful when the column width in tables is forced with <N> cookies
226 in table fields. Such tables will look correct only after the first re-align.
227 This can also be configured on a per-file basis by adding one of
228 the following lines anywhere in the buffer:
229 #+STARTUP: align
230 #+STARTUP: noalign"
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-insert-mode-line-in-empty-file nil
235 "Non-nil means insert the first line setting Org-mode in empty files.
236 When the function `org-mode' is called interactively in an empty file, this
237 normally means that the file name does not automatically trigger Org-mode.
238 To ensure that the file will always be in Org-mode in the future, a
239 line enforcing Org-mode will be inserted into the buffer, if this option
240 has been set."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-replace-disputed-keys nil
245 "Non-nil means use alternative key bindings for some keys.
246 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
247 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
248 If you want to use Org-mode together with one of these other modes,
249 or more generally if you would like to move some Org-mode commands to
250 other keys, set this variable and configure the keys with the variable
251 `org-disputed-keys'.
253 This option is only relevant at load-time of Org-mode, and must be set
254 *before* org.el is loaded. Changing it requires a restart of Emacs to
255 become effective."
256 :group 'org-startup
257 :type 'boolean)
259 (if (fboundp 'defvaralias)
260 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
262 (defcustom org-disputed-keys
263 '(([(shift up)] . [(meta p)])
264 ([(shift down)] . [(meta n)])
265 ([(shift left)] . [(meta -)])
266 ([(shift right)] . [(meta +)])
267 ([(control shift right)] . [(meta shift +)])
268 ([(control shift left)] . [(meta shift -)]))
269 "Keys for which Org-mode and other modes compete.
270 This is an alist, cars are the default keys, second element specifies
271 the alternative to use when `org-replace-disputed-keys' is t.
273 Keys can be specified in any syntax supported by `define-key'.
274 The value of this option takes effect only at Org-mode's startup,
275 therefore you'll have to restart Emacs to apply it after changing."
276 :group 'org-startup
277 :type 'alist)
279 (defun org-key (key)
280 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
281 Or return the original if not disputed."
282 (if org-replace-disputed-keys
283 (let* ((nkey (key-description key))
284 (x (org-find-if (lambda (x)
285 (equal (key-description (car x)) nkey))
286 org-disputed-keys)))
287 (if x (cdr x) key))
288 key))
290 (defun org-find-if (predicate seq)
291 (catch 'exit
292 (while seq
293 (if (funcall predicate (car seq))
294 (throw 'exit (car seq))
295 (pop seq)))))
297 (defun org-defkey (keymap key def)
298 "Define a key, possibly translated, as returned by `org-key'."
299 (define-key keymap (org-key key) def))
301 (defcustom org-ellipsis nil
302 "The ellipsis to use in the Org-mode outline.
303 When nil, just use the standard three dots. When a string, use that instead,
304 When a face, use the standart 3 dots, but with the specified face.
305 The change affects only Org-mode (which will then use its own display table).
306 Changing this requires executing `M-x org-mode' in a buffer to become
307 effective."
308 :group 'org-startup
309 :type '(choice (const :tag "Default" nil)
310 (face :tag "Face" :value org-warning)
311 (string :tag "String" :value "...#")))
313 (defvar org-display-table nil
314 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
316 (defgroup org-keywords nil
317 "Keywords in Org-mode."
318 :tag "Org Keywords"
319 :group 'org)
321 (defcustom org-deadline-string "DEADLINE:"
322 "String to mark deadline entries.
323 A deadline is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-deadline].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-scheduled-string "SCHEDULED:"
331 "String to mark scheduled TODO entries.
332 A schedule is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-schedule].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-closed-string "CLOSED:"
340 "String used as the prefix for timestamps logging closing a TODO entry."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-clock-string "CLOCK:"
345 "String used as prefix for timestamps clocking work hours on an item."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-comment-string "COMMENT"
350 "Entries starting with this keyword will never be exported.
351 An entry can be toggled between COMMENT and normal with
352 \\[org-toggle-comment].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-quote-string "QUOTE"
358 "Entries starting with this keyword will be exported in fixed-width font.
359 Quoting applies only to the text in the entry following the headline, and does
360 not extend beyond the next headline, even if that is lower level.
361 An entry can be toggled between QUOTE and normal with
362 \\[org-toggle-fixed-width-section]."
363 :group 'org-keywords
364 :type 'string)
366 (defconst org-repeat-re
367 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
368 "Regular expression for specifying repeated events.
369 After a match, group 1 contains the repeat expression.")
371 (defgroup org-structure nil
372 "Options concerning the general structure of Org-mode files."
373 :tag "Org Structure"
374 :group 'org)
376 (defgroup org-reveal-location nil
377 "Options about how to make context of a location visible."
378 :tag "Org Reveal Location"
379 :group 'org-structure)
381 (defconst org-context-choice
382 '(choice
383 (const :tag "Always" t)
384 (const :tag "Never" nil)
385 (repeat :greedy t :tag "Individual contexts"
386 (cons
387 (choice :tag "Context"
388 (const agenda)
389 (const org-goto)
390 (const occur-tree)
391 (const tags-tree)
392 (const link-search)
393 (const mark-goto)
394 (const bookmark-jump)
395 (const isearch)
396 (const default))
397 (boolean))))
398 "Contexts for the reveal options.")
400 (defcustom org-show-hierarchy-above '((default . t))
401 "Non-nil means, show full hierarchy when revealing a location.
402 Org-mode often shows locations in an org-mode file which might have
403 been invisible before. When this is set, the hierarchy of headings
404 above the exposed location is shown.
405 Turning this off for example for sparse trees makes them very compact.
406 Instead of t, this can also be an alist specifying this option for different
407 contexts. Valid contexts are
408 agenda when exposing an entry from the agenda
409 org-goto when using the command `org-goto' on key C-c C-j
410 occur-tree when using the command `org-occur' on key C-c /
411 tags-tree when constructing a sparse tree based on tags matches
412 link-search when exposing search matches associated with a link
413 mark-goto when exposing the jump goal of a mark
414 bookmark-jump when exposing a bookmark location
415 isearch when exiting from an incremental search
416 default default for all contexts not set explicitly"
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defcustom org-show-following-heading '((default . nil))
421 "Non-nil means, show following heading when revealing a location.
422 Org-mode often shows locations in an org-mode file which might have
423 been invisible before. When this is set, the heading following the
424 match is shown.
425 Turning this off for example for sparse trees makes them very compact,
426 but makes it harder to edit the location of the match. In such a case,
427 use the command \\[org-reveal] to show more context.
428 Instead of t, this can also be an alist specifying this option for different
429 contexts. See `org-show-hierarchy-above' for valid contexts."
430 :group 'org-reveal-location
431 :type org-context-choice)
433 (defcustom org-show-siblings '((default . nil) (isearch t))
434 "Non-nil means, show all sibling heading when revealing a location.
435 Org-mode often shows locations in an org-mode file which might have
436 been invisible before. When this is set, the sibling of the current entry
437 heading are all made visible. If `org-show-hierarchy-above' is t,
438 the same happens on each level of the hierarchy above the current entry.
440 By default this is on for the isearch context, off for all other contexts.
441 Turning this off for example for sparse trees makes them very compact,
442 but makes it harder to edit the location of the match. In such a case,
443 use the command \\[org-reveal] to show more context.
444 Instead of t, this can also be an alist specifying this option for different
445 contexts. See `org-show-hierarchy-above' for valid contexts."
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-entry-below '((default . nil))
450 "Non-nil means, show the entry below a headline when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the text below the headline that is
453 exposed is also shown.
455 By default this is off for all contexts.
456 Instead of t, this can also be an alist specifying this option for different
457 contexts. See `org-show-hierarchy-above' for valid contexts."
458 :group 'org-reveal-location
459 :type org-context-choice)
461 (defcustom org-indirect-buffer-display 'other-window
462 "How should indirect tree buffers be displayed?
463 This applies to indirect buffers created with the commands
464 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
465 Valid values are:
466 current-window Display in the current window
467 other-window Just display in another window.
468 dedicated-frame Create one new frame, and re-use it each time.
469 new-frame Make a new frame each time. Note that in this case
470 previously-made indirect buffers are kept, and you need to
471 kill these buffers yourself."
472 :group 'org-structure
473 :group 'org-agenda-windows
474 :type '(choice
475 (const :tag "In current window" current-window)
476 (const :tag "In current frame, other window" other-window)
477 (const :tag "Each time a new frame" new-frame)
478 (const :tag "One dedicated frame" dedicated-frame)))
480 (defgroup org-cycle nil
481 "Options concerning visibility cycling in Org-mode."
482 :tag "Org Cycle"
483 :group 'org-structure)
485 (defcustom org-drawers '("PROPERTIES" "CLOCK")
486 "Names of drawers. Drawers are not opened by cycling on the headline above.
487 Drawers only open with a TAB on the drawer line itself. A drawer looks like
488 this:
489 :DRAWERNAME:
490 .....
491 :END:
492 The drawer \"PROPERTIES\" is special for capturing properties through
493 the property API.
495 Drawers can be defined on the per-file basis with a line like:
497 #+DRAWERS: HIDDEN STATE PROPERTIES"
498 :group 'org-structure
499 :type '(repeat (string :tag "Drawer Name")))
501 (defcustom org-cycle-global-at-bob nil
502 "Cycle globally if cursor is at beginning of buffer and not at a headline.
503 This makes it possible to do global cycling without having to use S-TAB or
504 C-u TAB. For this special case to work, the first line of the buffer
505 must not be a headline - it may be empty ot some other text. When used in
506 this way, `org-cycle-hook' is disables temporarily, to make sure the
507 cursor stays at the beginning of the buffer.
508 When this option is nil, don't do anything special at the beginning
509 of the buffer."
510 :group 'org-cycle
511 :type 'boolean)
513 (defcustom org-cycle-emulate-tab t
514 "Where should `org-cycle' emulate TAB.
515 nil Never
516 white Only in completely white lines
517 whitestart Only at the beginning of lines, before the first non-white char
518 t Everywhere except in headlines
519 exc-hl-bol Everywhere except at the start of a headline
520 If TAB is used in a place where it does not emulate TAB, the current subtree
521 visibility is cycled."
522 :group 'org-cycle
523 :type '(choice (const :tag "Never" nil)
524 (const :tag "Only in completely white lines" white)
525 (const :tag "Before first char in a line" whitestart)
526 (const :tag "Everywhere except in headlines" t)
527 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
530 (defcustom org-cycle-separator-lines 2
531 "Number of empty lines needed to keep an empty line between collapsed trees.
532 If you leave an empty line between the end of a subtree and the following
533 headline, this empty line is hidden when the subtree is folded.
534 Org-mode will leave (exactly) one empty line visible if the number of
535 empty lines is equal or larger to the number given in this variable.
536 So the default 2 means, at least 2 empty lines after the end of a subtree
537 are needed to produce free space between a collapsed subtree and the
538 following headline.
540 Special case: when 0, never leave empty lines in collapsed view."
541 :group 'org-cycle
542 :type 'integer)
543 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
545 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
546 org-cycle-hide-drawers
547 org-cycle-show-empty-lines
548 org-optimize-window-after-visibility-change)
549 "Hook that is run after `org-cycle' has changed the buffer visibility.
550 The function(s) in this hook must accept a single argument which indicates
551 the new state that was set by the most recent `org-cycle' command. The
552 argument is a symbol. After a global state change, it can have the values
553 `overview', `content', or `all'. After a local state change, it can have
554 the values `folded', `children', or `subtree'."
555 :group 'org-cycle
556 :type 'hook)
558 (defgroup org-edit-structure nil
559 "Options concerning structure editing in Org-mode."
560 :tag "Org Edit Structure"
561 :group 'org-structure)
563 (defcustom org-odd-levels-only nil
564 "Non-nil means, skip even levels and only use odd levels for the outline.
565 This has the effect that two stars are being added/taken away in
566 promotion/demotion commands. It also influences how levels are
567 handled by the exporters.
568 Changing it requires restart of `font-lock-mode' to become effective
569 for fontification also in regions already fontified.
570 You may also set this on a per-file basis by adding one of the following
571 lines to the buffer:
573 #+STARTUP: odd
574 #+STARTUP: oddeven"
575 :group 'org-edit-structure
576 :group 'org-font-lock
577 :type 'boolean)
579 (defcustom org-adapt-indentation t
580 "Non-nil means, adapt indentation when promoting and demoting.
581 When this is set and the *entire* text in an entry is indented, the
582 indentation is increased by one space in a demotion command, and
583 decreased by one in a promotion command. If any line in the entry
584 body starts at column 0, indentation is not changed at all."
585 :group 'org-edit-structure
586 :type 'boolean)
588 (defcustom org-special-ctrl-a/e nil
589 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
590 When t, `C-a' will bring back the cursor to the beginning of the
591 headline text, i.e. after the stars and after a possible TODO keyword.
592 In an item, this will be the position after the bullet.
593 When the cursor is already at that position, another `C-a' will bring
594 it to the beginning of the line.
595 `C-e' will jump to the end of the headline, ignoring the presence of tags
596 in the headline. A second `C-e' will then jump to the true end of the
597 line, after any tags.
598 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
599 and only a directly following, identical keypress will bring the cursor
600 to the special positions."
601 :group 'org-edit-structure
602 :type '(choice
603 (const :tag "off" nil)
604 (const :tag "after bullet first" t)
605 (const :tag "border first" reversed)))
607 (if (fboundp 'defvaralias)
608 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
610 (defcustom org-special-ctrl-k nil
611 "Non-nil means `C-k' will behave specially in headlines.
612 When nil, `C-k' will call the default `kill-line' command.
613 When t, the following will happen while the cursor is in the headline:
615 - When the cursor is at the beginning of a headline, kill the entire
616 line and possible the folded subtree below the line.
617 - When in the middle of the headline text, kill the headline up to the tags.
618 - When after the headline text, kill the tags."
619 :group 'org-edit-structure
620 :type 'boolean)
622 (defcustom org-M-RET-may-split-line '((default . t))
623 "Non-nil means, M-RET will split the line at the cursor position.
624 When nil, it will go to the end of the line before making a
625 new line.
626 You may also set this option in a different way for different
627 contexts. Valid contexts are:
629 headline when creating a new headline
630 item when creating a new item
631 table in a table field
632 default the value to be used for all contexts not explicitly
633 customized"
634 :group 'org-structure
635 :group 'org-table
636 :type '(choice
637 (const :tag "Always" t)
638 (const :tag "Never" nil)
639 (repeat :greedy t :tag "Individual contexts"
640 (cons
641 (choice :tag "Context"
642 (const headline)
643 (const item)
644 (const table)
645 (const default))
646 (boolean)))))
649 (defcustom org-blank-before-new-entry '((heading . nil)
650 (plain-list-item . nil))
651 "Should `org-insert-heading' leave a blank line before new heading/item?
652 The value is an alist, with `heading' and `plain-list-item' as car,
653 and a boolean flag as cdr."
654 :group 'org-edit-structure
655 :type '(list
656 (cons (const heading) (boolean))
657 (cons (const plain-list-item) (boolean))))
659 (defcustom org-insert-heading-hook nil
660 "Hook being run after inserting a new heading."
661 :group 'org-edit-structure
662 :type 'hook)
664 (defcustom org-enable-fixed-width-editor t
665 "Non-nil means, lines starting with \":\" are treated as fixed-width.
666 This currently only means, they are never auto-wrapped.
667 When nil, such lines will be treated like ordinary lines.
668 See also the QUOTE keyword."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defcustom org-goto-auto-isearch t
673 "Non-nil means, typing characters in org-goto starts incremental search."
674 :group 'org-edit-structure
675 :type 'boolean)
677 (defgroup org-sparse-trees nil
678 "Options concerning sparse trees in Org-mode."
679 :tag "Org Sparse Trees"
680 :group 'org-structure)
682 (defcustom org-highlight-sparse-tree-matches t
683 "Non-nil means, highlight all matches that define a sparse tree.
684 The highlights will automatically disappear the next time the buffer is
685 changed by an edit command."
686 :group 'org-sparse-trees
687 :type 'boolean)
689 (defcustom org-remove-highlights-with-change t
690 "Non-nil means, any change to the buffer will remove temporary highlights.
691 Such highlights are created by `org-occur' and `org-clock-display'.
692 When nil, `C-c C-c needs to be used to get rid of the highlights.
693 The highlights created by `org-preview-latex-fragment' always need
694 `C-c C-c' to be removed."
695 :group 'org-sparse-trees
696 :group 'org-time
697 :type 'boolean)
700 (defcustom org-occur-hook '(org-first-headline-recenter)
701 "Hook that is run after `org-occur' has constructed a sparse tree.
702 This can be used to recenter the window to show as much of the structure
703 as possible."
704 :group 'org-sparse-trees
705 :type 'hook)
707 (defgroup org-plain-lists nil
708 "Options concerning plain lists in Org-mode."
709 :tag "Org Plain lists"
710 :group 'org-structure)
712 (defcustom org-cycle-include-plain-lists nil
713 "Non-nil means, include plain lists into visibility cycling.
714 This means that during cycling, plain list items will *temporarily* be
715 interpreted as outline headlines with a level given by 1000+i where i is the
716 indentation of the bullet. In all other operations, plain list items are
717 not seen as headlines. For example, you cannot assign a TODO keyword to
718 such an item."
719 :group 'org-plain-lists
720 :type 'boolean)
722 (defcustom org-plain-list-ordered-item-terminator t
723 "The character that makes a line with leading number an ordered list item.
724 Valid values are ?. and ?\). To get both terminators, use t. While
725 ?. may look nicer, it creates the danger that a line with leading
726 number may be incorrectly interpreted as an item. ?\) therefore is
727 the safe choice."
728 :group 'org-plain-lists
729 :type '(choice (const :tag "dot like in \"2.\"" ?.)
730 (const :tag "paren like in \"2)\"" ?\))
731 (const :tab "both" t)))
733 (defcustom org-empty-line-terminates-plain-lists nil
734 "Non-nil means, an empty line ends all plain list levels.
735 When nil, empty lines are part of the preceeding item."
736 :group 'org-plain-lists
737 :type 'boolean)
739 (defcustom org-auto-renumber-ordered-lists t
740 "Non-nil means, automatically renumber ordered plain lists.
741 Renumbering happens when the sequence have been changed with
742 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
743 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
744 :group 'org-plain-lists
745 :type 'boolean)
747 (defcustom org-provide-checkbox-statistics t
748 "Non-nil means, update checkbox statistics after insert and toggle.
749 When this is set, checkbox statistics is updated each time you either insert
750 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
751 with \\[org-ctrl-c-ctrl-c\\]."
752 :group 'org-plain-lists
753 :type 'boolean)
755 (defcustom org-description-max-indent 20
756 "Maximum indentation for the second line of a description list.
757 When the indentation would be larger than this, it will become
758 5 characters instead."
759 :group 'org-plain-lists
760 :type 'integer)
762 (defgroup org-imenu-and-speedbar nil
763 "Options concerning imenu and speedbar in Org-mode."
764 :tag "Org Imenu and Speedbar"
765 :group 'org-structure)
767 (defcustom org-imenu-depth 2
768 "The maximum level for Imenu access to Org-mode headlines.
769 This also applied for speedbar access."
770 :group 'org-imenu-and-speedbar
771 :type 'number)
773 (defgroup org-table nil
774 "Options concerning tables in Org-mode."
775 :tag "Org Table"
776 :group 'org)
778 (defcustom org-enable-table-editor 'optimized
779 "Non-nil means, lines starting with \"|\" are handled by the table editor.
780 When nil, such lines will be treated like ordinary lines.
782 When equal to the symbol `optimized', the table editor will be optimized to
783 do the following:
784 - Automatic overwrite mode in front of whitespace in table fields.
785 This makes the structure of the table stay in tact as long as the edited
786 field does not exceed the column width.
787 - Minimize the number of realigns. Normally, the table is aligned each time
788 TAB or RET are pressed to move to another field. With optimization this
789 happens only if changes to a field might have changed the column width.
790 Optimization requires replacing the functions `self-insert-command',
791 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
792 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
793 very good at guessing when a re-align will be necessary, but you can always
794 force one with \\[org-ctrl-c-ctrl-c].
796 If you would like to use the optimized version in Org-mode, but the
797 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
799 This variable can be used to turn on and off the table editor during a session,
800 but in order to toggle optimization, a restart is required.
802 See also the variable `org-table-auto-blank-field'."
803 :group 'org-table
804 :type '(choice
805 (const :tag "off" nil)
806 (const :tag "on" t)
807 (const :tag "on, optimized" optimized)))
809 (defcustom org-table-tab-recognizes-table.el t
810 "Non-nil means, TAB will automatically notice a table.el table.
811 When it sees such a table, it moves point into it and - if necessary -
812 calls `table-recognize-table'."
813 :group 'org-table-editing
814 :type 'boolean)
816 (defgroup org-link nil
817 "Options concerning links in Org-mode."
818 :tag "Org Link"
819 :group 'org)
821 (defvar org-link-abbrev-alist-local nil
822 "Buffer-local version of `org-link-abbrev-alist', which see.
823 The value of this is taken from the #+LINK lines.")
824 (make-variable-buffer-local 'org-link-abbrev-alist-local)
826 (defcustom org-link-abbrev-alist nil
827 "Alist of link abbreviations.
828 The car of each element is a string, to be replaced at the start of a link.
829 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
830 links in Org-mode buffers can have an optional tag after a double colon, e.g.
832 [[linkkey:tag][description]]
834 If REPLACE is a string, the tag will simply be appended to create the link.
835 If the string contains \"%s\", the tag will be inserted there.
837 REPLACE may also be a function that will be called with the tag as the
838 only argument to create the link, which should be returned as a string.
840 See the manual for examples."
841 :group 'org-link
842 :type 'alist)
844 (defcustom org-descriptive-links t
845 "Non-nil means, hide link part and only show description of bracket links.
846 Bracket links are like [[link][descritpion]]. This variable sets the initial
847 state in new org-mode buffers. The setting can then be toggled on a
848 per-buffer basis from the Org->Hyperlinks menu."
849 :group 'org-link
850 :type 'boolean)
852 (defcustom org-link-file-path-type 'adaptive
853 "How the path name in file links should be stored.
854 Valid values are:
856 relative Relative to the current directory, i.e. the directory of the file
857 into which the link is being inserted.
858 absolute Absolute path, if possible with ~ for home directory.
859 noabbrev Absolute path, no abbreviation of home directory.
860 adaptive Use relative path for files in the current directory and sub-
861 directories of it. For other files, use an absolute path."
862 :group 'org-link
863 :type '(choice
864 (const relative)
865 (const absolute)
866 (const noabbrev)
867 (const adaptive)))
869 (defcustom org-activate-links '(bracket angle plain radio tag date)
870 "Types of links that should be activated in Org-mode files.
871 This is a list of symbols, each leading to the activation of a certain link
872 type. In principle, it does not hurt to turn on most link types - there may
873 be a small gain when turning off unused link types. The types are:
875 bracket The recommended [[link][description]] or [[link]] links with hiding.
876 angular Links in angular brackes that may contain whitespace like
877 <bbdb:Carsten Dominik>.
878 plain Plain links in normal text, no whitespace, like http://google.com.
879 radio Text that is matched by a radio target, see manual for details.
880 tag Tag settings in a headline (link to tag search).
881 date Time stamps (link to calendar).
883 Changing this variable requires a restart of Emacs to become effective."
884 :group 'org-link
885 :type '(set (const :tag "Double bracket links (new style)" bracket)
886 (const :tag "Angular bracket links (old style)" angular)
887 (const :tag "Plain text links" plain)
888 (const :tag "Radio target matches" radio)
889 (const :tag "Tags" tag)
890 (const :tag "Timestamps" date)))
892 (defcustom org-make-link-description-function nil
893 "Function to use to generate link descriptions from links. If
894 nil the link location will be used. This function must take two
895 parameters; the first is the link and the second the description
896 org-insert-link has generated, and should return the description
897 to use."
898 :group 'org-link
899 :type 'function)
901 (defgroup org-link-store nil
902 "Options concerning storing links in Org-mode."
903 :tag "Org Store Link"
904 :group 'org-link)
906 (defcustom org-email-link-description-format "Email %c: %.30s"
907 "Format of the description part of a link to an email or usenet message.
908 The following %-excapes will be replaced by corresponding information:
910 %F full \"From\" field
911 %f name, taken from \"From\" field, address if no name
912 %T full \"To\" field
913 %t first name in \"To\" field, address if no name
914 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
915 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
916 %s subject
917 %m message-id.
919 You may use normal field width specification between the % and the letter.
920 This is for example useful to limit the length of the subject.
922 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
923 :group 'org-link-store
924 :type 'string)
926 (defcustom org-from-is-user-regexp
927 (let (r1 r2)
928 (when (and user-mail-address (not (string= user-mail-address "")))
929 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
930 (when (and user-full-name (not (string= user-full-name "")))
931 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
932 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
933 "Regexp mached against the \"From:\" header of an email or usenet message.
934 It should match if the message is from the user him/herself."
935 :group 'org-link-store
936 :type 'regexp)
938 (defcustom org-context-in-file-links t
939 "Non-nil means, file links from `org-store-link' contain context.
940 A search string will be added to the file name with :: as separator and
941 used to find the context when the link is activated by the command
942 `org-open-at-point'.
943 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
944 negates this setting for the duration of the command."
945 :group 'org-link-store
946 :type 'boolean)
948 (defcustom org-keep-stored-link-after-insertion nil
949 "Non-nil means, keep link in list for entire session.
951 The command `org-store-link' adds a link pointing to the current
952 location to an internal list. These links accumulate during a session.
953 The command `org-insert-link' can be used to insert links into any
954 Org-mode file (offering completion for all stored links). When this
955 option is nil, every link which has been inserted once using \\[org-insert-link]
956 will be removed from the list, to make completing the unused links
957 more efficient."
958 :group 'org-link-store
959 :type 'boolean)
961 (defgroup org-link-follow nil
962 "Options concerning following links in Org-mode."
963 :tag "Org Follow Link"
964 :group 'org-link)
966 (defcustom org-follow-link-hook nil
967 "Hook that is run after a link has been followed."
968 :group 'org-link-follow
969 :type 'hook)
971 (defcustom org-tab-follows-link nil
972 "Non-nil means, on links TAB will follow the link.
973 Needs to be set before org.el is loaded."
974 :group 'org-link-follow
975 :type 'boolean)
977 (defcustom org-return-follows-link nil
978 "Non-nil means, on links RET will follow the link.
979 Needs to be set before org.el is loaded."
980 :group 'org-link-follow
981 :type 'boolean)
983 (defcustom org-mouse-1-follows-link
984 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
985 "Non-nil means, mouse-1 on a link will follow the link.
986 A longer mouse click will still set point. Does not work on XEmacs.
987 Needs to be set before org.el is loaded."
988 :group 'org-link-follow
989 :type 'boolean)
991 (defcustom org-mark-ring-length 4
992 "Number of different positions to be recorded in the ring
993 Changing this requires a restart of Emacs to work correctly."
994 :group 'org-link-follow
995 :type 'interger)
997 (defcustom org-link-frame-setup
998 '((vm . vm-visit-folder-other-frame)
999 (gnus . gnus-other-frame)
1000 (file . find-file-other-window))
1001 "Setup the frame configuration for following links.
1002 When following a link with Emacs, it may often be useful to display
1003 this link in another window or frame. This variable can be used to
1004 set this up for the different types of links.
1005 For VM, use any of
1006 `vm-visit-folder'
1007 `vm-visit-folder-other-frame'
1008 For Gnus, use any of
1009 `gnus'
1010 `gnus-other-frame'
1011 For FILE, use any of
1012 `find-file'
1013 `find-file-other-window'
1014 `find-file-other-frame'
1015 For the calendar, use the variable `calendar-setup'.
1016 For BBDB, it is currently only possible to display the matches in
1017 another window."
1018 :group 'org-link-follow
1019 :type '(list
1020 (cons (const vm)
1021 (choice
1022 (const vm-visit-folder)
1023 (const vm-visit-folder-other-window)
1024 (const vm-visit-folder-other-frame)))
1025 (cons (const gnus)
1026 (choice
1027 (const gnus)
1028 (const gnus-other-frame)))
1029 (cons (const file)
1030 (choice
1031 (const find-file)
1032 (const find-file-other-window)
1033 (const find-file-other-frame)))))
1035 (defcustom org-display-internal-link-with-indirect-buffer nil
1036 "Non-nil means, use indirect buffer to display infile links.
1037 Activating internal links (from one location in a file to another location
1038 in the same file) normally just jumps to the location. When the link is
1039 activated with a C-u prefix (or with mouse-3), the link is displayed in
1040 another window. When this option is set, the other window actually displays
1041 an indirect buffer clone of the current buffer, to avoid any visibility
1042 changes to the current buffer."
1043 :group 'org-link-follow
1044 :type 'boolean)
1046 (defcustom org-open-non-existing-files nil
1047 "Non-nil means, `org-open-file' will open non-existing files.
1048 When nil, an error will be generated."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-open-directory-means-index-dot-org nil
1053 "Non-nil means, a link to a directory really means to index.org.
1054 When nil, following a directory link will run dired or open a finder/explorer
1055 window on that directory."
1056 :group 'org-link-follow
1057 :type 'boolean)
1059 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1060 "Function and arguments to call for following mailto links.
1061 This is a list with the first element being a lisp function, and the
1062 remaining elements being arguments to the function. In string arguments,
1063 %a will be replaced by the address, and %s will be replaced by the subject
1064 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1065 :group 'org-link-follow
1066 :type '(choice
1067 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1068 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1069 (const :tag "message-mail" (message-mail "%a" "%s"))
1070 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1072 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1073 "Non-nil means, ask for confirmation before executing shell links.
1074 Shell links can be dangerous: just think about a link
1076 [[shell:rm -rf ~/*][Google Search]]
1078 This link would show up in your Org-mode document as \"Google Search\",
1079 but really it would remove your entire home directory.
1080 Therefore we advise against setting this variable to nil.
1081 Just change it to `y-or-n-p' of you want to confirm with a
1082 single keystroke rather than having to type \"yes\"."
1083 :group 'org-link-follow
1084 :type '(choice
1085 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1086 (const :tag "with y-or-n (faster)" y-or-n-p)
1087 (const :tag "no confirmation (dangerous)" nil)))
1089 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1090 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1091 Elisp links can be dangerous: just think about a link
1093 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1095 This link would show up in your Org-mode document as \"Google Search\",
1096 but really it would remove your entire home directory.
1097 Therefore we advise against setting this variable to nil.
1098 Just change it to `y-or-n-p' of you want to confirm with a
1099 single keystroke rather than having to type \"yes\"."
1100 :group 'org-link-follow
1101 :type '(choice
1102 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1103 (const :tag "with y-or-n (faster)" y-or-n-p)
1104 (const :tag "no confirmation (dangerous)" nil)))
1106 (defconst org-file-apps-defaults-gnu
1107 '((remote . emacs)
1108 (t . mailcap))
1109 "Default file applications on a UNIX or GNU/Linux system.
1110 See `org-file-apps'.")
1112 (defconst org-file-apps-defaults-macosx
1113 '((remote . emacs)
1114 (t . "open %s")
1115 ("ps" . "gv %s")
1116 ("ps.gz" . "gv %s")
1117 ("eps" . "gv %s")
1118 ("eps.gz" . "gv %s")
1119 ("dvi" . "xdvi %s")
1120 ("fig" . "xfig %s"))
1121 "Default file applications on a MacOS X system.
1122 The system \"open\" is known as a default, but we use X11 applications
1123 for some files for which the OS does not have a good default.
1124 See `org-file-apps'.")
1126 (defconst org-file-apps-defaults-windowsnt
1127 (list
1128 '(remote . emacs)
1129 (cons t
1130 (list (if (featurep 'xemacs)
1131 'mswindows-shell-execute
1132 'w32-shell-execute)
1133 "open" 'file)))
1134 "Default file applications on a Windows NT system.
1135 The system \"open\" is used for most files.
1136 See `org-file-apps'.")
1138 (defcustom org-file-apps
1140 ("txt" . emacs)
1141 ("tex" . emacs)
1142 ("ltx" . emacs)
1143 ("org" . emacs)
1144 ("el" . emacs)
1145 ("bib" . emacs)
1147 "External applications for opening `file:path' items in a document.
1148 Org-mode uses system defaults for different file types, but
1149 you can use this variable to set the application for a given file
1150 extension. The entries in this list are cons cells where the car identifies
1151 files and the cdr the corresponding command. Possible values for the
1152 file identifier are
1153 \"ext\" A string identifying an extension
1154 `directory' Matches a directory
1155 `remote' Matches a remote file, accessible through tramp or efs.
1156 Remote files most likely should be visited through Emacs
1157 because external applications cannot handle such paths.
1158 t Default for all remaining files
1160 Possible values for the command are:
1161 `emacs' The file will be visited by the current Emacs process.
1162 `default' Use the default application for this file type.
1163 string A command to be executed by a shell; %s will be replaced
1164 by the path to the file.
1165 sexp A Lisp form which will be evaluated. The file path will
1166 be available in the Lisp variable `file'.
1167 For more examples, see the system specific constants
1168 `org-file-apps-defaults-macosx'
1169 `org-file-apps-defaults-windowsnt'
1170 `org-file-apps-defaults-gnu'."
1171 :group 'org-link-follow
1172 :type '(repeat
1173 (cons (choice :value ""
1174 (string :tag "Extension")
1175 (const :tag "Default for unrecognized files" t)
1176 (const :tag "Remote file" remote)
1177 (const :tag "Links to a directory" directory))
1178 (choice :value ""
1179 (const :tag "Visit with Emacs" emacs)
1180 (const :tag "Use system default" default)
1181 (string :tag "Command")
1182 (sexp :tag "Lisp form")))))
1184 (defgroup org-refile nil
1185 "Options concerning refiling entries in Org-mode."
1186 :tag "Org Remember"
1187 :group 'org)
1189 (defcustom org-directory "~/org"
1190 "Directory with org files.
1191 This directory will be used as default to prompt for org files.
1192 Used by the hooks for remember.el."
1193 :group 'org-refile
1194 :group 'org-remember
1195 :type 'directory)
1197 (defcustom org-default-notes-file "~/.notes"
1198 "Default target for storing notes.
1199 Used by the hooks for remember.el. This can be a string, or nil to mean
1200 the value of `remember-data-file'.
1201 You can set this on a per-template basis with the variable
1202 `org-remember-templates'."
1203 :group 'org-refile
1204 :group 'org-remember
1205 :type '(choice
1206 (const :tag "Default from remember-data-file" nil)
1207 file))
1209 (defcustom org-goto-interface 'outline
1210 "The default interface to be used for `org-goto'.
1211 Allowed vaues are:
1212 outline The interface shows an outline of the relevant file
1213 and the correct heading is found by moving through
1214 the outline or by searching with incremental search.
1215 outline-path-completion Headlines in the current buffer are offered via
1216 completion."
1217 :group 'org-refile
1218 :type '(choice
1219 (const :tag "Outline" outline)
1220 (const :tag "Outline-path-completion" outline-path-completion)))
1222 (defcustom org-reverse-note-order nil
1223 "Non-nil means, store new notes at the beginning of a file or entry.
1224 When nil, new notes will be filed to the end of a file or entry.
1225 This can also be a list with cons cells of regular expressions that
1226 are matched against file names, and values."
1227 :group 'org-remember
1228 :type '(choice
1229 (const :tag "Reverse always" t)
1230 (const :tag "Reverse never" nil)
1231 (repeat :tag "By file name regexp"
1232 (cons regexp boolean))))
1234 (defcustom org-refile-targets nil
1235 "Targets for refiling entries with \\[org-refile].
1236 This is list of cons cells. Each cell contains:
1237 - a specification of the files to be considered, either a list of files,
1238 or a symbol whose function or variable value will be used to retrieve
1239 a file name or a list of file names. Nil means, refile to a different
1240 heading in the current buffer.
1241 - A specification of how to find candidate refile targets. This may be
1242 any of
1243 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1244 This tag has to be present in all target headlines, inheritance will
1245 not be considered.
1246 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1247 todo keyword.
1248 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1249 headlines that are refiling targets.
1250 - a cons cell (:level . N). Any headline of level N is considered a target.
1251 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1252 :group 'org-remember
1253 :type '(repeat
1254 (cons
1255 (choice :value org-agenda-files
1256 (const :tag "All agenda files" org-agenda-files)
1257 (const :tag "Current buffer" nil)
1258 (function) (variable) (file))
1259 (choice :tag "Identify target headline by"
1260 (cons :tag "Specific tag" (const :tag) (string))
1261 (cons :tag "TODO keyword" (const :todo) (string))
1262 (cons :tag "Regular expression" (const :regexp) (regexp))
1263 (cons :tag "Level number" (const :level) (integer))
1264 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1266 (defcustom org-refile-use-outline-path nil
1267 "Non-nil means, provide refile targets as paths.
1268 So a level 3 headline will be available as level1/level2/level3.
1269 When the value is `file', also include the file name (without directory)
1270 into the path. When `full-file-path', include the full file path."
1271 :group 'org-remember
1272 :type '(choice
1273 (const :tag "Not" nil)
1274 (const :tag "Yes" t)
1275 (const :tag "Start with file name" file)
1276 (const :tag "Start with full file path" full-file-path)))
1278 (defgroup org-todo nil
1279 "Options concerning TODO items in Org-mode."
1280 :tag "Org TODO"
1281 :group 'org)
1283 (defgroup org-progress nil
1284 "Options concerning Progress logging in Org-mode."
1285 :tag "Org Progress"
1286 :group 'org-time)
1288 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1289 "List of TODO entry keyword sequences and their interpretation.
1290 \\<org-mode-map>This is a list of sequences.
1292 Each sequence starts with a symbol, either `sequence' or `type',
1293 indicating if the keywords should be interpreted as a sequence of
1294 action steps, or as different types of TODO items. The first
1295 keywords are states requiring action - these states will select a headline
1296 for inclusion into the global TODO list Org-mode produces. If one of
1297 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1298 signify that no further action is necessary. If \"|\" is not found,
1299 the last keyword is treated as the only DONE state of the sequence.
1301 The command \\[org-todo] cycles an entry through these states, and one
1302 additional state where no keyword is present. For details about this
1303 cycling, see the manual.
1305 TODO keywords and interpretation can also be set on a per-file basis with
1306 the special #+SEQ_TODO and #+TYP_TODO lines.
1308 Each keyword can optionally specify a character for fast state selection
1309 \(in combination with the variable `org-use-fast-todo-selection')
1310 and specifiers for state change logging, using the same syntax
1311 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1312 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1313 indicates to record a time stamp each time this state is selected.
1315 Each keyword may also specify if a timestamp or a note should be
1316 recorded when entering or leaving the state, by adding additional
1317 characters in the parenthesis after the keyword. This looks like this:
1318 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1319 record only the time of the state change. With X and Y being either
1320 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1321 Y when leaving the state if and only if the *target* state does not
1322 define X. You may omit any of the fast-selection key or X or /Y,
1323 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1325 For backward compatibility, this variable may also be just a list
1326 of keywords - in this case the interptetation (sequence or type) will be
1327 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1328 :group 'org-todo
1329 :group 'org-keywords
1330 :type '(choice
1331 (repeat :tag "Old syntax, just keywords"
1332 (string :tag "Keyword"))
1333 (repeat :tag "New syntax"
1334 (cons
1335 (choice
1336 :tag "Interpretation"
1337 (const :tag "Sequence (cycling hits every state)" sequence)
1338 (const :tag "Type (cycling directly to DONE)" type))
1339 (repeat
1340 (string :tag "Keyword"))))))
1342 (defvar org-todo-keywords-1 nil
1343 "All TODO and DONE keywords active in a buffer.")
1344 (make-variable-buffer-local 'org-todo-keywords-1)
1345 (defvar org-todo-keywords-for-agenda nil)
1346 (defvar org-done-keywords-for-agenda nil)
1347 (defvar org-agenda-contributing-files nil)
1348 (defvar org-not-done-keywords nil)
1349 (make-variable-buffer-local 'org-not-done-keywords)
1350 (defvar org-done-keywords nil)
1351 (make-variable-buffer-local 'org-done-keywords)
1352 (defvar org-todo-heads nil)
1353 (make-variable-buffer-local 'org-todo-heads)
1354 (defvar org-todo-sets nil)
1355 (make-variable-buffer-local 'org-todo-sets)
1356 (defvar org-todo-log-states nil)
1357 (make-variable-buffer-local 'org-todo-log-states)
1358 (defvar org-todo-kwd-alist nil)
1359 (make-variable-buffer-local 'org-todo-kwd-alist)
1360 (defvar org-todo-key-alist nil)
1361 (make-variable-buffer-local 'org-todo-key-alist)
1362 (defvar org-todo-key-trigger nil)
1363 (make-variable-buffer-local 'org-todo-key-trigger)
1365 (defcustom org-todo-interpretation 'sequence
1366 "Controls how TODO keywords are interpreted.
1367 This variable is in principle obsolete and is only used for
1368 backward compatibility, if the interpretation of todo keywords is
1369 not given already in `org-todo-keywords'. See that variable for
1370 more information."
1371 :group 'org-todo
1372 :group 'org-keywords
1373 :type '(choice (const sequence)
1374 (const type)))
1376 (defcustom org-use-fast-todo-selection 'prefix
1377 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1378 This variable describes if and under what circumstances the cycling
1379 mechanism for TODO keywords will be replaced by a single-key, direct
1380 selection scheme.
1382 When nil, fast selection is never used.
1384 When the symbol `prefix', it will be used when `org-todo' is called with
1385 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1386 in an agenda buffer.
1388 When t, fast selection is used by default. In this case, the prefix
1389 argument forces cycling instead.
1391 In all cases, the special interface is only used if access keys have actually
1392 been assigned by the user, i.e. if keywords in the configuration are followed
1393 by a letter in parenthesis, like TODO(t)."
1394 :group 'org-todo
1395 :type '(choice
1396 (const :tag "Never" nil)
1397 (const :tag "By default" t)
1398 (const :tag "Only with C-u C-c C-t" prefix)))
1400 (defcustom org-provide-todo-statistics t
1401 "Non-nil means, update todo statistics after insert and toggle.
1402 When this is set, todo statistics is updated in the parent of the current
1403 entry each time a todo state is changed."
1404 :group 'org-todo
1405 :type 'boolean)
1407 (defcustom org-after-todo-state-change-hook nil
1408 "Hook which is run after the state of a TODO item was changed.
1409 The new state (a string with a TODO keyword, or nil) is available in the
1410 Lisp variable `state'."
1411 :group 'org-todo
1412 :type 'hook)
1414 (defcustom org-log-done nil
1415 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1416 When equal to the list (done), also prompt for a closing note.
1417 This can also be configured on a per-file basis by adding one of
1418 the following lines anywhere in the buffer:
1420 #+STARTUP: logdone
1421 #+STARTUP: lognotedone
1422 #+STARTUP: nologdone"
1423 :group 'org-todo
1424 :group 'org-progress
1425 :type '(choice
1426 (const :tag "No logging" nil)
1427 (const :tag "Record CLOSED timestamp" time)
1428 (const :tag "Record CLOSED timestamp with closing note." note)))
1430 ;; Normalize old uses of org-log-done.
1431 (cond
1432 ((eq org-log-done t) (setq org-log-done 'time))
1433 ((and (listp org-log-done) (memq 'done org-log-done))
1434 (setq org-log-done 'note)))
1436 (defcustom org-log-note-clock-out nil
1437 "Non-nil means, recored a note when clocking out of an item.
1438 This can also be configured on a per-file basis by adding one of
1439 the following lines anywhere in the buffer:
1441 #+STARTUP: lognoteclock-out
1442 #+STARTUP: nolognoteclock-out"
1443 :group 'org-todo
1444 :group 'org-progress
1445 :type 'boolean)
1447 (defcustom org-log-done-with-time t
1448 "Non-nil means, the CLOSED time stamp will contain date and time.
1449 When nil, only the date will be recorded."
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-note-headings
1454 '((done . "CLOSING NOTE %t")
1455 (state . "State %-12s %t")
1456 (note . "Note taken on %t")
1457 (clock-out . ""))
1458 "Headings for notes added to entries.
1459 The value is an alist, with the car being a symbol indicating the note
1460 context, and the cdr is the heading to be used. The heading may also be the
1461 empty string.
1462 %t in the heading will be replaced by a time stamp.
1463 %s will be replaced by the new TODO state, in double quotes.
1464 %u will be replaced by the user name.
1465 %U will be replaced by the full user name."
1466 :group 'org-todo
1467 :group 'org-progress
1468 :type '(list :greedy t
1469 (cons (const :tag "Heading when closing an item" done) string)
1470 (cons (const :tag
1471 "Heading when changing todo state (todo sequence only)"
1472 state) string)
1473 (cons (const :tag "Heading when just taking a note" note) string)
1474 (cons (const :tag "Heading when clocking out" clock-out) string)))
1476 (unless (assq 'note org-log-note-headings)
1477 (push '(note . "%t") org-log-note-headings))
1479 (defcustom org-log-states-order-reversed t
1480 "Non-nil means, the latest state change note will be directly after heading.
1481 When nil, the notes will be orderer according to time."
1482 :group 'org-todo
1483 :group 'org-progress
1484 :type 'boolean)
1486 (defcustom org-log-repeat 'time
1487 "Non-nil means, record moving through the DONE state when triggering repeat.
1488 An auto-repeating tasks is immediately switched back to TODO when marked
1489 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1490 the TODO keyword definition, or recording a closing note by setting
1491 `org-log-done', there will be no record of the task moving through DONE.
1492 This variable forces taking a note anyway. Possible values are:
1494 nil Don't force a record
1495 time Record a time stamp
1496 note Record a note
1498 This option can also be set with on a per-file-basis with
1500 #+STARTUP: logrepeat
1501 #+STARTUP: lognoterepeat
1502 #+STARTUP: nologrepeat
1504 You can have local logging settings for a subtree by setting the LOGGING
1505 property to one or more of these keywords."
1506 :group 'org-todo
1507 :group 'org-progress
1508 :type '(choice
1509 (const :tag "Don't force a record" nil)
1510 (const :tag "Force recording the DONE state" time)
1511 (const :tag "Force recording a note with the DONE state" note)))
1514 (defgroup org-priorities nil
1515 "Priorities in Org-mode."
1516 :tag "Org Priorities"
1517 :group 'org-todo)
1519 (defcustom org-highest-priority ?A
1520 "The highest priority of TODO items. A character like ?A, ?B etc.
1521 Must have a smaller ASCII number than `org-lowest-priority'."
1522 :group 'org-priorities
1523 :type 'character)
1525 (defcustom org-lowest-priority ?C
1526 "The lowest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a larger ASCII number than `org-highest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-default-priority ?B
1532 "The default priority of TODO items.
1533 This is the priority an item get if no explicit priority is given."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-priority-start-cycle-with-default t
1538 "Non-nil means, start with default priority when starting to cycle.
1539 When this is nil, the first step in the cycle will be (depending on the
1540 command used) one higher or lower that the default priority."
1541 :group 'org-priorities
1542 :type 'boolean)
1544 (defgroup org-time nil
1545 "Options concerning time stamps and deadlines in Org-mode."
1546 :tag "Org Time"
1547 :group 'org)
1549 (defcustom org-insert-labeled-timestamps-at-point nil
1550 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1551 When nil, these labeled time stamps are forces into the second line of an
1552 entry, just after the headline. When scheduling from the global TODO list,
1553 the time stamp will always be forced into the second line."
1554 :group 'org-time
1555 :type 'boolean)
1557 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1558 "Formats for `format-time-string' which are used for time stamps.
1559 It is not recommended to change this constant.")
1561 (defcustom org-time-stamp-rounding-minutes '(0 5)
1562 "Number of minutes to round time stamps to.
1563 These are two values, the first applies when first creating a time stamp.
1564 The second applies when changing it with the commands `S-up' and `S-down'.
1565 When changing the time stamp, this means that it will change in steps
1566 of N minutes, as given by the second value.
1568 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1569 numbers should be factors of 60, so for example 5, 10, 15.
1571 When this is larger than 1, you can still force an exact time-stamp by using
1572 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1573 and by using a prefix arg to `S-up/down' to specify the exact number
1574 of minutes to shift."
1575 :group 'org-time
1576 :get '(lambda (var) ; Make sure all entries have 5 elements
1577 (if (integerp (default-value var))
1578 (list (default-value var) 5)
1579 (default-value var)))
1580 :type '(list
1581 (integer :tag "when inserting times")
1582 (integer :tag "when modifying times")))
1584 ;; Normalize old customizations of this variable.
1585 (when (integerp org-time-stamp-rounding-minutes)
1586 (setq org-time-stamp-rounding-minutes
1587 (list org-time-stamp-rounding-minutes
1588 org-time-stamp-rounding-minutes)))
1590 (defcustom org-display-custom-times nil
1591 "Non-nil means, overlay custom formats over all time stamps.
1592 The formats are defined through the variable `org-time-stamp-custom-formats'.
1593 To turn this on on a per-file basis, insert anywhere in the file:
1594 #+STARTUP: customtime"
1595 :group 'org-time
1596 :set 'set-default
1597 :type 'sexp)
1598 (make-variable-buffer-local 'org-display-custom-times)
1600 (defcustom org-time-stamp-custom-formats
1601 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1602 "Custom formats for time stamps. See `format-time-string' for the syntax.
1603 These are overlayed over the default ISO format if the variable
1604 `org-display-custom-times' is set. Time like %H:%M should be at the
1605 end of the second format."
1606 :group 'org-time
1607 :type 'sexp)
1609 (defun org-time-stamp-format (&optional long inactive)
1610 "Get the right format for a time string."
1611 (let ((f (if long (cdr org-time-stamp-formats)
1612 (car org-time-stamp-formats))))
1613 (if inactive
1614 (concat "[" (substring f 1 -1) "]")
1615 f)))
1617 (defcustom org-time-clocksum-format "%d:%02d"
1618 "The format string used when creating CLOCKSUM lines, or when
1619 org-mode generates a time duration."
1620 :group 'org-time
1621 :type 'string)
1623 (defcustom org-deadline-warning-days 14
1624 "No. of days before expiration during which a deadline becomes active.
1625 This variable governs the display in sparse trees and in the agenda.
1626 When 0 or negative, it means use this number (the absolute value of it)
1627 even if a deadline has a different individual lead time specified."
1628 :group 'org-time
1629 :group 'org-agenda-daily/weekly
1630 :type 'number)
1632 (defcustom org-read-date-prefer-future t
1633 "Non-nil means, assume future for incomplete date input from user.
1634 This affects the following situations:
1635 1. The user gives a day, but no month.
1636 For example, if today is the 15th, and you enter \"3\", Org-mode will
1637 read this as the third of *next* month. However, if you enter \"17\",
1638 it will be considered as *this* month.
1639 2. The user gives a month but not a year.
1640 For example, if it is april and you enter \"feb 2\", this will be read
1641 as feb 2, *next* year. \"May 5\", however, will be this year.
1643 Currently this does not work for ISO week specifications.
1645 When this option is nil, the current month and year will always be used
1646 as defaults."
1647 :group 'org-time
1648 :type 'boolean)
1650 (defcustom org-read-date-display-live t
1651 "Non-nil means, display current interpretation of date prompt live.
1652 This display will be in an overlay, in the minibuffer."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-popup-calendar t
1657 "Non-nil means, pop up a calendar when prompting for a date.
1658 In the calendar, the date can be selected with mouse-1. However, the
1659 minibuffer will also be active, and you can simply enter the date as well.
1660 When nil, only the minibuffer will be available."
1661 :group 'org-time
1662 :type 'boolean)
1663 (if (fboundp 'defvaralias)
1664 (defvaralias 'org-popup-calendar-for-date-prompt
1665 'org-read-date-popup-calendar))
1667 (defcustom org-extend-today-until 0
1668 "The hour when your day really ends.
1669 This has influence for the following applications:
1670 - When switching the agenda to \"today\". It it is still earlier than
1671 the time given here, the day recognized as TODAY is actually yesterday.
1672 - When a date is read from the user and it is still before the time given
1673 here, the current date and time will be assumed to be yesterday, 23:59.
1675 FIXME:
1676 IMPORTANT: This is still a very experimental feature, it may disappear
1677 again or it may be extended to mean more things."
1678 :group 'org-time
1679 :type 'number)
1681 (defcustom org-edit-timestamp-down-means-later nil
1682 "Non-nil means, S-down will increase the time in a time stamp.
1683 When nil, S-up will increase."
1684 :group 'org-time
1685 :type 'boolean)
1687 (defcustom org-calendar-follow-timestamp-change t
1688 "Non-nil means, make the calendar window follow timestamp changes.
1689 When a timestamp is modified and the calendar window is visible, it will be
1690 moved to the new date."
1691 :group 'org-time
1692 :type 'boolean)
1694 (defgroup org-tags nil
1695 "Options concerning tags in Org-mode."
1696 :tag "Org Tags"
1697 :group 'org)
1699 (defcustom org-tag-alist nil
1700 "List of tags allowed in Org-mode files.
1701 When this list is nil, Org-mode will base TAG input on what is already in the
1702 buffer.
1703 The value of this variable is an alist, the car of each entry must be a
1704 keyword as a string, the cdr may be a character that is used to select
1705 that tag through the fast-tag-selection interface.
1706 See the manual for details."
1707 :group 'org-tags
1708 :type '(repeat
1709 (choice
1710 (cons (string :tag "Tag name")
1711 (character :tag "Access char"))
1712 (const :tag "Start radio group" (:startgroup))
1713 (const :tag "End radio group" (:endgroup)))))
1715 (defvar org-file-tags nil
1716 "List of tags that can be inherited by all entries in the file.
1717 The tags will be inherited if the variable `org-use-tag-inheritance'
1718 says they should be.
1719 This variable is populated from #+TAG lines.")
1721 (defcustom org-use-fast-tag-selection 'auto
1722 "Non-nil means, use fast tag selection scheme.
1723 This is a special interface to select and deselect tags with single keys.
1724 When nil, fast selection is never used.
1725 When the symbol `auto', fast selection is used if and only if selection
1726 characters for tags have been configured, either through the variable
1727 `org-tag-alist' or through a #+TAGS line in the buffer.
1728 When t, fast selection is always used and selection keys are assigned
1729 automatically if necessary."
1730 :group 'org-tags
1731 :type '(choice
1732 (const :tag "Always" t)
1733 (const :tag "Never" nil)
1734 (const :tag "When selection characters are configured" 'auto)))
1736 (defcustom org-fast-tag-selection-single-key nil
1737 "Non-nil means, fast tag selection exits after first change.
1738 When nil, you have to press RET to exit it.
1739 During fast tag selection, you can toggle this flag with `C-c'.
1740 This variable can also have the value `expert'. In this case, the window
1741 displaying the tags menu is not even shown, until you press C-c again."
1742 :group 'org-tags
1743 :type '(choice
1744 (const :tag "No" nil)
1745 (const :tag "Yes" t)
1746 (const :tag "Expert" expert)))
1748 (defvar org-fast-tag-selection-include-todo nil
1749 "Non-nil means, fast tags selection interface will also offer TODO states.
1750 This is an undocumented feature, you should not rely on it.")
1752 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1753 "The column to which tags should be indented in a headline.
1754 If this number is positive, it specifies the column. If it is negative,
1755 it means that the tags should be flushright to that column. For example,
1756 -80 works well for a normal 80 character screen."
1757 :group 'org-tags
1758 :type 'integer)
1760 (defcustom org-auto-align-tags t
1761 "Non-nil means, realign tags after pro/demotion of TODO state change.
1762 These operations change the length of a headline and therefore shift
1763 the tags around. With this options turned on, after each such operation
1764 the tags are again aligned to `org-tags-column'."
1765 :group 'org-tags
1766 :type 'boolean)
1768 (defcustom org-use-tag-inheritance t
1769 "Non-nil means, tags in levels apply also for sublevels.
1770 When nil, only the tags directly given in a specific line apply there.
1771 If this option is t, a match early-on in a tree can lead to a large
1772 number of matches in the subtree. If you only want to see the first
1773 match in a tree during a search, check out the variable
1774 `org-tags-match-list-sublevels'.
1776 This may also be a list of tags that should be inherited, or a regexp that
1777 matches tags that should be inherited."
1778 :group 'org-tags
1779 :type '(choice
1780 (const :tag "Not" nil)
1781 (const :tag "Always" t)
1782 (repeat :tag "Specific tags" (string :tag "Tag"))
1783 (regexp :tag "Tags matched by regexp")))
1785 (defun org-tag-inherit-p (tag)
1786 "Check if TAG is one that should be inherited."
1787 (cond
1788 ((eq org-use-tag-inheritance t) t)
1789 ((not org-use-tag-inheritance) nil)
1790 ((stringp org-use-tag-inheritance)
1791 (string-match org-use-tag-inheritance tag))
1792 ((listp org-use-tag-inheritance)
1793 (member tag org-use-tag-inheritance))
1794 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1796 (defcustom org-tags-match-list-sublevels t
1797 "Non-nil means list also sublevels of headlines matching tag search.
1798 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1799 the sublevels of a headline matching a tag search often also match
1800 the same search. Listing all of them can create very long lists.
1801 Setting this variable to nil causes subtrees of a match to be skipped.
1802 This option is off by default, because inheritance in on. If you turn
1803 inheritance off, you very likely want to turn this option on.
1805 As a special case, if the tag search is restricted to TODO items, the
1806 value of this variable is ignored and sublevels are always checked, to
1807 make sure all corresponding TODO items find their way into the list."
1808 :group 'org-tags
1809 :type 'boolean)
1811 (defvar org-tags-history nil
1812 "History of minibuffer reads for tags.")
1813 (defvar org-last-tags-completion-table nil
1814 "The last used completion table for tags.")
1815 (defvar org-after-tags-change-hook nil
1816 "Hook that is run after the tags in a line have changed.")
1818 (defgroup org-properties nil
1819 "Options concerning properties in Org-mode."
1820 :tag "Org Properties"
1821 :group 'org)
1823 (defcustom org-property-format "%-10s %s"
1824 "How property key/value pairs should be formatted by `indent-line'.
1825 When `indent-line' hits a property definition, it will format the line
1826 according to this format, mainly to make sure that the values are
1827 lined-up with respect to each other."
1828 :group 'org-properties
1829 :type 'string)
1831 (defcustom org-use-property-inheritance nil
1832 "Non-nil means, properties apply also for sublevels.
1834 This setting is chiefly used during property searches. Turning it on can
1835 cause significant overhead when doing a search, which is why it is not
1836 on by default.
1838 When nil, only the properties directly given in the current entry count.
1839 When t, every property is inherited. The value may also be a list of
1840 properties that should have inheritance, or a regular expression matching
1841 properties that should be inherited.
1843 However, note that some special properties use inheritance under special
1844 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1845 and the properties ending in \"_ALL\" when they are used as descriptor
1846 for valid values of a property.
1848 Note for programmers:
1849 When querying an entry with `org-entry-get', you can control if inheritance
1850 should be used. By default, `org-entry-get' looks only at the local
1851 properties. You can request inheritance by setting the inherit argument
1852 to t (to force inheritance) or to `selective' (to respect the setting
1853 in this variable)."
1854 :group 'org-properties
1855 :type '(choice
1856 (const :tag "Not" nil)
1857 (const :tag "Always" t)
1858 (repeat :tag "Specific properties" (string :tag "Property"))
1859 (regexp :tag "Properties matched by regexp")))
1861 (defun org-property-inherit-p (property)
1862 "Check if PROPERTY is one that should be inherited."
1863 (cond
1864 ((eq org-use-property-inheritance t) t)
1865 ((not org-use-property-inheritance) nil)
1866 ((stringp org-use-property-inheritance)
1867 (string-match org-use-property-inheritance property))
1868 ((listp org-use-property-inheritance)
1869 (member property org-use-property-inheritance))
1870 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1872 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1873 "The default column format, if no other format has been defined.
1874 This variable can be set on the per-file basis by inserting a line
1876 #+COLUMNS: %25ITEM ....."
1877 :group 'org-properties
1878 :type 'string)
1880 (defcustom org-columns-ellipses ".."
1881 "The ellipses to be used when a field in column view is truncated.
1882 When this is the empty string, as many characters as possible are shown,
1883 but then there will be no visual indication that the field has been truncated.
1884 When this is a string of length N, the last N characters of a truncated
1885 field are replaced by this string. If the column is narrower than the
1886 ellipses string, only part of the ellipses string will be shown."
1887 :group 'org-properties
1888 :type 'string)
1890 (defcustom org-columns-modify-value-for-display-function nil
1891 "Function that modifies values for display in column view.
1892 For example, it can be used to cut out a certain part from a time stamp.
1893 The function must take 2 argments:
1895 column-title The tite of the column (*not* the property name)
1896 value The value that should be modified.
1898 The function should return the value that should be displayed,
1899 or nil if the normal value should be used."
1900 :group 'org-properties
1901 :type 'function)
1903 (defcustom org-effort-property "Effort"
1904 "The property that is being used to keep track of effort estimates.
1905 Effort estimates given in this property need to have the format H:MM."
1906 :group 'org-properties
1907 :group 'org-progress
1908 :type '(string :tag "Property"))
1910 (defconst org-global-properties-fixed
1911 '(("VISIBILITY_ALL" . "folded children content all"))
1912 "List of property/value pairs that can be inherited by any entry.
1913 These are fixed values, for the preset properties.")
1916 (defcustom org-global-properties nil
1917 "List of property/value pairs that can be inherited by any entry.
1918 You can set buffer-local values for this by adding lines like
1920 #+PROPERTY: NAME VALUE"
1921 :group 'org-properties
1922 :type '(repeat
1923 (cons (string :tag "Property")
1924 (string :tag "Value"))))
1926 (defvar org-file-properties nil
1927 "List of property/value pairs that can be inherited by any entry.
1928 Valid for the current buffer.
1929 This variable is populated from #+PROPERTY lines.")
1930 (make-variable-buffer-local 'org-file-properties)
1932 (defgroup org-agenda nil
1933 "Options concerning agenda views in Org-mode."
1934 :tag "Org Agenda"
1935 :group 'org)
1937 (defvar org-category nil
1938 "Variable used by org files to set a category for agenda display.
1939 Such files should use a file variable to set it, for example
1941 # -*- mode: org; org-category: \"ELisp\"
1943 or contain a special line
1945 #+CATEGORY: ELisp
1947 If the file does not specify a category, then file's base name
1948 is used instead.")
1949 (make-variable-buffer-local 'org-category)
1950 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1952 (defcustom org-agenda-files nil
1953 "The files to be used for agenda display.
1954 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1955 \\[org-remove-file]. You can also use customize to edit the list.
1957 If an entry is a directory, all files in that directory that are matched by
1958 `org-agenda-file-regexp' will be part of the file list.
1960 If the value of the variable is not a list but a single file name, then
1961 the list of agenda files is actually stored and maintained in that file, one
1962 agenda file per line."
1963 :group 'org-agenda
1964 :type '(choice
1965 (repeat :tag "List of files and directories" file)
1966 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1968 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1969 "Regular expression to match files for `org-agenda-files'.
1970 If any element in the list in that variable contains a directory instead
1971 of a normal file, all files in that directory that are matched by this
1972 regular expression will be included."
1973 :group 'org-agenda
1974 :type 'regexp)
1976 (defcustom org-agenda-text-search-extra-files nil
1977 "List of extra files to be searched by text search commands.
1978 These files will be search in addition to the agenda files by the
1979 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1980 Note that these files will only be searched for text search commands,
1981 not for the other agenda views like todo lists, tag searches or the weekly
1982 agenda. This variable is intended to list notes and possibly archive files
1983 that should also be searched by these two commands.
1984 In fact, if the first element in the list is the symbol `agenda-archives',
1985 than all archive files of all agenda files will be added to the search
1986 scope."
1987 :group 'org-agenda
1988 :type '(set :greedy t
1989 (const :tag "Agenda Archives" agenda-archives)
1990 (repeat :inline t (file))))
1992 (if (fboundp 'defvaralias)
1993 (defvaralias 'org-agenda-multi-occur-extra-files
1994 'org-agenda-text-search-extra-files))
1996 (defcustom org-agenda-skip-unavailable-files nil
1997 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
1998 A nil value means to remove them, after a query, from the list."
1999 :group 'org-agenda
2000 :type 'boolean)
2002 (defcustom org-calendar-to-agenda-key [?c]
2003 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2004 The command `org-calendar-goto-agenda' will be bound to this key. The
2005 default is the character `c' because then `c' can be used to switch back and
2006 forth between agenda and calendar."
2007 :group 'org-agenda
2008 :type 'sexp)
2010 (defcustom org-calendar-agenda-action-key [?k]
2011 "The key to be installed in `calendar-mode-map' for agenda-action.
2012 The command `org-agenda-action' will be bound to this key. The
2013 default is the character `k' because we use the same key in the agenda."
2014 :group 'org-agenda
2015 :type 'sexp)
2017 (eval-after-load "calendar"
2018 '(progn
2019 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2020 'org-calendar-goto-agenda)
2021 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2022 'org-agenda-action)))
2024 (defgroup org-latex nil
2025 "Options for embedding LaTeX code into Org-mode."
2026 :tag "Org LaTeX"
2027 :group 'org)
2029 (defcustom org-format-latex-options
2030 '(:foreground default :background default :scale 1.0
2031 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2032 :matchers ("begin" "$" "$$" "\\(" "\\["))
2033 "Options for creating images from LaTeX fragments.
2034 This is a property list with the following properties:
2035 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2036 `default' means use the foreground of the default face.
2037 :background the background color, or \"Transparent\".
2038 `default' means use the background of the default face.
2039 :scale a scaling factor for the size of the images.
2040 :html-foreground, :html-background, :html-scale
2041 the same numbers for HTML export.
2042 :matchers a list indicating which matchers should be used to
2043 find LaTeX fragments. Valid members of this list are:
2044 \"begin\" find environments
2045 \"$\" find math expressions surrounded by $...$
2046 \"$$\" find math expressions surrounded by $$....$$
2047 \"\\(\" find math expressions surrounded by \\(...\\)
2048 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2049 :group 'org-latex
2050 :type 'plist)
2052 (defcustom org-format-latex-header "\\documentclass{article}
2053 \\usepackage{fullpage} % do not remove
2054 \\usepackage{amssymb}
2055 \\usepackage[usenames]{color}
2056 \\usepackage{amsmath}
2057 \\usepackage{latexsym}
2058 \\usepackage[mathscr]{eucal}
2059 \\pagestyle{empty} % do not remove"
2060 "The document header used for processing LaTeX fragments."
2061 :group 'org-latex
2062 :type 'string)
2065 (defgroup org-font-lock nil
2066 "Font-lock settings for highlighting in Org-mode."
2067 :tag "Org Font Lock"
2068 :group 'org)
2070 (defcustom org-level-color-stars-only nil
2071 "Non-nil means fontify only the stars in each headline.
2072 When nil, the entire headline is fontified.
2073 Changing it requires restart of `font-lock-mode' to become effective
2074 also in regions already fontified."
2075 :group 'org-font-lock
2076 :type 'boolean)
2078 (defcustom org-hide-leading-stars nil
2079 "Non-nil means, hide the first N-1 stars in a headline.
2080 This works by using the face `org-hide' for these stars. This
2081 face is white for a light background, and black for a dark
2082 background. You may have to customize the face `org-hide' to
2083 make this work.
2084 Changing it requires restart of `font-lock-mode' to become effective
2085 also in regions already fontified.
2086 You may also set this on a per-file basis by adding one of the following
2087 lines to the buffer:
2089 #+STARTUP: hidestars
2090 #+STARTUP: showstars"
2091 :group 'org-font-lock
2092 :type 'boolean)
2094 (defcustom org-fontify-done-headline nil
2095 "Non-nil means, change the face of a headline if it is marked DONE.
2096 Normally, only the TODO/DONE keyword indicates the state of a headline.
2097 When this is non-nil, the headline after the keyword is set to the
2098 `org-headline-done' as an additional indication."
2099 :group 'org-font-lock
2100 :type 'boolean)
2102 (defcustom org-fontify-emphasized-text t
2103 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2104 Changing this variable requires a restart of Emacs to take effect."
2105 :group 'org-font-lock
2106 :type 'boolean)
2108 (defcustom org-highlight-latex-fragments-and-specials nil
2109 "Non-nil means, fontify what is treated specially by the exporters."
2110 :group 'org-font-lock
2111 :type 'boolean)
2113 (defcustom org-hide-emphasis-markers nil
2114 "Non-nil mean font-lock should hide the emphasis marker characters."
2115 :group 'org-font-lock
2116 :type 'boolean)
2118 (defvar org-emph-re nil
2119 "Regular expression for matching emphasis.")
2120 (defvar org-verbatim-re nil
2121 "Regular expression for matching verbatim text.")
2122 (defvar org-emphasis-regexp-components) ; defined just below
2123 (defvar org-emphasis-alist) ; defined just below
2124 (defun org-set-emph-re (var val)
2125 "Set variable and compute the emphasis regular expression."
2126 (set var val)
2127 (when (and (boundp 'org-emphasis-alist)
2128 (boundp 'org-emphasis-regexp-components)
2129 org-emphasis-alist org-emphasis-regexp-components)
2130 (let* ((e org-emphasis-regexp-components)
2131 (pre (car e))
2132 (post (nth 1 e))
2133 (border (nth 2 e))
2134 (body (nth 3 e))
2135 (nl (nth 4 e))
2136 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2137 (body1 (concat body "*?"))
2138 (markers (mapconcat 'car org-emphasis-alist ""))
2139 (vmarkers (mapconcat
2140 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2141 org-emphasis-alist "")))
2142 ;; make sure special characters appear at the right position in the class
2143 (if (string-match "\\^" markers)
2144 (setq markers (concat (replace-match "" t t markers) "^")))
2145 (if (string-match "-" markers)
2146 (setq markers (concat (replace-match "" t t markers) "-")))
2147 (if (string-match "\\^" vmarkers)
2148 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2149 (if (string-match "-" vmarkers)
2150 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2151 (if (> nl 0)
2152 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2153 (int-to-string nl) "\\}")))
2154 ;; Make the regexp
2155 (setq org-emph-re
2156 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2157 "\\("
2158 "\\([" markers "]\\)"
2159 "\\("
2160 "[^" border "]\\|"
2161 "[^" border (if (and nil stacked) markers) "]"
2162 body1
2163 "[^" border (if (and nil stacked) markers) "]"
2164 "\\)"
2165 "\\3\\)"
2166 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2167 (setq org-verbatim-re
2168 (concat "\\([" pre "]\\|^\\)"
2169 "\\("
2170 "\\([" vmarkers "]\\)"
2171 "\\("
2172 "[^" border "]\\|"
2173 "[^" border "]"
2174 body1
2175 "[^" border "]"
2176 "\\)"
2177 "\\3\\)"
2178 "\\([" post "]\\|$\\)")))))
2180 (defcustom org-emphasis-regexp-components
2181 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2182 "Components used to build the regular expression for emphasis.
2183 This is a list with 6 entries. Terminology: In an emphasis string
2184 like \" *strong word* \", we call the initial space PREMATCH, the final
2185 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2186 and \"trong wor\" is the body. The different components in this variable
2187 specify what is allowed/forbidden in each part:
2189 pre Chars allowed as prematch. Beginning of line will be allowed too.
2190 post Chars allowed as postmatch. End of line will be allowed too.
2191 border The chars *forbidden* as border characters.
2192 body-regexp A regexp like \".\" to match a body character. Don't use
2193 non-shy groups here, and don't allow newline here.
2194 newline The maximum number of newlines allowed in an emphasis exp.
2196 Use customize to modify this, or restart Emacs after changing it."
2197 :group 'org-font-lock
2198 :set 'org-set-emph-re
2199 :type '(list
2200 (sexp :tag "Allowed chars in pre ")
2201 (sexp :tag "Allowed chars in post ")
2202 (sexp :tag "Forbidden chars in border ")
2203 (sexp :tag "Regexp for body ")
2204 (integer :tag "number of newlines allowed")
2205 (option (boolean :tag "Please ignore this button"))))
2207 (defcustom org-emphasis-alist
2208 `(("*" bold "<b>" "</b>")
2209 ("/" italic "<i>" "</i>")
2210 ("_" underline "<u>" "</u>")
2211 ("=" org-code "<code>" "</code>" verbatim)
2212 ("~" org-verbatim "" "" verbatim)
2213 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2214 "<del>" "</del>")
2216 "Special syntax for emphasized text.
2217 Text starting and ending with a special character will be emphasized, for
2218 example *bold*, _underlined_ and /italic/. This variable sets the marker
2219 characters, the face to be used by font-lock for highlighting in Org-mode
2220 Emacs buffers, and the HTML tags to be used for this.
2221 Use customize to modify this, or restart Emacs after changing it."
2222 :group 'org-font-lock
2223 :set 'org-set-emph-re
2224 :type '(repeat
2225 (list
2226 (string :tag "Marker character")
2227 (choice
2228 (face :tag "Font-lock-face")
2229 (plist :tag "Face property list"))
2230 (string :tag "HTML start tag")
2231 (string :tag "HTML end tag")
2232 (option (const verbatim)))))
2234 ;;; Miscellaneous options
2236 (defgroup org-completion nil
2237 "Completion in Org-mode."
2238 :tag "Org Completion"
2239 :group 'org)
2241 (defcustom org-completion-fallback-command 'hippie-expand
2242 "The expansion command called by \\[org-complete] in normal context.
2243 Normal means, no org-mode-specific context."
2244 :group 'org-completion
2245 :type 'function)
2247 ;;; Functions and variables from ther packages
2248 ;; Declared here to avoid compiler warnings
2250 ;; XEmacs only
2251 (defvar outline-mode-menu-heading)
2252 (defvar outline-mode-menu-show)
2253 (defvar outline-mode-menu-hide)
2254 (defvar zmacs-regions) ; XEmacs regions
2256 ;; Emacs only
2257 (defvar mark-active)
2259 ;; Various packages
2260 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2261 (declare-function calendar-forward-day "cal-move" (arg))
2262 (declare-function calendar-goto-date "cal-move" (date))
2263 (declare-function calendar-goto-today "cal-move" ())
2264 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2265 (defvar calc-embedded-close-formula)
2266 (defvar calc-embedded-open-formula)
2267 (declare-function cdlatex-tab "ext:cdlatex" ())
2268 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2269 (defvar font-lock-unfontify-region-function)
2270 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2271 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2272 (defvar iswitchb-temp-buflist)
2273 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2274 (declare-function org-agenda-skip "org-agenda" ())
2275 (declare-function org-format-agenda-item "org-agenda"
2276 (extra txt &optional category tags dotime noprefix remove-re))
2277 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2278 (declare-function org-agenda-change-all-lines "org-agenda"
2279 (newhead hdmarker &optional fixface))
2280 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2281 (declare-function org-agenda-maybe-redo "org-agenda" ())
2282 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2283 (beg end))
2284 (declare-function parse-time-string "parse-time" (string))
2285 (declare-function remember "remember" (&optional initial))
2286 (declare-function remember-buffer-desc "remember" ())
2287 (declare-function remember-finalize "remember" ())
2288 (defvar remember-save-after-remembering)
2289 (defvar remember-data-file)
2290 (defvar remember-register)
2291 (defvar remember-buffer)
2292 (defvar remember-handler-functions)
2293 (defvar remember-annotation-functions)
2294 (defvar texmathp-why)
2295 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2296 (declare-function table--at-cell-p "table" (position &optional object at-column))
2298 (defvar w3m-current-url)
2299 (defvar w3m-current-title)
2301 (defvar org-latex-regexps)
2303 ;;; Autoload and prepare some org modules
2305 ;; Some table stuff that needs to be defined here, because it is used
2306 ;; by the functions setting up org-mode or checking for table context.
2308 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2309 "Detects an org-type or table-type table.")
2310 (defconst org-table-line-regexp "^[ \t]*|"
2311 "Detects an org-type table line.")
2312 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2313 "Detects an org-type table line.")
2314 (defconst org-table-hline-regexp "^[ \t]*|-"
2315 "Detects an org-type table hline.")
2316 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2317 "Detects a table-type table hline.")
2318 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2319 "Searching from within a table (any type) this finds the first line
2320 outside the table.")
2322 ;; Autoload the functions in org-table.el that are needed by functions here.
2324 (eval-and-compile
2325 (org-autoload "org-table"
2326 '(org-table-align org-table-begin org-table-blank-field
2327 org-table-convert org-table-convert-region org-table-copy-down
2328 org-table-copy-region org-table-create
2329 org-table-create-or-convert-from-region
2330 org-table-create-with-table.el org-table-current-dline
2331 org-table-cut-region org-table-delete-column org-table-edit-field
2332 org-table-edit-formulas org-table-end org-table-eval-formula
2333 org-table-export org-table-field-info
2334 org-table-get-stored-formulas org-table-goto-column
2335 org-table-hline-and-move org-table-import org-table-insert-column
2336 org-table-insert-hline org-table-insert-row org-table-iterate
2337 org-table-justify-field-maybe org-table-kill-row
2338 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2339 org-table-move-column org-table-move-column-left
2340 org-table-move-column-right org-table-move-row
2341 org-table-move-row-down org-table-move-row-up
2342 org-table-next-field org-table-next-row org-table-paste-rectangle
2343 org-table-previous-field org-table-recalculate
2344 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2345 org-table-toggle-coordinate-overlays
2346 org-table-toggle-formula-debugger org-table-wrap-region
2347 orgtbl-mode turn-on-orgtbl)))
2349 (defun org-at-table-p (&optional table-type)
2350 "Return t if the cursor is inside an org-type table.
2351 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2352 (if org-enable-table-editor
2353 (save-excursion
2354 (beginning-of-line 1)
2355 (looking-at (if table-type org-table-any-line-regexp
2356 org-table-line-regexp)))
2357 nil))
2358 (defsubst org-table-p () (org-at-table-p))
2360 (defun org-at-table.el-p ()
2361 "Return t if and only if we are at a table.el table."
2362 (and (org-at-table-p 'any)
2363 (save-excursion
2364 (goto-char (org-table-begin 'any))
2365 (looking-at org-table1-hline-regexp))))
2366 (defun org-table-recognize-table.el ()
2367 "If there is a table.el table nearby, recognize it and move into it."
2368 (if org-table-tab-recognizes-table.el
2369 (if (org-at-table.el-p)
2370 (progn
2371 (beginning-of-line 1)
2372 (if (looking-at org-table-dataline-regexp)
2374 (if (looking-at org-table1-hline-regexp)
2375 (progn
2376 (beginning-of-line 2)
2377 (if (looking-at org-table-any-border-regexp)
2378 (beginning-of-line -1)))))
2379 (if (re-search-forward "|" (org-table-end t) t)
2380 (progn
2381 (require 'table)
2382 (if (table--at-cell-p (point))
2384 (message "recognizing table.el table...")
2385 (table-recognize-table)
2386 (message "recognizing table.el table...done")))
2387 (error "This should not happen..."))
2389 nil)
2390 nil))
2392 (defun org-at-table-hline-p ()
2393 "Return t if the cursor is inside a hline in a table."
2394 (if org-enable-table-editor
2395 (save-excursion
2396 (beginning-of-line 1)
2397 (looking-at org-table-hline-regexp))
2398 nil))
2400 (defvar org-table-clean-did-remove-column nil)
2402 (defun org-table-map-tables (function)
2403 "Apply FUNCTION to the start of all tables in the buffer."
2404 (save-excursion
2405 (save-restriction
2406 (widen)
2407 (goto-char (point-min))
2408 (while (re-search-forward org-table-any-line-regexp nil t)
2409 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2410 (beginning-of-line 1)
2411 (if (looking-at org-table-line-regexp)
2412 (save-excursion (funcall function)))
2413 (re-search-forward org-table-any-border-regexp nil 1))))
2414 (message "Mapping tables: done"))
2416 ;; Declare and autoload functions from org-exp.el
2418 (declare-function org-default-export-plist "org-exp")
2419 (declare-function org-infile-export-plist "org-exp")
2420 (declare-function org-get-current-options "org-exp")
2421 (eval-and-compile
2422 (org-autoload "org-exp"
2423 '(org-export org-export-as-ascii org-export-visible
2424 org-insert-export-options-template org-export-as-html-and-open
2425 org-export-as-html-batch org-export-as-html-to-buffer
2426 org-replace-region-by-html org-export-region-as-html
2427 org-export-as-html org-export-icalendar-this-file
2428 org-export-icalendar-all-agenda-files
2429 org-table-clean-before-export
2430 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2432 ;; Declare and autoload functions from org-exp.el
2434 (eval-and-compile
2435 (org-autoload "org-exp"
2436 '(org-agenda org-agenda-list org-search-view
2437 org-todo-list org-tags-view org-agenda-list-stuck-projects
2438 org-diary org-agenda-to-appt)))
2440 ;; Autoload org-remember
2442 (eval-and-compile
2443 (org-autoload "org-remember"
2444 '(org-remember-insinuate org-remember-annotation
2445 org-remember-apply-template org-remember org-remember-handler)))
2447 ;; Autoload org-clock.el
2450 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2451 (beg end))
2452 (declare-function org-update-mode-line "org-clock" ())
2453 (defvar org-clock-start-time)
2454 (defvar org-clock-marker (make-marker)
2455 "Marker recording the last clock-in.")
2457 (eval-and-compile
2458 (org-autoload
2459 "org-clock"
2460 '(org-clock-in org-clock-out org-clock-cancel
2461 org-clock-goto org-clock-sum org-clock-display
2462 org-remove-clock-overlays org-clock-report
2463 org-clocktable-shift org-dblock-write:clocktable
2464 org-get-clocktable)))
2466 (defun org-clock-update-time-maybe ()
2467 "If this is a CLOCK line, update it and return t.
2468 Otherwise, return nil."
2469 (interactive)
2470 (save-excursion
2471 (beginning-of-line 1)
2472 (skip-chars-forward " \t")
2473 (when (looking-at org-clock-string)
2474 (let ((re (concat "[ \t]*" org-clock-string
2475 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2476 "\\([ \t]*=>.*\\)?\\)?"))
2477 ts te h m s)
2478 (cond
2479 ((not (looking-at re))
2480 nil)
2481 ((not (match-end 2))
2482 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2483 (> org-clock-marker (point))
2484 (<= org-clock-marker (point-at-eol)))
2485 ;; The clock is running here
2486 (setq org-clock-start-time
2487 (apply 'encode-time
2488 (org-parse-time-string (match-string 1))))
2489 (org-update-mode-line)))
2491 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2492 (end-of-line 1)
2493 (setq ts (match-string 1)
2494 te (match-string 3))
2495 (setq s (- (time-to-seconds
2496 (apply 'encode-time (org-parse-time-string te)))
2497 (time-to-seconds
2498 (apply 'encode-time (org-parse-time-string ts))))
2499 h (floor (/ s 3600))
2500 s (- s (* 3600 h))
2501 m (floor (/ s 60))
2502 s (- s (* 60 s)))
2503 (insert " => " (format "%2d:%02d" h m))
2504 t))))))
2506 (defun org-check-running-clock ()
2507 "Check if the current buffer contains the running clock.
2508 If yes, offer to stop it and to save the buffer with the changes."
2509 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2510 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2511 (buffer-name))))
2512 (org-clock-out)
2513 (when (y-or-n-p "Save changed buffer?")
2514 (save-buffer))))
2516 (defun org-clocktable-try-shift (dir n)
2517 "Check if this line starts a clock table, if yes, shift the time block."
2518 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2519 (org-clocktable-shift dir n)))
2521 ;; Autoload archiving code
2522 ;; The stuff that is needed for cycling and tags has to be defined here.
2524 (defgroup org-archive nil
2525 "Options concerning archiving in Org-mode."
2526 :tag "Org Archive"
2527 :group 'org-structure)
2529 (defcustom org-archive-location "%s_archive::"
2530 "The location where subtrees should be archived.
2532 Otherwise, the value of this variable is a string, consisting of two
2533 parts, separated by a double-colon.
2535 The first part is a file name - when omitted, archiving happens in the same
2536 file. %s will be replaced by the current file name (without directory part).
2537 Archiving to a different file is useful to keep archived entries from
2538 contributing to the Org-mode Agenda.
2540 The part after the double colon is a headline. The archived entries will be
2541 filed under that headline. When omitted, the subtrees are simply filed away
2542 at the end of the file, as top-level entries.
2544 Here are a few examples:
2545 \"%s_archive::\"
2546 If the current file is Projects.org, archive in file
2547 Projects.org_archive, as top-level trees. This is the default.
2549 \"::* Archived Tasks\"
2550 Archive in the current file, under the top-level headline
2551 \"* Archived Tasks\".
2553 \"~/org/archive.org::\"
2554 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2556 \"basement::** Finished Tasks\"
2557 Archive in file ./basement (relative path), as level 3 trees
2558 below the level 2 heading \"** Finished Tasks\".
2560 You may set this option on a per-file basis by adding to the buffer a
2561 line like
2563 #+ARCHIVE: basement::** Finished Tasks
2565 You may also define it locally for a subtree by setting an ARCHIVE property
2566 in the entry. If such a property is found in an entry, or anywhere up
2567 the hierarchy, it will be used."
2568 :group 'org-archive
2569 :type 'string)
2571 (defcustom org-archive-tag "ARCHIVE"
2572 "The tag that marks a subtree as archived.
2573 An archived subtree does not open during visibility cycling, and does
2574 not contribute to the agenda listings.
2575 After changing this, font-lock must be restarted in the relevant buffers to
2576 get the proper fontification."
2577 :group 'org-archive
2578 :group 'org-keywords
2579 :type 'string)
2581 (defcustom org-agenda-skip-archived-trees t
2582 "Non-nil means, the agenda will skip any items located in archived trees.
2583 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2584 variable is no longer recommended, you should leave it at the value t.
2585 Instead, use the key `v' to cycle the archives-mode in the agenda."
2586 :group 'org-archive
2587 :group 'org-agenda-skip
2588 :type 'boolean)
2590 (defcustom org-cycle-open-archived-trees nil
2591 "Non-nil means, `org-cycle' will open archived trees.
2592 An archived tree is a tree marked with the tag ARCHIVE.
2593 When nil, archived trees will stay folded. You can still open them with
2594 normal outline commands like `show-all', but not with the cycling commands."
2595 :group 'org-archive
2596 :group 'org-cycle
2597 :type 'boolean)
2599 (defcustom org-sparse-tree-open-archived-trees nil
2600 "Non-nil means sparse tree construction shows matches in archived trees.
2601 When nil, matches in these trees are highlighted, but the trees are kept in
2602 collapsed state."
2603 :group 'org-archive
2604 :group 'org-sparse-trees
2605 :type 'boolean)
2607 (defun org-cycle-hide-archived-subtrees (state)
2608 "Re-hide all archived subtrees after a visibility state change."
2609 (when (and (not org-cycle-open-archived-trees)
2610 (not (memq state '(overview folded))))
2611 (save-excursion
2612 (let* ((globalp (memq state '(contents all)))
2613 (beg (if globalp (point-min) (point)))
2614 (end (if globalp (point-max) (org-end-of-subtree t))))
2615 (org-hide-archived-subtrees beg end)
2616 (goto-char beg)
2617 (if (looking-at (concat ".*:" org-archive-tag ":"))
2618 (message "%s" (substitute-command-keys
2619 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2621 (defun org-force-cycle-archived ()
2622 "Cycle subtree even if it is archived."
2623 (interactive)
2624 (setq this-command 'org-cycle)
2625 (let ((org-cycle-open-archived-trees t))
2626 (call-interactively 'org-cycle)))
2628 (defun org-hide-archived-subtrees (beg end)
2629 "Re-hide all archived subtrees after a visibility state change."
2630 (save-excursion
2631 (let* ((re (concat ":" org-archive-tag ":")))
2632 (goto-char beg)
2633 (while (re-search-forward re end t)
2634 (and (org-on-heading-p) (hide-subtree))
2635 (org-end-of-subtree t)))))
2637 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2639 (eval-and-compile
2640 (org-autoload "org-archive"
2641 '(org-add-archive-files org-archive-subtree
2642 org-archive-to-archive-sibling org-toggle-archive-tag)))
2644 ;; Autoload Column View Code
2646 (declare-function org-columns-number-to-string "org-colview")
2647 (declare-function org-columns-get-format-and-top-level "org-colview")
2648 (declare-function org-columns-compute "org-colview")
2650 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2651 '(org-columns-number-to-string org-columns-get-format-and-top-level
2652 org-columns-compute org-agenda-columns org-columns-remove-overlays
2653 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2655 ;; Autoload ID code
2657 (org-autoload "org-id"
2658 '(org-id-get-create org-id-new org-id-copy org-id-get
2659 org-id-get-with-outline-path-completion
2660 org-id-get-with-outline-drilling
2661 org-id-goto org-id-find))
2663 ;;; Variables for pre-computed regular expressions, all buffer local
2665 (defvar org-drawer-regexp nil
2666 "Matches first line of a hidden block.")
2667 (make-variable-buffer-local 'org-drawer-regexp)
2668 (defvar org-todo-regexp nil
2669 "Matches any of the TODO state keywords.")
2670 (make-variable-buffer-local 'org-todo-regexp)
2671 (defvar org-not-done-regexp nil
2672 "Matches any of the TODO state keywords except the last one.")
2673 (make-variable-buffer-local 'org-not-done-regexp)
2674 (defvar org-todo-line-regexp nil
2675 "Matches a headline and puts TODO state into group 2 if present.")
2676 (make-variable-buffer-local 'org-todo-line-regexp)
2677 (defvar org-complex-heading-regexp nil
2678 "Matches a headline and puts everything into groups:
2679 group 1: the stars
2680 group 2: The todo keyword, maybe
2681 group 3: Priority cookie
2682 group 4: True headline
2683 group 5: Tags")
2684 (make-variable-buffer-local 'org-complex-heading-regexp)
2685 (defvar org-todo-line-tags-regexp nil
2686 "Matches a headline and puts TODO state into group 2 if present.
2687 Also put tags into group 4 if tags are present.")
2688 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2689 (defvar org-nl-done-regexp nil
2690 "Matches newline followed by a headline with the DONE keyword.")
2691 (make-variable-buffer-local 'org-nl-done-regexp)
2692 (defvar org-looking-at-done-regexp nil
2693 "Matches the DONE keyword a point.")
2694 (make-variable-buffer-local 'org-looking-at-done-regexp)
2695 (defvar org-ds-keyword-length 12
2696 "Maximum length of the Deadline and SCHEDULED keywords.")
2697 (make-variable-buffer-local 'org-ds-keyword-length)
2698 (defvar org-deadline-regexp nil
2699 "Matches the DEADLINE keyword.")
2700 (make-variable-buffer-local 'org-deadline-regexp)
2701 (defvar org-deadline-time-regexp nil
2702 "Matches the DEADLINE keyword together with a time stamp.")
2703 (make-variable-buffer-local 'org-deadline-time-regexp)
2704 (defvar org-deadline-line-regexp nil
2705 "Matches the DEADLINE keyword and the rest of the line.")
2706 (make-variable-buffer-local 'org-deadline-line-regexp)
2707 (defvar org-scheduled-regexp nil
2708 "Matches the SCHEDULED keyword.")
2709 (make-variable-buffer-local 'org-scheduled-regexp)
2710 (defvar org-scheduled-time-regexp nil
2711 "Matches the SCHEDULED keyword together with a time stamp.")
2712 (make-variable-buffer-local 'org-scheduled-time-regexp)
2713 (defvar org-closed-time-regexp nil
2714 "Matches the CLOSED keyword together with a time stamp.")
2715 (make-variable-buffer-local 'org-closed-time-regexp)
2717 (defvar org-keyword-time-regexp nil
2718 "Matches any of the 4 keywords, together with the time stamp.")
2719 (make-variable-buffer-local 'org-keyword-time-regexp)
2720 (defvar org-keyword-time-not-clock-regexp nil
2721 "Matches any of the 3 keywords, together with the time stamp.")
2722 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2723 (defvar org-maybe-keyword-time-regexp nil
2724 "Matches a timestamp, possibly preceeded by a keyword.")
2725 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2726 (defvar org-planning-or-clock-line-re nil
2727 "Matches a line with planning or clock info.")
2728 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2730 (defconst org-plain-time-of-day-regexp
2731 (concat
2732 "\\(\\<[012]?[0-9]"
2733 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2734 "\\(--?"
2735 "\\(\\<[012]?[0-9]"
2736 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2737 "\\)?")
2738 "Regular expression to match a plain time or time range.
2739 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2740 groups carry important information:
2741 0 the full match
2742 1 the first time, range or not
2743 8 the second time, if it is a range.")
2745 (defconst org-plain-time-extension-regexp
2746 (concat
2747 "\\(\\<[012]?[0-9]"
2748 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2749 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2750 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2751 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2752 groups carry important information:
2753 0 the full match
2754 7 hours of duration
2755 9 minutes of duration")
2757 (defconst org-stamp-time-of-day-regexp
2758 (concat
2759 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2760 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2761 "\\(--?"
2762 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2763 "Regular expression to match a timestamp time or time range.
2764 After a match, the following groups carry important information:
2765 0 the full match
2766 1 date plus weekday, for backreferencing to make sure both times on same day
2767 2 the first time, range or not
2768 4 the second time, if it is a range.")
2770 (defconst org-startup-options
2771 '(("fold" org-startup-folded t)
2772 ("overview" org-startup-folded t)
2773 ("nofold" org-startup-folded nil)
2774 ("showall" org-startup-folded nil)
2775 ("content" org-startup-folded content)
2776 ("hidestars" org-hide-leading-stars t)
2777 ("showstars" org-hide-leading-stars nil)
2778 ("odd" org-odd-levels-only t)
2779 ("oddeven" org-odd-levels-only nil)
2780 ("align" org-startup-align-all-tables t)
2781 ("noalign" org-startup-align-all-tables nil)
2782 ("customtime" org-display-custom-times t)
2783 ("logdone" org-log-done time)
2784 ("lognotedone" org-log-done note)
2785 ("nologdone" org-log-done nil)
2786 ("lognoteclock-out" org-log-note-clock-out t)
2787 ("nolognoteclock-out" org-log-note-clock-out nil)
2788 ("logrepeat" org-log-repeat state)
2789 ("lognoterepeat" org-log-repeat note)
2790 ("nologrepeat" org-log-repeat nil)
2791 ("constcgs" constants-unit-system cgs)
2792 ("constSI" constants-unit-system SI))
2793 "Variable associated with STARTUP options for org-mode.
2794 Each element is a list of three items: The startup options as written
2795 in the #+STARTUP line, the corresponding variable, and the value to
2796 set this variable to if the option is found. An optional forth element PUSH
2797 means to push this value onto the list in the variable.")
2799 (defun org-set-regexps-and-options ()
2800 "Precompute regular expressions for current buffer."
2801 (when (org-mode-p)
2802 (org-set-local 'org-todo-kwd-alist nil)
2803 (org-set-local 'org-todo-key-alist nil)
2804 (org-set-local 'org-todo-key-trigger nil)
2805 (org-set-local 'org-todo-keywords-1 nil)
2806 (org-set-local 'org-done-keywords nil)
2807 (org-set-local 'org-todo-heads nil)
2808 (org-set-local 'org-todo-sets nil)
2809 (org-set-local 'org-todo-log-states nil)
2810 (org-set-local 'org-file-properties nil)
2811 (org-set-local 'org-file-tags nil)
2812 (let ((re (org-make-options-regexp
2813 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2814 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2815 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2816 (splitre "[ \t]+")
2817 kwds kws0 kwsa key log value cat arch tags const links hw dws
2818 tail sep kws1 prio props ftags drawers
2819 ext-setup-or-nil setup-contents (start 0))
2820 (save-excursion
2821 (save-restriction
2822 (widen)
2823 (goto-char (point-min))
2824 (while (or (and ext-setup-or-nil
2825 (string-match re ext-setup-or-nil start)
2826 (setq start (match-end 0)))
2827 (and (setq ext-setup-or-nil nil start 0)
2828 (re-search-forward re nil t)))
2829 (setq key (upcase (match-string 1 ext-setup-or-nil))
2830 value (org-match-string-no-properties 2 ext-setup-or-nil))
2831 (cond
2832 ((equal key "CATEGORY")
2833 (if (string-match "[ \t]+$" value)
2834 (setq value (replace-match "" t t value)))
2835 (setq cat value))
2836 ((member key '("SEQ_TODO" "TODO"))
2837 (push (cons 'sequence (org-split-string value splitre)) kwds))
2838 ((equal key "TYP_TODO")
2839 (push (cons 'type (org-split-string value splitre)) kwds))
2840 ((equal key "TAGS")
2841 (setq tags (append tags (org-split-string value splitre))))
2842 ((equal key "COLUMNS")
2843 (org-set-local 'org-columns-default-format value))
2844 ((equal key "LINK")
2845 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2846 (push (cons (match-string 1 value)
2847 (org-trim (match-string 2 value)))
2848 links)))
2849 ((equal key "PRIORITIES")
2850 (setq prio (org-split-string value " +")))
2851 ((equal key "PROPERTY")
2852 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2853 (push (cons (match-string 1 value) (match-string 2 value))
2854 props)))
2855 ((equal key "FILETAGS")
2856 (when (string-match "\\S-" value)
2857 (setq ftags
2858 (append
2859 ftags
2860 (apply 'append
2861 (mapcar (lambda (x) (org-split-string x ":"))
2862 (org-split-string value)))))))
2863 ((equal key "DRAWERS")
2864 (setq drawers (org-split-string value splitre)))
2865 ((equal key "CONSTANTS")
2866 (setq const (append const (org-split-string value splitre))))
2867 ((equal key "STARTUP")
2868 (let ((opts (org-split-string value splitre))
2869 l var val)
2870 (while (setq l (pop opts))
2871 (when (setq l (assoc l org-startup-options))
2872 (setq var (nth 1 l) val (nth 2 l))
2873 (if (not (nth 3 l))
2874 (set (make-local-variable var) val)
2875 (if (not (listp (symbol-value var)))
2876 (set (make-local-variable var) nil))
2877 (set (make-local-variable var) (symbol-value var))
2878 (add-to-list var val))))))
2879 ((equal key "ARCHIVE")
2880 (string-match " *$" value)
2881 (setq arch (replace-match "" t t value))
2882 (remove-text-properties 0 (length arch)
2883 '(face t fontified t) arch))
2884 ((equal key "SETUPFILE")
2885 (setq setup-contents (org-file-contents
2886 (expand-file-name
2887 (org-remove-double-quotes value))
2888 'noerror))
2889 (if (not ext-setup-or-nil)
2890 (setq ext-setup-or-nil setup-contents start 0)
2891 (setq ext-setup-or-nil
2892 (concat (substring ext-setup-or-nil 0 start)
2893 "\n" setup-contents "\n"
2894 (substring ext-setup-or-nil start)))))
2895 ))))
2896 (when cat
2897 (org-set-local 'org-category (intern cat))
2898 (push (cons "CATEGORY" cat) props))
2899 (when prio
2900 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2901 (setq prio (mapcar 'string-to-char prio))
2902 (org-set-local 'org-highest-priority (nth 0 prio))
2903 (org-set-local 'org-lowest-priority (nth 1 prio))
2904 (org-set-local 'org-default-priority (nth 2 prio)))
2905 (and props (org-set-local 'org-file-properties (nreverse props)))
2906 (and ftags (org-set-local 'org-file-tags ftags))
2907 (and drawers (org-set-local 'org-drawers drawers))
2908 (and arch (org-set-local 'org-archive-location arch))
2909 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2910 ;; Process the TODO keywords
2911 (unless kwds
2912 ;; Use the global values as if they had been given locally.
2913 (setq kwds (default-value 'org-todo-keywords))
2914 (if (stringp (car kwds))
2915 (setq kwds (list (cons org-todo-interpretation
2916 (default-value 'org-todo-keywords)))))
2917 (setq kwds (reverse kwds)))
2918 (setq kwds (nreverse kwds))
2919 (let (inter kws kw)
2920 (while (setq kws (pop kwds))
2921 (setq inter (pop kws) sep (member "|" kws)
2922 kws0 (delete "|" (copy-sequence kws))
2923 kwsa nil
2924 kws1 (mapcar
2925 (lambda (x)
2926 ;; 1 2
2927 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2928 (progn
2929 (setq kw (match-string 1 x)
2930 key (and (match-end 2) (match-string 2 x))
2931 log (org-extract-log-state-settings x))
2932 (push (cons kw (and key (string-to-char key))) kwsa)
2933 (and log (push log org-todo-log-states))
2935 (error "Invalid TODO keyword %s" x)))
2936 kws0)
2937 kwsa (if kwsa (append '((:startgroup))
2938 (nreverse kwsa)
2939 '((:endgroup))))
2940 hw (car kws1)
2941 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2942 tail (list inter hw (car dws) (org-last dws)))
2943 (add-to-list 'org-todo-heads hw 'append)
2944 (push kws1 org-todo-sets)
2945 (setq org-done-keywords (append org-done-keywords dws nil))
2946 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2947 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2948 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2949 (setq org-todo-sets (nreverse org-todo-sets)
2950 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2951 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2952 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2953 ;; Process the constants
2954 (when const
2955 (let (e cst)
2956 (while (setq e (pop const))
2957 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2958 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2959 (setq org-table-formula-constants-local cst)))
2961 ;; Process the tags.
2962 (when tags
2963 (let (e tgs)
2964 (while (setq e (pop tags))
2965 (cond
2966 ((equal e "{") (push '(:startgroup) tgs))
2967 ((equal e "}") (push '(:endgroup) tgs))
2968 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2969 (push (cons (match-string 1 e)
2970 (string-to-char (match-string 2 e)))
2971 tgs))
2972 (t (push (list e) tgs))))
2973 (org-set-local 'org-tag-alist nil)
2974 (while (setq e (pop tgs))
2975 (or (and (stringp (car e))
2976 (assoc (car e) org-tag-alist))
2977 (push e org-tag-alist)))))
2979 ;; Compute the regular expressions and other local variables
2980 (if (not org-done-keywords)
2981 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2982 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2983 (length org-scheduled-string)
2984 (length org-clock-string)
2985 (length org-closed-string)))
2986 org-drawer-regexp
2987 (concat "^[ \t]*:\\("
2988 (mapconcat 'regexp-quote org-drawers "\\|")
2989 "\\):[ \t]*$")
2990 org-not-done-keywords
2991 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2992 org-todo-regexp
2993 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2994 "\\|") "\\)\\>")
2995 org-not-done-regexp
2996 (concat "\\<\\("
2997 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2998 "\\)\\>")
2999 org-todo-line-regexp
3000 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3001 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3002 "\\)\\>\\)?[ \t]*\\(.*\\)")
3003 org-complex-heading-regexp
3004 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3005 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3006 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3007 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3008 org-nl-done-regexp
3009 (concat "\n\\*+[ \t]+"
3010 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3011 "\\)" "\\>")
3012 org-todo-line-tags-regexp
3013 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3014 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3015 (org-re
3016 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3017 org-looking-at-done-regexp
3018 (concat "^" "\\(?:"
3019 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3020 "\\>")
3021 org-deadline-regexp (concat "\\<" org-deadline-string)
3022 org-deadline-time-regexp
3023 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3024 org-deadline-line-regexp
3025 (concat "\\<\\(" org-deadline-string "\\).*")
3026 org-scheduled-regexp
3027 (concat "\\<" org-scheduled-string)
3028 org-scheduled-time-regexp
3029 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3030 org-closed-time-regexp
3031 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3032 org-keyword-time-regexp
3033 (concat "\\<\\(" org-scheduled-string
3034 "\\|" org-deadline-string
3035 "\\|" org-closed-string
3036 "\\|" org-clock-string "\\)"
3037 " *[[<]\\([^]>]+\\)[]>]")
3038 org-keyword-time-not-clock-regexp
3039 (concat "\\<\\(" org-scheduled-string
3040 "\\|" org-deadline-string
3041 "\\|" org-closed-string
3042 "\\)"
3043 " *[[<]\\([^]>]+\\)[]>]")
3044 org-maybe-keyword-time-regexp
3045 (concat "\\(\\<\\(" org-scheduled-string
3046 "\\|" org-deadline-string
3047 "\\|" org-closed-string
3048 "\\|" org-clock-string "\\)\\)?"
3049 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3050 org-planning-or-clock-line-re
3051 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3052 "\\|" org-deadline-string
3053 "\\|" org-closed-string "\\|" org-clock-string
3054 "\\)\\>\\)")
3056 (org-compute-latex-and-specials-regexp)
3057 (org-set-font-lock-defaults))))
3059 (defun org-file-contents (file &optional noerror)
3060 "Return the contents of FILE, as a string."
3061 (if (or (not file)
3062 (not (file-readable-p file)))
3063 (if noerror
3064 (progn
3065 (message "Cannot read file %s" file)
3066 (ding) (sit-for 2)
3068 (error "Cannot read file %s" file))
3069 (with-temp-buffer
3070 (insert-file-contents file)
3071 (buffer-string))))
3073 (defun org-extract-log-state-settings (x)
3074 "Extract the log state setting from a TODO keyword string.
3075 This will extract info from a string like \"WAIT(w@/!)\"."
3076 (let (kw key log1 log2)
3077 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3078 (setq kw (match-string 1 x)
3079 key (and (match-end 2) (match-string 2 x))
3080 log1 (and (match-end 3) (match-string 3 x))
3081 log2 (and (match-end 4) (match-string 4 x)))
3082 (and (or log1 log2)
3083 (list kw
3084 (and log1 (if (equal log1 "!") 'time 'note))
3085 (and log2 (if (equal log2 "!") 'time 'note)))))))
3087 (defun org-remove-keyword-keys (list)
3088 "Remove a pair of parenthesis at the end of each string in LIST."
3089 (mapcar (lambda (x)
3090 (if (string-match "(.*)$" x)
3091 (substring x 0 (match-beginning 0))
3093 list))
3095 ;; FIXME: this could be done much better, using second characters etc.
3096 (defun org-assign-fast-keys (alist)
3097 "Assign fast keys to a keyword-key alist.
3098 Respect keys that are already there."
3099 (let (new e k c c1 c2 (char ?a))
3100 (while (setq e (pop alist))
3101 (cond
3102 ((equal e '(:startgroup)) (push e new))
3103 ((equal e '(:endgroup)) (push e new))
3105 (setq k (car e) c2 nil)
3106 (if (cdr e)
3107 (setq c (cdr e))
3108 ;; automatically assign a character.
3109 (setq c1 (string-to-char
3110 (downcase (substring
3111 k (if (= (string-to-char k) ?@) 1 0)))))
3112 (if (or (rassoc c1 new) (rassoc c1 alist))
3113 (while (or (rassoc char new) (rassoc char alist))
3114 (setq char (1+ char)))
3115 (setq c2 c1))
3116 (setq c (or c2 char)))
3117 (push (cons k c) new))))
3118 (nreverse new)))
3120 ;;; Some variables used in various places
3122 (defvar org-window-configuration nil
3123 "Used in various places to store a window configuration.")
3124 (defvar org-finish-function nil
3125 "Function to be called when `C-c C-c' is used.
3126 This is for getting out of special buffers like remember.")
3129 ;; FIXME: Occasionally check by commenting these, to make sure
3130 ;; no other functions uses these, forgetting to let-bind them.
3131 (defvar entry)
3132 (defvar state)
3133 (defvar last-state)
3134 (defvar date)
3135 (defvar description)
3137 ;; Defined somewhere in this file, but used before definition.
3138 (defvar org-html-entities)
3139 (defvar org-struct-menu)
3140 (defvar org-org-menu)
3141 (defvar org-tbl-menu)
3142 (defvar org-agenda-keymap)
3144 ;;;; Define the Org-mode
3146 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3147 (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."))
3150 ;; We use a before-change function to check if a table might need
3151 ;; an update.
3152 (defvar org-table-may-need-update t
3153 "Indicates that a table might need an update.
3154 This variable is set by `org-before-change-function'.
3155 `org-table-align' sets it back to nil.")
3156 (defun org-before-change-function (beg end)
3157 "Every change indicates that a table might need an update."
3158 (setq org-table-may-need-update t))
3159 (defvar org-mode-map)
3160 (defvar org-mode-hook nil)
3161 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3162 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3163 (defvar org-table-buffer-is-an nil)
3164 (defconst org-outline-regexp "\\*+ ")
3166 ;;;###autoload
3167 (define-derived-mode org-mode outline-mode "Org"
3168 "Outline-based notes management and organizer, alias
3169 \"Carsten's outline-mode for keeping track of everything.\"
3171 Org-mode develops organizational tasks around a NOTES file which
3172 contains information about projects as plain text. Org-mode is
3173 implemented on top of outline-mode, which is ideal to keep the content
3174 of large files well structured. It supports ToDo items, deadlines and
3175 time stamps, which magically appear in the diary listing of the Emacs
3176 calendar. Tables are easily created with a built-in table editor.
3177 Plain text URL-like links connect to websites, emails (VM), Usenet
3178 messages (Gnus), BBDB entries, and any files related to the project.
3179 For printing and sharing of notes, an Org-mode file (or a part of it)
3180 can be exported as a structured ASCII or HTML file.
3182 The following commands are available:
3184 \\{org-mode-map}"
3186 ;; Get rid of Outline menus, they are not needed
3187 ;; Need to do this here because define-derived-mode sets up
3188 ;; the keymap so late. Still, it is a waste to call this each time
3189 ;; we switch another buffer into org-mode.
3190 (if (featurep 'xemacs)
3191 (when (boundp 'outline-mode-menu-heading)
3192 ;; Assume this is Greg's port, it used easymenu
3193 (easy-menu-remove outline-mode-menu-heading)
3194 (easy-menu-remove outline-mode-menu-show)
3195 (easy-menu-remove outline-mode-menu-hide))
3196 (define-key org-mode-map [menu-bar headings] 'undefined)
3197 (define-key org-mode-map [menu-bar hide] 'undefined)
3198 (define-key org-mode-map [menu-bar show] 'undefined))
3200 (org-load-modules-maybe)
3201 (easy-menu-add org-org-menu)
3202 (easy-menu-add org-tbl-menu)
3203 (org-install-agenda-files-menu)
3204 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3205 (org-add-to-invisibility-spec '(org-cwidth))
3206 (when (featurep 'xemacs)
3207 (org-set-local 'line-move-ignore-invisible t))
3208 (org-set-local 'outline-regexp org-outline-regexp)
3209 (org-set-local 'outline-level 'org-outline-level)
3210 (when (and org-ellipsis
3211 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3212 (fboundp 'make-glyph-code))
3213 (unless org-display-table
3214 (setq org-display-table (make-display-table)))
3215 (set-display-table-slot
3216 org-display-table 4
3217 (vconcat (mapcar
3218 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3219 org-ellipsis)))
3220 (if (stringp org-ellipsis) org-ellipsis "..."))))
3221 (setq buffer-display-table org-display-table))
3222 (org-set-regexps-and-options)
3223 ;; Calc embedded
3224 (org-set-local 'calc-embedded-open-mode "# ")
3225 (modify-syntax-entry ?# "<")
3226 (modify-syntax-entry ?@ "w")
3227 (if org-startup-truncated (setq truncate-lines t))
3228 (org-set-local 'font-lock-unfontify-region-function
3229 'org-unfontify-region)
3230 ;; Activate before-change-function
3231 (org-set-local 'org-table-may-need-update t)
3232 (org-add-hook 'before-change-functions 'org-before-change-function nil
3233 'local)
3234 ;; Check for running clock before killing a buffer
3235 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3236 ;; Paragraphs and auto-filling
3237 (org-set-autofill-regexps)
3238 (setq indent-line-function 'org-indent-line-function)
3239 (org-update-radio-target-regexp)
3241 ;; Comment characters
3242 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3243 (org-set-local 'comment-padding " ")
3245 ;; Align options lines
3246 (org-set-local
3247 'align-mode-rules-list
3248 '((org-in-buffer-settings
3249 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3250 (modes . '(org-mode)))))
3252 ;; Imenu
3253 (org-set-local 'imenu-create-index-function
3254 'org-imenu-get-tree)
3256 ;; Make isearch reveal context
3257 (if (or (featurep 'xemacs)
3258 (not (boundp 'outline-isearch-open-invisible-function)))
3259 ;; Emacs 21 and XEmacs make use of the hook
3260 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3261 ;; Emacs 22 deals with this through a special variable
3262 (org-set-local 'outline-isearch-open-invisible-function
3263 (lambda (&rest ignore) (org-show-context 'isearch))))
3265 ;; If empty file that did not turn on org-mode automatically, make it to.
3266 (if (and org-insert-mode-line-in-empty-file
3267 (interactive-p)
3268 (= (point-min) (point-max)))
3269 (insert "# -*- mode: org -*-\n\n"))
3271 (unless org-inhibit-startup
3272 (when org-startup-align-all-tables
3273 (let ((bmp (buffer-modified-p)))
3274 (org-table-map-tables 'org-table-align)
3275 (set-buffer-modified-p bmp)))
3276 (org-set-startup-visibility)))
3278 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3280 (defun org-current-time ()
3281 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3282 (if (> (car org-time-stamp-rounding-minutes) 1)
3283 (let ((r (car org-time-stamp-rounding-minutes))
3284 (time (decode-time)))
3285 (apply 'encode-time
3286 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3287 (nthcdr 2 time))))
3288 (current-time)))
3290 ;;;; Font-Lock stuff, including the activators
3292 (defvar org-mouse-map (make-sparse-keymap))
3293 (org-defkey org-mouse-map
3294 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3295 (org-defkey org-mouse-map
3296 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3297 (when org-mouse-1-follows-link
3298 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3299 (when org-tab-follows-link
3300 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3301 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3302 (when org-return-follows-link
3303 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3304 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3306 (require 'font-lock)
3308 (defconst org-non-link-chars "]\t\n\r<>")
3309 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3310 "shell" "elisp"))
3311 (defvar org-link-types-re nil
3312 "Matches a link that has a url-like prefix like \"http:\"")
3313 (defvar org-link-re-with-space nil
3314 "Matches a link with spaces, optional angular brackets around it.")
3315 (defvar org-link-re-with-space2 nil
3316 "Matches a link with spaces, optional angular brackets around it.")
3317 (defvar org-angle-link-re nil
3318 "Matches link with angular brackets, spaces are allowed.")
3319 (defvar org-plain-link-re nil
3320 "Matches plain link, without spaces.")
3321 (defvar org-bracket-link-regexp nil
3322 "Matches a link in double brackets.")
3323 (defvar org-bracket-link-analytic-regexp nil
3324 "Regular expression used to analyze links.
3325 Here is what the match groups contain after a match:
3326 1: http:
3327 2: http
3328 3: path
3329 4: [desc]
3330 5: desc")
3331 (defvar org-any-link-re nil
3332 "Regular expression matching any link.")
3334 (defun org-make-link-regexps ()
3335 "Update the link regular expressions.
3336 This should be called after the variable `org-link-types' has changed."
3337 (setq org-link-types-re
3338 (concat
3339 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3340 org-link-re-with-space
3341 (concat
3342 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3343 "\\([^" org-non-link-chars " ]"
3344 "[^" org-non-link-chars "]*"
3345 "[^" org-non-link-chars " ]\\)>?")
3346 org-link-re-with-space2
3347 (concat
3348 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3349 "\\([^" org-non-link-chars " ]"
3350 "[^]\t\n\r]*"
3351 "[^" org-non-link-chars " ]\\)>?")
3352 org-angle-link-re
3353 (concat
3354 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3355 "\\([^" org-non-link-chars " ]"
3356 "[^" org-non-link-chars "]*"
3357 "\\)>")
3358 org-plain-link-re
3359 (concat
3360 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3361 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3362 org-bracket-link-regexp
3363 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3364 org-bracket-link-analytic-regexp
3365 (concat
3366 "\\[\\["
3367 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3368 "\\([^]]+\\)"
3369 "\\]"
3370 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3371 "\\]")
3372 org-any-link-re
3373 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3374 org-angle-link-re "\\)\\|\\("
3375 org-plain-link-re "\\)")))
3377 (org-make-link-regexps)
3379 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3380 "Regular expression for fast time stamp matching.")
3381 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3382 "Regular expression for fast time stamp matching.")
3383 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3384 "Regular expression matching time strings for analysis.
3385 This one does not require the space after the date, so it can be used
3386 on a string that terminates immediately after the date.")
3387 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3388 "Regular expression matching time strings for analysis.")
3389 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3390 "Regular expression matching time stamps, with groups.")
3391 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3392 "Regular expression matching time stamps (also [..]), with groups.")
3393 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3394 "Regular expression matching a time stamp range.")
3395 (defconst org-tr-regexp-both
3396 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3397 "Regular expression matching a time stamp range.")
3398 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3399 org-ts-regexp "\\)?")
3400 "Regular expression matching a time stamp or time stamp range.")
3401 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3402 org-ts-regexp-both "\\)?")
3403 "Regular expression matching a time stamp or time stamp range.
3404 The time stamps may be either active or inactive.")
3406 (defvar org-emph-face nil)
3408 (defun org-do-emphasis-faces (limit)
3409 "Run through the buffer and add overlays to links."
3410 (let (rtn)
3411 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3412 (if (not (= (char-after (match-beginning 3))
3413 (char-after (match-beginning 4))))
3414 (progn
3415 (setq rtn t)
3416 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3417 'face
3418 (nth 1 (assoc (match-string 3)
3419 org-emphasis-alist)))
3420 (add-text-properties (match-beginning 2) (match-end 2)
3421 '(font-lock-multiline t))
3422 (when org-hide-emphasis-markers
3423 (add-text-properties (match-end 4) (match-beginning 5)
3424 '(invisible org-link))
3425 (add-text-properties (match-beginning 3) (match-end 3)
3426 '(invisible org-link)))))
3427 (backward-char 1))
3428 rtn))
3430 (defun org-emphasize (&optional char)
3431 "Insert or change an emphasis, i.e. a font like bold or italic.
3432 If there is an active region, change that region to a new emphasis.
3433 If there is no region, just insert the marker characters and position
3434 the cursor between them.
3435 CHAR should be either the marker character, or the first character of the
3436 HTML tag associated with that emphasis. If CHAR is a space, the means
3437 to remove the emphasis of the selected region.
3438 If char is not given (for example in an interactive call) it
3439 will be prompted for."
3440 (interactive)
3441 (let ((eal org-emphasis-alist) e det
3442 (erc org-emphasis-regexp-components)
3443 (prompt "")
3444 (string "") beg end move tag c s)
3445 (if (org-region-active-p)
3446 (setq beg (region-beginning) end (region-end)
3447 string (buffer-substring beg end))
3448 (setq move t))
3450 (while (setq e (pop eal))
3451 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3452 c (aref tag 0))
3453 (push (cons c (string-to-char (car e))) det)
3454 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3455 (substring tag 1)))))
3456 (unless char
3457 (message "%s" (concat "Emphasis marker or tag:" prompt))
3458 (setq char (read-char-exclusive)))
3459 (setq char (or (cdr (assoc char det)) char))
3460 (if (equal char ?\ )
3461 (setq s "" move nil)
3462 (unless (assoc (char-to-string char) org-emphasis-alist)
3463 (error "No such emphasis marker: \"%c\"" char))
3464 (setq s (char-to-string char)))
3465 (while (and (> (length string) 1)
3466 (equal (substring string 0 1) (substring string -1))
3467 (assoc (substring string 0 1) org-emphasis-alist))
3468 (setq string (substring string 1 -1)))
3469 (setq string (concat s string s))
3470 (if beg (delete-region beg end))
3471 (unless (or (bolp)
3472 (string-match (concat "[" (nth 0 erc) "\n]")
3473 (char-to-string (char-before (point)))))
3474 (insert " "))
3475 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3476 (char-to-string (char-after (point))))
3477 (insert " ") (backward-char 1))
3478 (insert string)
3479 (and move (backward-char 1))))
3481 (defconst org-nonsticky-props
3482 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3485 (defun org-activate-plain-links (limit)
3486 "Run through the buffer and add overlays to links."
3487 (catch 'exit
3488 (let (f)
3489 (while (re-search-forward org-plain-link-re limit t)
3490 (setq f (get-text-property (match-beginning 0) 'face))
3491 (if (or (eq f 'org-tag)
3492 (and (listp f) (memq 'org-tag f)))
3494 (add-text-properties (match-beginning 0) (match-end 0)
3495 (list 'mouse-face 'highlight
3496 'rear-nonsticky org-nonsticky-props
3497 'keymap org-mouse-map
3499 (throw 'exit t))))))
3501 (defun org-activate-code (limit)
3502 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3503 (unless (get-text-property (match-beginning 1) 'face)
3504 (remove-text-properties (match-beginning 0) (match-end 0)
3505 '(display t invisible t intangible t))
3506 t)))
3508 (defun org-activate-angle-links (limit)
3509 "Run through the buffer and add overlays to links."
3510 (if (re-search-forward org-angle-link-re limit t)
3511 (progn
3512 (add-text-properties (match-beginning 0) (match-end 0)
3513 (list 'mouse-face 'highlight
3514 'rear-nonsticky org-nonsticky-props
3515 'keymap org-mouse-map
3517 t)))
3519 (defun org-activate-bracket-links (limit)
3520 "Run through the buffer and add overlays to bracketed links."
3521 (if (re-search-forward org-bracket-link-regexp limit t)
3522 (let* ((help (concat "LINK: "
3523 (org-match-string-no-properties 1)))
3524 ;; FIXME: above we should remove the escapes.
3525 ;; but that requires another match, protecting match data,
3526 ;; a lot of overhead for font-lock.
3527 (ip (org-maybe-intangible
3528 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3529 'keymap org-mouse-map 'mouse-face 'highlight
3530 'font-lock-multiline t 'help-echo help)))
3531 (vp (list 'rear-nonsticky org-nonsticky-props
3532 'keymap org-mouse-map 'mouse-face 'highlight
3533 ' font-lock-multiline t 'help-echo help)))
3534 ;; We need to remove the invisible property here. Table narrowing
3535 ;; may have made some of this invisible.
3536 (remove-text-properties (match-beginning 0) (match-end 0)
3537 '(invisible nil))
3538 (if (match-end 3)
3539 (progn
3540 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3541 (add-text-properties (match-beginning 3) (match-end 3) vp)
3542 (add-text-properties (match-end 3) (match-end 0) ip))
3543 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3544 (add-text-properties (match-beginning 1) (match-end 1) vp)
3545 (add-text-properties (match-end 1) (match-end 0) ip))
3546 t)))
3548 (defun org-activate-dates (limit)
3549 "Run through the buffer and add overlays to dates."
3550 (if (re-search-forward org-tsr-regexp-both limit t)
3551 (progn
3552 (add-text-properties (match-beginning 0) (match-end 0)
3553 (list 'mouse-face 'highlight
3554 'rear-nonsticky org-nonsticky-props
3555 'keymap org-mouse-map))
3556 (when org-display-custom-times
3557 (if (match-end 3)
3558 (org-display-custom-time (match-beginning 3) (match-end 3)))
3559 (org-display-custom-time (match-beginning 1) (match-end 1)))
3560 t)))
3562 (defvar org-target-link-regexp nil
3563 "Regular expression matching radio targets in plain text.")
3564 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3565 "Regular expression matching a link target.")
3566 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3567 "Regular expression matching a radio target.")
3568 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3569 "Regular expression matching any target.")
3571 (defun org-activate-target-links (limit)
3572 "Run through the buffer and add overlays to target matches."
3573 (when org-target-link-regexp
3574 (let ((case-fold-search t))
3575 (if (re-search-forward org-target-link-regexp limit t)
3576 (progn
3577 (add-text-properties (match-beginning 0) (match-end 0)
3578 (list 'mouse-face 'highlight
3579 'rear-nonsticky org-nonsticky-props
3580 'keymap org-mouse-map
3581 'help-echo "Radio target link"
3582 'org-linked-text t))
3583 t)))))
3585 (defun org-update-radio-target-regexp ()
3586 "Find all radio targets in this file and update the regular expression."
3587 (interactive)
3588 (when (memq 'radio org-activate-links)
3589 (setq org-target-link-regexp
3590 (org-make-target-link-regexp (org-all-targets 'radio)))
3591 (org-restart-font-lock)))
3593 (defun org-hide-wide-columns (limit)
3594 (let (s e)
3595 (setq s (text-property-any (point) (or limit (point-max))
3596 'org-cwidth t))
3597 (when s
3598 (setq e (next-single-property-change s 'org-cwidth))
3599 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3600 (goto-char e)
3601 t)))
3603 (defvar org-latex-and-specials-regexp nil
3604 "Regular expression for highlighting export special stuff.")
3605 (defvar org-match-substring-regexp)
3606 (defvar org-match-substring-with-braces-regexp)
3607 (defvar org-export-html-special-string-regexps)
3609 (defun org-compute-latex-and-specials-regexp ()
3610 "Compute regular expression for stuff treated specially by exporters."
3611 (if (not org-highlight-latex-fragments-and-specials)
3612 (org-set-local 'org-latex-and-specials-regexp nil)
3613 (require 'org-exp)
3614 (let*
3615 ((matchers (plist-get org-format-latex-options :matchers))
3616 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3617 org-latex-regexps)))
3618 (options (org-combine-plists (org-default-export-plist)
3619 (org-infile-export-plist)))
3620 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3621 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3622 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3623 (org-export-html-expand (plist-get options :expand-quoted-html))
3624 (org-export-with-special-strings (plist-get options :special-strings))
3625 (re-sub
3626 (cond
3627 ((equal org-export-with-sub-superscripts '{})
3628 (list org-match-substring-with-braces-regexp))
3629 (org-export-with-sub-superscripts
3630 (list org-match-substring-regexp))
3631 (t nil)))
3632 (re-latex
3633 (if org-export-with-LaTeX-fragments
3634 (mapcar (lambda (x) (nth 1 x)) latexs)))
3635 (re-macros
3636 (if org-export-with-TeX-macros
3637 (list (concat "\\\\"
3638 (regexp-opt
3639 (append (mapcar 'car org-html-entities)
3640 (if (boundp 'org-latex-entities)
3641 org-latex-entities nil))
3642 'words))) ; FIXME
3644 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3645 (re-special (if org-export-with-special-strings
3646 (mapcar (lambda (x) (car x))
3647 org-export-html-special-string-regexps)))
3648 (re-rest
3649 (delq nil
3650 (list
3651 (if org-export-html-expand "@<[^>\n]+>")
3652 ))))
3653 (org-set-local
3654 'org-latex-and-specials-regexp
3655 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3656 re-rest) "\\|")))))
3658 (defun org-do-latex-and-special-faces (limit)
3659 "Run through the buffer and add overlays to links."
3660 (when org-latex-and-specials-regexp
3661 (let (rtn d)
3662 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3663 limit t))
3664 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3665 'face))
3666 '(org-code org-verbatim underline)))
3667 (progn
3668 (setq rtn t
3669 d (cond ((member (char-after (1+ (match-beginning 0)))
3670 '(?_ ?^)) 1)
3671 (t 0)))
3672 (font-lock-prepend-text-property
3673 (+ d (match-beginning 0)) (match-end 0)
3674 'face 'org-latex-and-export-specials)
3675 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3676 '(font-lock-multiline t)))))
3677 rtn)))
3679 (defun org-restart-font-lock ()
3680 "Restart font-lock-mode, to force refontification."
3681 (when (and (boundp 'font-lock-mode) font-lock-mode)
3682 (font-lock-mode -1)
3683 (font-lock-mode 1)))
3685 (defun org-all-targets (&optional radio)
3686 "Return a list of all targets in this file.
3687 With optional argument RADIO, only find radio targets."
3688 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3689 rtn)
3690 (save-excursion
3691 (goto-char (point-min))
3692 (while (re-search-forward re nil t)
3693 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3694 rtn)))
3696 (defun org-make-target-link-regexp (targets)
3697 "Make regular expression matching all strings in TARGETS.
3698 The regular expression finds the targets also if there is a line break
3699 between words."
3700 (and targets
3701 (concat
3702 "\\<\\("
3703 (mapconcat
3704 (lambda (x)
3705 (while (string-match " +" x)
3706 (setq x (replace-match "\\s-+" t t x)))
3708 targets
3709 "\\|")
3710 "\\)\\>")))
3712 (defun org-activate-tags (limit)
3713 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3714 (progn
3715 (add-text-properties (match-beginning 1) (match-end 1)
3716 (list 'mouse-face 'highlight
3717 'rear-nonsticky org-nonsticky-props
3718 'keymap org-mouse-map))
3719 t)))
3721 (defun org-outline-level ()
3722 (save-excursion
3723 (looking-at outline-regexp)
3724 (if (match-beginning 1)
3725 (+ (org-get-string-indentation (match-string 1)) 1000)
3726 (1- (- (match-end 0) (match-beginning 0))))))
3728 (defvar org-font-lock-keywords nil)
3730 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3731 "Regular expression matching a property line.")
3733 (defvar org-font-lock-hook nil
3734 "Functions to be called for special font lock stuff.")
3736 (defun org-font-lock-hook (limit)
3737 (run-hook-with-args 'org-font-lock-hook limit))
3739 (defun org-set-font-lock-defaults ()
3740 (let* ((em org-fontify-emphasized-text)
3741 (lk org-activate-links)
3742 (org-font-lock-extra-keywords
3743 (list
3744 ;; Call the hook
3745 '(org-font-lock-hook)
3746 ;; Headlines
3747 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3748 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3749 ;; Table lines
3750 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3751 (1 'org-table t))
3752 ;; Table internals
3753 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3754 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3755 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3756 ;; Drawers
3757 (list org-drawer-regexp '(0 'org-special-keyword t))
3758 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3759 ;; Properties
3760 (list org-property-re
3761 '(1 'org-special-keyword t)
3762 '(3 'org-property-value t))
3763 (if org-format-transports-properties-p
3764 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3765 ;; Links
3766 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3767 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3768 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3769 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3770 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3771 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3772 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3773 '(org-hide-wide-columns (0 nil append))
3774 ;; TODO lines
3775 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3776 '(1 (org-get-todo-face 1) t))
3777 ;; DONE
3778 (if org-fontify-done-headline
3779 (list (concat "^[*]+ +\\<\\("
3780 (mapconcat 'regexp-quote org-done-keywords "\\|")
3781 "\\)\\(.*\\)")
3782 '(2 'org-headline-done t))
3783 nil)
3784 ;; Priorities
3785 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3786 ;; Special keywords
3787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3790 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3791 ;; Emphasis
3792 (if em
3793 (if (featurep 'xemacs)
3794 '(org-do-emphasis-faces (0 nil append))
3795 '(org-do-emphasis-faces)))
3796 ;; Checkboxes
3797 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3798 2 'bold prepend)
3799 (if org-provide-checkbox-statistics
3800 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3801 (0 (org-get-checkbox-statistics-face) t)))
3802 ;; Description list items
3803 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3804 2 'bold prepend)
3805 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3806 '(1 'org-archived prepend))
3807 ;; Specials
3808 '(org-do-latex-and-special-faces)
3809 ;; Code
3810 '(org-activate-code (1 'org-code t))
3811 ;; COMMENT
3812 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3813 "\\|" org-quote-string "\\)\\>")
3814 '(1 'org-special-keyword t))
3815 '("^#.*" (0 'font-lock-comment-face t))
3817 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3818 ;; Now set the full font-lock-keywords
3819 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3820 (org-set-local 'font-lock-defaults
3821 '(org-font-lock-keywords t nil nil backward-paragraph))
3822 (kill-local-variable 'font-lock-keywords) nil))
3824 (defvar org-m nil)
3825 (defvar org-l nil)
3826 (defvar org-f nil)
3827 (defun org-get-level-face (n)
3828 "Get the right face for match N in font-lock matching of healdines."
3829 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3830 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3831 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3832 (cond
3833 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3834 ((eq n 2) org-f)
3835 (t (if org-level-color-stars-only nil org-f))))
3837 (defun org-get-todo-face (kwd)
3838 "Get the right face for a TODO keyword KWD.
3839 If KWD is a number, get the corresponding match group."
3840 (if (numberp kwd) (setq kwd (match-string kwd)))
3841 (or (cdr (assoc kwd org-todo-keyword-faces))
3842 (and (member kwd org-done-keywords) 'org-done)
3843 'org-todo))
3845 (defun org-unfontify-region (beg end &optional maybe_loudly)
3846 "Remove fontification and activation overlays from links."
3847 (font-lock-default-unfontify-region beg end)
3848 (let* ((buffer-undo-list t)
3849 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3850 (inhibit-modification-hooks t)
3851 deactivate-mark buffer-file-name buffer-file-truename)
3852 (remove-text-properties beg end
3853 '(mouse-face t keymap t org-linked-text t
3854 invisible t intangible t))))
3856 ;;;; Visibility cycling, including org-goto and indirect buffer
3858 ;;; Cycling
3860 (defvar org-cycle-global-status nil)
3861 (make-variable-buffer-local 'org-cycle-global-status)
3862 (defvar org-cycle-subtree-status nil)
3863 (make-variable-buffer-local 'org-cycle-subtree-status)
3865 ;;;###autoload
3866 (defun org-cycle (&optional arg)
3867 "Visibility cycling for Org-mode.
3869 - When this function is called with a prefix argument, rotate the entire
3870 buffer through 3 states (global cycling)
3871 1. OVERVIEW: Show only top-level headlines.
3872 2. CONTENTS: Show all headlines of all levels, but no body text.
3873 3. SHOW ALL: Show everything.
3874 When called with two C-c C-u prefixes, switch to the startup visibility,
3875 determined by the variable `org-startup-folded', and by any VISIBILITY
3876 properties in the buffer.
3878 - When point is at the beginning of a headline, rotate the subtree started
3879 by this line through 3 different states (local cycling)
3880 1. FOLDED: Only the main headline is shown.
3881 2. CHILDREN: The main headline and the direct children are shown.
3882 From this state, you can move to one of the children
3883 and zoom in further.
3884 3. SUBTREE: Show the entire subtree, including body text.
3886 - When there is a numeric prefix, go up to a heading with level ARG, do
3887 a `show-subtree' and return to the previous cursor position. If ARG
3888 is negative, go up that many levels.
3890 - When point is not at the beginning of a headline, execute the global
3891 binding for TAB, which is re-indenting the line. See the option
3892 `org-cycle-emulate-tab' for details.
3894 - Special case: if point is at the beginning of the buffer and there is
3895 no headline in line 1, this function will act as if called with prefix arg.
3896 But only if also the variable `org-cycle-global-at-bob' is t."
3897 (interactive "P")
3898 (org-load-modules-maybe)
3899 (let* ((outline-regexp
3900 (if (and (org-mode-p) org-cycle-include-plain-lists)
3901 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3902 outline-regexp))
3903 (bob-special (and org-cycle-global-at-bob (bobp)
3904 (not (looking-at outline-regexp))))
3905 (org-cycle-hook
3906 (if bob-special
3907 (delq 'org-optimize-window-after-visibility-change
3908 (copy-sequence org-cycle-hook))
3909 org-cycle-hook))
3910 (pos (point)))
3912 (if (or bob-special (equal arg '(4)))
3913 ;; special case: use global cycling
3914 (setq arg t))
3916 (cond
3918 ((equal arg '(16))
3919 (org-set-startup-visibility)
3920 (message "Startup visibility, plus VISIBILITY properties."))
3922 ((org-at-table-p 'any)
3923 ;; Enter the table or move to the next field in the table
3924 (or (org-table-recognize-table.el)
3925 (progn
3926 (if arg (org-table-edit-field t)
3927 (org-table-justify-field-maybe)
3928 (call-interactively 'org-table-next-field)))))
3930 ((eq arg t) ;; Global cycling
3932 (cond
3933 ((and (eq last-command this-command)
3934 (eq org-cycle-global-status 'overview))
3935 ;; We just created the overview - now do table of contents
3936 ;; This can be slow in very large buffers, so indicate action
3937 (message "CONTENTS...")
3938 (org-content)
3939 (message "CONTENTS...done")
3940 (setq org-cycle-global-status 'contents)
3941 (run-hook-with-args 'org-cycle-hook 'contents))
3943 ((and (eq last-command this-command)
3944 (eq org-cycle-global-status 'contents))
3945 ;; We just showed the table of contents - now show everything
3946 (show-all)
3947 (message "SHOW ALL")
3948 (setq org-cycle-global-status 'all)
3949 (run-hook-with-args 'org-cycle-hook 'all))
3952 ;; Default action: go to overview
3953 (org-overview)
3954 (message "OVERVIEW")
3955 (setq org-cycle-global-status 'overview)
3956 (run-hook-with-args 'org-cycle-hook 'overview))))
3958 ((and org-drawers org-drawer-regexp
3959 (save-excursion
3960 (beginning-of-line 1)
3961 (looking-at org-drawer-regexp)))
3962 ;; Toggle block visibility
3963 (org-flag-drawer
3964 (not (get-char-property (match-end 0) 'invisible))))
3966 ((integerp arg)
3967 ;; Show-subtree, ARG levels up from here.
3968 (save-excursion
3969 (org-back-to-heading)
3970 (outline-up-heading (if (< arg 0) (- arg)
3971 (- (funcall outline-level) arg)))
3972 (org-show-subtree)))
3974 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3975 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3976 ;; At a heading: rotate between three different views
3977 (org-back-to-heading)
3978 (let ((goal-column 0) eoh eol eos)
3979 ;; First, some boundaries
3980 (save-excursion
3981 (org-back-to-heading)
3982 (save-excursion
3983 (beginning-of-line 2)
3984 (while (and (not (eobp)) ;; this is like `next-line'
3985 (get-char-property (1- (point)) 'invisible))
3986 (beginning-of-line 2)) (setq eol (point)))
3987 (outline-end-of-heading) (setq eoh (point))
3988 (org-end-of-subtree t)
3989 (unless (eobp)
3990 (skip-chars-forward " \t\n")
3991 (beginning-of-line 1) ; in case this is an item
3993 (setq eos (1- (point))))
3994 ;; Find out what to do next and set `this-command'
3995 (cond
3996 ((= eos eoh)
3997 ;; Nothing is hidden behind this heading
3998 (message "EMPTY ENTRY")
3999 (setq org-cycle-subtree-status nil)
4000 (save-excursion
4001 (goto-char eos)
4002 (outline-next-heading)
4003 (if (org-invisible-p) (org-flag-heading nil))))
4004 ((or (>= eol eos)
4005 (not (string-match "\\S-" (buffer-substring eol eos))))
4006 ;; Entire subtree is hidden in one line: open it
4007 (org-show-entry)
4008 (show-children)
4009 (message "CHILDREN")
4010 (save-excursion
4011 (goto-char eos)
4012 (outline-next-heading)
4013 (if (org-invisible-p) (org-flag-heading nil)))
4014 (setq org-cycle-subtree-status 'children)
4015 (run-hook-with-args 'org-cycle-hook 'children))
4016 ((and (eq last-command this-command)
4017 (eq org-cycle-subtree-status 'children))
4018 ;; We just showed the children, now show everything.
4019 (org-show-subtree)
4020 (message "SUBTREE")
4021 (setq org-cycle-subtree-status 'subtree)
4022 (run-hook-with-args 'org-cycle-hook 'subtree))
4024 ;; Default action: hide the subtree.
4025 (hide-subtree)
4026 (message "FOLDED")
4027 (setq org-cycle-subtree-status 'folded)
4028 (run-hook-with-args 'org-cycle-hook 'folded)))))
4030 ;; TAB emulation and template completion
4031 (buffer-read-only (org-back-to-heading))
4033 ((org-try-structure-completion))
4035 ((org-try-cdlatex-tab))
4037 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4038 (or (not (bolp))
4039 (not (looking-at outline-regexp))))
4040 (call-interactively (global-key-binding "\t")))
4042 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4043 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4044 (or (and (eq org-cycle-emulate-tab 'white)
4045 (= (match-end 0) (point-at-eol)))
4046 (and (eq org-cycle-emulate-tab 'whitestart)
4047 (>= (match-end 0) pos))))
4049 (eq org-cycle-emulate-tab t))
4050 (call-interactively (global-key-binding "\t")))
4052 (t (save-excursion
4053 (org-back-to-heading)
4054 (org-cycle))))))
4056 ;;;###autoload
4057 (defun org-global-cycle (&optional arg)
4058 "Cycle the global visibility. For details see `org-cycle'.
4059 With C-u prefix arg, switch to startup visibility.
4060 With a numeric prefix, show all headlines up to that level."
4061 (interactive "P")
4062 (let ((org-cycle-include-plain-lists
4063 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4064 (cond
4065 ((integerp arg)
4066 (show-all)
4067 (hide-sublevels arg)
4068 (setq org-cycle-global-status 'contents))
4069 ((equal arg '(4))
4070 (org-set-startup-visibility)
4071 (message "Startup visibility, plus VISIBILITY properties."))
4073 (org-cycle '(4))))))
4075 (defun org-set-startup-visibility ()
4076 "Set the visibility required by startup options and properties."
4077 (cond
4078 ((eq org-startup-folded t)
4079 (org-cycle '(4)))
4080 ((eq org-startup-folded 'content)
4081 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4082 (org-cycle '(4)) (org-cycle '(4)))))
4083 (org-set-visibility-according-to-property 'no-cleanup)
4084 (org-cycle-hide-archived-subtrees 'all)
4085 (org-cycle-hide-drawers 'all)
4086 (org-cycle-show-empty-lines 'all))
4088 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4089 "Switch subtree visibilities according to :VISIBILITY: property."
4090 (interactive)
4091 (let (state)
4092 (save-excursion
4093 (goto-char (point-min))
4094 (while (re-search-forward
4095 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4096 nil t)
4097 (setq state (match-string 1))
4098 (save-excursion
4099 (org-back-to-heading t)
4100 (hide-subtree)
4101 (org-reveal)
4102 (cond
4103 ((equal state '("fold" "folded"))
4104 (hide-subtree))
4105 ((equal state "children")
4106 (org-show-hidden-entry)
4107 (show-children))
4108 ((equal state "content")
4109 (save-excursion
4110 (save-restriction
4111 (org-narrow-to-subtree)
4112 (org-content))))
4113 ((member state '("all" "showall"))
4114 (show-subtree)))))
4115 (unless no-cleanup
4116 (org-cycle-hide-archived-subtrees 'all)
4117 (org-cycle-hide-drawers 'all)
4118 (org-cycle-show-empty-lines 'all)))))
4120 (defun org-overview ()
4121 "Switch to overview mode, shoing only top-level headlines.
4122 Really, this shows all headlines with level equal or greater than the level
4123 of the first headline in the buffer. This is important, because if the
4124 first headline is not level one, then (hide-sublevels 1) gives confusing
4125 results."
4126 (interactive)
4127 (let ((level (save-excursion
4128 (goto-char (point-min))
4129 (if (re-search-forward (concat "^" outline-regexp) nil t)
4130 (progn
4131 (goto-char (match-beginning 0))
4132 (funcall outline-level))))))
4133 (and level (hide-sublevels level))))
4135 (defun org-content (&optional arg)
4136 "Show all headlines in the buffer, like a table of contents.
4137 With numerical argument N, show content up to level N."
4138 (interactive "P")
4139 (save-excursion
4140 ;; Visit all headings and show their offspring
4141 (and (integerp arg) (org-overview))
4142 (goto-char (point-max))
4143 (catch 'exit
4144 (while (and (progn (condition-case nil
4145 (outline-previous-visible-heading 1)
4146 (error (goto-char (point-min))))
4148 (looking-at outline-regexp))
4149 (if (integerp arg)
4150 (show-children (1- arg))
4151 (show-branches))
4152 (if (bobp) (throw 'exit nil))))))
4155 (defun org-optimize-window-after-visibility-change (state)
4156 "Adjust the window after a change in outline visibility.
4157 This function is the default value of the hook `org-cycle-hook'."
4158 (when (get-buffer-window (current-buffer))
4159 (cond
4160 ; ((eq state 'overview) (org-first-headline-recenter 1))
4161 ; ((eq state 'overview) (org-beginning-of-line))
4162 ((eq state 'content) nil)
4163 ((eq state 'all) nil)
4164 ((eq state 'folded) nil)
4165 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4166 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4168 (defun org-compact-display-after-subtree-move ()
4169 (let (beg end)
4170 (save-excursion
4171 (if (org-up-heading-safe)
4172 (progn
4173 (hide-subtree)
4174 (show-entry)
4175 (show-children)
4176 (org-cycle-show-empty-lines 'children)
4177 (org-cycle-hide-drawers 'children))
4178 (org-overview)))))
4180 (defun org-cycle-show-empty-lines (state)
4181 "Show empty lines above all visible headlines.
4182 The region to be covered depends on STATE when called through
4183 `org-cycle-hook'. Lisp program can use t for STATE to get the
4184 entire buffer covered. Note that an empty line is only shown if there
4185 are at least `org-cycle-separator-lines' empty lines before the headeline."
4186 (when (> org-cycle-separator-lines 0)
4187 (save-excursion
4188 (let* ((n org-cycle-separator-lines)
4189 (re (cond
4190 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4191 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4192 (t (let ((ns (number-to-string (- n 2))))
4193 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4194 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4195 beg end)
4196 (cond
4197 ((memq state '(overview contents t))
4198 (setq beg (point-min) end (point-max)))
4199 ((memq state '(children folded))
4200 (setq beg (point) end (progn (org-end-of-subtree t t)
4201 (beginning-of-line 2)
4202 (point)))))
4203 (when beg
4204 (goto-char beg)
4205 (while (re-search-forward re end t)
4206 (if (not (get-char-property (match-end 1) 'invisible))
4207 (outline-flag-region
4208 (match-beginning 1) (match-end 1) nil)))))))
4209 ;; Never hide empty lines at the end of the file.
4210 (save-excursion
4211 (goto-char (point-max))
4212 (outline-previous-heading)
4213 (outline-end-of-heading)
4214 (if (and (looking-at "[ \t\n]+")
4215 (= (match-end 0) (point-max)))
4216 (outline-flag-region (point) (match-end 0) nil))))
4218 (defun org-show-empty-lines-in-parent ()
4219 "Move to the parent and re-show empty lines before visible headlines."
4220 (save-excursion
4221 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4222 (org-cycle-show-empty-lines context))))
4224 (defun org-cycle-hide-drawers (state)
4225 "Re-hide all drawers after a visibility state change."
4226 (when (and (org-mode-p)
4227 (not (memq state '(overview folded))))
4228 (save-excursion
4229 (let* ((globalp (memq state '(contents all)))
4230 (beg (if globalp (point-min) (point)))
4231 (end (if globalp (point-max) (org-end-of-subtree t))))
4232 (goto-char beg)
4233 (while (re-search-forward org-drawer-regexp end t)
4234 (org-flag-drawer t))))))
4236 (defun org-flag-drawer (flag)
4237 (save-excursion
4238 (beginning-of-line 1)
4239 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4240 (let ((b (match-end 0))
4241 (outline-regexp org-outline-regexp))
4242 (if (re-search-forward
4243 "^[ \t]*:END:"
4244 (save-excursion (outline-next-heading) (point)) t)
4245 (outline-flag-region b (point-at-eol) flag)
4246 (error ":END: line missing"))))))
4248 (defun org-subtree-end-visible-p ()
4249 "Is the end of the current subtree visible?"
4250 (pos-visible-in-window-p
4251 (save-excursion (org-end-of-subtree t) (point))))
4253 (defun org-first-headline-recenter (&optional N)
4254 "Move cursor to the first headline and recenter the headline.
4255 Optional argument N means, put the headline into the Nth line of the window."
4256 (goto-char (point-min))
4257 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4258 (beginning-of-line)
4259 (recenter (prefix-numeric-value N))))
4261 ;;; Org-goto
4263 (defvar org-goto-window-configuration nil)
4264 (defvar org-goto-marker nil)
4265 (defvar org-goto-map
4266 (let ((map (make-sparse-keymap)))
4267 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4268 (while (setq cmd (pop cmds))
4269 (substitute-key-definition cmd cmd map global-map)))
4270 (suppress-keymap map)
4271 (org-defkey map "\C-m" 'org-goto-ret)
4272 (org-defkey map [(return)] 'org-goto-ret)
4273 (org-defkey map [(left)] 'org-goto-left)
4274 (org-defkey map [(right)] 'org-goto-right)
4275 (org-defkey map [(control ?g)] 'org-goto-quit)
4276 (org-defkey map "\C-i" 'org-cycle)
4277 (org-defkey map [(tab)] 'org-cycle)
4278 (org-defkey map [(down)] 'outline-next-visible-heading)
4279 (org-defkey map [(up)] 'outline-previous-visible-heading)
4280 (if org-goto-auto-isearch
4281 (if (fboundp 'define-key-after)
4282 (define-key-after map [t] 'org-goto-local-auto-isearch)
4283 nil)
4284 (org-defkey map "q" 'org-goto-quit)
4285 (org-defkey map "n" 'outline-next-visible-heading)
4286 (org-defkey map "p" 'outline-previous-visible-heading)
4287 (org-defkey map "f" 'outline-forward-same-level)
4288 (org-defkey map "b" 'outline-backward-same-level)
4289 (org-defkey map "u" 'outline-up-heading))
4290 (org-defkey map "/" 'org-occur)
4291 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4292 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4293 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4294 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4295 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4296 map))
4298 (defconst org-goto-help
4299 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4300 RET=jump to location [Q]uit and return to previous location
4301 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4303 (defvar org-goto-start-pos) ; dynamically scoped parameter
4305 ;; FIXME: Docstring doe not mention both interfaces
4306 (defun org-goto (&optional alternative-interface)
4307 "Look up a different location in the current file, keeping current visibility.
4309 When you want look-up or go to a different location in a document, the
4310 fastest way is often to fold the entire buffer and then dive into the tree.
4311 This method has the disadvantage, that the previous location will be folded,
4312 which may not be what you want.
4314 This command works around this by showing a copy of the current buffer
4315 in an indirect buffer, in overview mode. You can dive into the tree in
4316 that copy, use org-occur and incremental search to find a location.
4317 When pressing RET or `Q', the command returns to the original buffer in
4318 which the visibility is still unchanged. After RET is will also jump to
4319 the location selected in the indirect buffer and expose the
4320 the headline hierarchy above."
4321 (interactive "P")
4322 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4323 (org-refile-use-outline-path t)
4324 (interface
4325 (if (not alternative-interface)
4326 org-goto-interface
4327 (if (eq org-goto-interface 'outline)
4328 'outline-path-completion
4329 'outline)))
4330 (org-goto-start-pos (point))
4331 (selected-point
4332 (if (eq interface 'outline)
4333 (car (org-get-location (current-buffer) org-goto-help))
4334 (nth 3 (org-refile-get-location "Goto: ")))))
4335 (if selected-point
4336 (progn
4337 (org-mark-ring-push org-goto-start-pos)
4338 (goto-char selected-point)
4339 (if (or (org-invisible-p) (org-invisible-p2))
4340 (org-show-context 'org-goto)))
4341 (message "Quit"))))
4343 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4344 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4345 (defvar org-goto-local-auto-isearch-map) ; defined below
4347 (defun org-get-location (buf help)
4348 "Let the user select a location in the Org-mode buffer BUF.
4349 This function uses a recursive edit. It returns the selected position
4350 or nil."
4351 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4352 (isearch-hide-immediately nil)
4353 (isearch-search-fun-function
4354 (lambda () 'org-goto-local-search-forward-headings))
4355 (org-goto-selected-point org-goto-exit-command))
4356 (save-excursion
4357 (save-window-excursion
4358 (delete-other-windows)
4359 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4360 (switch-to-buffer
4361 (condition-case nil
4362 (make-indirect-buffer (current-buffer) "*org-goto*")
4363 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4364 (with-output-to-temp-buffer "*Help*"
4365 (princ help))
4366 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4367 (setq buffer-read-only nil)
4368 (let ((org-startup-truncated t)
4369 (org-startup-folded nil)
4370 (org-startup-align-all-tables nil))
4371 (org-mode)
4372 (org-overview))
4373 (setq buffer-read-only t)
4374 (if (and (boundp 'org-goto-start-pos)
4375 (integer-or-marker-p org-goto-start-pos))
4376 (let ((org-show-hierarchy-above t)
4377 (org-show-siblings t)
4378 (org-show-following-heading t))
4379 (goto-char org-goto-start-pos)
4380 (and (org-invisible-p) (org-show-context)))
4381 (goto-char (point-min)))
4382 (org-beginning-of-line)
4383 (message "Select location and press RET")
4384 (use-local-map org-goto-map)
4385 (recursive-edit)
4387 (kill-buffer "*org-goto*")
4388 (cons org-goto-selected-point org-goto-exit-command)))
4390 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4391 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4392 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4393 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4395 (defun org-goto-local-search-forward-headings (string bound noerror)
4396 "Search and make sure that anu matches are in headlines."
4397 (catch 'return
4398 (while (search-forward string bound noerror)
4399 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4400 (and (member :headline context)
4401 (not (member :tags context))))
4402 (throw 'return (point))))))
4404 (defun org-goto-local-auto-isearch ()
4405 "Start isearch."
4406 (interactive)
4407 (goto-char (point-min))
4408 (let ((keys (this-command-keys)))
4409 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4410 (isearch-mode t)
4411 (isearch-process-search-char (string-to-char keys)))))
4413 (defun org-goto-ret (&optional arg)
4414 "Finish `org-goto' by going to the new location."
4415 (interactive "P")
4416 (setq org-goto-selected-point (point)
4417 org-goto-exit-command 'return)
4418 (throw 'exit nil))
4420 (defun org-goto-left ()
4421 "Finish `org-goto' by going to the new location."
4422 (interactive)
4423 (if (org-on-heading-p)
4424 (progn
4425 (beginning-of-line 1)
4426 (setq org-goto-selected-point (point)
4427 org-goto-exit-command 'left)
4428 (throw 'exit nil))
4429 (error "Not on a heading")))
4431 (defun org-goto-right ()
4432 "Finish `org-goto' by going to the new location."
4433 (interactive)
4434 (if (org-on-heading-p)
4435 (progn
4436 (setq org-goto-selected-point (point)
4437 org-goto-exit-command 'right)
4438 (throw 'exit nil))
4439 (error "Not on a heading")))
4441 (defun org-goto-quit ()
4442 "Finish `org-goto' without cursor motion."
4443 (interactive)
4444 (setq org-goto-selected-point nil)
4445 (setq org-goto-exit-command 'quit)
4446 (throw 'exit nil))
4448 ;;; Indirect buffer display of subtrees
4450 (defvar org-indirect-dedicated-frame nil
4451 "This is the frame being used for indirect tree display.")
4452 (defvar org-last-indirect-buffer nil)
4454 (defun org-tree-to-indirect-buffer (&optional arg)
4455 "Create indirect buffer and narrow it to current subtree.
4456 With numerical prefix ARG, go up to this level and then take that tree.
4457 If ARG is negative, go up that many levels.
4458 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4459 indirect buffer previously made with this command, to avoid proliferation of
4460 indirect buffers. However, when you call the command with a `C-u' prefix, or
4461 when `org-indirect-buffer-display' is `new-frame', the last buffer
4462 is kept so that you can work with several indirect buffers at the same time.
4463 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4464 requests that a new frame be made for the new buffer, so that the dedicated
4465 frame is not changed."
4466 (interactive "P")
4467 (let ((cbuf (current-buffer))
4468 (cwin (selected-window))
4469 (pos (point))
4470 beg end level heading ibuf)
4471 (save-excursion
4472 (org-back-to-heading t)
4473 (when (numberp arg)
4474 (setq level (org-outline-level))
4475 (if (< arg 0) (setq arg (+ level arg)))
4476 (while (> (setq level (org-outline-level)) arg)
4477 (outline-up-heading 1 t)))
4478 (setq beg (point)
4479 heading (org-get-heading))
4480 (org-end-of-subtree t) (setq end (point)))
4481 (if (and (buffer-live-p org-last-indirect-buffer)
4482 (not (eq org-indirect-buffer-display 'new-frame))
4483 (not arg))
4484 (kill-buffer org-last-indirect-buffer))
4485 (setq ibuf (org-get-indirect-buffer cbuf)
4486 org-last-indirect-buffer ibuf)
4487 (cond
4488 ((or (eq org-indirect-buffer-display 'new-frame)
4489 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4490 (select-frame (make-frame))
4491 (delete-other-windows)
4492 (switch-to-buffer ibuf)
4493 (org-set-frame-title heading))
4494 ((eq org-indirect-buffer-display 'dedicated-frame)
4495 (raise-frame
4496 (select-frame (or (and org-indirect-dedicated-frame
4497 (frame-live-p org-indirect-dedicated-frame)
4498 org-indirect-dedicated-frame)
4499 (setq org-indirect-dedicated-frame (make-frame)))))
4500 (delete-other-windows)
4501 (switch-to-buffer ibuf)
4502 (org-set-frame-title (concat "Indirect: " heading)))
4503 ((eq org-indirect-buffer-display 'current-window)
4504 (switch-to-buffer ibuf))
4505 ((eq org-indirect-buffer-display 'other-window)
4506 (pop-to-buffer ibuf))
4507 (t (error "Invalid value.")))
4508 (if (featurep 'xemacs)
4509 (save-excursion (org-mode) (turn-on-font-lock)))
4510 (narrow-to-region beg end)
4511 (show-all)
4512 (goto-char pos)
4513 (and (window-live-p cwin) (select-window cwin))))
4515 (defun org-get-indirect-buffer (&optional buffer)
4516 (setq buffer (or buffer (current-buffer)))
4517 (let ((n 1) (base (buffer-name buffer)) bname)
4518 (while (buffer-live-p
4519 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4520 (setq n (1+ n)))
4521 (condition-case nil
4522 (make-indirect-buffer buffer bname 'clone)
4523 (error (make-indirect-buffer buffer bname)))))
4525 (defun org-set-frame-title (title)
4526 "Set the title of the current frame to the string TITLE."
4527 ;; FIXME: how to name a single frame in XEmacs???
4528 (unless (featurep 'xemacs)
4529 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4531 ;;;; Structure editing
4533 ;;; Inserting headlines
4535 (defun org-insert-heading (&optional force-heading)
4536 "Insert a new heading or item with same depth at point.
4537 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4538 If point is at the beginning of a headline, insert a sibling before the
4539 current headline. If point is not at the beginning, do not split the line,
4540 but create the new hedline after the current line."
4541 (interactive "P")
4542 (if (= (buffer-size) 0)
4543 (insert "\n* ")
4544 (when (or force-heading (not (org-insert-item)))
4545 (let* ((head (save-excursion
4546 (condition-case nil
4547 (progn
4548 (org-back-to-heading)
4549 (match-string 0))
4550 (error "*"))))
4551 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4552 pos)
4553 (cond
4554 ((and (org-on-heading-p) (bolp)
4555 (or (bobp)
4556 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4557 ;; insert before the current line
4558 (open-line (if blank 2 1)))
4559 ((and (bolp)
4560 (or (bobp)
4561 (save-excursion
4562 (backward-char 1) (not (org-invisible-p)))))
4563 ;; insert right here
4564 nil)
4566 ;; in the middle of the line
4567 (org-show-entry)
4568 (let ((split
4569 (org-get-alist-option org-M-RET-may-split-line 'headline))
4570 tags pos)
4571 (if (org-on-heading-p)
4572 (progn
4573 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4574 (setq tags (and (match-end 2) (match-string 2)))
4575 (and (match-end 1)
4576 (delete-region (match-beginning 1) (match-end 1)))
4577 (setq pos (point-at-bol))
4578 (or split (end-of-line 1))
4579 (delete-horizontal-space)
4580 (newline (if blank 2 1))
4581 (when tags
4582 (save-excursion
4583 (goto-char pos)
4584 (end-of-line 1)
4585 (insert " " tags)
4586 (org-set-tags nil 'align))))
4587 (or split (end-of-line 1))
4588 (newline (if blank 2 1))))))
4589 (insert head) (just-one-space)
4590 (setq pos (point))
4591 (end-of-line 1)
4592 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4593 (run-hooks 'org-insert-heading-hook)))))
4595 (defun org-get-heading (&optional no-tags)
4596 "Return the heading of the current entry, without the stars."
4597 (save-excursion
4598 (org-back-to-heading t)
4599 (if (looking-at
4600 (if no-tags
4601 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4602 "\\*+[ \t]+\\([^\r\n]*\\)"))
4603 (match-string 1) "")))
4605 (defun org-insert-heading-after-current ()
4606 "Insert a new heading with same level as current, after current subtree."
4607 (interactive)
4608 (org-back-to-heading)
4609 (org-insert-heading)
4610 (org-move-subtree-down)
4611 (end-of-line 1))
4613 (defun org-insert-todo-heading (arg)
4614 "Insert a new heading with the same level and TODO state as current heading.
4615 If the heading has no TODO state, or if the state is DONE, use the first
4616 state (TODO by default). Also with prefix arg, force first state."
4617 (interactive "P")
4618 (when (not (org-insert-item 'checkbox))
4619 (org-insert-heading)
4620 (save-excursion
4621 (org-back-to-heading)
4622 (outline-previous-heading)
4623 (looking-at org-todo-line-regexp))
4624 (if (or arg
4625 (not (match-beginning 2))
4626 (member (match-string 2) org-done-keywords))
4627 (insert (car org-todo-keywords-1) " ")
4628 (insert (match-string 2) " "))
4629 (when org-provide-todo-statistics
4630 (org-update-parent-todo-statistics))))
4632 (defun org-insert-subheading (arg)
4633 "Insert a new subheading and demote it.
4634 Works for outline headings and for plain lists alike."
4635 (interactive "P")
4636 (org-insert-heading arg)
4637 (cond
4638 ((org-on-heading-p) (org-do-demote))
4639 ((org-at-item-p) (org-indent-item 1))))
4641 (defun org-insert-todo-subheading (arg)
4642 "Insert a new subheading with TODO keyword or checkbox and demote it.
4643 Works for outline headings and for plain lists alike."
4644 (interactive "P")
4645 (org-insert-todo-heading arg)
4646 (cond
4647 ((org-on-heading-p) (org-do-demote))
4648 ((org-at-item-p) (org-indent-item 1))))
4650 ;;; Promotion and Demotion
4652 (defun org-promote-subtree ()
4653 "Promote the entire subtree.
4654 See also `org-promote'."
4655 (interactive)
4656 (save-excursion
4657 (org-map-tree 'org-promote))
4658 (org-fix-position-after-promote))
4660 (defun org-demote-subtree ()
4661 "Demote the entire subtree. See `org-demote'.
4662 See also `org-promote'."
4663 (interactive)
4664 (save-excursion
4665 (org-map-tree 'org-demote))
4666 (org-fix-position-after-promote))
4669 (defun org-do-promote ()
4670 "Promote the current heading higher up the tree.
4671 If the region is active in `transient-mark-mode', promote all headings
4672 in the region."
4673 (interactive)
4674 (save-excursion
4675 (if (org-region-active-p)
4676 (org-map-region 'org-promote (region-beginning) (region-end))
4677 (org-promote)))
4678 (org-fix-position-after-promote))
4680 (defun org-do-demote ()
4681 "Demote the current heading lower down the tree.
4682 If the region is active in `transient-mark-mode', demote all headings
4683 in the region."
4684 (interactive)
4685 (save-excursion
4686 (if (org-region-active-p)
4687 (org-map-region 'org-demote (region-beginning) (region-end))
4688 (org-demote)))
4689 (org-fix-position-after-promote))
4691 (defun org-fix-position-after-promote ()
4692 "Make sure that after pro/demotion cursor position is right."
4693 (let ((pos (point)))
4694 (when (save-excursion
4695 (beginning-of-line 1)
4696 (looking-at org-todo-line-regexp)
4697 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4698 (cond ((eobp) (insert " "))
4699 ((eolp) (insert " "))
4700 ((equal (char-after) ?\ ) (forward-char 1))))))
4702 (defun org-reduced-level (l)
4703 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4705 (defun org-get-valid-level (level &optional change)
4706 "Rectify a level change under the influence of `org-odd-levels-only'
4707 LEVEL is a current level, CHANGE is by how much the level should be
4708 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4709 even level numbers will become the next higher odd number."
4710 (if org-odd-levels-only
4711 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4712 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4713 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4714 (max 1 (+ level change))))
4716 (if (boundp 'define-obsolete-function-alias)
4717 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4718 (define-obsolete-function-alias 'org-get-legal-level
4719 'org-get-valid-level)
4720 (define-obsolete-function-alias 'org-get-legal-level
4721 'org-get-valid-level "23.1")))
4723 (defun org-promote ()
4724 "Promote the current heading higher up the tree.
4725 If the region is active in `transient-mark-mode', promote all headings
4726 in the region."
4727 (org-back-to-heading t)
4728 (let* ((level (save-match-data (funcall outline-level)))
4729 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4730 (diff (abs (- level (length up-head) -1))))
4731 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4732 (replace-match up-head nil t)
4733 ;; Fixup tag positioning
4734 (and org-auto-align-tags (org-set-tags nil t))
4735 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4737 (defun org-demote ()
4738 "Demote the current heading lower down the tree.
4739 If the region is active in `transient-mark-mode', demote all headings
4740 in the region."
4741 (org-back-to-heading t)
4742 (let* ((level (save-match-data (funcall outline-level)))
4743 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4744 (diff (abs (- level (length down-head) -1))))
4745 (replace-match down-head nil t)
4746 ;; Fixup tag positioning
4747 (and org-auto-align-tags (org-set-tags nil t))
4748 (if org-adapt-indentation (org-fixup-indentation diff))))
4750 (defun org-map-tree (fun)
4751 "Call FUN for every heading underneath the current one."
4752 (org-back-to-heading)
4753 (let ((level (funcall outline-level)))
4754 (save-excursion
4755 (funcall fun)
4756 (while (and (progn
4757 (outline-next-heading)
4758 (> (funcall outline-level) level))
4759 (not (eobp)))
4760 (funcall fun)))))
4762 (defun org-map-region (fun beg end)
4763 "Call FUN for every heading between BEG and END."
4764 (let ((org-ignore-region t))
4765 (save-excursion
4766 (setq end (copy-marker end))
4767 (goto-char beg)
4768 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4769 (< (point) end))
4770 (funcall fun))
4771 (while (and (progn
4772 (outline-next-heading)
4773 (< (point) end))
4774 (not (eobp)))
4775 (funcall fun)))))
4777 (defun org-fixup-indentation (diff)
4778 "Change the indentation in the current entry by DIFF
4779 However, if any line in the current entry has no indentation, or if it
4780 would end up with no indentation after the change, nothing at all is done."
4781 (save-excursion
4782 (let ((end (save-excursion (outline-next-heading)
4783 (point-marker)))
4784 (prohibit (if (> diff 0)
4785 "^\\S-"
4786 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4787 col)
4788 (unless (save-excursion (end-of-line 1)
4789 (re-search-forward prohibit end t))
4790 (while (and (< (point) end)
4791 (re-search-forward "^[ \t]+" end t))
4792 (goto-char (match-end 0))
4793 (setq col (current-column))
4794 (if (< diff 0) (replace-match ""))
4795 (indent-to (+ diff col))))
4796 (move-marker end nil))))
4798 (defun org-convert-to-odd-levels ()
4799 "Convert an org-mode file with all levels allowed to one with odd levels.
4800 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4801 level 5 etc."
4802 (interactive)
4803 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4804 (let ((org-odd-levels-only nil) n)
4805 (save-excursion
4806 (goto-char (point-min))
4807 (while (re-search-forward "^\\*\\*+ " nil t)
4808 (setq n (- (length (match-string 0)) 2))
4809 (while (>= (setq n (1- n)) 0)
4810 (org-demote))
4811 (end-of-line 1))))))
4814 (defun org-convert-to-oddeven-levels ()
4815 "Convert an org-mode file with only odd levels to one with odd and even levels.
4816 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4817 section with an even level, conversion would destroy the structure of the file. An error
4818 is signaled in this case."
4819 (interactive)
4820 (goto-char (point-min))
4821 ;; First check if there are no even levels
4822 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4823 (org-show-context t)
4824 (error "Not all levels are odd in this file. Conversion not possible."))
4825 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4826 (let ((org-odd-levels-only nil) n)
4827 (save-excursion
4828 (goto-char (point-min))
4829 (while (re-search-forward "^\\*\\*+ " nil t)
4830 (setq n (/ (1- (length (match-string 0))) 2))
4831 (while (>= (setq n (1- n)) 0)
4832 (org-promote))
4833 (end-of-line 1))))))
4835 (defun org-tr-level (n)
4836 "Make N odd if required."
4837 (if org-odd-levels-only (1+ (/ n 2)) n))
4839 ;;; Vertical tree motion, cutting and pasting of subtrees
4841 (defun org-move-subtree-up (&optional arg)
4842 "Move the current subtree up past ARG headlines of the same level."
4843 (interactive "p")
4844 (org-move-subtree-down (- (prefix-numeric-value arg))))
4846 (defun org-move-subtree-down (&optional arg)
4847 "Move the current subtree down past ARG headlines of the same level."
4848 (interactive "p")
4849 (setq arg (prefix-numeric-value arg))
4850 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4851 'outline-get-last-sibling))
4852 (ins-point (make-marker))
4853 (cnt (abs arg))
4854 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4855 ;; Select the tree
4856 (org-back-to-heading)
4857 (setq beg0 (point))
4858 (save-excursion
4859 (setq ne-beg (org-back-over-empty-lines))
4860 (setq beg (point)))
4861 (save-match-data
4862 (save-excursion (outline-end-of-heading)
4863 (setq folded (org-invisible-p)))
4864 (outline-end-of-subtree))
4865 (outline-next-heading)
4866 (setq ne-end (org-back-over-empty-lines))
4867 (setq end (point))
4868 (goto-char beg0)
4869 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4870 ;; include less whitespace
4871 (save-excursion
4872 (goto-char beg)
4873 (forward-line (- ne-beg ne-end))
4874 (setq beg (point))))
4875 ;; Find insertion point, with error handling
4876 (while (> cnt 0)
4877 (or (and (funcall movfunc) (looking-at outline-regexp))
4878 (progn (goto-char beg0)
4879 (error "Cannot move past superior level or buffer limit")))
4880 (setq cnt (1- cnt)))
4881 (if (> arg 0)
4882 ;; Moving forward - still need to move over subtree
4883 (progn (org-end-of-subtree t t)
4884 (save-excursion
4885 (org-back-over-empty-lines)
4886 (or (bolp) (newline)))))
4887 (setq ne-ins (org-back-over-empty-lines))
4888 (move-marker ins-point (point))
4889 (setq txt (buffer-substring beg end))
4890 (org-save-markers-in-region beg end)
4891 (delete-region beg end)
4892 (outline-flag-region (1- beg) beg nil)
4893 (outline-flag-region (1- (point)) (point) nil)
4894 (let ((bbb (point)))
4895 (insert-before-markers txt)
4896 (org-reinstall-markers-in-region bbb)
4897 (move-marker ins-point bbb))
4898 (or (bolp) (insert "\n"))
4899 (setq ins-end (point))
4900 (goto-char ins-point)
4901 (org-skip-whitespace)
4902 (when (and (< arg 0)
4903 (org-first-sibling-p)
4904 (> ne-ins ne-beg))
4905 ;; Move whitespace back to beginning
4906 (save-excursion
4907 (goto-char ins-end)
4908 (let ((kill-whole-line t))
4909 (kill-line (- ne-ins ne-beg)) (point)))
4910 (insert (make-string (- ne-ins ne-beg) ?\n)))
4911 (move-marker ins-point nil)
4912 (org-compact-display-after-subtree-move)
4913 (org-show-empty-lines-in-parent)
4914 (unless folded
4915 (org-show-entry)
4916 (show-children)
4917 (org-cycle-hide-drawers 'children))))
4919 (defvar org-subtree-clip ""
4920 "Clipboard for cut and paste of subtrees.
4921 This is actually only a copy of the kill, because we use the normal kill
4922 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4924 (defvar org-subtree-clip-folded nil
4925 "Was the last copied subtree folded?
4926 This is used to fold the tree back after pasting.")
4928 (defun org-cut-subtree (&optional n)
4929 "Cut the current subtree into the clipboard.
4930 With prefix arg N, cut this many sequential subtrees.
4931 This is a short-hand for marking the subtree and then cutting it."
4932 (interactive "p")
4933 (org-copy-subtree n 'cut))
4935 (defun org-copy-subtree (&optional n cut force-store-markers)
4936 "Cut the current subtree into the clipboard.
4937 With prefix arg N, cut this many sequential subtrees.
4938 This is a short-hand for marking the subtree and then copying it.
4939 If CUT is non-nil, actually cut the subtree.
4940 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4941 of some markers in the region, even if CUT is non-nil. This is
4942 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4943 (interactive "p")
4944 (let (beg end folded (beg0 (point)))
4945 (if (interactive-p)
4946 (org-back-to-heading nil) ; take what looks like a subtree
4947 (org-back-to-heading t)) ; take what is really there
4948 (org-back-over-empty-lines)
4949 (setq beg (point))
4950 (skip-chars-forward " \t\r\n")
4951 (save-match-data
4952 (save-excursion (outline-end-of-heading)
4953 (setq folded (org-invisible-p)))
4954 (condition-case nil
4955 (outline-forward-same-level (1- n))
4956 (error nil))
4957 (org-end-of-subtree t t))
4958 (org-back-over-empty-lines)
4959 (setq end (point))
4960 (goto-char beg0)
4961 (when (> end beg)
4962 (setq org-subtree-clip-folded folded)
4963 (when (or cut force-store-markers)
4964 (org-save-markers-in-region beg end))
4965 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4966 (setq org-subtree-clip (current-kill 0))
4967 (message "%s: Subtree(s) with %d characters"
4968 (if cut "Cut" "Copied")
4969 (length org-subtree-clip)))))
4971 (defun org-paste-subtree (&optional level tree)
4972 "Paste the clipboard as a subtree, with modification of headline level.
4973 The entire subtree is promoted or demoted in order to match a new headline
4974 level. By default, the new level is derived from the visible headings
4975 before and after the insertion point, and taken to be the inferior headline
4976 level of the two. So if the previous visible heading is level 3 and the
4977 next is level 4 (or vice versa), level 4 will be used for insertion.
4978 This makes sure that the subtree remains an independent subtree and does
4979 not swallow low level entries.
4981 You can also force a different level, either by using a numeric prefix
4982 argument, or by inserting the heading marker by hand. For example, if the
4983 cursor is after \"*****\", then the tree will be shifted to level 5.
4985 If you want to insert the tree as is, just use \\[yank].
4987 If optional TREE is given, use this text instead of the kill ring."
4988 (interactive "P")
4989 (unless (org-kill-is-subtree-p tree)
4990 (error "%s"
4991 (substitute-command-keys
4992 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4993 (let* ((visp (not (org-invisible-p)))
4994 (txt (or tree (and kill-ring (current-kill 0))))
4995 (^re (concat "^\\(" outline-regexp "\\)"))
4996 (re (concat "\\(" outline-regexp "\\)"))
4997 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4999 (old-level (if (string-match ^re txt)
5000 (- (match-end 0) (match-beginning 0) 1)
5001 -1))
5002 (force-level (cond (level (prefix-numeric-value level))
5003 ((string-match
5004 ^re_ (buffer-substring (point-at-bol) (point)))
5005 (- (match-end 1) (match-beginning 1)))
5006 (t nil)))
5007 (previous-level (save-excursion
5008 (condition-case nil
5009 (progn
5010 (outline-previous-visible-heading 1)
5011 (if (looking-at re)
5012 (- (match-end 0) (match-beginning 0) 1)
5014 (error 1))))
5015 (next-level (save-excursion
5016 (condition-case nil
5017 (progn
5018 (or (looking-at outline-regexp)
5019 (outline-next-visible-heading 1))
5020 (if (looking-at re)
5021 (- (match-end 0) (match-beginning 0) 1)
5023 (error 1))))
5024 (new-level (or force-level (max previous-level next-level)))
5025 (shift (if (or (= old-level -1)
5026 (= new-level -1)
5027 (= old-level new-level))
5029 (- new-level old-level)))
5030 (delta (if (> shift 0) -1 1))
5031 (func (if (> shift 0) 'org-demote 'org-promote))
5032 (org-odd-levels-only nil)
5033 beg end)
5034 ;; Remove the forced level indicator
5035 (if force-level
5036 (delete-region (point-at-bol) (point)))
5037 ;; Paste
5038 (beginning-of-line 1)
5039 (org-back-over-empty-lines)
5040 (setq beg (point))
5041 (insert-before-markers txt)
5042 (unless (string-match "\n\\'" txt) (insert "\n"))
5043 (org-reinstall-markers-in-region beg)
5044 (setq end (point))
5045 (goto-char beg)
5046 (skip-chars-forward " \t\n\r")
5047 (setq beg (point))
5048 (if (and (org-invisible-p) visp)
5049 (save-excursion (outline-show-heading)))
5050 ;; Shift if necessary
5051 (unless (= shift 0)
5052 (save-restriction
5053 (narrow-to-region beg end)
5054 (while (not (= shift 0))
5055 (org-map-region func (point-min) (point-max))
5056 (setq shift (+ delta shift)))
5057 (goto-char (point-min))))
5058 (when (interactive-p)
5059 (message "Clipboard pasted as level %d subtree" new-level))
5060 (if (and kill-ring
5061 (eq org-subtree-clip (current-kill 0))
5062 org-subtree-clip-folded)
5063 ;; The tree was folded before it was killed/copied
5064 (hide-subtree))))
5066 (defun org-kill-is-subtree-p (&optional txt)
5067 "Check if the current kill is an outline subtree, or a set of trees.
5068 Returns nil if kill does not start with a headline, or if the first
5069 headline level is not the largest headline level in the tree.
5070 So this will actually accept several entries of equal levels as well,
5071 which is OK for `org-paste-subtree'.
5072 If optional TXT is given, check this string instead of the current kill."
5073 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5074 (start-level (and kill
5075 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5076 org-outline-regexp "\\)")
5077 kill)
5078 (- (match-end 2) (match-beginning 2) 1)))
5079 (re (concat "^" org-outline-regexp))
5080 (start (1+ (match-beginning 2))))
5081 (if (not start-level)
5082 (progn
5083 nil) ;; does not even start with a heading
5084 (catch 'exit
5085 (while (setq start (string-match re kill (1+ start)))
5086 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5087 (throw 'exit nil)))
5088 t))))
5090 (defvar org-markers-to-move nil
5091 "Markers that should be moved with a cut-and-paste operation.
5092 Those markers are stored together with their positions relative to
5093 the start of the region.")
5095 (defun org-save-markers-in-region (beg end)
5096 "Check markers in region.
5097 If these markers are between BEG and END, record their position relative
5098 to BEG, so that after moving the block of text, we can put the markers back
5099 into place.
5100 This function gets called just before an entry or tree gets cut from the
5101 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5102 called immediately, to move the markers with the entries."
5103 (setq org-markers-to-move nil)
5104 (when (featurep 'org-clock)
5105 (org-clock-save-markers-for-cut-and-paste beg end))
5106 (when (featurep 'org-agenda)
5107 (org-agenda-save-markers-for-cut-and-paste beg end)))
5109 (defun org-check-and-save-marker (marker beg end)
5110 "Check if MARKER is between BEG and END.
5111 If yes, remember the marker and the distance to BEG."
5112 (when (and (marker-buffer marker)
5113 (equal (marker-buffer marker) (current-buffer)))
5114 (if (and (>= marker beg) (< marker end))
5115 (push (cons marker (- marker beg)) org-markers-to-move))))
5117 (defun org-reinstall-markers-in-region (beg)
5118 "Move all remembered markers to their position relative to BEG."
5119 (mapc (lambda (x)
5120 (move-marker (car x) (+ beg (cdr x))))
5121 org-markers-to-move)
5122 (setq org-markers-to-move nil))
5124 (defun org-narrow-to-subtree ()
5125 "Narrow buffer to the current subtree."
5126 (interactive)
5127 (save-excursion
5128 (save-match-data
5129 (narrow-to-region
5130 (progn (org-back-to-heading) (point))
5131 (progn (org-end-of-subtree t) (point))))))
5134 ;;; Outline Sorting
5136 (defun org-sort (with-case)
5137 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5138 Optional argument WITH-CASE means sort case-sensitively."
5139 (interactive "P")
5140 (if (org-at-table-p)
5141 (org-call-with-arg 'org-table-sort-lines with-case)
5142 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5144 (defun org-sort-remove-invisible (s)
5145 (remove-text-properties 0 (length s) org-rm-props s)
5146 (while (string-match org-bracket-link-regexp s)
5147 (setq s (replace-match (if (match-end 2)
5148 (match-string 3 s)
5149 (match-string 1 s)) t t s)))
5152 (defvar org-priority-regexp) ; defined later in the file
5154 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5155 "Sort entries on a certain level of an outline tree.
5156 If there is an active region, the entries in the region are sorted.
5157 Else, if the cursor is before the first entry, sort the top-level items.
5158 Else, the children of the entry at point are sorted.
5160 Sorting can be alphabetically, numerically, and by date/time as given by
5161 the first time stamp in the entry. The command prompts for the sorting
5162 type unless it has been given to the function through the SORTING-TYPE
5163 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5164 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5165 called with point at the beginning of the record. It must return either
5166 a string or a number that should serve as the sorting key for that record.
5168 Comparing entries ignores case by default. However, with an optional argument
5169 WITH-CASE, the sorting considers case as well."
5170 (interactive "P")
5171 (let ((case-func (if with-case 'identity 'downcase))
5172 start beg end stars re re2
5173 txt what tmp plain-list-p)
5174 ;; Find beginning and end of region to sort
5175 (cond
5176 ((org-region-active-p)
5177 ;; we will sort the region
5178 (setq end (region-end)
5179 what "region")
5180 (goto-char (region-beginning))
5181 (if (not (org-on-heading-p)) (outline-next-heading))
5182 (setq start (point)))
5183 ((org-at-item-p)
5184 ;; we will sort this plain list
5185 (org-beginning-of-item-list) (setq start (point))
5186 (org-end-of-item-list) (setq end (point))
5187 (goto-char start)
5188 (setq plain-list-p t
5189 what "plain list"))
5190 ((or (org-on-heading-p)
5191 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5192 ;; we will sort the children of the current headline
5193 (org-back-to-heading)
5194 (setq start (point)
5195 end (progn (org-end-of-subtree t t)
5196 (org-back-over-empty-lines)
5197 (point))
5198 what "children")
5199 (goto-char start)
5200 (show-subtree)
5201 (outline-next-heading))
5203 ;; we will sort the top-level entries in this file
5204 (goto-char (point-min))
5205 (or (org-on-heading-p) (outline-next-heading))
5206 (setq start (point) end (point-max) what "top-level")
5207 (goto-char start)
5208 (show-all)))
5210 (setq beg (point))
5211 (if (>= beg end) (error "Nothing to sort"))
5213 (unless plain-list-p
5214 (looking-at "\\(\\*+\\)")
5215 (setq stars (match-string 1)
5216 re (concat "^" (regexp-quote stars) " +")
5217 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5218 txt (buffer-substring beg end))
5219 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5220 (if (and (not (equal stars "*")) (string-match re2 txt))
5221 (error "Region to sort contains a level above the first entry")))
5223 (unless sorting-type
5224 (message
5225 (if plain-list-p
5226 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5227 "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:")
5228 what)
5229 (setq sorting-type (read-char-exclusive))
5231 (and (= (downcase sorting-type) ?f)
5232 (setq getkey-func
5233 (completing-read "Sort using function: "
5234 obarray 'fboundp t nil nil))
5235 (setq getkey-func (intern getkey-func)))
5237 (and (= (downcase sorting-type) ?r)
5238 (setq property
5239 (completing-read "Property: "
5240 (mapcar 'list (org-buffer-property-keys t))
5241 nil t))))
5243 (message "Sorting entries...")
5245 (save-restriction
5246 (narrow-to-region start end)
5248 (let ((dcst (downcase sorting-type))
5249 (now (current-time)))
5250 (sort-subr
5251 (/= dcst sorting-type)
5252 ;; This function moves to the beginning character of the "record" to
5253 ;; be sorted.
5254 (if plain-list-p
5255 (lambda nil
5256 (if (org-at-item-p) t (goto-char (point-max))))
5257 (lambda nil
5258 (if (re-search-forward re nil t)
5259 (goto-char (match-beginning 0))
5260 (goto-char (point-max)))))
5261 ;; This function moves to the last character of the "record" being
5262 ;; sorted.
5263 (if plain-list-p
5264 'org-end-of-item
5265 (lambda nil
5266 (save-match-data
5267 (condition-case nil
5268 (outline-forward-same-level 1)
5269 (error
5270 (goto-char (point-max)))))))
5272 ;; This function returns the value that gets sorted against.
5273 (if plain-list-p
5274 (lambda nil
5275 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5276 (cond
5277 ((= dcst ?n)
5278 (string-to-number (buffer-substring (match-end 0)
5279 (point-at-eol))))
5280 ((= dcst ?a)
5281 (buffer-substring (match-end 0) (point-at-eol)))
5282 ((= dcst ?t)
5283 (if (re-search-forward org-ts-regexp
5284 (point-at-eol) t)
5285 (org-time-string-to-time (match-string 0))
5286 now))
5287 ((= dcst ?f)
5288 (if getkey-func
5289 (progn
5290 (setq tmp (funcall getkey-func))
5291 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5292 tmp)
5293 (error "Invalid key function `%s'" getkey-func)))
5294 (t (error "Invalid sorting type `%c'" sorting-type)))))
5295 (lambda nil
5296 (cond
5297 ((= dcst ?n)
5298 (if (looking-at outline-regexp)
5299 (string-to-number (buffer-substring (match-end 0)
5300 (point-at-eol)))
5301 nil))
5302 ((= dcst ?a)
5303 (funcall case-func (buffer-substring (point-at-bol)
5304 (point-at-eol))))
5305 ((= dcst ?t)
5306 (if (re-search-forward org-ts-regexp
5307 (save-excursion
5308 (forward-line 2)
5309 (point)) t)
5310 (org-time-string-to-time (match-string 0))
5311 now))
5312 ((= dcst ?p)
5313 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5314 (string-to-char (match-string 2))
5315 org-default-priority))
5316 ((= dcst ?r)
5317 (or (org-entry-get nil property) ""))
5318 ((= dcst ?o)
5319 (if (looking-at org-complex-heading-regexp)
5320 (- 9999 (length (member (match-string 2)
5321 org-todo-keywords-1)))))
5322 ((= dcst ?f)
5323 (if getkey-func
5324 (progn
5325 (setq tmp (funcall getkey-func))
5326 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5327 tmp)
5328 (error "Invalid key function `%s'" getkey-func)))
5329 (t (error "Invalid sorting type `%c'" sorting-type)))))
5331 (cond
5332 ((= dcst ?a) 'string<)
5333 ((= dcst ?t) 'time-less-p)
5334 (t nil)))))
5335 (message "Sorting entries...done")))
5337 (defun org-do-sort (table what &optional with-case sorting-type)
5338 "Sort TABLE of WHAT according to SORTING-TYPE.
5339 The user will be prompted for the SORTING-TYPE if the call to this
5340 function does not specify it. WHAT is only for the prompt, to indicate
5341 what is being sorted. The sorting key will be extracted from
5342 the car of the elements of the table.
5343 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5344 (unless sorting-type
5345 (message
5346 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5347 what)
5348 (setq sorting-type (read-char-exclusive)))
5349 (let ((dcst (downcase sorting-type))
5350 extractfun comparefun)
5351 ;; Define the appropriate functions
5352 (cond
5353 ((= dcst ?n)
5354 (setq extractfun 'string-to-number
5355 comparefun (if (= dcst sorting-type) '< '>)))
5356 ((= dcst ?a)
5357 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5358 (lambda(x) (downcase (org-sort-remove-invisible x))))
5359 comparefun (if (= dcst sorting-type)
5360 'string<
5361 (lambda (a b) (and (not (string< a b))
5362 (not (string= a b)))))))
5363 ((= dcst ?t)
5364 (setq extractfun
5365 (lambda (x)
5366 (if (string-match org-ts-regexp x)
5367 (time-to-seconds
5368 (org-time-string-to-time (match-string 0 x)))
5370 comparefun (if (= dcst sorting-type) '< '>)))
5371 (t (error "Invalid sorting type `%c'" sorting-type)))
5373 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5374 table)
5375 (lambda (a b) (funcall comparefun (car a) (car b))))))
5377 ;;; Editing source examples
5379 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5380 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5381 (defvar org-edit-src-force-single-line nil)
5382 (defvar org-edit-src-from-org-mode nil)
5384 (define-minor-mode org-exit-edit-mode
5385 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5387 (defun org-edit-src-code ()
5388 "Edit the source code example at point.
5389 An indirect buffer is created, and that buffer is then narrowed to the
5390 example at point and switched to the correct language mode. When done,
5391 exit by killing the buffer with \\[org-edit-src-exit]."
5392 (interactive)
5393 (let ((line (org-current-line))
5394 (case-fold-search t)
5395 (msg (substitute-command-keys
5396 "Edit, then exit with C-c ' (C-c and single quote)"))
5397 (info (org-edit-src-find-region-and-lang))
5398 (org-mode-p (eq major-mode 'org-mode))
5399 beg end lang lang-f single)
5400 (if (not info)
5402 (setq beg (nth 0 info)
5403 end (nth 1 info)
5404 lang (nth 2 info)
5405 single (nth 3 info)
5406 lang-f (intern (concat lang "-mode")))
5407 (unless (functionp lang-f)
5408 (error "No such language mode: %s" lang-f))
5409 (goto-line line)
5410 (if (get-buffer "*Org Edit Src Example*")
5411 (kill-buffer "*Org Edit Src Example*"))
5412 (switch-to-buffer (make-indirect-buffer (current-buffer)
5413 "*Org Edit Src Example*"))
5414 (narrow-to-region beg end)
5415 (remove-text-properties beg end '(display nil invisible nil
5416 intangible nil))
5417 (let ((org-inhibit-startup t))
5418 (funcall lang-f))
5419 (set (make-local-variable 'org-edit-src-force-single-line) single)
5420 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5421 (when org-mode-p
5422 (goto-char (point-min))
5423 (while (re-search-forward "^," nil t)
5424 (replace-match "")))
5425 (goto-line line)
5426 (org-exit-edit-mode)
5427 (org-set-local 'header-line-format msg)
5428 (message "%s" msg)
5429 t)))
5431 (defun org-edit-src-find-region-and-lang ()
5432 "Find the region and language for a local edit.
5433 Return a list with beginning and end of the region, a string representing
5434 the language, a switch telling of the content should be in a single line."
5435 (let ((re-list
5437 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5438 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5439 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5440 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5441 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5442 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5443 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5444 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5445 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5446 ("^#\\+html:" "\n" "html" single-line)
5447 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5448 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5449 ("^#\\+latex:" "\n" "latex" single-line)
5450 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5451 ("^#\\+ascii:" "\n" "ascii" single-line)
5453 (pos (point))
5454 re re1 re2 single beg end lang)
5455 (catch 'exit
5456 (while (setq entry (pop re-list))
5457 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5458 single (nth 3 entry))
5459 (save-excursion
5460 (if (or (looking-at re1)
5461 (re-search-backward re1 nil t))
5462 (progn
5463 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5464 (if (and (re-search-forward re2 nil t)
5465 (>= (match-end 0) pos))
5466 (throw 'exit (list beg (match-beginning 0) lang single))))
5467 (if (or (looking-at re2)
5468 (re-search-forward re2 nil t))
5469 (progn
5470 (setq end (match-beginning 0))
5471 (if (and (re-search-backward re1 nil t)
5472 (<= (match-beginning 0) pos))
5473 (throw 'exit
5474 (list (match-end 0) end
5475 (org-edit-src-get-lang lang) single)))))))))))
5477 (defun org-edit-src-get-lang (lang)
5478 "Extract the src language."
5479 (let ((m (match-string 0)))
5480 (cond
5481 ((stringp lang) lang)
5482 ((integerp lang) (match-string lang))
5483 ((and (eq lang lang)
5484 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5485 (match-string 1 m))
5486 ((and (eq lang lang)
5487 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5488 (match-string 1 m))
5489 (t "fundamental"))))
5491 (defun org-edit-src-exit ()
5492 "Exit special edit and protect problematic lines."
5493 (interactive)
5494 (unless (buffer-base-buffer (current-buffer))
5495 (error "This is not an indirect buffer, something is wrong..."))
5496 (unless (> (point-min) 1)
5497 (error "This buffer is not narrowed, something is wrong..."))
5498 (goto-char (point-min))
5499 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5500 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5501 (when (org-bound-and-true-p org-edit-src-force-single-line)
5502 (goto-char (point-min))
5503 (while (re-search-forward "\n" nil t)
5504 (replace-match " "))
5505 (goto-char (point-min))
5506 (if (looking-at "\\s-*") (replace-match " "))
5507 (if (re-search-forward "\\s-+\\'" nil t)
5508 (replace-match "")))
5509 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5510 (goto-char (point-min))
5511 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5512 (replace-match ",\\1"))
5513 (when font-lock-mode
5514 (font-lock-unfontify-region (point-min) (point-max)))
5515 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5516 (kill-buffer (current-buffer))
5517 (and (org-mode-p) (org-restart-font-lock)))
5519 ;;;; Plain list items, including checkboxes
5521 ;;; Plain list items
5523 (defun org-at-item-p ()
5524 "Is point in a line starting a hand-formatted item?"
5525 (let ((llt org-plain-list-ordered-item-terminator))
5526 (save-excursion
5527 (goto-char (point-at-bol))
5528 (looking-at
5529 (cond
5530 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5531 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5532 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5533 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5535 (defun org-in-item-p ()
5536 "It the cursor inside a plain list item.
5537 Does not have to be the first line."
5538 (save-excursion
5539 (condition-case nil
5540 (progn
5541 (org-beginning-of-item)
5542 (org-at-item-p)
5544 (error nil))))
5546 (defun org-insert-item (&optional checkbox)
5547 "Insert a new item at the current level.
5548 Return t when things worked, nil when we are not in an item."
5549 (when (save-excursion
5550 (condition-case nil
5551 (progn
5552 (org-beginning-of-item)
5553 (org-at-item-p)
5554 (if (org-invisible-p) (error "Invisible item"))
5556 (error nil)))
5557 (let* ((bul (match-string 0))
5558 (descp (save-excursion (goto-char (match-beginning 0))
5559 (beginning-of-line 1)
5560 (save-match-data
5561 (looking-at "[ \t]*.*? ::"))))
5562 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5563 (match-end 0)))
5564 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5565 pos)
5566 (if descp (setq checkbox nil))
5567 (cond
5568 ((and (org-at-item-p) (<= (point) eow))
5569 ;; before the bullet
5570 (beginning-of-line 1)
5571 (open-line (if blank 2 1)))
5572 ((<= (point) eow)
5573 (beginning-of-line 1))
5575 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5576 (end-of-line 1)
5577 (delete-horizontal-space))
5578 (newline (if blank 2 1))))
5579 (insert bul
5580 (if checkbox "[ ]" "")
5581 (if descp (concat (if checkbox " " "")
5582 (read-string "Term: ") " :: ") ""))
5583 (just-one-space)
5584 (setq pos (point))
5585 (end-of-line 1)
5586 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5587 (org-maybe-renumber-ordered-list)
5588 (and checkbox (org-update-checkbox-count-maybe))
5591 ;;; Checkboxes
5593 (defun org-at-item-checkbox-p ()
5594 "Is point at a line starting a plain-list item with a checklet?"
5595 (and (org-at-item-p)
5596 (save-excursion
5597 (goto-char (match-end 0))
5598 (skip-chars-forward " \t")
5599 (looking-at "\\[[- X]\\]"))))
5601 (defun org-toggle-checkbox (&optional arg)
5602 "Toggle the checkbox in the current line."
5603 (interactive "P")
5604 (catch 'exit
5605 (let (beg end status (firstnew 'unknown))
5606 (cond
5607 ((org-region-active-p)
5608 (setq beg (region-beginning) end (region-end)))
5609 ((org-on-heading-p)
5610 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5611 ((org-at-item-checkbox-p)
5612 (let ((pos (point)))
5613 (replace-match
5614 (cond (arg "[-]")
5615 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5616 (t "[ ]"))
5617 t t)
5618 (goto-char pos))
5619 (throw 'exit t))
5620 (t (error "Not at a checkbox or heading, and no active region")))
5621 (save-excursion
5622 (goto-char beg)
5623 (while (< (point) end)
5624 (when (org-at-item-checkbox-p)
5625 (setq status (equal (match-string 0) "[X]"))
5626 (when (eq firstnew 'unknown)
5627 (setq firstnew (not status)))
5628 (replace-match
5629 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5630 (beginning-of-line 2)))))
5631 (org-update-checkbox-count-maybe))
5633 (defun org-update-checkbox-count-maybe ()
5634 "Update checkbox statistics unless turned off by user."
5635 (when org-provide-checkbox-statistics
5636 (org-update-checkbox-count)))
5638 (defun org-update-checkbox-count (&optional all)
5639 "Update the checkbox statistics in the current section.
5640 This will find all statistic cookies like [57%] and [6/12] and update them
5641 with the current numbers. With optional prefix argument ALL, do this for
5642 the whole buffer."
5643 (interactive "P")
5644 (save-excursion
5645 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5646 (beg (condition-case nil
5647 (progn (outline-back-to-heading) (point))
5648 (error (point-min))))
5649 (end (move-marker (make-marker)
5650 (progn (outline-next-heading) (point))))
5651 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5652 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5653 (re-find (concat re "\\|" re-box))
5654 beg-cookie end-cookie is-percent c-on c-off lim
5655 eline curr-ind next-ind continue-from startsearch
5656 (cstat 0)
5658 (when all
5659 (goto-char (point-min))
5660 (outline-next-heading)
5661 (setq beg (point) end (point-max)))
5662 (goto-char end)
5663 ;; find each statistic cookie
5664 (while (re-search-backward re-find beg t)
5665 (setq beg-cookie (match-beginning 1)
5666 end-cookie (match-end 1)
5667 cstat (+ cstat (if end-cookie 1 0))
5668 startsearch (point-at-eol)
5669 continue-from (point-at-bol)
5670 is-percent (match-beginning 2)
5671 lim (cond
5672 ((org-on-heading-p) (outline-next-heading) (point))
5673 ((org-at-item-p) (org-end-of-item) (point))
5674 (t nil))
5675 c-on 0
5676 c-off 0)
5677 (when lim
5678 ;; find first checkbox for this cookie and gather
5679 ;; statistics from all that are at this indentation level
5680 (goto-char startsearch)
5681 (if (re-search-forward re-box lim t)
5682 (progn
5683 (org-beginning-of-item)
5684 (setq curr-ind (org-get-indentation))
5685 (setq next-ind curr-ind)
5686 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5687 (save-excursion (end-of-line) (setq eline (point)))
5688 (if (re-search-forward re-box eline t)
5689 (if (member (match-string 2) '("[ ]" "[-]"))
5690 (setq c-off (1+ c-off))
5691 (setq c-on (1+ c-on))
5694 (org-end-of-item)
5695 (setq next-ind (org-get-indentation))
5697 (goto-char continue-from)
5698 ;; update cookie
5699 (when end-cookie
5700 (delete-region beg-cookie end-cookie)
5701 (goto-char beg-cookie)
5702 (insert
5703 (if is-percent
5704 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5705 (format "[%d/%d]" c-on (+ c-on c-off)))))
5706 ;; update items checkbox if it has one
5707 (when (org-at-item-p)
5708 (org-beginning-of-item)
5709 (when (and (> (+ c-on c-off) 0)
5710 (re-search-forward re-box (point-at-eol) t))
5711 (setq beg-cookie (match-beginning 2)
5712 end-cookie (match-end 2))
5713 (delete-region beg-cookie end-cookie)
5714 (goto-char beg-cookie)
5715 (cond ((= c-off 0) (insert "[X]"))
5716 ((= c-on 0) (insert "[ ]"))
5717 (t (insert "[-]")))
5719 (goto-char continue-from))
5720 (when (interactive-p)
5721 (message "Checkbox satistics updated %s (%d places)"
5722 (if all "in entire file" "in current outline entry") cstat)))))
5724 (defun org-get-checkbox-statistics-face ()
5725 "Select the face for checkbox statistics.
5726 The face will be `org-done' when all relevant boxes are checked. Otherwise
5727 it will be `org-todo'."
5728 (if (match-end 1)
5729 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5730 (if (and (> (match-end 2) (match-beginning 2))
5731 (equal (match-string 2) (match-string 3)))
5732 'org-done
5733 'org-todo)))
5735 (defun org-get-indentation (&optional line)
5736 "Get the indentation of the current line, interpreting tabs.
5737 When LINE is given, assume it represents a line and compute its indentation."
5738 (if line
5739 (if (string-match "^ *" (org-remove-tabs line))
5740 (match-end 0))
5741 (save-excursion
5742 (beginning-of-line 1)
5743 (skip-chars-forward " \t")
5744 (current-column))))
5746 (defun org-remove-tabs (s &optional width)
5747 "Replace tabulators in S with spaces.
5748 Assumes that s is a single line, starting in column 0."
5749 (setq width (or width tab-width))
5750 (while (string-match "\t" s)
5751 (setq s (replace-match
5752 (make-string
5753 (- (* width (/ (+ (match-beginning 0) width) width))
5754 (match-beginning 0)) ?\ )
5755 t t s)))
5758 (defun org-fix-indentation (line ind)
5759 "Fix indentation in LINE.
5760 IND is a cons cell with target and minimum indentation.
5761 If the current indenation in LINE is smaller than the minimum,
5762 leave it alone. If it is larger than ind, set it to the target."
5763 (let* ((l (org-remove-tabs line))
5764 (i (org-get-indentation l))
5765 (i1 (car ind)) (i2 (cdr ind)))
5766 (if (>= i i2) (setq l (substring line i2)))
5767 (if (> i1 0)
5768 (concat (make-string i1 ?\ ) l)
5769 l)))
5771 (defun org-beginning-of-item ()
5772 "Go to the beginning of the current hand-formatted item.
5773 If the cursor is not in an item, throw an error."
5774 (interactive)
5775 (let ((pos (point))
5776 (limit (save-excursion
5777 (condition-case nil
5778 (progn
5779 (org-back-to-heading)
5780 (beginning-of-line 2) (point))
5781 (error (point-min)))))
5782 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5783 ind ind1)
5784 (if (org-at-item-p)
5785 (beginning-of-line 1)
5786 (beginning-of-line 1)
5787 (skip-chars-forward " \t")
5788 (setq ind (current-column))
5789 (if (catch 'exit
5790 (while t
5791 (beginning-of-line 0)
5792 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5794 (if (looking-at "[ \t]*$")
5795 (setq ind1 ind-empty)
5796 (skip-chars-forward " \t")
5797 (setq ind1 (current-column)))
5798 (if (< ind1 ind)
5799 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5801 (goto-char pos)
5802 (error "Not in an item")))))
5804 (defun org-end-of-item ()
5805 "Go to the end of the current hand-formatted item.
5806 If the cursor is not in an item, throw an error."
5807 (interactive)
5808 (let* ((pos (point))
5809 ind1
5810 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5811 (limit (save-excursion (outline-next-heading) (point)))
5812 (ind (save-excursion
5813 (org-beginning-of-item)
5814 (skip-chars-forward " \t")
5815 (current-column)))
5816 (end (catch 'exit
5817 (while t
5818 (beginning-of-line 2)
5819 (if (eobp) (throw 'exit (point)))
5820 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5821 (if (looking-at "[ \t]*$")
5822 (setq ind1 ind-empty)
5823 (skip-chars-forward " \t")
5824 (setq ind1 (current-column)))
5825 (if (<= ind1 ind)
5826 (throw 'exit (point-at-bol)))))))
5827 (if end
5828 (goto-char end)
5829 (goto-char pos)
5830 (error "Not in an item"))))
5832 (defun org-next-item ()
5833 "Move to the beginning of the next item in the current plain list.
5834 Error if not at a plain list, or if this is the last item in the list."
5835 (interactive)
5836 (let (ind ind1 (pos (point)))
5837 (org-beginning-of-item)
5838 (setq ind (org-get-indentation))
5839 (org-end-of-item)
5840 (setq ind1 (org-get-indentation))
5841 (unless (and (org-at-item-p) (= ind ind1))
5842 (goto-char pos)
5843 (error "On last item"))))
5845 (defun org-previous-item ()
5846 "Move to the beginning of the previous item in the current plain list.
5847 Error if not at a plain list, or if this is the first item in the list."
5848 (interactive)
5849 (let (beg ind ind1 (pos (point)))
5850 (org-beginning-of-item)
5851 (setq beg (point))
5852 (setq ind (org-get-indentation))
5853 (goto-char beg)
5854 (catch 'exit
5855 (while t
5856 (beginning-of-line 0)
5857 (if (looking-at "[ \t]*$")
5859 (if (<= (setq ind1 (org-get-indentation)) ind)
5860 (throw 'exit t)))))
5861 (condition-case nil
5862 (if (or (not (org-at-item-p))
5863 (< ind1 (1- ind)))
5864 (error "")
5865 (org-beginning-of-item))
5866 (error (goto-char pos)
5867 (error "On first item")))))
5869 (defun org-first-list-item-p ()
5870 "Is this heading the item in a plain list?"
5871 (unless (org-at-item-p)
5872 (error "Not at a plain list item"))
5873 (org-beginning-of-item)
5874 (= (point) (save-excursion (org-beginning-of-item-list))))
5876 (defun org-move-item-down ()
5877 "Move the plain list item at point down, i.e. swap with following item.
5878 Subitems (items with larger indentation) are considered part of the item,
5879 so this really moves item trees."
5880 (interactive)
5881 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5882 (org-beginning-of-item)
5883 (setq beg0 (point))
5884 (save-excursion
5885 (setq ne-beg (org-back-over-empty-lines))
5886 (setq beg (point)))
5887 (goto-char beg0)
5888 (setq ind (org-get-indentation))
5889 (org-end-of-item)
5890 (setq end0 (point))
5891 (setq ind1 (org-get-indentation))
5892 (setq ne-end (org-back-over-empty-lines))
5893 (setq end (point))
5894 (goto-char beg0)
5895 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5896 ;; include less whitespace
5897 (save-excursion
5898 (goto-char beg)
5899 (forward-line (- ne-beg ne-end))
5900 (setq beg (point))))
5901 (goto-char end0)
5902 (if (and (org-at-item-p) (= ind ind1))
5903 (progn
5904 (org-end-of-item)
5905 (org-back-over-empty-lines)
5906 (setq txt (buffer-substring beg end))
5907 (save-excursion
5908 (delete-region beg end))
5909 (setq pos (point))
5910 (insert txt)
5911 (goto-char pos) (org-skip-whitespace)
5912 (org-maybe-renumber-ordered-list))
5913 (goto-char pos)
5914 (error "Cannot move this item further down"))))
5916 (defun org-move-item-up (arg)
5917 "Move the plain list item at point up, i.e. swap with previous item.
5918 Subitems (items with larger indentation) are considered part of the item,
5919 so this really moves item trees."
5920 (interactive "p")
5921 (let (beg beg0 end ind ind1 (pos (point)) txt
5922 ne-beg ne-ins ins-end)
5923 (org-beginning-of-item)
5924 (setq beg0 (point))
5925 (setq ind (org-get-indentation))
5926 (save-excursion
5927 (setq ne-beg (org-back-over-empty-lines))
5928 (setq beg (point)))
5929 (goto-char beg0)
5930 (org-end-of-item)
5931 (org-back-over-empty-lines)
5932 (setq end (point))
5933 (goto-char beg0)
5934 (catch 'exit
5935 (while t
5936 (beginning-of-line 0)
5937 (if (looking-at "[ \t]*$")
5938 (if org-empty-line-terminates-plain-lists
5939 (progn
5940 (goto-char pos)
5941 (error "Cannot move this item further up"))
5942 nil)
5943 (if (<= (setq ind1 (org-get-indentation)) ind)
5944 (throw 'exit t)))))
5945 (condition-case nil
5946 (org-beginning-of-item)
5947 (error (goto-char beg0)
5948 (error "Cannot move this item further up")))
5949 (setq ind1 (org-get-indentation))
5950 (if (and (org-at-item-p) (= ind ind1))
5951 (progn
5952 (setq ne-ins (org-back-over-empty-lines))
5953 (setq txt (buffer-substring beg end))
5954 (save-excursion
5955 (delete-region beg end))
5956 (setq pos (point))
5957 (insert txt)
5958 (setq ins-end (point))
5959 (goto-char pos) (org-skip-whitespace)
5961 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5962 ;; Move whitespace back to beginning
5963 (save-excursion
5964 (goto-char ins-end)
5965 (let ((kill-whole-line t))
5966 (kill-line (- ne-ins ne-beg)) (point)))
5967 (insert (make-string (- ne-ins ne-beg) ?\n)))
5969 (org-maybe-renumber-ordered-list))
5970 (goto-char pos)
5971 (error "Cannot move this item further up"))))
5973 (defun org-maybe-renumber-ordered-list ()
5974 "Renumber the ordered list at point if setup allows it.
5975 This tests the user option `org-auto-renumber-ordered-lists' before
5976 doing the renumbering."
5977 (interactive)
5978 (when (and org-auto-renumber-ordered-lists
5979 (org-at-item-p))
5980 (if (match-beginning 3)
5981 (org-renumber-ordered-list 1)
5982 (org-fix-bullet-type))))
5984 (defun org-maybe-renumber-ordered-list-safe ()
5985 (condition-case nil
5986 (save-excursion
5987 (org-maybe-renumber-ordered-list))
5988 (error nil)))
5990 (defun org-cycle-list-bullet (&optional which)
5991 "Cycle through the different itemize/enumerate bullets.
5992 This cycle the entire list level through the sequence:
5994 `-' -> `+' -> `*' -> `1.' -> `1)'
5996 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5997 0 meand `-', 1 means `+' etc."
5998 (interactive "P")
5999 (org-preserve-lc
6000 (org-beginning-of-item-list)
6001 (org-at-item-p)
6002 (beginning-of-line 1)
6003 (let ((current (match-string 0))
6004 (prevp (eq which 'previous))
6005 new)
6006 (setq new (cond
6007 ((and (numberp which)
6008 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6009 ((string-match "-" current) (if prevp "1)" "+"))
6010 ((string-match "\\+" current)
6011 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6012 ((string-match "\\*" current) (if prevp "+" "1."))
6013 ((string-match "\\." current) (if prevp "*" "1)"))
6014 ((string-match ")" current) (if prevp "1." "-"))
6015 (t (error "This should not happen"))))
6016 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6017 (org-fix-bullet-type)
6018 (org-maybe-renumber-ordered-list))))
6020 (defun org-get-string-indentation (s)
6021 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6022 (let ((n -1) (i 0) (w tab-width) c)
6023 (catch 'exit
6024 (while (< (setq n (1+ n)) (length s))
6025 (setq c (aref s n))
6026 (cond ((= c ?\ ) (setq i (1+ i)))
6027 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6028 (t (throw 'exit t)))))
6031 (defun org-renumber-ordered-list (arg)
6032 "Renumber an ordered plain list.
6033 Cursor needs to be in the first line of an item, the line that starts
6034 with something like \"1.\" or \"2)\"."
6035 (interactive "p")
6036 (unless (and (org-at-item-p)
6037 (match-beginning 3))
6038 (error "This is not an ordered list"))
6039 (let ((line (org-current-line))
6040 (col (current-column))
6041 (ind (org-get-string-indentation
6042 (buffer-substring (point-at-bol) (match-beginning 3))))
6043 ;; (term (substring (match-string 3) -1))
6044 ind1 (n (1- arg))
6045 fmt bob)
6046 ;; find where this list begins
6047 (org-beginning-of-item-list)
6048 (setq bobp (bobp))
6049 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6050 (setq fmt (concat "%d" (match-string 1)))
6051 (beginning-of-line 0)
6052 ;; walk forward and replace these numbers
6053 (catch 'exit
6054 (while t
6055 (catch 'next
6056 (if bobp (setq bobp nil) (beginning-of-line 2))
6057 (if (eobp) (throw 'exit nil))
6058 (if (looking-at "[ \t]*$") (throw 'next nil))
6059 (skip-chars-forward " \t") (setq ind1 (current-column))
6060 (if (> ind1 ind) (throw 'next t))
6061 (if (< ind1 ind) (throw 'exit t))
6062 (if (not (org-at-item-p)) (throw 'exit nil))
6063 (delete-region (match-beginning 2) (match-end 2))
6064 (goto-char (match-beginning 2))
6065 (insert (format fmt (setq n (1+ n)))))))
6066 (goto-line line)
6067 (org-move-to-column col)))
6069 (defun org-fix-bullet-type ()
6070 "Make sure all items in this list have the same bullet as the firsst item."
6071 (interactive)
6072 (unless (org-at-item-p) (error "This is not a list"))
6073 (let ((line (org-current-line))
6074 (col (current-column))
6075 (ind (current-indentation))
6076 ind1 bullet)
6077 ;; find where this list begins
6078 (org-beginning-of-item-list)
6079 (beginning-of-line 1)
6080 ;; find out what the bullet type is
6081 (looking-at "[ \t]*\\(\\S-+\\)")
6082 (setq bullet (match-string 1))
6083 ;; walk forward and replace these numbers
6084 (beginning-of-line 0)
6085 (catch 'exit
6086 (while t
6087 (catch 'next
6088 (beginning-of-line 2)
6089 (if (eobp) (throw 'exit nil))
6090 (if (looking-at "[ \t]*$") (throw 'next nil))
6091 (skip-chars-forward " \t") (setq ind1 (current-column))
6092 (if (> ind1 ind) (throw 'next t))
6093 (if (< ind1 ind) (throw 'exit t))
6094 (if (not (org-at-item-p)) (throw 'exit nil))
6095 (skip-chars-forward " \t")
6096 (looking-at "\\S-+")
6097 (replace-match bullet))))
6098 (goto-line line)
6099 (org-move-to-column col)
6100 (if (string-match "[0-9]" bullet)
6101 (org-renumber-ordered-list 1))))
6103 (defun org-beginning-of-item-list ()
6104 "Go to the beginning of the current item list.
6105 I.e. to the first item in this list."
6106 (interactive)
6107 (org-beginning-of-item)
6108 (let ((pos (point-at-bol))
6109 (ind (org-get-indentation))
6110 ind1)
6111 ;; find where this list begins
6112 (catch 'exit
6113 (while t
6114 (catch 'next
6115 (beginning-of-line 0)
6116 (if (looking-at "[ \t]*$")
6117 (throw (if (bobp) 'exit 'next) t))
6118 (skip-chars-forward " \t") (setq ind1 (current-column))
6119 (if (or (< ind1 ind)
6120 (and (= ind1 ind)
6121 (not (org-at-item-p)))
6122 (and (= (point-at-bol) (point-min))
6123 (setq pos (point-min))))
6124 (throw 'exit t)
6125 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6126 (goto-char pos)))
6129 (defun org-end-of-item-list ()
6130 "Go to the end of the current item list.
6131 I.e. to the text after the last item."
6132 (interactive)
6133 (org-beginning-of-item)
6134 (let ((pos (point-at-bol))
6135 (ind (org-get-indentation))
6136 ind1)
6137 ;; find where this list begins
6138 (catch 'exit
6139 (while t
6140 (catch 'next
6141 (beginning-of-line 2)
6142 (if (looking-at "[ \t]*$")
6143 (throw (if (eobp) 'exit 'next) t))
6144 (skip-chars-forward " \t") (setq ind1 (current-column))
6145 (if (or (< ind1 ind)
6146 (and (= ind1 ind)
6147 (not (org-at-item-p)))
6148 (eobp))
6149 (progn
6150 (setq pos (point-at-bol))
6151 (throw 'exit t))))))
6152 (goto-char pos)))
6155 (defvar org-last-indent-begin-marker (make-marker))
6156 (defvar org-last-indent-end-marker (make-marker))
6158 (defun org-outdent-item (arg)
6159 "Outdent a local list item."
6160 (interactive "p")
6161 (org-indent-item (- arg)))
6163 (defun org-indent-item (arg)
6164 "Indent a local list item."
6165 (interactive "p")
6166 (unless (org-at-item-p)
6167 (error "Not on an item"))
6168 (save-excursion
6169 (let (beg end ind ind1 tmp delta ind-down ind-up)
6170 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6171 (setq beg org-last-indent-begin-marker
6172 end org-last-indent-end-marker)
6173 (org-beginning-of-item)
6174 (setq beg (move-marker org-last-indent-begin-marker (point)))
6175 (org-end-of-item)
6176 (setq end (move-marker org-last-indent-end-marker (point))))
6177 (goto-char beg)
6178 (setq tmp (org-item-indent-positions)
6179 ind (car tmp)
6180 ind-down (nth 2 tmp)
6181 ind-up (nth 1 tmp)
6182 delta (if (> arg 0)
6183 (if ind-down (- ind-down ind) 2)
6184 (if ind-up (- ind-up ind) -2)))
6185 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6186 (while (< (point) end)
6187 (beginning-of-line 1)
6188 (skip-chars-forward " \t") (setq ind1 (current-column))
6189 (delete-region (point-at-bol) (point))
6190 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6191 (beginning-of-line 2))))
6192 (org-fix-bullet-type)
6193 (org-maybe-renumber-ordered-list-safe)
6194 (save-excursion
6195 (beginning-of-line 0)
6196 (condition-case nil (org-beginning-of-item) (error nil))
6197 (org-maybe-renumber-ordered-list-safe)))
6199 (defun org-item-indent-positions ()
6200 "Return indentation for plain list items.
6201 This returns a list with three values: The current indentation, the
6202 parent indentation and the indentation a child should habe.
6203 Assumes cursor in item line."
6204 (let* ((bolpos (point-at-bol))
6205 (ind (org-get-indentation))
6206 ind-down ind-up pos)
6207 (save-excursion
6208 (org-beginning-of-item-list)
6209 (skip-chars-backward "\n\r \t")
6210 (when (org-in-item-p)
6211 (org-beginning-of-item)
6212 (setq ind-up (org-get-indentation))))
6213 (setq pos (point))
6214 (save-excursion
6215 (cond
6216 ((and (condition-case nil (progn (org-previous-item) t)
6217 (error nil))
6218 (or (forward-char 1) t)
6219 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6220 (setq ind-down (org-get-indentation)))
6221 ((and (goto-char pos)
6222 (org-at-item-p))
6223 (goto-char (match-end 0))
6224 (skip-chars-forward " \t")
6225 (setq ind-down (current-column)))))
6226 (list ind ind-up ind-down)))
6228 ;;; The orgstruct minor mode
6230 ;; Define a minor mode which can be used in other modes in order to
6231 ;; integrate the org-mode structure editing commands.
6233 ;; This is really a hack, because the org-mode structure commands use
6234 ;; keys which normally belong to the major mode. Here is how it
6235 ;; works: The minor mode defines all the keys necessary to operate the
6236 ;; structure commands, but wraps the commands into a function which
6237 ;; tests if the cursor is currently at a headline or a plain list
6238 ;; item. If that is the case, the structure command is used,
6239 ;; temporarily setting many Org-mode variables like regular
6240 ;; expressions for filling etc. However, when any of those keys is
6241 ;; used at a different location, function uses `key-binding' to look
6242 ;; up if the key has an associated command in another currently active
6243 ;; keymap (minor modes, major mode, global), and executes that
6244 ;; command. There might be problems if any of the keys is otherwise
6245 ;; used as a prefix key.
6247 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6248 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6249 ;; addresses this by checking explicitly for both bindings.
6251 (defvar orgstruct-mode-map (make-sparse-keymap)
6252 "Keymap for the minor `orgstruct-mode'.")
6254 (defvar org-local-vars nil
6255 "List of local variables, for use by `orgstruct-mode'")
6257 ;;;###autoload
6258 (define-minor-mode orgstruct-mode
6259 "Toggle the minor more `orgstruct-mode'.
6260 This mode is for using Org-mode structure commands in other modes.
6261 The following key behave as if Org-mode was active, if the cursor
6262 is on a headline, or on a plain list item (both in the definition
6263 of Org-mode).
6265 M-up Move entry/item up
6266 M-down Move entry/item down
6267 M-left Promote
6268 M-right Demote
6269 M-S-up Move entry/item up
6270 M-S-down Move entry/item down
6271 M-S-left Promote subtree
6272 M-S-right Demote subtree
6273 M-q Fill paragraph and items like in Org-mode
6274 C-c ^ Sort entries
6275 C-c - Cycle list bullet
6276 TAB Cycle item visibility
6277 M-RET Insert new heading/item
6278 S-M-RET Insert new TODO heading / Chekbox item
6279 C-c C-c Set tags / toggle checkbox"
6280 nil " OrgStruct" nil
6281 (org-load-modules-maybe)
6282 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6284 ;;;###autoload
6285 (defun turn-on-orgstruct ()
6286 "Unconditionally turn on `orgstruct-mode'."
6287 (orgstruct-mode 1))
6289 ;;;###autoload
6290 (defun turn-on-orgstruct++ ()
6291 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6292 In addition to setting orgstruct-mode, this also exports all indentation and
6293 autofilling variables from org-mode into the buffer. Note that turning
6294 off orgstruct-mode will *not* remove these additional settings."
6295 (orgstruct-mode 1)
6296 (let (var val)
6297 (mapc
6298 (lambda (x)
6299 (when (string-match
6300 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6301 (symbol-name (car x)))
6302 (setq var (car x) val (nth 1 x))
6303 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6304 org-local-vars)))
6306 (defun orgstruct-error ()
6307 "Error when there is no default binding for a structure key."
6308 (interactive)
6309 (error "This key has no function outside structure elements"))
6311 (defun orgstruct-setup ()
6312 "Setup orgstruct keymaps."
6313 (let ((nfunc 0)
6314 (bindings
6315 (list
6316 '([(meta up)] org-metaup)
6317 '([(meta down)] org-metadown)
6318 '([(meta left)] org-metaleft)
6319 '([(meta right)] org-metaright)
6320 '([(meta shift up)] org-shiftmetaup)
6321 '([(meta shift down)] org-shiftmetadown)
6322 '([(meta shift left)] org-shiftmetaleft)
6323 '([(meta shift right)] org-shiftmetaright)
6324 '([(shift up)] org-shiftup)
6325 '([(shift down)] org-shiftdown)
6326 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6327 '("\M-q" fill-paragraph)
6328 '("\C-c^" org-sort)
6329 '("\C-c-" org-cycle-list-bullet)))
6330 elt key fun cmd)
6331 (while (setq elt (pop bindings))
6332 (setq nfunc (1+ nfunc))
6333 (setq key (org-key (car elt))
6334 fun (nth 1 elt)
6335 cmd (orgstruct-make-binding fun nfunc key))
6336 (org-defkey orgstruct-mode-map key cmd))
6338 ;; Special treatment needed for TAB and RET
6339 (org-defkey orgstruct-mode-map [(tab)]
6340 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6341 (org-defkey orgstruct-mode-map "\C-i"
6342 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6344 (org-defkey orgstruct-mode-map "\M-\C-m"
6345 (orgstruct-make-binding 'org-insert-heading 105
6346 "\M-\C-m" [(meta return)]))
6347 (org-defkey orgstruct-mode-map [(meta return)]
6348 (orgstruct-make-binding 'org-insert-heading 106
6349 [(meta return)] "\M-\C-m"))
6351 (org-defkey orgstruct-mode-map [(shift meta return)]
6352 (orgstruct-make-binding 'org-insert-todo-heading 107
6353 [(meta return)] "\M-\C-m"))
6355 (unless org-local-vars
6356 (setq org-local-vars (org-get-local-variables)))
6360 (defun orgstruct-make-binding (fun n &rest keys)
6361 "Create a function for binding in the structure minor mode.
6362 FUN is the command to call inside a table. N is used to create a unique
6363 command name. KEYS are keys that should be checked in for a command
6364 to execute outside of tables."
6365 (eval
6366 (list 'defun
6367 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6368 '(arg)
6369 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6370 "Outside of structure, run the binding of `"
6371 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6372 "'.")
6373 '(interactive "p")
6374 (list 'if
6375 '(org-context-p 'headline 'item)
6376 (list 'org-run-like-in-org-mode (list 'quote fun))
6377 (list 'let '(orgstruct-mode)
6378 (list 'call-interactively
6379 (append '(or)
6380 (mapcar (lambda (k)
6381 (list 'key-binding k))
6382 keys)
6383 '('orgstruct-error))))))))
6385 (defun org-context-p (&rest contexts)
6386 "Check if local context is and of CONTEXTS.
6387 Possible values in the list of contexts are `table', `headline', and `item'."
6388 (let ((pos (point)))
6389 (goto-char (point-at-bol))
6390 (prog1 (or (and (memq 'table contexts)
6391 (looking-at "[ \t]*|"))
6392 (and (memq 'headline contexts)
6393 (looking-at "\\*+"))
6394 (and (memq 'item contexts)
6395 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6396 (goto-char pos))))
6398 (defun org-get-local-variables ()
6399 "Return a list of all local variables in an org-mode buffer."
6400 (let (varlist)
6401 (with-current-buffer (get-buffer-create "*Org tmp*")
6402 (erase-buffer)
6403 (org-mode)
6404 (setq varlist (buffer-local-variables)))
6405 (kill-buffer "*Org tmp*")
6406 (delq nil
6407 (mapcar
6408 (lambda (x)
6409 (setq x
6410 (if (symbolp x)
6411 (list x)
6412 (list (car x) (list 'quote (cdr x)))))
6413 (if (string-match
6414 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6415 (symbol-name (car x)))
6416 x nil))
6417 varlist))))
6419 ;;;###autoload
6420 (defun org-run-like-in-org-mode (cmd)
6421 (org-load-modules-maybe)
6422 (unless org-local-vars
6423 (setq org-local-vars (org-get-local-variables)))
6424 (eval (list 'let org-local-vars
6425 (list 'call-interactively (list 'quote cmd)))))
6427 ;;;; Archiving
6429 (defun org-get-category (&optional pos)
6430 "Get the category applying to position POS."
6431 (get-text-property (or pos (point)) 'org-category))
6433 (defun org-refresh-category-properties ()
6434 "Refresh category text properties in the buffer."
6435 (let ((def-cat (cond
6436 ((null org-category)
6437 (if buffer-file-name
6438 (file-name-sans-extension
6439 (file-name-nondirectory buffer-file-name))
6440 "???"))
6441 ((symbolp org-category) (symbol-name org-category))
6442 (t org-category)))
6443 beg end cat pos optionp)
6444 (org-unmodified
6445 (save-excursion
6446 (save-restriction
6447 (widen)
6448 (goto-char (point-min))
6449 (put-text-property (point) (point-max) 'org-category def-cat)
6450 (while (re-search-forward
6451 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6452 (setq pos (match-end 0)
6453 optionp (equal (char-after (match-beginning 0)) ?#)
6454 cat (org-trim (match-string 2)))
6455 (if optionp
6456 (setq beg (point-at-bol) end (point-max))
6457 (org-back-to-heading t)
6458 (setq beg (point) end (org-end-of-subtree t t)))
6459 (put-text-property beg end 'org-category cat)
6460 (goto-char pos)))))))
6463 ;;;; Link Stuff
6465 ;;; Link abbreviations
6467 (defun org-link-expand-abbrev (link)
6468 "Apply replacements as defined in `org-link-abbrev-alist."
6469 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6470 (let* ((key (match-string 1 link))
6471 (as (or (assoc key org-link-abbrev-alist-local)
6472 (assoc key org-link-abbrev-alist)))
6473 (tag (and (match-end 2) (match-string 3 link)))
6474 rpl)
6475 (if (not as)
6476 link
6477 (setq rpl (cdr as))
6478 (cond
6479 ((symbolp rpl) (funcall rpl tag))
6480 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6481 (t (concat rpl tag)))))
6482 link))
6484 ;;; Storing and inserting links
6486 (defvar org-insert-link-history nil
6487 "Minibuffer history for links inserted with `org-insert-link'.")
6489 (defvar org-stored-links nil
6490 "Contains the links stored with `org-store-link'.")
6492 (defvar org-store-link-plist nil
6493 "Plist with info about the most recently link created with `org-store-link'.")
6495 (defvar org-link-protocols nil
6496 "Link protocols added to Org-mode using `org-add-link-type'.")
6498 (defvar org-store-link-functions nil
6499 "List of functions that are called to create and store a link.
6500 Each function will be called in turn until one returns a non-nil
6501 value. Each function should check if it is responsible for creating
6502 this link (for example by looking at the major mode).
6503 If not, it must exit and return nil.
6504 If yes, it should return a non-nil value after a calling
6505 `org-store-link-props' with a list of properties and values.
6506 Special properties are:
6508 :type The link prefix. like \"http\". This must be given.
6509 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6510 This is obligatory as well.
6511 :description Optional default description for the second pair
6512 of brackets in an Org-mode link. The user can still change
6513 this when inserting this link into an Org-mode buffer.
6515 In addition to these, any additional properties can be specified
6516 and then used in remember templates.")
6518 (defun org-add-link-type (type &optional follow export)
6519 "Add TYPE to the list of `org-link-types'.
6520 Re-compute all regular expressions depending on `org-link-types'
6522 FOLLOW and EXPORT are two functions.
6524 FOLLOW should take the link path as the single argument and do whatever
6525 is necessary to follow the link, for example find a file or display
6526 a mail message.
6528 EXPORT should format the link path for export to one of the export formats.
6529 It should be a function accepting three arguments:
6531 path the path of the link, the text after the prefix (like \"http:\")
6532 desc the description of the link, if any, nil if there was no descripton
6533 format the export format, a symbol like `html' or `latex'.
6535 The function may use the FORMAT information to return different values
6536 depending on the format. The return value will be put literally into
6537 the exported file.
6538 Org-mode has a built-in default for exporting links. If you are happy with
6539 this default, there is no need to define an export function for the link
6540 type. For a simple example of an export function, see `org-bbdb.el'."
6541 (add-to-list 'org-link-types type t)
6542 (org-make-link-regexps)
6543 (if (assoc type org-link-protocols)
6544 (setcdr (assoc type org-link-protocols) (list follow export))
6545 (push (list type follow export) org-link-protocols)))
6548 ;;;###autoload
6549 (defun org-store-link (arg)
6550 "\\<org-mode-map>Store an org-link to the current location.
6551 This link is added to `org-stored-links' and can later be inserted
6552 into an org-buffer with \\[org-insert-link].
6554 For some link types, a prefix arg is interpreted:
6555 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6556 For file links, arg negates `org-context-in-file-links'."
6557 (interactive "P")
6558 (org-load-modules-maybe)
6559 (setq org-store-link-plist nil) ; reset
6560 (let (link cpltxt desc description search txt)
6561 (cond
6563 ((run-hook-with-args-until-success 'org-store-link-functions)
6564 (setq link (plist-get org-store-link-plist :link)
6565 desc (or (plist-get org-store-link-plist :description) link)))
6567 ((eq major-mode 'calendar-mode)
6568 (let ((cd (calendar-cursor-to-date)))
6569 (setq link
6570 (format-time-string
6571 (car org-time-stamp-formats)
6572 (apply 'encode-time
6573 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6574 nil nil nil))))
6575 (org-store-link-props :type "calendar" :date cd)))
6577 ((eq major-mode 'w3-mode)
6578 (setq cpltxt (url-view-url t)
6579 link (org-make-link cpltxt))
6580 (org-store-link-props :type "w3" :url (url-view-url t)))
6582 ((eq major-mode 'w3m-mode)
6583 (setq cpltxt (or w3m-current-title w3m-current-url)
6584 link (org-make-link w3m-current-url))
6585 (org-store-link-props :type "w3m" :url (url-view-url t)))
6587 ((setq search (run-hook-with-args-until-success
6588 'org-create-file-search-functions))
6589 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6590 "::" search))
6591 (setq cpltxt (or description link)))
6593 ((eq major-mode 'image-mode)
6594 (setq cpltxt (concat "file:"
6595 (abbreviate-file-name buffer-file-name))
6596 link (org-make-link cpltxt))
6597 (org-store-link-props :type "image" :file buffer-file-name))
6599 ((eq major-mode 'dired-mode)
6600 ;; link to the file in the current line
6601 (setq cpltxt (concat "file:"
6602 (abbreviate-file-name
6603 (expand-file-name
6604 (dired-get-filename nil t))))
6605 link (org-make-link cpltxt)))
6607 ((and buffer-file-name (org-mode-p))
6608 ;; Just link to current headline
6609 (setq cpltxt (concat "file:"
6610 (abbreviate-file-name buffer-file-name)))
6611 ;; Add a context search string
6612 (when (org-xor org-context-in-file-links arg)
6613 ;; Check if we are on a target
6614 (if (org-in-regexp "<<\\(.*?\\)>>")
6615 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6616 (setq txt (cond
6617 ((org-on-heading-p) nil)
6618 ((org-region-active-p)
6619 (buffer-substring (region-beginning) (region-end)))
6620 (t nil)))
6621 (when (or (null txt) (string-match "\\S-" txt))
6622 (setq cpltxt
6623 (concat cpltxt "::"
6624 (condition-case nil
6625 (org-make-org-heading-search-string txt)
6626 (error "")))
6627 desc "NONE"))))
6628 (if (string-match "::\\'" cpltxt)
6629 (setq cpltxt (substring cpltxt 0 -2)))
6630 (setq link (org-make-link cpltxt)))
6632 ((buffer-file-name (buffer-base-buffer))
6633 ;; Just link to this file here.
6634 (setq cpltxt (concat "file:"
6635 (abbreviate-file-name
6636 (buffer-file-name (buffer-base-buffer)))))
6637 ;; Add a context string
6638 (when (org-xor org-context-in-file-links arg)
6639 (setq txt (if (org-region-active-p)
6640 (buffer-substring (region-beginning) (region-end))
6641 (buffer-substring (point-at-bol) (point-at-eol))))
6642 ;; Only use search option if there is some text.
6643 (when (string-match "\\S-" txt)
6644 (setq cpltxt
6645 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6646 desc "NONE")))
6647 (setq link (org-make-link cpltxt)))
6649 ((interactive-p)
6650 (error "Cannot link to a buffer which is not visiting a file"))
6652 (t (setq link nil)))
6654 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6655 (setq link (or link cpltxt)
6656 desc (or desc cpltxt))
6657 (if (equal desc "NONE") (setq desc nil))
6659 (if (and (interactive-p) link)
6660 (progn
6661 (setq org-stored-links
6662 (cons (list link desc) org-stored-links))
6663 (message "Stored: %s" (or desc link)))
6664 (and link (org-make-link-string link desc)))))
6666 (defun org-store-link-props (&rest plist)
6667 "Store link properties, extract names and addresses."
6668 (let (x adr)
6669 (when (setq x (plist-get plist :from))
6670 (setq adr (mail-extract-address-components x))
6671 (plist-put plist :fromname (car adr))
6672 (plist-put plist :fromaddress (nth 1 adr)))
6673 (when (setq x (plist-get plist :to))
6674 (setq adr (mail-extract-address-components x))
6675 (plist-put plist :toname (car adr))
6676 (plist-put plist :toaddress (nth 1 adr))))
6677 (let ((from (plist-get plist :from))
6678 (to (plist-get plist :to)))
6679 (when (and from to org-from-is-user-regexp)
6680 (plist-put plist :fromto
6681 (if (string-match org-from-is-user-regexp from)
6682 (concat "to %t")
6683 (concat "from %f")))))
6684 (setq org-store-link-plist plist))
6686 (defun org-add-link-props (&rest plist)
6687 "Add these properties to the link property list."
6688 (let (key value)
6689 (while plist
6690 (setq key (pop plist) value (pop plist))
6691 (setq org-store-link-plist
6692 (plist-put org-store-link-plist key value)))))
6694 (defun org-email-link-description (&optional fmt)
6695 "Return the description part of an email link.
6696 This takes information from `org-store-link-plist' and formats it
6697 according to FMT (default from `org-email-link-description-format')."
6698 (setq fmt (or fmt org-email-link-description-format))
6699 (let* ((p org-store-link-plist)
6700 (to (plist-get p :toaddress))
6701 (from (plist-get p :fromaddress))
6702 (table
6703 (list
6704 (cons "%c" (plist-get p :fromto))
6705 (cons "%F" (plist-get p :from))
6706 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6707 (cons "%T" (plist-get p :to))
6708 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6709 (cons "%s" (plist-get p :subject))
6710 (cons "%m" (plist-get p :message-id)))))
6711 (when (string-match "%c" fmt)
6712 ;; Check if the user wrote this message
6713 (if (and org-from-is-user-regexp from to
6714 (save-match-data (string-match org-from-is-user-regexp from)))
6715 (setq fmt (replace-match "to %t" t t fmt))
6716 (setq fmt (replace-match "from %f" t t fmt))))
6717 (org-replace-escapes fmt table)))
6719 (defun org-make-org-heading-search-string (&optional string heading)
6720 "Make search string for STRING or current headline."
6721 (interactive)
6722 (let ((s (or string (org-get-heading))))
6723 (unless (and string (not heading))
6724 ;; We are using a headline, clean up garbage in there.
6725 (if (string-match org-todo-regexp s)
6726 (setq s (replace-match "" t t s)))
6727 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6728 (setq s (replace-match "" t t s)))
6729 (setq s (org-trim s))
6730 (if (string-match (concat "^\\(" org-quote-string "\\|"
6731 org-comment-string "\\)") s)
6732 (setq s (replace-match "" t t s)))
6733 (while (string-match org-ts-regexp s)
6734 (setq s (replace-match "" t t s))))
6735 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6736 (setq s (replace-match " " t t s)))
6737 (or string (setq s (concat "*" s))) ; Add * for headlines
6738 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6740 (defun org-make-link (&rest strings)
6741 "Concatenate STRINGS."
6742 (apply 'concat strings))
6744 (defun org-make-link-string (link &optional description)
6745 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6746 (unless (string-match "\\S-" link)
6747 (error "Empty link"))
6748 (when (stringp description)
6749 ;; Remove brackets from the description, they are fatal.
6750 (while (string-match "\\[" description)
6751 (setq description (replace-match "{" t t description)))
6752 (while (string-match "\\]" description)
6753 (setq description (replace-match "}" t t description))))
6754 (when (equal (org-link-escape link) description)
6755 ;; No description needed, it is identical
6756 (setq description nil))
6757 (when (and (not description)
6758 (not (equal link (org-link-escape link))))
6759 (setq description (org-extract-attributes link)))
6760 (concat "[[" (org-link-escape link) "]"
6761 (if description (concat "[" description "]") "")
6762 "]"))
6764 (defconst org-link-escape-chars
6765 '((?\ . "%20")
6766 (?\[ . "%5B")
6767 (?\] . "%5D")
6768 (?\340 . "%E0") ; `a
6769 (?\342 . "%E2") ; ^a
6770 (?\347 . "%E7") ; ,c
6771 (?\350 . "%E8") ; `e
6772 (?\351 . "%E9") ; 'e
6773 (?\352 . "%EA") ; ^e
6774 (?\356 . "%EE") ; ^i
6775 (?\364 . "%F4") ; ^o
6776 (?\371 . "%F9") ; `u
6777 (?\373 . "%FB") ; ^u
6778 (?\; . "%3B")
6779 (?? . "%3F")
6780 (?= . "%3D")
6781 (?+ . "%2B")
6783 "Association list of escapes for some characters problematic in links.
6784 This is the list that is used for internal purposes.")
6786 (defconst org-link-escape-chars-browser
6787 '((?\ . "%20")) ; 32 for the SPC char
6788 "Association list of escapes for some characters problematic in links.
6789 This is the list that is used before handing over to the browser.")
6791 (defun org-link-escape (text &optional table)
6792 "Escape charaters in TEXT that are problematic for links."
6793 (setq table (or table org-link-escape-chars))
6794 (when text
6795 (let ((re (mapconcat (lambda (x) (regexp-quote
6796 (char-to-string (car x))))
6797 table "\\|")))
6798 (while (string-match re text)
6799 (setq text
6800 (replace-match
6801 (cdr (assoc (string-to-char (match-string 0 text))
6802 table))
6803 t t text)))
6804 text)))
6806 (defun org-link-unescape (text &optional table)
6807 "Reverse the action of `org-link-escape'."
6808 (setq table (or table org-link-escape-chars))
6809 (when text
6810 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6811 table "\\|")))
6812 (while (string-match re text)
6813 (setq text
6814 (replace-match
6815 (char-to-string (car (rassoc (match-string 0 text) table)))
6816 t t text)))
6817 text)))
6819 (defun org-xor (a b)
6820 "Exclusive or."
6821 (if a (not b) b))
6823 (defun org-get-header (header)
6824 "Find a header field in the current buffer."
6825 (save-excursion
6826 (goto-char (point-min))
6827 (let ((case-fold-search t) s)
6828 (cond
6829 ((eq header 'from)
6830 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6831 (setq s (match-string 1)))
6832 (while (string-match "\"" s)
6833 (setq s (replace-match "" t t s)))
6834 (if (string-match "[<(].*" s)
6835 (setq s (replace-match "" t t s))))
6836 ((eq header 'message-id)
6837 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6838 (setq s (match-string 1))))
6839 ((eq header 'subject)
6840 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6841 (setq s (match-string 1)))))
6842 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6843 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6844 s)))
6847 (defun org-fixup-message-id-for-http (s)
6848 "Replace special characters in a message id, so it can be used in an http query."
6849 (while (string-match "<" s)
6850 (setq s (replace-match "%3C" t t s)))
6851 (while (string-match ">" s)
6852 (setq s (replace-match "%3E" t t s)))
6853 (while (string-match "@" s)
6854 (setq s (replace-match "%40" t t s)))
6857 ;;;###autoload
6858 (defun org-insert-link-global ()
6859 "Insert a link like Org-mode does.
6860 This command can be called in any mode to insert a link in Org-mode syntax."
6861 (interactive)
6862 (org-load-modules-maybe)
6863 (org-run-like-in-org-mode 'org-insert-link))
6865 (defun org-insert-link (&optional complete-file link-location)
6866 "Insert a link. At the prompt, enter the link.
6868 Completion can be used to select a link previously stored with
6869 `org-store-link'. When the empty string is entered (i.e. if you just
6870 press RET at the prompt), the link defaults to the most recently
6871 stored link. As SPC triggers completion in the minibuffer, you need to
6872 use M-SPC or C-q SPC to force the insertion of a space character.
6874 You will also be prompted for a description, and if one is given, it will
6875 be displayed in the buffer instead of the link.
6877 If there is already a link at point, this command will allow you to edit link
6878 and description parts.
6880 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6881 be selected using completion. The path to the file will be relative to the
6882 current directory if the file is in the current directory or a subdirectory.
6883 Otherwise, the link will be the absolute path as completed in the minibuffer
6884 \(i.e. normally ~/path/to/file).
6886 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6887 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6888 of `org-keep-stored-link-after-insertion'.
6890 If `org-make-link-description-function' is non-nil, this function will be
6891 called with the link target, and the result will be the default
6892 link description.
6894 If the LINK-LOCATION parameter is non-nil, this value will be
6895 used as the link location instead of reading one interactively."
6896 (interactive "P")
6897 (let* ((wcf (current-window-configuration))
6898 (region (if (org-region-active-p)
6899 (buffer-substring (region-beginning) (region-end))))
6900 (remove (and region (list (region-beginning) (region-end))))
6901 (desc region)
6902 tmphist ; byte-compile incorrectly complains about this
6903 (link link-location)
6904 entry file)
6905 (cond
6906 (link-location) ; specified by arg, just use it.
6907 ((org-in-regexp org-bracket-link-regexp 1)
6908 ;; We do have a link at point, and we are going to edit it.
6909 (setq remove (list (match-beginning 0) (match-end 0)))
6910 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6911 (setq link (read-string "Link: "
6912 (org-link-unescape
6913 (org-match-string-no-properties 1)))))
6914 ((or (org-in-regexp org-angle-link-re)
6915 (org-in-regexp org-plain-link-re))
6916 ;; Convert to bracket link
6917 (setq remove (list (match-beginning 0) (match-end 0))
6918 link (read-string "Link: "
6919 (org-remove-angle-brackets (match-string 0)))))
6920 ((equal complete-file '(4))
6921 ;; Completing read for file names.
6922 (setq file (read-file-name "File: "))
6923 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6924 (pwd1 (file-name-as-directory (abbreviate-file-name
6925 (expand-file-name ".")))))
6926 (cond
6927 ((equal complete-file '(16))
6928 (setq link (org-make-link
6929 "file:"
6930 (abbreviate-file-name (expand-file-name file)))))
6931 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6932 (setq link (org-make-link "file:" (match-string 1 file))))
6933 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6934 (expand-file-name file))
6935 (setq link (org-make-link
6936 "file:" (match-string 1 (expand-file-name file)))))
6937 (t (setq link (org-make-link "file:" file))))))
6939 ;; Read link, with completion for stored links.
6940 (with-output-to-temp-buffer "*Org Links*"
6941 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6942 (when org-stored-links
6943 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6944 (princ (mapconcat
6945 (lambda (x)
6946 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6947 (reverse org-stored-links) "\n"))))
6948 (let ((cw (selected-window)))
6949 (select-window (get-buffer-window "*Org Links*"))
6950 (shrink-window-if-larger-than-buffer)
6951 (setq truncate-lines t)
6952 (select-window cw))
6953 ;; Fake a link history, containing the stored links.
6954 (setq tmphist (append (mapcar 'car org-stored-links)
6955 org-insert-link-history))
6956 (unwind-protect
6957 (setq link (org-completing-read
6958 "Link: "
6959 (append
6960 (mapcar (lambda (x) (list (concat (car x) ":")))
6961 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6962 (mapcar (lambda (x) (list (concat x ":")))
6963 org-link-types))
6964 nil nil nil
6965 'tmphist
6966 (or (car (car org-stored-links)))))
6967 (set-window-configuration wcf)
6968 (kill-buffer "*Org Links*"))
6969 (setq entry (assoc link org-stored-links))
6970 (or entry (push link org-insert-link-history))
6971 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6972 (not org-keep-stored-link-after-insertion))
6973 (setq org-stored-links (delq (assoc link org-stored-links)
6974 org-stored-links)))
6975 (setq desc (or desc (nth 1 entry)))))
6977 (if (string-match org-plain-link-re link)
6978 ;; URL-like link, normalize the use of angular brackets.
6979 (setq link (org-make-link (org-remove-angle-brackets link))))
6981 ;; Check if we are linking to the current file with a search option
6982 ;; If yes, simplify the link by using only the search option.
6983 (when (and buffer-file-name
6984 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6985 (let* ((path (match-string 1 link))
6986 (case-fold-search nil)
6987 (search (match-string 2 link)))
6988 (save-match-data
6989 (if (equal (file-truename buffer-file-name) (file-truename path))
6990 ;; We are linking to this same file, with a search option
6991 (setq link search)))))
6993 ;; Check if we can/should use a relative path. If yes, simplify the link
6994 (when (string-match "\\<file:\\(.*\\)" link)
6995 (let* ((path (match-string 1 link))
6996 (origpath path)
6997 (case-fold-search nil))
6998 (cond
6999 ((eq org-link-file-path-type 'absolute)
7000 (setq path (abbreviate-file-name (expand-file-name path))))
7001 ((eq org-link-file-path-type 'noabbrev)
7002 (setq path (expand-file-name path)))
7003 ((eq org-link-file-path-type 'relative)
7004 (setq path (file-relative-name path)))
7006 (save-match-data
7007 (if (string-match (concat "^" (regexp-quote
7008 (file-name-as-directory
7009 (expand-file-name "."))))
7010 (expand-file-name path))
7011 ;; We are linking a file with relative path name.
7012 (setq path (substring (expand-file-name path)
7013 (match-end 0)))))))
7014 (setq link (concat "file:" path))
7015 (if (equal desc origpath)
7016 (setq desc path))))
7018 (if org-make-link-description-function
7019 (setq desc (funcall org-make-link-description-function link desc)))
7021 (setq desc (read-string "Description: " desc))
7022 (unless (string-match "\\S-" desc) (setq desc nil))
7023 (if remove (apply 'delete-region remove))
7024 (insert (org-make-link-string link desc))))
7026 (defun org-completing-read (&rest args)
7027 (let ((minibuffer-local-completion-map
7028 (copy-keymap minibuffer-local-completion-map)))
7029 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7030 (apply 'completing-read args)))
7032 (defun org-extract-attributes (s)
7033 "Extract the attributes cookie from a string and set as text property."
7034 (let (a attr (start 0))
7035 (save-match-data
7036 (when (string-match "{{\\([^}]+\\)}}$" s)
7037 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7038 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7039 (setq key (match-string 1 a) value (match-string 2 a)
7040 start (match-end 0)
7041 attr (plist-put attr (intern key) value))))
7042 (org-add-props s nil 'org-attributes attr))
7045 (defun org-attributes-to-string (plist)
7046 "Format a property list into an HTML attribute list."
7047 (let ((s "") key value)
7048 (while plist
7049 (setq key (pop plist) value (pop plist))
7050 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7053 ;;; Opening/following a link
7055 (defvar org-link-search-failed nil)
7057 (defun org-next-link ()
7058 "Move forward to the next link.
7059 If the link is in hidden text, expose it."
7060 (interactive)
7061 (when (and org-link-search-failed (eq this-command last-command))
7062 (goto-char (point-min))
7063 (message "Link search wrapped back to beginning of buffer"))
7064 (setq org-link-search-failed nil)
7065 (let* ((pos (point))
7066 (ct (org-context))
7067 (a (assoc :link ct)))
7068 (if a (goto-char (nth 2 a)))
7069 (if (re-search-forward org-any-link-re nil t)
7070 (progn
7071 (goto-char (match-beginning 0))
7072 (if (org-invisible-p) (org-show-context)))
7073 (goto-char pos)
7074 (setq org-link-search-failed t)
7075 (error "No further link found"))))
7077 (defun org-previous-link ()
7078 "Move backward to the previous link.
7079 If the link is in hidden text, expose it."
7080 (interactive)
7081 (when (and org-link-search-failed (eq this-command last-command))
7082 (goto-char (point-max))
7083 (message "Link search wrapped back to end of buffer"))
7084 (setq org-link-search-failed nil)
7085 (let* ((pos (point))
7086 (ct (org-context))
7087 (a (assoc :link ct)))
7088 (if a (goto-char (nth 1 a)))
7089 (if (re-search-backward org-any-link-re nil t)
7090 (progn
7091 (goto-char (match-beginning 0))
7092 (if (org-invisible-p) (org-show-context)))
7093 (goto-char pos)
7094 (setq org-link-search-failed t)
7095 (error "No further link found"))))
7097 (defun org-find-file-at-mouse (ev)
7098 "Open file link or URL at mouse."
7099 (interactive "e")
7100 (mouse-set-point ev)
7101 (org-open-at-point 'in-emacs))
7103 (defun org-open-at-mouse (ev)
7104 "Open file link or URL at mouse."
7105 (interactive "e")
7106 (mouse-set-point ev)
7107 (org-open-at-point))
7109 (defvar org-window-config-before-follow-link nil
7110 "The window configuration before following a link.
7111 This is saved in case the need arises to restore it.")
7113 (defvar org-open-link-marker (make-marker)
7114 "Marker pointing to the location where `org-open-at-point; was called.")
7116 ;;;###autoload
7117 (defun org-open-at-point-global ()
7118 "Follow a link like Org-mode does.
7119 This command can be called in any mode to follow a link that has
7120 Org-mode syntax."
7121 (interactive)
7122 (org-run-like-in-org-mode 'org-open-at-point))
7124 ;;;###autoload
7125 (defun org-open-link-from-string (s &optional arg)
7126 "Open a link in the string S, as if it was in Org-mode."
7127 (interactive "sLink: \nP")
7128 (with-temp-buffer
7129 (let ((org-inhibit-startup t))
7130 (org-mode)
7131 (insert s)
7132 (goto-char (point-min))
7133 (org-open-at-point arg))))
7135 (defun org-open-at-point (&optional in-emacs)
7136 "Open link at or after point.
7137 If there is no link at point, this function will search forward up to
7138 the end of the current subtree.
7139 Normally, files will be opened by an appropriate application. If the
7140 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7141 (interactive "P")
7142 (org-load-modules-maybe)
7143 (move-marker org-open-link-marker (point))
7144 (setq org-window-config-before-follow-link (current-window-configuration))
7145 (org-remove-occur-highlights nil nil t)
7146 (if (org-at-timestamp-p t)
7147 (org-follow-timestamp-link)
7148 (let (type path link line search (pos (point)))
7149 (catch 'match
7150 (save-excursion
7151 (skip-chars-forward "^]\n\r")
7152 (when (org-in-regexp org-bracket-link-regexp)
7153 (setq link (org-extract-attributes
7154 (org-link-unescape (org-match-string-no-properties 1))))
7155 (while (string-match " *\n *" link)
7156 (setq link (replace-match " " t t link)))
7157 (setq link (org-link-expand-abbrev link))
7158 (cond
7159 ((or (file-name-absolute-p link)
7160 (string-match "^\\.\\.?/" link))
7161 (setq type "file" path link))
7162 ((string-match org-link-re-with-space2 link)
7163 (setq type (match-string 1 link) path (match-string 2 link)))
7164 (t (setq type "thisfile" path link)))
7165 (throw 'match t)))
7167 (when (get-text-property (point) 'org-linked-text)
7168 (setq type "thisfile"
7169 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7170 (1+ (point)) (point))
7171 path (buffer-substring
7172 (previous-single-property-change pos 'org-linked-text)
7173 (next-single-property-change pos 'org-linked-text)))
7174 (throw 'match t))
7176 (save-excursion
7177 (when (or (org-in-regexp org-angle-link-re)
7178 (org-in-regexp org-plain-link-re))
7179 (setq type (match-string 1) path (match-string 2))
7180 (throw 'match t)))
7181 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7182 (setq type "tree-match"
7183 path (match-string 1))
7184 (throw 'match t))
7185 (save-excursion
7186 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7187 (setq type "tags"
7188 path (match-string 1))
7189 (while (string-match ":" path)
7190 (setq path (replace-match "+" t t path)))
7191 (throw 'match t))))
7192 (unless path
7193 (error "No link found"))
7194 ;; Remove any trailing spaces in path
7195 (if (string-match " +\\'" path)
7196 (setq path (replace-match "" t t path)))
7198 (cond
7200 ((assoc type org-link-protocols)
7201 (funcall (nth 1 (assoc type org-link-protocols)) path))
7203 ((equal type "mailto")
7204 (let ((cmd (car org-link-mailto-program))
7205 (args (cdr org-link-mailto-program)) args1
7206 (address path) (subject "") a)
7207 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7208 (setq address (match-string 1 path)
7209 subject (org-link-escape (match-string 2 path))))
7210 (while args
7211 (cond
7212 ((not (stringp (car args))) (push (pop args) args1))
7213 (t (setq a (pop args))
7214 (if (string-match "%a" a)
7215 (setq a (replace-match address t t a)))
7216 (if (string-match "%s" a)
7217 (setq a (replace-match subject t t a)))
7218 (push a args1))))
7219 (apply cmd (nreverse args1))))
7221 ((member type '("http" "https" "ftp" "news"))
7222 (browse-url (concat type ":" (org-link-escape
7223 path org-link-escape-chars-browser))))
7225 ((member type '("message"))
7226 (browse-url (concat type ":" path)))
7228 ((string= type "tags")
7229 (org-tags-view in-emacs path))
7230 ((string= type "thisfile")
7231 (if in-emacs
7232 (switch-to-buffer-other-window
7233 (org-get-buffer-for-internal-link (current-buffer)))
7234 (org-mark-ring-push))
7235 (let ((cmd `(org-link-search
7236 ,path
7237 ,(cond ((equal in-emacs '(4)) 'occur)
7238 ((equal in-emacs '(16)) 'org-occur)
7239 (t nil))
7240 ,pos)))
7241 (condition-case nil (eval cmd)
7242 (error (progn (widen) (eval cmd))))))
7244 ((string= type "tree-match")
7245 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7247 ((string= type "file")
7248 (if (string-match "::\\([0-9]+\\)\\'" path)
7249 (setq line (string-to-number (match-string 1 path))
7250 path (substring path 0 (match-beginning 0)))
7251 (if (string-match "::\\(.+\\)\\'" path)
7252 (setq search (match-string 1 path)
7253 path (substring path 0 (match-beginning 0)))))
7254 (if (string-match "[*?{]" (file-name-nondirectory path))
7255 (dired path)
7256 (org-open-file path in-emacs line search)))
7258 ((string= type "news")
7259 (require 'org-gnus)
7260 (org-gnus-follow-link path))
7262 ((string= type "shell")
7263 (let ((cmd path))
7264 (if (or (not org-confirm-shell-link-function)
7265 (funcall org-confirm-shell-link-function
7266 (format "Execute \"%s\" in shell? "
7267 (org-add-props cmd nil
7268 'face 'org-warning))))
7269 (progn
7270 (message "Executing %s" cmd)
7271 (shell-command cmd))
7272 (error "Abort"))))
7274 ((string= type "elisp")
7275 (let ((cmd path))
7276 (if (or (not org-confirm-elisp-link-function)
7277 (funcall org-confirm-elisp-link-function
7278 (format "Execute \"%s\" as elisp? "
7279 (org-add-props cmd nil
7280 'face 'org-warning))))
7281 (message "%s => %s" cmd (eval (read cmd)))
7282 (error "Abort"))))
7285 (browse-url-at-point)))))
7286 (move-marker org-open-link-marker nil)
7287 (run-hook-with-args 'org-follow-link-hook))
7289 ;;;; Time estimates
7291 (defun org-get-effort (&optional pom)
7292 "Get the effort estimate for the current entry."
7293 (org-entry-get pom org-effort-property))
7295 ;;; File search
7297 (defvar org-create-file-search-functions nil
7298 "List of functions to construct the right search string for a file link.
7299 These functions are called in turn with point at the location to
7300 which the link should point.
7302 A function in the hook should first test if it would like to
7303 handle this file type, for example by checking the major-mode or
7304 the file extension. If it decides not to handle this file, it
7305 should just return nil to give other functions a chance. If it
7306 does handle the file, it must return the search string to be used
7307 when following the link. The search string will be part of the
7308 file link, given after a double colon, and `org-open-at-point'
7309 will automatically search for it. If special measures must be
7310 taken to make the search successful, another function should be
7311 added to the companion hook `org-execute-file-search-functions',
7312 which see.
7314 A function in this hook may also use `setq' to set the variable
7315 `description' to provide a suggestion for the descriptive text to
7316 be used for this link when it gets inserted into an Org-mode
7317 buffer with \\[org-insert-link].")
7319 (defvar org-execute-file-search-functions nil
7320 "List of functions to execute a file search triggered by a link.
7322 Functions added to this hook must accept a single argument, the
7323 search string that was part of the file link, the part after the
7324 double colon. The function must first check if it would like to
7325 handle this search, for example by checking the major-mode or the
7326 file extension. If it decides not to handle this search, it
7327 should just return nil to give other functions a chance. If it
7328 does handle the search, it must return a non-nil value to keep
7329 other functions from trying.
7331 Each function can access the current prefix argument through the
7332 variable `current-prefix-argument'. Note that a single prefix is
7333 used to force opening a link in Emacs, so it may be good to only
7334 use a numeric or double prefix to guide the search function.
7336 In case this is needed, a function in this hook can also restore
7337 the window configuration before `org-open-at-point' was called using:
7339 (set-window-configuration org-window-config-before-follow-link)")
7341 (defun org-link-search (s &optional type avoid-pos)
7342 "Search for a link search option.
7343 If S is surrounded by forward slashes, it is interpreted as a
7344 regular expression. In org-mode files, this will create an `org-occur'
7345 sparse tree. In ordinary files, `occur' will be used to list matches.
7346 If the current buffer is in `dired-mode', grep will be used to search
7347 in all files. If AVOID-POS is given, ignore matches near that position."
7348 (let ((case-fold-search t)
7349 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7350 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7351 (append '(("") (" ") ("\t") ("\n"))
7352 org-emphasis-alist)
7353 "\\|") "\\)"))
7354 (pos (point))
7355 (pre nil) (post nil)
7356 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7357 (cond
7358 ;; First check if there are any special
7359 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7360 ;; Now try the builtin stuff
7361 ((save-excursion
7362 (goto-char (point-min))
7363 (and
7364 (re-search-forward
7365 (concat "<<" (regexp-quote s0) ">>") nil t)
7366 (setq type 'dedicated
7367 pos (match-beginning 0))))
7368 ;; There is an exact target for this
7369 (goto-char pos))
7370 ((string-match "^/\\(.*\\)/$" s)
7371 ;; A regular expression
7372 (cond
7373 ((org-mode-p)
7374 (org-occur (match-string 1 s)))
7375 ;;((eq major-mode 'dired-mode)
7376 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7377 (t (org-do-occur (match-string 1 s)))))
7379 ;; A normal search strings
7380 (when (equal (string-to-char s) ?*)
7381 ;; Anchor on headlines, post may include tags.
7382 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7383 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7384 s (substring s 1)))
7385 (remove-text-properties
7386 0 (length s)
7387 '(face nil mouse-face nil keymap nil fontified nil) s)
7388 ;; Make a series of regular expressions to find a match
7389 (setq words (org-split-string s "[ \n\r\t]+")
7391 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7392 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7393 "\\)" markers)
7394 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7395 re2a (concat "[ \t\r\n]" re2a_)
7396 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7397 re4 (concat "[^a-zA-Z_]" re4_)
7399 re1 (concat pre re2 post)
7400 re3 (concat pre (if pre re4_ re4) post)
7401 re5 (concat pre ".*" re4)
7402 re2 (concat pre re2)
7403 re2a (concat pre (if pre re2a_ re2a))
7404 re4 (concat pre (if pre re4_ re4))
7405 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7406 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7407 re5 "\\)"
7409 (cond
7410 ((eq type 'org-occur) (org-occur reall))
7411 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7412 (t (goto-char (point-min))
7413 (setq type 'fuzzy)
7414 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7415 (org-search-not-self 1 re1 nil t)
7416 (org-search-not-self 1 re2 nil t)
7417 (org-search-not-self 1 re2a nil t)
7418 (org-search-not-self 1 re3 nil t)
7419 (org-search-not-self 1 re4 nil t)
7420 (org-search-not-self 1 re5 nil t)
7422 (goto-char (match-beginning 1))
7423 (goto-char pos)
7424 (error "No match")))))
7426 ;; Normal string-search
7427 (goto-char (point-min))
7428 (if (search-forward s nil t)
7429 (goto-char (match-beginning 0))
7430 (error "No match"))))
7431 (and (org-mode-p) (org-show-context 'link-search))
7432 type))
7434 (defun org-search-not-self (group &rest args)
7435 "Execute `re-search-forward', but only accept matches that do not
7436 enclose the position of `org-open-link-marker'."
7437 (let ((m org-open-link-marker))
7438 (catch 'exit
7439 (while (apply 're-search-forward args)
7440 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7441 (goto-char (match-end group))
7442 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7443 (> (match-beginning 0) (marker-position m))
7444 (< (match-end 0) (marker-position m)))
7445 (save-match-data
7446 (or (not (org-in-regexp
7447 org-bracket-link-analytic-regexp 1))
7448 (not (match-end 4)) ; no description
7449 (and (<= (match-beginning 4) (point))
7450 (>= (match-end 4) (point))))))
7451 (throw 'exit (point))))))))
7453 (defun org-get-buffer-for-internal-link (buffer)
7454 "Return a buffer to be used for displaying the link target of internal links."
7455 (cond
7456 ((not org-display-internal-link-with-indirect-buffer)
7457 buffer)
7458 ((string-match "(Clone)$" (buffer-name buffer))
7459 (message "Buffer is already a clone, not making another one")
7460 ;; we also do not modify visibility in this case
7461 buffer)
7462 (t ; make a new indirect buffer for displaying the link
7463 (let* ((bn (buffer-name buffer))
7464 (ibn (concat bn "(Clone)"))
7465 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7466 (with-current-buffer ib (org-overview))
7467 ib))))
7469 (defun org-do-occur (regexp &optional cleanup)
7470 "Call the Emacs command `occur'.
7471 If CLEANUP is non-nil, remove the printout of the regular expression
7472 in the *Occur* buffer. This is useful if the regex is long and not useful
7473 to read."
7474 (occur regexp)
7475 (when cleanup
7476 (let ((cwin (selected-window)) win beg end)
7477 (when (setq win (get-buffer-window "*Occur*"))
7478 (select-window win))
7479 (goto-char (point-min))
7480 (when (re-search-forward "match[a-z]+" nil t)
7481 (setq beg (match-end 0))
7482 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7483 (setq end (1- (match-beginning 0)))))
7484 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7485 (goto-char (point-min))
7486 (select-window cwin))))
7488 ;;; The mark ring for links jumps
7490 (defvar org-mark-ring nil
7491 "Mark ring for positions before jumps in Org-mode.")
7492 (defvar org-mark-ring-last-goto nil
7493 "Last position in the mark ring used to go back.")
7494 ;; Fill and close the ring
7495 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7496 (loop for i from 1 to org-mark-ring-length do
7497 (push (make-marker) org-mark-ring))
7498 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7499 org-mark-ring)
7501 (defun org-mark-ring-push (&optional pos buffer)
7502 "Put the current position or POS into the mark ring and rotate it."
7503 (interactive)
7504 (setq pos (or pos (point)))
7505 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7506 (move-marker (car org-mark-ring)
7507 (or pos (point))
7508 (or buffer (current-buffer)))
7509 (message "%s"
7510 (substitute-command-keys
7511 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7513 (defun org-mark-ring-goto (&optional n)
7514 "Jump to the previous position in the mark ring.
7515 With prefix arg N, jump back that many stored positions. When
7516 called several times in succession, walk through the entire ring.
7517 Org-mode commands jumping to a different position in the current file,
7518 or to another Org-mode file, automatically push the old position
7519 onto the ring."
7520 (interactive "p")
7521 (let (p m)
7522 (if (eq last-command this-command)
7523 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7524 (setq p org-mark-ring))
7525 (setq org-mark-ring-last-goto p)
7526 (setq m (car p))
7527 (switch-to-buffer (marker-buffer m))
7528 (goto-char m)
7529 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7531 (defun org-remove-angle-brackets (s)
7532 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7533 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7535 (defun org-add-angle-brackets (s)
7536 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7537 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7539 (defun org-remove-double-quotes (s)
7540 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7541 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7544 ;;; Following specific links
7546 (defun org-follow-timestamp-link ()
7547 (cond
7548 ((org-at-date-range-p t)
7549 (let ((org-agenda-start-on-weekday)
7550 (t1 (match-string 1))
7551 (t2 (match-string 2)))
7552 (setq t1 (time-to-days (org-time-string-to-time t1))
7553 t2 (time-to-days (org-time-string-to-time t2)))
7554 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7555 ((org-at-timestamp-p t)
7556 (org-agenda-list nil (time-to-days (org-time-string-to-time
7557 (substring (match-string 1) 0 10)))
7559 (t (error "This should not happen"))))
7562 ;;; Following file links
7563 (defvar org-wait nil)
7564 (defun org-open-file (path &optional in-emacs line search)
7565 "Open the file at PATH.
7566 First, this expands any special file name abbreviations. Then the
7567 configuration variable `org-file-apps' is checked if it contains an
7568 entry for this file type, and if yes, the corresponding command is launched.
7569 If no application is found, Emacs simply visits the file.
7570 With optional argument IN-EMACS, Emacs will visit the file.
7571 Optional LINE specifies a line to go to, optional SEARCH a string to
7572 search for. If LINE or SEARCH is given, the file will always be
7573 opened in Emacs.
7574 If the file does not exist, an error is thrown."
7575 (setq in-emacs (or in-emacs line search))
7576 (let* ((file (if (equal path "")
7577 buffer-file-name
7578 (substitute-in-file-name (expand-file-name path))))
7579 (apps (append org-file-apps (org-default-apps)))
7580 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7581 (dirp (if remp nil (file-directory-p file)))
7582 (file (if (and dirp org-open-directory-means-index-dot-org)
7583 (concat (file-name-as-directory file) "index.org")
7584 file))
7585 (dfile (downcase file))
7586 (old-buffer (current-buffer))
7587 (old-pos (point))
7588 (old-mode major-mode)
7589 ext cmd)
7590 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7591 (setq ext (match-string 1 dfile))
7592 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7593 (setq ext (match-string 1 dfile))))
7594 (if in-emacs
7595 (setq cmd 'emacs)
7596 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7597 (and dirp (cdr (assoc 'directory apps)))
7598 (cdr (assoc ext apps))
7599 (cdr (assoc t apps)))))
7600 (when (eq cmd 'mailcap)
7601 (require 'mailcap)
7602 (mailcap-parse-mailcaps)
7603 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7604 (command (mailcap-mime-info mime-type)))
7605 (if (stringp command)
7606 (setq cmd command)
7607 (setq cmd 'emacs))))
7608 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7609 (not (file-exists-p file))
7610 (not org-open-non-existing-files))
7611 (error "No such file: %s" file))
7612 (cond
7613 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7614 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7615 (while (string-match "['\"]%s['\"]" cmd)
7616 (setq cmd (replace-match "%s" t t cmd)))
7617 (while (string-match "%s" cmd)
7618 (setq cmd (replace-match
7619 (save-match-data
7620 (shell-quote-argument
7621 (convert-standard-filename file)))
7622 t t cmd)))
7623 (save-window-excursion
7624 (start-process-shell-command cmd nil cmd)
7625 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7627 ((or (stringp cmd)
7628 (eq cmd 'emacs))
7629 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7630 (widen)
7631 (if line (goto-line line)
7632 (if search (org-link-search search))))
7633 ((consp cmd)
7634 (let ((file (convert-standard-filename file)))
7635 (eval cmd)))
7636 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7637 (and (org-mode-p) (eq old-mode 'org-mode)
7638 (or (not (equal old-buffer (current-buffer)))
7639 (not (equal old-pos (point))))
7640 (org-mark-ring-push old-pos old-buffer))))
7642 (defun org-default-apps ()
7643 "Return the default applications for this operating system."
7644 (cond
7645 ((eq system-type 'darwin)
7646 org-file-apps-defaults-macosx)
7647 ((eq system-type 'windows-nt)
7648 org-file-apps-defaults-windowsnt)
7649 (t org-file-apps-defaults-gnu)))
7651 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7652 (defun org-file-remote-p (file)
7653 "Test whether FILE specifies a location on a remote system.
7654 Return non-nil if the location is indeed remote.
7656 For example, the filename \"/user@host:/foo\" specifies a location
7657 on the system \"/user@host:\"."
7658 (cond ((fboundp 'file-remote-p)
7659 (file-remote-p file))
7660 ((fboundp 'tramp-handle-file-remote-p)
7661 (tramp-handle-file-remote-p file))
7662 ((and (boundp 'ange-ftp-name-format)
7663 (string-match (car ange-ftp-name-format) file))
7665 (t nil)))
7668 ;;;; Refiling
7670 (defun org-get-org-file ()
7671 "Read a filename, with default directory `org-directory'."
7672 (let ((default (or org-default-notes-file remember-data-file)))
7673 (read-file-name (format "File name [%s]: " default)
7674 (file-name-as-directory org-directory)
7675 default)))
7677 (defun org-notes-order-reversed-p ()
7678 "Check if the current file should receive notes in reversed order."
7679 (cond
7680 ((not org-reverse-note-order) nil)
7681 ((eq t org-reverse-note-order) t)
7682 ((not (listp org-reverse-note-order)) nil)
7683 (t (catch 'exit
7684 (let ((all org-reverse-note-order)
7685 entry)
7686 (while (setq entry (pop all))
7687 (if (string-match (car entry) buffer-file-name)
7688 (throw 'exit (cdr entry))))
7689 nil)))))
7691 (defvar org-refile-target-table nil
7692 "The list of refile targets, created by `org-refile'.")
7694 (defvar org-agenda-new-buffers nil
7695 "Buffers created to visit agenda files.")
7697 (defun org-get-refile-targets (&optional default-buffer)
7698 "Produce a table with refile targets."
7699 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7700 targets txt re files f desc descre)
7701 (with-current-buffer (or default-buffer (current-buffer))
7702 (while (setq entry (pop entries))
7703 (setq files (car entry) desc (cdr entry))
7704 (cond
7705 ((null files) (setq files (list (current-buffer))))
7706 ((eq files 'org-agenda-files)
7707 (setq files (org-agenda-files 'unrestricted)))
7708 ((and (symbolp files) (fboundp files))
7709 (setq files (funcall files)))
7710 ((and (symbolp files) (boundp files))
7711 (setq files (symbol-value files))))
7712 (if (stringp files) (setq files (list files)))
7713 (cond
7714 ((eq (car desc) :tag)
7715 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7716 ((eq (car desc) :todo)
7717 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7718 ((eq (car desc) :regexp)
7719 (setq descre (cdr desc)))
7720 ((eq (car desc) :level)
7721 (setq descre (concat "^\\*\\{" (number-to-string
7722 (if org-odd-levels-only
7723 (1- (* 2 (cdr desc)))
7724 (cdr desc)))
7725 "\\}[ \t]")))
7726 ((eq (car desc) :maxlevel)
7727 (setq descre (concat "^\\*\\{1," (number-to-string
7728 (if org-odd-levels-only
7729 (1- (* 2 (cdr desc)))
7730 (cdr desc)))
7731 "\\}[ \t]")))
7732 (t (error "Bad refiling target description %s" desc)))
7733 (while (setq f (pop files))
7734 (save-excursion
7735 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7736 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7737 (save-excursion
7738 (save-restriction
7739 (widen)
7740 (goto-char (point-min))
7741 (while (re-search-forward descre nil t)
7742 (goto-char (point-at-bol))
7743 (when (looking-at org-complex-heading-regexp)
7744 (setq txt (match-string 4)
7745 re (concat "^" (regexp-quote
7746 (buffer-substring (match-beginning 1)
7747 (match-end 4)))))
7748 (if (match-end 5) (setq re (concat re "[ \t]+"
7749 (regexp-quote
7750 (match-string 5)))))
7751 (setq re (concat re "[ \t]*$"))
7752 (when org-refile-use-outline-path
7753 (setq txt (mapconcat 'identity
7754 (append
7755 (if (eq org-refile-use-outline-path 'file)
7756 (list (file-name-nondirectory
7757 (buffer-file-name (buffer-base-buffer))))
7758 (if (eq org-refile-use-outline-path 'full-file-path)
7759 (list (buffer-file-name (buffer-base-buffer)))))
7760 (org-get-outline-path)
7761 (list txt))
7762 "/")))
7763 (push (list txt f re (point)) targets))
7764 (goto-char (point-at-eol))))))))
7765 (nreverse targets))))
7767 (defun org-get-outline-path ()
7768 "Return the outline path to the current entry, as a list."
7769 (let (rtn)
7770 (save-excursion
7771 (while (org-up-heading-safe)
7772 (when (looking-at org-complex-heading-regexp)
7773 (push (org-match-string-no-properties 4) rtn)))
7774 rtn)))
7776 (defvar org-refile-history nil
7777 "History for refiling operations.")
7779 (defun org-refile (&optional goto default-buffer)
7780 "Move the entry at point to another heading.
7781 The list of target headings is compiled using the information in
7782 `org-refile-targets', which see. This list is created before each use
7783 and will therefore always be up-to-date.
7785 At the target location, the entry is filed as a subitem of the target heading.
7786 Depending on `org-reverse-note-order', the new subitem will either be the
7787 first of the last subitem.
7789 With prefix arg GOTO, the command will only visit the target location,
7790 not actually move anything.
7791 With a double prefix `C-c C-c', go to the location where the last refiling
7792 operation has put the subtree."
7793 (interactive "P")
7794 (let* ((cbuf (current-buffer))
7795 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7796 pos it nbuf file re level reversed)
7797 (if (equal goto '(16))
7798 (org-refile-goto-last-stored)
7799 (when (setq it (org-refile-get-location
7800 (if goto "Goto: " "Refile to: ") default-buffer))
7801 (setq file (nth 1 it)
7802 re (nth 2 it)
7803 pos (nth 3 it))
7804 (setq nbuf (or (find-buffer-visiting file)
7805 (find-file-noselect file)))
7806 (if goto
7807 (progn
7808 (switch-to-buffer nbuf)
7809 (goto-char pos)
7810 (org-show-context 'org-goto))
7811 (org-copy-subtree 1 nil t)
7812 (save-excursion
7813 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7814 (find-file-noselect file))))
7815 (setq reversed (org-notes-order-reversed-p))
7816 (save-excursion
7817 (save-restriction
7818 (widen)
7819 (goto-char pos)
7820 (looking-at outline-regexp)
7821 (setq level (org-get-valid-level (funcall outline-level) 1))
7822 (goto-char
7823 (if reversed
7824 (outline-next-heading)
7825 (or (save-excursion (outline-get-next-sibling))
7826 (org-end-of-subtree t t)
7827 (point-max))))
7828 (bookmark-set "org-refile-last-stored")
7829 (org-paste-subtree level))))
7830 (org-cut-subtree)
7831 (setq org-markers-to-move nil)
7832 (message "Entry refiled to \"%s\"" (car it)))))))
7834 (defun org-refile-goto-last-stored ()
7835 "Go to the location where the last refile was stored."
7836 (interactive)
7837 (bookmark-jump "org-refile-last-stored")
7838 (message "This is the location of the last refile"))
7840 (defun org-refile-get-location (&optional prompt default-buffer)
7841 "Prompt the user for a refile location, using PROMPT."
7842 (let ((org-refile-targets org-refile-targets)
7843 (org-refile-use-outline-path org-refile-use-outline-path))
7844 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7845 (unless org-refile-target-table
7846 (error "No refile targets"))
7847 (let* ((cbuf (current-buffer))
7848 (cfunc (if org-refile-use-outline-path
7849 'org-olpath-completing-read
7850 'completing-read))
7851 (extra (if org-refile-use-outline-path "/" ""))
7852 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7853 (fname (and filename (file-truename filename)))
7854 (tbl (mapcar
7855 (lambda (x)
7856 (if (not (equal fname (file-truename (nth 1 x))))
7857 (cons (concat (car x) extra " ("
7858 (file-name-nondirectory (nth 1 x)) ")")
7859 (cdr x))
7860 (cons (concat (car x) extra) (cdr x))))
7861 org-refile-target-table))
7862 (completion-ignore-case t))
7863 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7864 tbl)))
7866 (defun org-olpath-completing-read (prompt collection &rest args)
7867 "Read an outline path like a file name."
7868 (let ((thetable collection))
7869 (apply
7870 'completing-read prompt
7871 (lambda (string predicate &optional flag)
7872 (let (rtn r s f (l (length string)))
7873 (cond
7874 ((eq flag nil)
7875 ;; try completion
7876 (try-completion string thetable))
7877 ((eq flag t)
7878 ;; all-completions
7879 (setq rtn (all-completions string thetable predicate))
7880 (mapcar
7881 (lambda (x)
7882 (setq r (substring x l))
7883 (if (string-match " ([^)]*)$" x)
7884 (setq f (match-string 0 x))
7885 (setq f ""))
7886 (if (string-match "/" r)
7887 (concat string (substring r 0 (match-end 0)) f)
7889 rtn))
7890 ((eq flag 'lambda)
7891 ;; exact match?
7892 (assoc string thetable)))
7894 args)))
7896 ;;;; Dynamic blocks
7898 (defun org-find-dblock (name)
7899 "Find the first dynamic block with name NAME in the buffer.
7900 If not found, stay at current position and return nil."
7901 (let (pos)
7902 (save-excursion
7903 (goto-char (point-min))
7904 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7905 nil t)
7906 (match-beginning 0))))
7907 (if pos (goto-char pos))
7908 pos))
7910 (defconst org-dblock-start-re
7911 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7912 "Matches the startline of a dynamic block, with parameters.")
7914 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7915 "Matches the end of a dyhamic block.")
7917 (defun org-create-dblock (plist)
7918 "Create a dynamic block section, with parameters taken from PLIST.
7919 PLIST must containe a :name entry which is used as name of the block."
7920 (unless (bolp) (newline))
7921 (let ((name (plist-get plist :name)))
7922 (insert "#+BEGIN: " name)
7923 (while plist
7924 (if (eq (car plist) :name)
7925 (setq plist (cddr plist))
7926 (insert " " (prin1-to-string (pop plist)))))
7927 (insert "\n\n#+END:\n")
7928 (beginning-of-line -2)))
7930 (defun org-prepare-dblock ()
7931 "Prepare dynamic block for refresh.
7932 This empties the block, puts the cursor at the insert position and returns
7933 the property list including an extra property :name with the block name."
7934 (unless (looking-at org-dblock-start-re)
7935 (error "Not at a dynamic block"))
7936 (let* ((begdel (1+ (match-end 0)))
7937 (name (org-no-properties (match-string 1)))
7938 (params (append (list :name name)
7939 (read (concat "(" (match-string 3) ")")))))
7940 (unless (re-search-forward org-dblock-end-re nil t)
7941 (error "Dynamic block not terminated"))
7942 (setq params
7943 (append params
7944 (list :content (buffer-substring
7945 begdel (match-beginning 0)))))
7946 (delete-region begdel (match-beginning 0))
7947 (goto-char begdel)
7948 (open-line 1)
7949 params))
7951 (defun org-map-dblocks (&optional command)
7952 "Apply COMMAND to all dynamic blocks in the current buffer.
7953 If COMMAND is not given, use `org-update-dblock'."
7954 (let ((cmd (or command 'org-update-dblock))
7955 pos)
7956 (save-excursion
7957 (goto-char (point-min))
7958 (while (re-search-forward org-dblock-start-re nil t)
7959 (goto-char (setq pos (match-beginning 0)))
7960 (condition-case nil
7961 (funcall cmd)
7962 (error (message "Error during update of dynamic block")))
7963 (goto-char pos)
7964 (unless (re-search-forward org-dblock-end-re nil t)
7965 (error "Dynamic block not terminated"))))))
7967 (defun org-dblock-update (&optional arg)
7968 "User command for updating dynamic blocks.
7969 Update the dynamic block at point. With prefix ARG, update all dynamic
7970 blocks in the buffer."
7971 (interactive "P")
7972 (if arg
7973 (org-update-all-dblocks)
7974 (or (looking-at org-dblock-start-re)
7975 (org-beginning-of-dblock))
7976 (org-update-dblock)))
7978 (defun org-update-dblock ()
7979 "Update the dynamic block at point
7980 This means to empty the block, parse for parameters and then call
7981 the correct writing function."
7982 (save-window-excursion
7983 (let* ((pos (point))
7984 (line (org-current-line))
7985 (params (org-prepare-dblock))
7986 (name (plist-get params :name))
7987 (cmd (intern (concat "org-dblock-write:" name))))
7988 (message "Updating dynamic block `%s' at line %d..." name line)
7989 (funcall cmd params)
7990 (message "Updating dynamic block `%s' at line %d...done" name line)
7991 (goto-char pos))))
7993 (defun org-beginning-of-dblock ()
7994 "Find the beginning of the dynamic block at point.
7995 Error if there is no scuh block at point."
7996 (let ((pos (point))
7997 beg)
7998 (end-of-line 1)
7999 (if (and (re-search-backward org-dblock-start-re nil t)
8000 (setq beg (match-beginning 0))
8001 (re-search-forward org-dblock-end-re nil t)
8002 (> (match-end 0) pos))
8003 (goto-char beg)
8004 (goto-char pos)
8005 (error "Not in a dynamic block"))))
8007 (defun org-update-all-dblocks ()
8008 "Update all dynamic blocks in the buffer.
8009 This function can be used in a hook."
8010 (when (org-mode-p)
8011 (org-map-dblocks 'org-update-dblock)))
8014 ;;;; Completion
8016 (defconst org-additional-option-like-keywords
8017 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8018 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8019 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8021 (defcustom org-structure-template-alist
8023 ("s" "#+begin_src ?\n\n#+end_src"
8024 "<src lang=\"?\">\n\n</src>")
8025 ("e" "#+begin_example\n?\n#+end_example"
8026 "<example>\n?\n</example>")
8027 ("q" "#+begin_quote\n?\n#+end_quote"
8028 "<quote>\n?\n</quote>")
8029 ("v" "#+begin_verse\n?\n#+end_verse"
8030 "<verse>\n?\n/verse>")
8031 ("l" "#+begin_latex\n?\n#+end_latex"
8032 "<literal style=\"latex\">\n?\n</literal>")
8033 ("L" "#+latex: "
8034 "<literal style=\"latex\">?</literal>")
8035 ("h" "#+begin_html\n?\n#+end_html"
8036 "<literal style=\"html\">\n?\n</literal>")
8037 ("H" "#+html: "
8038 "<literal style=\"html\">?</literal>")
8039 ("a" "#+begin_ascii\n?\n#+end_ascii")
8040 ("A" "#+ascii: ")
8041 ("i" "#+include %file ?"
8042 "<include file=%file markup=\"?\">")
8044 "Structure completion elements.
8045 This is a list of abbreviation keys and values. The value gets inserted
8046 it you type @samp{.} followed by the key and then the completion key,
8047 usually `M-TAB'. %file will be replaced by a file name after prompting
8048 for the file uning completion.
8049 There are two templates for each key, the first uses the original Org syntax,
8050 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8051 the default when the /org-mtags.el/ module has been loaded. See also the
8052 variable `org-mtags-prefere-muse-templates'.
8053 This is an experimental feature, it is undecided if it is going to stay in."
8054 :group 'org-completion
8055 :type '(repeat
8056 (string :tag "Key")
8057 (string :tag "Template")
8058 (string :tag "Muse Template")))
8060 (defun org-try-structure-completion ()
8061 "Try to complete a structure template before point.
8062 This looks for strings like \"<e\" on an otherwise empty line and
8063 expands them."
8064 (let ((l (buffer-substring (point-at-bol) (point)))
8066 (when (and (looking-at "[ \t]*$")
8067 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8068 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8069 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8070 (match-beginning 1)) a)
8071 t)))
8073 (defun org-complete-expand-structure-template (start cell)
8074 "Expand a structure template."
8075 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8076 (rpl (nth (if musep 2 1) cell)))
8077 (delete-region start (point))
8078 (when (string-match "\\`#\\+" rpl)
8079 (cond
8080 ((bolp))
8081 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8082 (delete-region (point-at-bol) (point)))
8083 (t (newline))))
8084 (setq start (point))
8085 (if (string-match "%file" rpl)
8086 (setq rpl (replace-match
8087 (concat
8088 "\""
8089 (save-match-data
8090 (abbreviate-file-name (read-file-name "Include file: ")))
8091 "\"")
8092 t t rpl)))
8093 (insert rpl)
8094 (if (re-search-backward "\\?" start t) (delete-char 1))))
8097 (defun org-complete (&optional arg)
8098 "Perform completion on word at point.
8099 At the beginning of a headline, this completes TODO keywords as given in
8100 `org-todo-keywords'.
8101 If the current word is preceded by a backslash, completes the TeX symbols
8102 that are supported for HTML support.
8103 If the current word is preceded by \"#+\", completes special words for
8104 setting file options.
8105 In the line after \"#+STARTUP:, complete valid keywords.\"
8106 At all other locations, this simply calls the value of
8107 `org-completion-fallback-command'."
8108 (interactive "P")
8109 (org-without-partial-completion
8110 (catch 'exit
8111 (let* ((a nil)
8112 (end (point))
8113 (beg1 (save-excursion
8114 (skip-chars-backward (org-re "[:alnum:]_@"))
8115 (point)))
8116 (beg (save-excursion
8117 (skip-chars-backward "a-zA-Z0-9_:$")
8118 (point)))
8119 (confirm (lambda (x) (stringp (car x))))
8120 (searchhead (equal (char-before beg) ?*))
8121 (struct
8122 (when (and (member (char-before beg1) '(?. ?<))
8123 (setq a (assoc (buffer-substring beg1 (point))
8124 org-structure-template-alist)))
8125 (org-complete-expand-structure-template (1- beg1) a)
8126 (throw 'exit t)))
8127 (tag (and (equal (char-before beg1) ?:)
8128 (equal (char-after (point-at-bol)) ?*)))
8129 (prop (and (equal (char-before beg1) ?:)
8130 (not (equal (char-after (point-at-bol)) ?*))))
8131 (texp (equal (char-before beg) ?\\))
8132 (link (equal (char-before beg) ?\[))
8133 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8134 beg)
8135 "#+"))
8136 (startup (string-match "^#\\+STARTUP:.*"
8137 (buffer-substring (point-at-bol) (point))))
8138 (completion-ignore-case opt)
8139 (type nil)
8140 (tbl nil)
8141 (table (cond
8142 (opt
8143 (setq type :opt)
8144 (require 'org-exp)
8145 (append
8146 (mapcar
8147 (lambda (x)
8148 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8149 (cons (match-string 2 x) (match-string 1 x)))
8150 (org-split-string (org-get-current-options) "\n"))
8151 (mapcar 'list org-additional-option-like-keywords)))
8152 (startup
8153 (setq type :startup)
8154 org-startup-options)
8155 (link (append org-link-abbrev-alist-local
8156 org-link-abbrev-alist))
8157 (texp
8158 (setq type :tex)
8159 org-html-entities)
8160 ((string-match "\\`\\*+[ \t]+\\'"
8161 (buffer-substring (point-at-bol) beg))
8162 (setq type :todo)
8163 (mapcar 'list org-todo-keywords-1))
8164 (searchhead
8165 (setq type :searchhead)
8166 (save-excursion
8167 (goto-char (point-min))
8168 (while (re-search-forward org-todo-line-regexp nil t)
8169 (push (list
8170 (org-make-org-heading-search-string
8171 (match-string 3) t))
8172 tbl)))
8173 tbl)
8174 (tag (setq type :tag beg beg1)
8175 (or org-tag-alist (org-get-buffer-tags)))
8176 (prop (setq type :prop beg beg1)
8177 (mapcar 'list (org-buffer-property-keys nil t t)))
8178 (t (progn
8179 (call-interactively org-completion-fallback-command)
8180 (throw 'exit nil)))))
8181 (pattern (buffer-substring-no-properties beg end))
8182 (completion (try-completion pattern table confirm)))
8183 (cond ((eq completion t)
8184 (if (not (assoc (upcase pattern) table))
8185 (message "Already complete")
8186 (if (and (equal type :opt)
8187 (not (member (car (assoc (upcase pattern) table))
8188 org-additional-option-like-keywords)))
8189 (insert (substring (cdr (assoc (upcase pattern) table))
8190 (length pattern)))
8191 (if (memq type '(:tag :prop)) (insert ":")))))
8192 ((null completion)
8193 (message "Can't find completion for \"%s\"" pattern)
8194 (ding))
8195 ((not (string= pattern completion))
8196 (delete-region beg end)
8197 (if (string-match " +$" completion)
8198 (setq completion (replace-match "" t t completion)))
8199 (insert completion)
8200 (if (get-buffer-window "*Completions*")
8201 (delete-window (get-buffer-window "*Completions*")))
8202 (if (assoc completion table)
8203 (if (eq type :todo) (insert " ")
8204 (if (memq type '(:tag :prop)) (insert ":"))))
8205 (if (and (equal type :opt) (assoc completion table))
8206 (message "%s" (substitute-command-keys
8207 "Press \\[org-complete] again to insert example settings"))))
8209 (message "Making completion list...")
8210 (let ((list (sort (all-completions pattern table confirm)
8211 'string<)))
8212 (with-output-to-temp-buffer "*Completions*"
8213 (condition-case nil
8214 ;; Protection needed for XEmacs and emacs 21
8215 (display-completion-list list pattern)
8216 (error (display-completion-list list)))))
8217 (message "Making completion list...%s" "done")))))))
8219 ;;;; TODO, DEADLINE, Comments
8221 (defun org-toggle-comment ()
8222 "Change the COMMENT state of an entry."
8223 (interactive)
8224 (save-excursion
8225 (org-back-to-heading)
8226 (let (case-fold-search)
8227 (if (looking-at (concat outline-regexp
8228 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8229 (replace-match "" t t nil 1)
8230 (if (looking-at outline-regexp)
8231 (progn
8232 (goto-char (match-end 0))
8233 (insert org-comment-string " ")))))))
8235 (defvar org-last-todo-state-is-todo nil
8236 "This is non-nil when the last TODO state change led to a TODO state.
8237 If the last change removed the TODO tag or switched to DONE, then
8238 this is nil.")
8240 (defvar org-setting-tags nil) ; dynamically skiped
8242 (defun org-parse-local-options (string var)
8243 "Parse STRING for startup setting relevant for variable VAR."
8244 (let ((rtn (symbol-value var))
8245 e opts)
8246 (save-match-data
8247 (if (or (not string) (not (string-match "\\S-" string)))
8249 (setq opts (delq nil (mapcar (lambda (x)
8250 (setq e (assoc x org-startup-options))
8251 (if (eq (nth 1 e) var) e nil))
8252 (org-split-string string "[ \t]+"))))
8253 (if (not opts)
8255 (setq rtn nil)
8256 (while (setq e (pop opts))
8257 (if (not (nth 3 e))
8258 (setq rtn (nth 2 e))
8259 (if (not (listp rtn)) (setq rtn nil))
8260 (push (nth 2 e) rtn)))
8261 rtn)))))
8263 (defvar org-blocker-hook nil
8264 "Hook for functions that are allowed to block a state change.
8266 Each function gets as its single argument a property list, see
8267 `org-trigger-hook' for more information about this list.
8269 If any of the functions in this hook returns nil, the state change
8270 is blocked.")
8272 (defvar org-trigger-hook nil
8273 "Hook for functions that are triggered by a state change.
8275 Each function gets as its single argument a property list with at least
8276 the following elements:
8278 (:type type-of-change :position pos-at-entry-start
8279 :from old-state :to new-state)
8281 Depending on the type, more properties may be present.
8283 This mechanism is currently implemented for:
8285 TODO state changes
8286 ------------------
8287 :type todo-state-change
8288 :from previous state (keyword as a string), or nil
8289 :to new state (keyword as a string), or nil")
8292 (defun org-todo (&optional arg)
8293 "Change the TODO state of an item.
8294 The state of an item is given by a keyword at the start of the heading,
8295 like
8296 *** TODO Write paper
8297 *** DONE Call mom
8299 The different keywords are specified in the variable `org-todo-keywords'.
8300 By default the available states are \"TODO\" and \"DONE\".
8301 So for this example: when the item starts with TODO, it is changed to DONE.
8302 When it starts with DONE, the DONE is removed. And when neither TODO nor
8303 DONE are present, add TODO at the beginning of the heading.
8305 With C-u prefix arg, use completion to determine the new state.
8306 With numeric prefix arg, switch to that state.
8308 For calling through lisp, arg is also interpreted in the following way:
8309 'none -> empty state
8310 \"\"(empty string) -> switch to empty state
8311 'done -> switch to DONE
8312 'nextset -> switch to the next set of keywords
8313 'previousset -> switch to the previous set of keywords
8314 \"WAITING\" -> switch to the specified keyword, but only if it
8315 really is a member of `org-todo-keywords'."
8316 (interactive "P")
8317 (save-excursion
8318 (catch 'exit
8319 (org-back-to-heading)
8320 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8321 (or (looking-at (concat " +" org-todo-regexp " *"))
8322 (looking-at " *"))
8323 (let* ((match-data (match-data))
8324 (startpos (point-at-bol))
8325 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8326 (org-log-done org-log-done)
8327 (org-log-repeat org-log-repeat)
8328 (org-todo-log-states org-todo-log-states)
8329 (this (match-string 1))
8330 (hl-pos (match-beginning 0))
8331 (head (org-get-todo-sequence-head this))
8332 (ass (assoc head org-todo-kwd-alist))
8333 (interpret (nth 1 ass))
8334 (done-word (nth 3 ass))
8335 (final-done-word (nth 4 ass))
8336 (last-state (or this ""))
8337 (completion-ignore-case t)
8338 (member (member this org-todo-keywords-1))
8339 (tail (cdr member))
8340 (state (cond
8341 ((and org-todo-key-trigger
8342 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8343 (and (not arg) org-use-fast-todo-selection
8344 (not (eq org-use-fast-todo-selection 'prefix)))))
8345 ;; Use fast selection
8346 (org-fast-todo-selection))
8347 ((and (equal arg '(4))
8348 (or (not org-use-fast-todo-selection)
8349 (not org-todo-key-trigger)))
8350 ;; Read a state with completion
8351 (completing-read "State: " (mapcar (lambda(x) (list x))
8352 org-todo-keywords-1)
8353 nil t))
8354 ((eq arg 'right)
8355 (if this
8356 (if tail (car tail) nil)
8357 (car org-todo-keywords-1)))
8358 ((eq arg 'left)
8359 (if (equal member org-todo-keywords-1)
8361 (if this
8362 (nth (- (length org-todo-keywords-1) (length tail) 2)
8363 org-todo-keywords-1)
8364 (org-last org-todo-keywords-1))))
8365 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8366 (setq arg nil))) ; hack to fall back to cycling
8367 (arg
8368 ;; user or caller requests a specific state
8369 (cond
8370 ((equal arg "") nil)
8371 ((eq arg 'none) nil)
8372 ((eq arg 'done) (or done-word (car org-done-keywords)))
8373 ((eq arg 'nextset)
8374 (or (car (cdr (member head org-todo-heads)))
8375 (car org-todo-heads)))
8376 ((eq arg 'previousset)
8377 (let ((org-todo-heads (reverse org-todo-heads)))
8378 (or (car (cdr (member head org-todo-heads)))
8379 (car org-todo-heads))))
8380 ((car (member arg org-todo-keywords-1)))
8381 ((nth (1- (prefix-numeric-value arg))
8382 org-todo-keywords-1))))
8383 ((null member) (or head (car org-todo-keywords-1)))
8384 ((equal this final-done-word) nil) ;; -> make empty
8385 ((null tail) nil) ;; -> first entry
8386 ((eq interpret 'sequence)
8387 (car tail))
8388 ((memq interpret '(type priority))
8389 (if (eq this-command last-command)
8390 (car tail)
8391 (if (> (length tail) 0)
8392 (or done-word (car org-done-keywords))
8393 nil)))
8394 (t nil)))
8395 (next (if state (concat " " state " ") " "))
8396 (change-plist (list :type 'todo-state-change :from this :to state
8397 :position startpos))
8398 dolog now-done-p)
8399 (when org-blocker-hook
8400 (unless (save-excursion
8401 (save-match-data
8402 (run-hook-with-args-until-failure
8403 'org-blocker-hook change-plist)))
8404 (if (interactive-p)
8405 (error "TODO state change from %s to %s blocked" this state)
8406 ;; fail silently
8407 (message "TODO state change from %s to %s blocked" this state)
8408 (throw 'exit nil))))
8409 (store-match-data match-data)
8410 (replace-match next t t)
8411 (unless (pos-visible-in-window-p hl-pos)
8412 (message "TODO state changed to %s" (org-trim next)))
8413 (unless head
8414 (setq head (org-get-todo-sequence-head state)
8415 ass (assoc head org-todo-kwd-alist)
8416 interpret (nth 1 ass)
8417 done-word (nth 3 ass)
8418 final-done-word (nth 4 ass)))
8419 (when (memq arg '(nextset previousset))
8420 (message "Keyword-Set %d/%d: %s"
8421 (- (length org-todo-sets) -1
8422 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8423 (length org-todo-sets)
8424 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8425 (setq org-last-todo-state-is-todo
8426 (not (member state org-done-keywords)))
8427 (setq now-done-p (and (member state org-done-keywords)
8428 (not (member this org-done-keywords))))
8429 (and logging (org-local-logging logging))
8430 (when (and (or org-todo-log-states org-log-done)
8431 (not (memq arg '(nextset previousset))))
8432 ;; we need to look at recording a time and note
8433 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8434 (nth 2 (assoc this org-todo-log-states))))
8435 (when (and state
8436 (member state org-not-done-keywords)
8437 (not (member this org-not-done-keywords)))
8438 ;; This is now a todo state and was not one before
8439 ;; If there was a CLOSED time stamp, get rid of it.
8440 (org-add-planning-info nil nil 'closed))
8441 (when (and now-done-p org-log-done)
8442 ;; It is now done, and it was not done before
8443 (org-add-planning-info 'closed (org-current-time))
8444 (if (and (not dolog) (eq 'note org-log-done))
8445 (org-add-log-setup 'done state 'findpos 'note)))
8446 (when (and state dolog)
8447 ;; This is a non-nil state, and we need to log it
8448 (org-add-log-setup 'state state 'findpos dolog)))
8449 ;; Fixup tag positioning
8450 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8451 (when org-provide-todo-statistics
8452 (org-update-parent-todo-statistics))
8453 (run-hooks 'org-after-todo-state-change-hook)
8454 (if (and arg (not (member state org-done-keywords)))
8455 (setq head (org-get-todo-sequence-head state)))
8456 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8457 ;; Do we need to trigger a repeat?
8458 (when now-done-p (org-auto-repeat-maybe state))
8459 ;; Fixup cursor location if close to the keyword
8460 (if (and (outline-on-heading-p)
8461 (not (bolp))
8462 (save-excursion (beginning-of-line 1)
8463 (looking-at org-todo-line-regexp))
8464 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8465 (progn
8466 (goto-char (or (match-end 2) (match-end 1)))
8467 (just-one-space)))
8468 (when org-trigger-hook
8469 (save-excursion
8470 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8472 (defun org-update-parent-todo-statistics ()
8473 "Update any statistics cookie in the parent of the current headline."
8474 (interactive)
8475 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8476 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8477 (catch 'exit
8478 (save-excursion
8479 (setq level (org-up-heading-safe))
8480 (unless (and level
8481 (re-search-forward box-re (point-at-eol) t))
8482 (throw 'exit nil))
8483 (setq is-percent (match-end 2))
8484 (save-match-data
8485 (unless (outline-next-heading) (throw 'exit nil))
8486 (while (looking-at org-todo-line-regexp)
8487 (setq kwd (match-string 2))
8488 (and kwd (setq cnt-all (1+ cnt-all)))
8489 (and (member kwd org-done-keywords)
8490 (setq cnt-done (1+ cnt-done)))
8491 (condition-case nil
8492 (outline-forward-same-level 1)
8493 (error (end-of-line 1)))))
8494 (replace-match
8495 (if is-percent
8496 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8497 (format "[%d/%d]" cnt-done cnt-all)))
8498 (run-hook-with-args 'org-after-todo-statistics-hook
8499 cnt-done (- cnt-all cnt-done))))))
8501 (defvar org-after-todo-statistics-hook nil
8502 "Hook that is called after a TODO statistics cookie has been updated.
8503 Each function is called with two arguments: the number of not-done entries
8504 and the number of done entries.
8506 For example, the following function, when added to this hook, will switch
8507 an entry to DONE when all children are done, and back to TODO when new
8508 entries are set to a TODO status. Note that this hook is only called
8509 when there is a statistics cookie in the headline!
8511 (defun org-summary-todo (n-done n-not-done)
8512 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8513 (let (org-log-done org-log-states) ; turn off logging
8514 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8517 (defun org-local-logging (value)
8518 "Get logging settings from a property VALUE."
8519 (let* (words w a)
8520 ;; directly set the variables, they are already local.
8521 (setq org-log-done nil
8522 org-log-repeat nil
8523 org-todo-log-states nil)
8524 (setq words (org-split-string value))
8525 (while (setq w (pop words))
8526 (cond
8527 ((setq a (assoc w org-startup-options))
8528 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8529 (set (nth 1 a) (nth 2 a))))
8530 ((setq a (org-extract-log-state-settings w))
8531 (and (member (car a) org-todo-keywords-1)
8532 (push a org-todo-log-states)))))))
8534 (defun org-get-todo-sequence-head (kwd)
8535 "Return the head of the TODO sequence to which KWD belongs.
8536 If KWD is not set, check if there is a text property remembering the
8537 right sequence."
8538 (let (p)
8539 (cond
8540 ((not kwd)
8541 (or (get-text-property (point-at-bol) 'org-todo-head)
8542 (progn
8543 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8544 nil (point-at-eol)))
8545 (get-text-property p 'org-todo-head))))
8546 ((not (member kwd org-todo-keywords-1))
8547 (car org-todo-keywords-1))
8548 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8550 (defun org-fast-todo-selection ()
8551 "Fast TODO keyword selection with single keys.
8552 Returns the new TODO keyword, or nil if no state change should occur."
8553 (let* ((fulltable org-todo-key-alist)
8554 (done-keywords org-done-keywords) ;; needed for the faces.
8555 (maxlen (apply 'max (mapcar
8556 (lambda (x)
8557 (if (stringp (car x)) (string-width (car x)) 0))
8558 fulltable)))
8559 (expert nil)
8560 (fwidth (+ maxlen 3 1 3))
8561 (ncol (/ (- (window-width) 4) fwidth))
8562 tg cnt e c tbl
8563 groups ingroup)
8564 (save-window-excursion
8565 (if expert
8566 (set-buffer (get-buffer-create " *Org todo*"))
8567 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8568 (erase-buffer)
8569 (org-set-local 'org-done-keywords done-keywords)
8570 (setq tbl fulltable cnt 0)
8571 (while (setq e (pop tbl))
8572 (cond
8573 ((equal e '(:startgroup))
8574 (push '() groups) (setq ingroup t)
8575 (when (not (= cnt 0))
8576 (setq cnt 0)
8577 (insert "\n"))
8578 (insert "{ "))
8579 ((equal e '(:endgroup))
8580 (setq ingroup nil cnt 0)
8581 (insert "}\n"))
8583 (setq tg (car e) c (cdr e))
8584 (if ingroup (push tg (car groups)))
8585 (setq tg (org-add-props tg nil 'face
8586 (org-get-todo-face tg)))
8587 (if (and (= cnt 0) (not ingroup)) (insert " "))
8588 (insert "[" c "] " tg (make-string
8589 (- fwidth 4 (length tg)) ?\ ))
8590 (when (= (setq cnt (1+ cnt)) ncol)
8591 (insert "\n")
8592 (if ingroup (insert " "))
8593 (setq cnt 0)))))
8594 (insert "\n")
8595 (goto-char (point-min))
8596 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8597 (fit-window-to-buffer))
8598 (message "[a-z..]:Set [SPC]:clear")
8599 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8600 (cond
8601 ((or (= c ?\C-g)
8602 (and (= c ?q) (not (rassoc c fulltable))))
8603 (setq quit-flag t))
8604 ((= c ?\ ) nil)
8605 ((setq e (rassoc c fulltable) tg (car e))
8607 (t (setq quit-flag t))))))
8609 (defun org-entry-is-todo-p ()
8610 (member (org-get-todo-state) org-not-done-keywords))
8612 (defun org-entry-is-done-p ()
8613 (member (org-get-todo-state) org-done-keywords))
8615 (defun org-get-todo-state ()
8616 (save-excursion
8617 (org-back-to-heading t)
8618 (and (looking-at org-todo-line-regexp)
8619 (match-end 2)
8620 (match-string 2))))
8622 (defun org-at-date-range-p (&optional inactive-ok)
8623 "Is the cursor inside a date range?"
8624 (interactive)
8625 (save-excursion
8626 (catch 'exit
8627 (let ((pos (point)))
8628 (skip-chars-backward "^[<\r\n")
8629 (skip-chars-backward "<[")
8630 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8631 (>= (match-end 0) pos)
8632 (throw 'exit t))
8633 (skip-chars-backward "^<[\r\n")
8634 (skip-chars-backward "<[")
8635 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8636 (>= (match-end 0) pos)
8637 (throw 'exit t)))
8638 nil)))
8640 (defun org-get-repeat ()
8641 "Check if there is a deadline/schedule with repeater in this entry."
8642 (save-match-data
8643 (save-excursion
8644 (org-back-to-heading t)
8645 (if (re-search-forward
8646 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8647 (match-string 1)))))
8649 (defvar org-last-changed-timestamp)
8650 (defvar org-last-inserted-timestamp)
8651 (defvar org-log-post-message)
8652 (defvar org-log-note-purpose)
8653 (defvar org-log-note-how)
8654 (defun org-auto-repeat-maybe (done-word)
8655 "Check if the current headline contains a repeated deadline/schedule.
8656 If yes, set TODO state back to what it was and change the base date
8657 of repeating deadline/scheduled time stamps to new date.
8658 This function is run automatically after each state change to a DONE state."
8659 ;; last-state is dynamically scoped into this function
8660 (let* ((repeat (org-get-repeat))
8661 (aa (assoc last-state org-todo-kwd-alist))
8662 (interpret (nth 1 aa))
8663 (head (nth 2 aa))
8664 (whata '(("d" . day) ("m" . month) ("y" . year)))
8665 (msg "Entry repeats: ")
8666 (org-log-done nil)
8667 (org-todo-log-states nil)
8668 (nshiftmax 10) (nshift 0)
8669 re type n what ts mb0 time)
8670 (when repeat
8671 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8672 (org-todo (if (eq interpret 'type) last-state head))
8673 (when org-log-repeat
8674 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8675 (memq 'org-add-log-note post-command-hook))
8676 ;; OK, we are already setup for some record
8677 (if (eq org-log-repeat 'note)
8678 ;; make sure we take a note, not only a time stamp
8679 (setq org-log-note-how 'note))
8680 ;; Set up for taking a record
8681 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8682 'findpos org-log-repeat)))
8683 (org-back-to-heading t)
8684 (org-add-planning-info nil nil 'closed)
8685 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8686 org-deadline-time-regexp "\\)\\|\\("
8687 org-ts-regexp "\\)"))
8688 (while (re-search-forward
8689 re (save-excursion (outline-next-heading) (point)) t)
8690 (setq type (if (match-end 1) org-scheduled-string
8691 (if (match-end 3) org-deadline-string "Plain:"))
8692 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8693 mb0 (match-beginning 0))
8694 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8695 (setq n (string-to-number (match-string 2 ts))
8696 what (match-string 3 ts))
8697 (if (equal what "w") (setq n (* n 7) what "d"))
8698 ;; Preparation, see if we need to modify the start date for the change
8699 (when (match-end 1)
8700 (setq time (save-match-data (org-time-string-to-time ts)))
8701 (cond
8702 ((equal (match-string 1 ts) ".")
8703 ;; Shift starting date to today
8704 (org-timestamp-change
8705 (- (time-to-days (current-time)) (time-to-days time))
8706 'day))
8707 ((equal (match-string 1 ts) "+")
8708 (while (or (= nshift 0)
8709 (<= (time-to-days time) (time-to-days (current-time))))
8710 (when (= (incf nshift) nshiftmax)
8711 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8712 (error "Abort")))
8713 (org-timestamp-change n (cdr (assoc what whata)))
8714 (org-at-timestamp-p t)
8715 (setq ts (match-string 1))
8716 (setq time (save-match-data (org-time-string-to-time ts))))
8717 (org-timestamp-change (- n) (cdr (assoc what whata)))
8718 ;; rematch, so that we have everything in place for the real shift
8719 (org-at-timestamp-p t)
8720 (setq ts (match-string 1))
8721 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8722 (org-timestamp-change n (cdr (assoc what whata)))
8723 (setq msg (concat msg type org-last-changed-timestamp " "))))
8724 (setq org-log-post-message msg)
8725 (message "%s" msg))))
8727 (defun org-show-todo-tree (arg)
8728 "Make a compact tree which shows all headlines marked with TODO.
8729 The tree will show the lines where the regexp matches, and all higher
8730 headlines above the match.
8731 With a \\[universal-argument] prefix, also show the DONE entries.
8732 With a numeric prefix N, construct a sparse tree for the Nth element
8733 of `org-todo-keywords-1'."
8734 (interactive "P")
8735 (let ((case-fold-search nil)
8736 (kwd-re
8737 (cond ((null arg) org-not-done-regexp)
8738 ((equal arg '(4))
8739 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8740 (mapcar 'list org-todo-keywords-1))))
8741 (concat "\\("
8742 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8743 "\\)\\>")))
8744 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8745 (regexp-quote (nth (1- (prefix-numeric-value arg))
8746 org-todo-keywords-1)))
8747 (t (error "Invalid prefix argument: %s" arg)))))
8748 (message "%d TODO entries found"
8749 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8751 (defun org-deadline (&optional remove time)
8752 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8753 With argument REMOVE, remove any deadline from the item.
8754 When TIME is set, it should be an internal time specification, and the
8755 scheduling will use the corresponding date."
8756 (interactive "P")
8757 (if remove
8758 (progn
8759 (org-remove-timestamp-with-keyword org-deadline-string)
8760 (message "Item no longer has a deadline."))
8761 (if (org-get-repeat)
8762 (error "Cannot change deadline on task with repeater, please do that by hand")
8763 (org-add-planning-info 'deadline time 'closed)
8764 (message "Deadline on %s" org-last-inserted-timestamp))))
8766 (defun org-schedule (&optional remove time)
8767 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8768 With argument REMOVE, remove any scheduling date from the item.
8769 When TIME is set, it should be an internal time specification, and the
8770 scheduling will use the corresponding date."
8771 (interactive "P")
8772 (if remove
8773 (progn
8774 (org-remove-timestamp-with-keyword org-scheduled-string)
8775 (message "Item is no longer scheduled."))
8776 (if (org-get-repeat)
8777 (error "Cannot reschedule task with repeater, please do that by hand")
8778 (org-add-planning-info 'scheduled time 'closed)
8779 (message "Scheduled to %s" org-last-inserted-timestamp))))
8781 (defun org-remove-timestamp-with-keyword (keyword)
8782 "Remove all time stamps with KEYWORD in the current entry."
8783 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8784 beg)
8785 (save-excursion
8786 (org-back-to-heading t)
8787 (setq beg (point))
8788 (org-end-of-subtree t t)
8789 (while (re-search-backward re beg t)
8790 (replace-match "")
8791 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8792 (equal (char-before) ?\ ))
8793 (backward-delete-char 1)
8794 (if (string-match "^[ \t]*$" (buffer-substring
8795 (point-at-bol) (point-at-eol)))
8796 (delete-region (point-at-bol)
8797 (min (point-max) (1+ (point-at-eol))))))))))
8799 (defun org-add-planning-info (what &optional time &rest remove)
8800 "Insert new timestamp with keyword in the line directly after the headline.
8801 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8802 If non is given, the user is prompted for a date.
8803 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8804 be removed."
8805 (interactive)
8806 (let (org-time-was-given org-end-time-was-given ts
8807 end default-time default-input)
8809 (when (and (not time) (memq what '(scheduled deadline)))
8810 ;; Try to get a default date/time from existing timestamp
8811 (save-excursion
8812 (org-back-to-heading t)
8813 (setq end (save-excursion (outline-next-heading) (point)))
8814 (when (re-search-forward (if (eq what 'scheduled)
8815 org-scheduled-time-regexp
8816 org-deadline-time-regexp)
8817 end t)
8818 (setq ts (match-string 1)
8819 default-time
8820 (apply 'encode-time (org-parse-time-string ts))
8821 default-input (and ts (org-get-compact-tod ts))))))
8822 (when what
8823 ;; If necessary, get the time from the user
8824 (setq time (or time (org-read-date nil 'to-time nil nil
8825 default-time default-input))))
8827 (when (and org-insert-labeled-timestamps-at-point
8828 (member what '(scheduled deadline)))
8829 (insert
8830 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8831 (org-insert-time-stamp time org-time-was-given
8832 nil nil nil (list org-end-time-was-given))
8833 (setq what nil))
8834 (save-excursion
8835 (save-restriction
8836 (let (col list elt ts buffer-invisibility-spec)
8837 (org-back-to-heading t)
8838 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8839 (goto-char (match-end 1))
8840 (setq col (current-column))
8841 (goto-char (match-end 0))
8842 (if (eobp) (insert "\n") (forward-char 1))
8843 (if (and (not (looking-at outline-regexp))
8844 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8845 "[^\r\n]*"))
8846 (not (equal (match-string 1) org-clock-string)))
8847 (narrow-to-region (match-beginning 0) (match-end 0))
8848 (insert-before-markers "\n")
8849 (backward-char 1)
8850 (narrow-to-region (point) (point))
8851 (and org-adapt-indentation (org-indent-to-column col)))
8852 ;; Check if we have to remove something.
8853 (setq list (cons what remove))
8854 (while list
8855 (setq elt (pop list))
8856 (goto-char (point-min))
8857 (when (or (and (eq elt 'scheduled)
8858 (re-search-forward org-scheduled-time-regexp nil t))
8859 (and (eq elt 'deadline)
8860 (re-search-forward org-deadline-time-regexp nil t))
8861 (and (eq elt 'closed)
8862 (re-search-forward org-closed-time-regexp nil t)))
8863 (replace-match "")
8864 (if (looking-at "--+<[^>]+>") (replace-match ""))
8865 (if (looking-at " +") (replace-match ""))))
8866 (goto-char (point-max))
8867 (when what
8868 (insert
8869 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8870 (cond ((eq what 'scheduled) org-scheduled-string)
8871 ((eq what 'deadline) org-deadline-string)
8872 ((eq what 'closed) org-closed-string))
8873 " ")
8874 (setq ts (org-insert-time-stamp
8875 time
8876 (or org-time-was-given
8877 (and (eq what 'closed) org-log-done-with-time))
8878 (eq what 'closed)
8879 nil nil (list org-end-time-was-given)))
8880 (end-of-line 1))
8881 (goto-char (point-min))
8882 (widen)
8883 (if (and (looking-at "[ \t]+\n")
8884 (equal (char-before) ?\n))
8885 (delete-region (1- (point)) (point-at-eol)))
8886 ts)))))
8888 (defvar org-log-note-marker (make-marker))
8889 (defvar org-log-note-purpose nil)
8890 (defvar org-log-note-state nil)
8891 (defvar org-log-note-how nil)
8892 (defvar org-log-note-window-configuration nil)
8893 (defvar org-log-note-return-to (make-marker))
8894 (defvar org-log-post-message nil
8895 "Message to be displayed after a log note has been stored.
8896 The auto-repeater uses this.")
8898 (defun org-add-note ()
8899 "Add a note to the current entry.
8900 This is done in the same way as adding a state change note."
8901 (interactive)
8902 (org-add-log-setup 'note nil t nil))
8904 (defun org-add-log-setup (&optional purpose state findpos how)
8905 "Set up the post command hook to take a note.
8906 If this is about to TODO state change, the new state is expected in STATE.
8907 When FINDPOS is non-nil, find the correct position for the note in
8908 the current entry. If not, assume that it can be inserted at point."
8909 (save-excursion
8910 (when findpos
8911 (org-back-to-heading t)
8912 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8913 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8914 "[^\r\n]*\\)?"))
8915 (goto-char (match-end 0))
8916 (unless org-log-states-order-reversed
8917 (and (= (char-after) ?\n) (forward-char 1))
8918 (org-skip-over-state-notes)
8919 (skip-chars-backward " \t\n\r")))
8920 (move-marker org-log-note-marker (point))
8921 (setq org-log-note-purpose purpose
8922 org-log-note-state state
8923 org-log-note-how how)
8924 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8926 (defun org-skip-over-state-notes ()
8927 "Skip past the list of State notes in an entry."
8928 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8929 (while (looking-at "[ \t]*- State")
8930 (condition-case nil
8931 (org-next-item)
8932 (error (org-end-of-item)))))
8934 (defun org-add-log-note (&optional purpose)
8935 "Pop up a window for taking a note, and add this note later at point."
8936 (remove-hook 'post-command-hook 'org-add-log-note)
8937 (setq org-log-note-window-configuration (current-window-configuration))
8938 (delete-other-windows)
8939 (move-marker org-log-note-return-to (point))
8940 (switch-to-buffer (marker-buffer org-log-note-marker))
8941 (goto-char org-log-note-marker)
8942 (org-switch-to-buffer-other-window "*Org Note*")
8943 (erase-buffer)
8944 (if (memq org-log-note-how '(time state))
8945 (org-store-log-note)
8946 (let ((org-inhibit-startup t)) (org-mode))
8947 (insert (format "# Insert note for %s.
8948 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8949 (cond
8950 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8951 ((eq org-log-note-purpose 'done) "closed todo item")
8952 ((eq org-log-note-purpose 'state)
8953 (format "state change to \"%s\"" org-log-note-state))
8954 ((eq org-log-note-purpose 'note)
8955 "this entry")
8956 (t (error "This should not happen")))))
8957 (org-set-local 'org-finish-function 'org-store-log-note)))
8959 (defvar org-note-abort nil) ; dynamically scoped
8960 (defun org-store-log-note ()
8961 "Finish taking a log note, and insert it to where it belongs."
8962 (let ((txt (buffer-string))
8963 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8964 lines ind)
8965 (kill-buffer (current-buffer))
8966 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8967 (setq txt (replace-match "" t t txt)))
8968 (if (string-match "\\s-+\\'" txt)
8969 (setq txt (replace-match "" t t txt)))
8970 (setq lines (org-split-string txt "\n"))
8971 (when (and note (string-match "\\S-" note))
8972 (setq note
8973 (org-replace-escapes
8974 note
8975 (list (cons "%u" (user-login-name))
8976 (cons "%U" user-full-name)
8977 (cons "%t" (format-time-string
8978 (org-time-stamp-format 'long 'inactive)
8979 (current-time)))
8980 (cons "%s" (if org-log-note-state
8981 (concat "\"" org-log-note-state "\"")
8982 "")))))
8983 (if lines (setq note (concat note " \\\\")))
8984 (push note lines))
8985 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8986 (when lines
8987 (save-excursion
8988 (set-buffer (marker-buffer org-log-note-marker))
8989 (save-excursion
8990 (goto-char org-log-note-marker)
8991 (move-marker org-log-note-marker nil)
8992 (end-of-line 1)
8993 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8994 (indent-relative nil)
8995 (insert "- " (pop lines))
8996 (org-indent-line-function)
8997 (beginning-of-line 1)
8998 (looking-at "[ \t]*")
8999 (setq ind (concat (match-string 0) " "))
9000 (end-of-line 1)
9001 (while lines (insert "\n" ind (pop lines)))))))
9002 (set-window-configuration org-log-note-window-configuration)
9003 (with-current-buffer (marker-buffer org-log-note-return-to)
9004 (goto-char org-log-note-return-to))
9005 (move-marker org-log-note-return-to nil)
9006 (and org-log-post-message (message "%s" org-log-post-message)))
9008 (defun org-sparse-tree (&optional arg)
9009 "Create a sparse tree, prompt for the details.
9010 This command can create sparse trees. You first need to select the type
9011 of match used to create the tree:
9013 t Show entries with a specific TODO keyword.
9014 T Show entries selected by a tags match.
9015 p Enter a property name and its value (both with completion on existing
9016 names/values) and show entries with that property.
9017 r Show entries matching a regular expression
9018 d Show deadlines due within `org-deadline-warning-days'."
9019 (interactive "P")
9020 (let (ans kwd value)
9021 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9022 (setq ans (read-char-exclusive))
9023 (cond
9024 ((equal ans ?d)
9025 (call-interactively 'org-check-deadlines))
9026 ((equal ans ?b)
9027 (call-interactively 'org-check-before-date))
9028 ((equal ans ?t)
9029 (org-show-todo-tree '(4)))
9030 ((equal ans ?T)
9031 (call-interactively 'org-tags-sparse-tree))
9032 ((member ans '(?p ?P))
9033 (setq kwd (completing-read "Property: "
9034 (mapcar 'list (org-buffer-property-keys))))
9035 (setq value (completing-read "Value: "
9036 (mapcar 'list (org-property-values kwd))))
9037 (unless (string-match "\\`{.*}\\'" value)
9038 (setq value (concat "\"" value "\"")))
9039 (org-tags-sparse-tree arg (concat kwd "=" value)))
9040 ((member ans '(?r ?R ?/))
9041 (call-interactively 'org-occur))
9042 (t (error "No such sparse tree command \"%c\"" ans)))))
9044 (defvar org-occur-highlights nil
9045 "List of overlays used for occur matches.")
9046 (make-variable-buffer-local 'org-occur-highlights)
9047 (defvar org-occur-parameters nil
9048 "Parameters of the active org-occur calls.
9049 This is a list, each call to org-occur pushes as cons cell,
9050 containing the regular expression and the callback, onto the list.
9051 The list can contain several entries if `org-occur' has been called
9052 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9053 will only contain one set of parameters. When the highlights are
9054 removed (for example with `C-c C-c', or with the next edit (depending
9055 on `org-remove-highlights-with-change'), this variable is emptied
9056 as well.")
9057 (make-variable-buffer-local 'org-occur-parameters)
9059 (defun org-occur (regexp &optional keep-previous callback)
9060 "Make a compact tree which shows all matches of REGEXP.
9061 The tree will show the lines where the regexp matches, and all higher
9062 headlines above the match. It will also show the heading after the match,
9063 to make sure editing the matching entry is easy.
9064 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9065 call to `org-occur' will be kept, to allow stacking of calls to this
9066 command.
9067 If CALLBACK is non-nil, it is a function which is called to confirm
9068 that the match should indeed be shown."
9069 (interactive "sRegexp: \nP")
9070 (unless keep-previous
9071 (org-remove-occur-highlights nil nil t))
9072 (push (cons regexp callback) org-occur-parameters)
9073 (let ((cnt 0))
9074 (save-excursion
9075 (goto-char (point-min))
9076 (if (or (not keep-previous) ; do not want to keep
9077 (not org-occur-highlights)) ; no previous matches
9078 ;; hide everything
9079 (org-overview))
9080 (while (re-search-forward regexp nil t)
9081 (when (or (not callback)
9082 (save-match-data (funcall callback)))
9083 (setq cnt (1+ cnt))
9084 (when org-highlight-sparse-tree-matches
9085 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9086 (org-show-context 'occur-tree))))
9087 (when org-remove-highlights-with-change
9088 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9089 nil 'local))
9090 (unless org-sparse-tree-open-archived-trees
9091 (org-hide-archived-subtrees (point-min) (point-max)))
9092 (run-hooks 'org-occur-hook)
9093 (if (interactive-p)
9094 (message "%d match(es) for regexp %s" cnt regexp))
9095 cnt))
9097 (defun org-show-context (&optional key)
9098 "Make sure point and context and visible.
9099 How much context is shown depends upon the variables
9100 `org-show-hierarchy-above', `org-show-following-heading'. and
9101 `org-show-siblings'."
9102 (let ((heading-p (org-on-heading-p t))
9103 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9104 (following-p (org-get-alist-option org-show-following-heading key))
9105 (entry-p (org-get-alist-option org-show-entry-below key))
9106 (siblings-p (org-get-alist-option org-show-siblings key)))
9107 (catch 'exit
9108 ;; Show heading or entry text
9109 (if (and heading-p (not entry-p))
9110 (org-flag-heading nil) ; only show the heading
9111 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9112 (org-show-hidden-entry))) ; show entire entry
9113 (when following-p
9114 ;; Show next sibling, or heading below text
9115 (save-excursion
9116 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9117 (org-flag-heading nil))))
9118 (when siblings-p (org-show-siblings))
9119 (when hierarchy-p
9120 ;; show all higher headings, possibly with siblings
9121 (save-excursion
9122 (while (and (condition-case nil
9123 (progn (org-up-heading-all 1) t)
9124 (error nil))
9125 (not (bobp)))
9126 (org-flag-heading nil)
9127 (when siblings-p (org-show-siblings))))))))
9129 (defun org-reveal (&optional siblings)
9130 "Show current entry, hierarchy above it, and the following headline.
9131 This can be used to show a consistent set of context around locations
9132 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9133 not t for the search context.
9135 With optional argument SIBLINGS, on each level of the hierarchy all
9136 siblings are shown. This repairs the tree structure to what it would
9137 look like when opened with hierarchical calls to `org-cycle'."
9138 (interactive "P")
9139 (let ((org-show-hierarchy-above t)
9140 (org-show-following-heading t)
9141 (org-show-siblings (if siblings t org-show-siblings)))
9142 (org-show-context nil)))
9144 (defun org-highlight-new-match (beg end)
9145 "Highlight from BEG to END and mark the highlight is an occur headline."
9146 (let ((ov (org-make-overlay beg end)))
9147 (org-overlay-put ov 'face 'secondary-selection)
9148 (push ov org-occur-highlights)))
9150 (defun org-remove-occur-highlights (&optional beg end noremove)
9151 "Remove the occur highlights from the buffer.
9152 BEG and END are ignored. If NOREMOVE is nil, remove this function
9153 from the `before-change-functions' in the current buffer."
9154 (interactive)
9155 (unless org-inhibit-highlight-removal
9156 (mapc 'org-delete-overlay org-occur-highlights)
9157 (setq org-occur-highlights nil)
9158 (setq org-occur-parameters nil)
9159 (unless noremove
9160 (remove-hook 'before-change-functions
9161 'org-remove-occur-highlights 'local))))
9163 ;;;; Priorities
9165 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9166 "Regular expression matching the priority indicator.")
9168 (defvar org-remove-priority-next-time nil)
9170 (defun org-priority-up ()
9171 "Increase the priority of the current item."
9172 (interactive)
9173 (org-priority 'up))
9175 (defun org-priority-down ()
9176 "Decrease the priority of the current item."
9177 (interactive)
9178 (org-priority 'down))
9180 (defun org-priority (&optional action)
9181 "Change the priority of an item by ARG.
9182 ACTION can be `set', `up', `down', or a character."
9183 (interactive)
9184 (setq action (or action 'set))
9185 (let (current new news have remove)
9186 (save-excursion
9187 (org-back-to-heading)
9188 (if (looking-at org-priority-regexp)
9189 (setq current (string-to-char (match-string 2))
9190 have t)
9191 (setq current org-default-priority))
9192 (cond
9193 ((or (eq action 'set)
9194 (if (featurep 'xemacs) (characterp action) (integerp action)))
9195 (if (not (eq action 'set))
9196 (setq new action)
9197 (message "Priority %c-%c, SPC to remove: "
9198 org-highest-priority org-lowest-priority)
9199 (setq new (read-char-exclusive)))
9200 (if (and (= (upcase org-highest-priority) org-highest-priority)
9201 (= (upcase org-lowest-priority) org-lowest-priority))
9202 (setq new (upcase new)))
9203 (cond ((equal new ?\ ) (setq remove t))
9204 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9205 (error "Priority must be between `%c' and `%c'"
9206 org-highest-priority org-lowest-priority))))
9207 ((eq action 'up)
9208 (if (and (not have) (eq last-command this-command))
9209 (setq new org-lowest-priority)
9210 (setq new (if (and org-priority-start-cycle-with-default (not have))
9211 org-default-priority (1- current)))))
9212 ((eq action 'down)
9213 (if (and (not have) (eq last-command this-command))
9214 (setq new org-highest-priority)
9215 (setq new (if (and org-priority-start-cycle-with-default (not have))
9216 org-default-priority (1+ current)))))
9217 (t (error "Invalid action")))
9218 (if (or (< (upcase new) org-highest-priority)
9219 (> (upcase new) org-lowest-priority))
9220 (setq remove t))
9221 (setq news (format "%c" new))
9222 (if have
9223 (if remove
9224 (replace-match "" t t nil 1)
9225 (replace-match news t t nil 2))
9226 (if remove
9227 (error "No priority cookie found in line")
9228 (looking-at org-todo-line-regexp)
9229 (if (match-end 2)
9230 (progn
9231 (goto-char (match-end 2))
9232 (insert " [#" news "]"))
9233 (goto-char (match-beginning 3))
9234 (insert "[#" news "] ")))))
9235 (org-preserve-lc (org-set-tags nil 'align))
9236 (if remove
9237 (message "Priority removed")
9238 (message "Priority of current item set to %s" news))))
9241 (defun org-get-priority (s)
9242 "Find priority cookie and return priority."
9243 (save-match-data
9244 (if (not (string-match org-priority-regexp s))
9245 (* 1000 (- org-lowest-priority org-default-priority))
9246 (* 1000 (- org-lowest-priority
9247 (string-to-char (match-string 2 s)))))))
9249 ;;;; Tags
9251 (defvar org-agenda-archives-mode)
9252 (defun org-scan-tags (action matcher &optional todo-only)
9253 "Scan headline tags with inheritance and produce output ACTION.
9255 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9256 or `agenda' to produce an entry list for an agenda view. It can also be
9257 a Lisp form or a function that should be called at each matched headline, in
9258 this case the return value is a list of all return values from these calls.
9260 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9261 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9262 only lines with a TODO keyword are included in the output."
9263 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9264 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9265 (org-re
9266 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9267 (props (list 'face 'default
9268 'done-face 'org-done
9269 'undone-face 'default
9270 'mouse-face 'highlight
9271 'org-not-done-regexp org-not-done-regexp
9272 'org-todo-regexp org-todo-regexp
9273 'keymap org-agenda-keymap
9274 'help-echo
9275 (format "mouse-2 or RET jump to org file %s"
9276 (abbreviate-file-name
9277 (or (buffer-file-name (buffer-base-buffer))
9278 (buffer-name (buffer-base-buffer)))))))
9279 (case-fold-search nil)
9280 lspos tags tags-list
9281 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9282 (llast 0) rtn rtn1 level category i txt
9283 todo marker entry priority)
9284 (when (not (member action '(agenda sparse-tree)))
9285 (setq action (list 'lambda nil action)))
9286 (save-excursion
9287 (goto-char (point-min))
9288 (when (eq action 'sparse-tree)
9289 (org-overview)
9290 (org-remove-occur-highlights))
9291 (while (re-search-forward re nil t)
9292 (catch :skip
9293 (setq todo (if (match-end 1) (match-string 2))
9294 tags (if (match-end 4) (match-string 4)))
9295 (goto-char (setq lspos (1+ (match-beginning 0))))
9296 (setq level (org-reduced-level (funcall outline-level))
9297 category (org-get-category))
9298 (setq i llast llast level)
9299 ;; remove tag lists from same and sublevels
9300 (while (>= i level)
9301 (when (setq entry (assoc i tags-alist))
9302 (setq tags-alist (delete entry tags-alist)))
9303 (setq i (1- i)))
9304 ;; add the next tags
9305 (when tags
9306 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9307 tags-alist
9308 (cons (cons level tags) tags-alist)))
9309 ;; compile tags for current headline
9310 (setq tags-list
9311 (if org-use-tag-inheritance
9312 (apply 'append (mapcar 'cdr tags-alist))
9313 tags))
9314 (when (and tags org-use-tag-inheritance
9315 (not (eq t org-use-tag-inheritance)))
9316 ;; selective inheritance, remove uninherited ones
9317 (setcdr (car tags-alist)
9318 (org-remove-uniherited-tags (cdar tags-alist))))
9319 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9320 (eval matcher)
9322 (not (member org-archive-tag tags-list))
9323 ;; we have an archive tag, should we use this anyway?
9324 (or (not org-agenda-skip-archived-trees)
9325 (and (eq action 'agenda) org-agenda-archives-mode))))
9326 (unless (eq action 'sparse-tree) (org-agenda-skip))
9328 ;; select this headline
9330 (cond
9331 ((eq action 'sparse-tree)
9332 (and org-highlight-sparse-tree-matches
9333 (org-get-heading) (match-end 0)
9334 (org-highlight-new-match
9335 (match-beginning 0) (match-beginning 1)))
9336 (org-show-context 'tags-tree))
9337 ((eq action 'agenda)
9338 (setq txt (org-format-agenda-item
9340 (concat
9341 (if org-tags-match-list-sublevels
9342 (make-string (1- level) ?.) "")
9343 (org-get-heading))
9344 category tags-list)
9345 priority (org-get-priority txt))
9346 (goto-char lspos)
9347 (setq marker (org-agenda-new-marker))
9348 (org-add-props txt props
9349 'org-marker marker 'org-hd-marker marker 'org-category category
9350 'priority priority 'type "tagsmatch")
9351 (push txt rtn))
9352 ((functionp action)
9353 (save-excursion
9354 (setq rtn1 (funcall action))
9355 (push rtn1 rtn))
9356 (goto-char (point-at-eol)))
9357 (t (error "Invalid action")))
9359 ;; if we are to skip sublevels, jump to end of subtree
9360 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9361 (when (and (eq action 'sparse-tree)
9362 (not org-sparse-tree-open-archived-trees))
9363 (org-hide-archived-subtrees (point-min) (point-max)))
9364 (nreverse rtn)))
9366 (defun org-remove-uniherited-tags (tags)
9367 "Remove all tags that are not inherited from the list TAGS."
9368 (cond
9369 ((eq org-use-tag-inheritance t) tags)
9370 ((not org-use-tag-inheritance) nil)
9371 ((stringp org-use-tag-inheritance)
9372 (delq nil (mapcar
9373 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9374 tags)))
9375 ((listp org-use-tag-inheritance)
9376 (org-delete-all org-use-tag-inheritance tags))))
9378 (defvar todo-only) ;; dynamically scoped
9380 (defun org-tags-sparse-tree (&optional todo-only match)
9381 "Create a sparse tree according to tags string MATCH.
9382 MATCH can contain positive and negative selection of tags, like
9383 \"+WORK+URGENT-WITHBOSS\".
9384 If optional argument TODO_ONLY is non-nil, only select lines that are
9385 also TODO lines."
9386 (interactive "P")
9387 (org-prepare-agenda-buffers (list (current-buffer)))
9388 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9390 (defvar org-cached-props nil)
9391 (defun org-cached-entry-get (pom property)
9392 (if (or (eq t org-use-property-inheritance)
9393 (and (stringp org-use-property-inheritance)
9394 (string-match org-use-property-inheritance property))
9395 (and (listp org-use-property-inheritance)
9396 (member property org-use-property-inheritance)))
9397 ;; Caching is not possible, check it directly
9398 (org-entry-get pom property 'inherit)
9399 ;; Get all properties, so that we can do complicated checks easily
9400 (cdr (assoc property (or org-cached-props
9401 (setq org-cached-props
9402 (org-entry-properties pom)))))))
9404 (defun org-global-tags-completion-table (&optional files)
9405 "Return the list of all tags in all agenda buffer/files."
9406 (save-excursion
9407 (org-uniquify
9408 (delq nil
9409 (apply 'append
9410 (mapcar
9411 (lambda (file)
9412 (set-buffer (find-file-noselect file))
9413 (append (org-get-buffer-tags)
9414 (mapcar (lambda (x) (if (stringp (car-safe x))
9415 (list (car-safe x)) nil))
9416 org-tag-alist)))
9417 (if (and files (car files))
9418 files
9419 (org-agenda-files))))))))
9421 (defun org-make-tags-matcher (match)
9422 "Create the TAGS//TODO matcher form for the selection string MATCH."
9423 ;; todo-only is scoped dynamically into this function, and the function
9424 ;; may change it it the matcher asksk for it.
9425 (unless match
9426 ;; Get a new match request, with completion
9427 (let ((org-last-tags-completion-table
9428 (org-global-tags-completion-table)))
9429 (setq match (completing-read
9430 "Match: " 'org-tags-completion-function nil nil nil
9431 'org-tags-history))))
9433 ;; Parse the string and create a lisp form
9434 (let ((match0 match)
9435 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9436 minus tag mm
9437 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9438 orterms term orlist re-p str-p level-p level-op
9439 prop-p pn pv po cat-p gv)
9440 (if (string-match "/+" match)
9441 ;; match contains also a todo-matching request
9442 (progn
9443 (setq tagsmatch (substring match 0 (match-beginning 0))
9444 todomatch (substring match (match-end 0)))
9445 (if (string-match "^!" todomatch)
9446 (setq todo-only t todomatch (substring todomatch 1)))
9447 (if (string-match "^\\s-*$" todomatch)
9448 (setq todomatch nil)))
9449 ;; only matching tags
9450 (setq tagsmatch match todomatch nil))
9452 ;; Make the tags matcher
9453 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9454 (setq tagsmatcher t)
9455 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9456 (while (setq term (pop orterms))
9457 (while (and (equal (substring term -1) "\\") orterms)
9458 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9459 (while (string-match re term)
9460 (setq minus (and (match-end 1)
9461 (equal (match-string 1 term) "-"))
9462 tag (match-string 2 term)
9463 re-p (equal (string-to-char tag) ?{)
9464 level-p (match-end 4)
9465 prop-p (match-end 5)
9466 mm (cond
9467 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9468 (level-p
9469 (setq level-op (org-op-to-function (match-string 3 term)))
9470 `(,level-op level ,(string-to-number
9471 (match-string 4 term))))
9472 (prop-p
9473 (setq pn (match-string 5 term)
9474 po (match-string 6 term)
9475 pv (match-string 7 term)
9476 cat-p (equal pn "CATEGORY")
9477 re-p (equal (string-to-char pv) ?{)
9478 str-p (equal (string-to-char pv) ?\")
9479 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9480 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9481 (if time-p (setq pv (org-matcher-time pv)))
9482 (setq po (org-op-to-function po (if time-p 'time str-p)))
9483 (if (equal pn "CATEGORY")
9484 (setq gv '(get-text-property (point) 'org-category))
9485 (setq gv `(org-cached-entry-get nil ,pn)))
9486 (if re-p
9487 (if (eq po 'org<>)
9488 `(not (string-match ,pv (or ,gv "")))
9489 `(string-match ,pv (or ,gv "")))
9490 (if str-p
9491 `(,po (or ,gv "") ,pv)
9492 `(,po (string-to-number (or ,gv ""))
9493 ,(string-to-number pv) ))))
9494 (t `(member ,(downcase tag) tags-list)))
9495 mm (if minus (list 'not mm) mm)
9496 term (substring term (match-end 0)))
9497 (push mm tagsmatcher))
9498 (push (if (> (length tagsmatcher) 1)
9499 (cons 'and tagsmatcher)
9500 (car tagsmatcher))
9501 orlist)
9502 (setq tagsmatcher nil))
9503 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9504 (setq tagsmatcher
9505 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9506 ;; Make the todo matcher
9507 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9508 (setq todomatcher t)
9509 (setq orterms (org-split-string todomatch "|") orlist nil)
9510 (while (setq term (pop orterms))
9511 (while (string-match re term)
9512 (setq minus (and (match-end 1)
9513 (equal (match-string 1 term) "-"))
9514 kwd (match-string 2 term)
9515 re-p (equal (string-to-char kwd) ?{)
9516 term (substring term (match-end 0))
9517 mm (if re-p
9518 `(string-match ,(substring kwd 1 -1) todo)
9519 (list 'equal 'todo kwd))
9520 mm (if minus (list 'not mm) mm))
9521 (push mm todomatcher))
9522 (push (if (> (length todomatcher) 1)
9523 (cons 'and todomatcher)
9524 (car todomatcher))
9525 orlist)
9526 (setq todomatcher nil))
9527 (setq todomatcher (if (> (length orlist) 1)
9528 (cons 'or orlist) (car orlist))))
9530 ;; Return the string and lisp forms of the matcher
9531 (setq matcher (if todomatcher
9532 (list 'and tagsmatcher todomatcher)
9533 tagsmatcher))
9534 (cons match0 matcher)))
9536 (defun org-op-to-function (op &optional stringp)
9537 "Turn an operator into the appropriate function."
9538 (setq op
9539 (cond
9540 ((equal op "<" ) '(< string< org-time<))
9541 ((equal op ">" ) '(> org-string> org-time>))
9542 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9543 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9544 ((member op '("=" "==")) '(= string= org-time=))
9545 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9546 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9548 (defun org<> (a b) (not (= a b)))
9549 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9550 (defun org-string>= (a b) (not (string< a b)))
9551 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9552 (defun org-string<> (a b) (not (string= a b)))
9553 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9554 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9555 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9556 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9557 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9558 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9559 (defun org-2ft (s)
9560 "Convert S to a floating point time.
9561 If S is already a number, just return it. If it is a string, parse
9562 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9563 (cond
9564 ((numberp s) s)
9565 ((stringp s)
9566 (condition-case nil
9567 (float-time (apply 'encode-time (org-parse-time-string s)))
9568 (error 0.)))
9569 (t 0.)))
9571 (defun org-matcher-time (s)
9572 (cond
9573 ((equal s "<now>") (float-time))
9574 ((equal s "<today>")
9575 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9576 (t (org-2ft s))))
9578 (defun org-match-any-p (re list)
9579 "Does re match any element of list?"
9580 (setq list (mapcar (lambda (x) (string-match re x)) list))
9581 (delq nil list))
9583 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9584 (defvar org-tags-overlay (org-make-overlay 1 1))
9585 (org-detach-overlay org-tags-overlay)
9587 (defun org-get-tags-at (&optional pos)
9588 "Get a list of all headline tags applicable at POS.
9589 POS defaults to point. If tags are inherited, the list contains
9590 the targets in the same sequence as the headlines appear, i.e.
9591 the tags of the current headline come last."
9592 (interactive)
9593 (let (tags ltags lastpos parent)
9594 (save-excursion
9595 (save-restriction
9596 (widen)
9597 (goto-char (or pos (point)))
9598 (save-match-data
9599 (condition-case nil
9600 (progn
9601 (org-back-to-heading t)
9602 (while (not (equal lastpos (point)))
9603 (setq lastpos (point))
9604 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9605 (setq ltags (org-split-string
9606 (org-match-string-no-properties 1) ":"))
9607 (setq tags (append (org-remove-uniherited-tags ltags)
9608 tags)))
9609 (or org-use-tag-inheritance (error ""))
9610 (org-up-heading-all 1)
9611 (setq parent t)))
9612 (error nil))))
9613 (append (org-remove-uniherited-tags org-file-tags) tags))))
9615 (defun org-toggle-tag (tag &optional onoff)
9616 "Toggle the tag TAG for the current line.
9617 If ONOFF is `on' or `off', don't toggle but set to this state."
9618 (unless (org-on-heading-p t) (error "Not on headling"))
9619 (let (res current)
9620 (save-excursion
9621 (beginning-of-line)
9622 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9623 (point-at-eol) t)
9624 (progn
9625 (setq current (match-string 1))
9626 (replace-match ""))
9627 (setq current ""))
9628 (setq current (nreverse (org-split-string current ":")))
9629 (cond
9630 ((eq onoff 'on)
9631 (setq res t)
9632 (or (member tag current) (push tag current)))
9633 ((eq onoff 'off)
9634 (or (not (member tag current)) (setq current (delete tag current))))
9635 (t (if (member tag current)
9636 (setq current (delete tag current))
9637 (setq res t)
9638 (push tag current))))
9639 (end-of-line 1)
9640 (if current
9641 (progn
9642 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9643 (org-set-tags nil t))
9644 (delete-horizontal-space))
9645 (run-hooks 'org-after-tags-change-hook))
9646 res))
9648 (defun org-align-tags-here (to-col)
9649 ;; Assumes that this is a headline
9650 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9651 (beginning-of-line 1)
9652 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9653 (< pos (match-beginning 2)))
9654 (progn
9655 (setq tags-l (- (match-end 2) (match-beginning 2)))
9656 (goto-char (match-beginning 1))
9657 (insert " ")
9658 (delete-region (point) (1+ (match-beginning 2)))
9659 (setq ncol (max (1+ (current-column))
9660 (1+ col)
9661 (if (> to-col 0)
9662 to-col
9663 (- (abs to-col) tags-l))))
9664 (setq p (point))
9665 (insert (make-string (- ncol (current-column)) ?\ ))
9666 (setq ncol (current-column))
9667 (when indent-tabs-mode (tabify p (point-at-eol)))
9668 (org-move-to-column (min ncol col) t))
9669 (goto-char pos))))
9671 (defun org-set-tags (&optional arg just-align)
9672 "Set the tags for the current headline.
9673 With prefix ARG, realign all tags in headings in the current buffer."
9674 (interactive "P")
9675 (let* ((re (concat "^" outline-regexp))
9676 (current (org-get-tags-string))
9677 (col (current-column))
9678 (org-setting-tags t)
9679 table current-tags inherited-tags ; computed below when needed
9680 tags p0 c0 c1 rpl)
9681 (if arg
9682 (save-excursion
9683 (goto-char (point-min))
9684 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9685 (while (re-search-forward re nil t)
9686 (org-set-tags nil t)
9687 (end-of-line 1)))
9688 (message "All tags realigned to column %d" org-tags-column))
9689 (if just-align
9690 (setq tags current)
9691 ;; Get a new set of tags from the user
9692 (save-excursion
9693 (setq table (or org-tag-alist (org-get-buffer-tags))
9694 org-last-tags-completion-table table
9695 current-tags (org-split-string current ":")
9696 inherited-tags (nreverse
9697 (nthcdr (length current-tags)
9698 (nreverse (org-get-tags-at))))
9699 tags
9700 (if (or (eq t org-use-fast-tag-selection)
9701 (and org-use-fast-tag-selection
9702 (delq nil (mapcar 'cdr table))))
9703 (org-fast-tag-selection
9704 current-tags inherited-tags table
9705 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9706 (let ((org-add-colon-after-tag-completion t))
9707 (org-trim
9708 (org-without-partial-completion
9709 (completing-read "Tags: " 'org-tags-completion-function
9710 nil nil current 'org-tags-history)))))))
9711 (while (string-match "[-+&]+" tags)
9712 ;; No boolean logic, just a list
9713 (setq tags (replace-match ":" t t tags))))
9715 (if (string-match "\\`[\t ]*\\'" tags)
9716 (setq tags "")
9717 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9718 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9720 ;; Insert new tags at the correct column
9721 (beginning-of-line 1)
9722 (cond
9723 ((and (equal current "") (equal tags "")))
9724 ((re-search-forward
9725 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9726 (point-at-eol) t)
9727 (if (equal tags "")
9728 (setq rpl "")
9729 (goto-char (match-beginning 0))
9730 (setq c0 (current-column) p0 (point)
9731 c1 (max (1+ c0) (if (> org-tags-column 0)
9732 org-tags-column
9733 (- (- org-tags-column) (length tags))))
9734 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9735 (replace-match rpl t t)
9736 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9737 tags)
9738 (t (error "Tags alignment failed")))
9739 (org-move-to-column col)
9740 (unless just-align
9741 (run-hooks 'org-after-tags-change-hook)))))
9743 (defun org-change-tag-in-region (beg end tag off)
9744 "Add or remove TAG for each entry in the region.
9745 This works in the agenda, and also in an org-mode buffer."
9746 (interactive
9747 (list (region-beginning) (region-end)
9748 (let ((org-last-tags-completion-table
9749 (if (org-mode-p)
9750 (org-get-buffer-tags)
9751 (org-global-tags-completion-table))))
9752 (completing-read
9753 "Tag: " 'org-tags-completion-function nil nil nil
9754 'org-tags-history))
9755 (progn
9756 (message "[s]et or [r]emove? ")
9757 (equal (read-char-exclusive) ?r))))
9758 (if (fboundp 'deactivate-mark) (deactivate-mark))
9759 (let ((agendap (equal major-mode 'org-agenda-mode))
9760 l1 l2 m buf pos newhead (cnt 0))
9761 (goto-char end)
9762 (setq l2 (1- (org-current-line)))
9763 (goto-char beg)
9764 (setq l1 (org-current-line))
9765 (loop for l from l1 to l2 do
9766 (goto-line l)
9767 (setq m (get-text-property (point) 'org-hd-marker))
9768 (when (or (and (org-mode-p) (org-on-heading-p))
9769 (and agendap m))
9770 (setq buf (if agendap (marker-buffer m) (current-buffer))
9771 pos (if agendap m (point)))
9772 (with-current-buffer buf
9773 (save-excursion
9774 (save-restriction
9775 (goto-char pos)
9776 (setq cnt (1+ cnt))
9777 (org-toggle-tag tag (if off 'off 'on))
9778 (setq newhead (org-get-heading)))))
9779 (and agendap (org-agenda-change-all-lines newhead m))))
9780 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9782 (defun org-tags-completion-function (string predicate &optional flag)
9783 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9784 (confirm (lambda (x) (stringp (car x)))))
9785 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9786 (setq s1 (match-string 1 string)
9787 s2 (match-string 2 string))
9788 (setq s1 "" s2 string))
9789 (cond
9790 ((eq flag nil)
9791 ;; try completion
9792 (setq rtn (try-completion s2 ctable confirm))
9793 (if (stringp rtn)
9794 (setq rtn
9795 (concat s1 s2 (substring rtn (length s2))
9796 (if (and org-add-colon-after-tag-completion
9797 (assoc rtn ctable))
9798 ":" ""))))
9799 rtn)
9800 ((eq flag t)
9801 ;; all-completions
9802 (all-completions s2 ctable confirm)
9804 ((eq flag 'lambda)
9805 ;; exact match?
9806 (assoc s2 ctable)))
9809 (defun org-fast-tag-insert (kwd tags face &optional end)
9810 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9811 (insert (format "%-12s" (concat kwd ":"))
9812 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9813 (or end "")))
9815 (defun org-fast-tag-show-exit (flag)
9816 (save-excursion
9817 (goto-line 3)
9818 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9819 (replace-match ""))
9820 (when flag
9821 (end-of-line 1)
9822 (org-move-to-column (- (window-width) 19) t)
9823 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9825 (defun org-set-current-tags-overlay (current prefix)
9826 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9827 (if (featurep 'xemacs)
9828 (org-overlay-display org-tags-overlay (concat prefix s)
9829 'secondary-selection)
9830 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9831 (org-overlay-display org-tags-overlay (concat prefix s)))))
9833 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9834 "Fast tag selection with single keys.
9835 CURRENT is the current list of tags in the headline, INHERITED is the
9836 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9837 possibly with grouping information. TODO-TABLE is a similar table with
9838 TODO keywords, should these have keys assigned to them.
9839 If the keys are nil, a-z are automatically assigned.
9840 Returns the new tags string, or nil to not change the current settings."
9841 (let* ((fulltable (append table todo-table))
9842 (maxlen (apply 'max (mapcar
9843 (lambda (x)
9844 (if (stringp (car x)) (string-width (car x)) 0))
9845 fulltable)))
9846 (buf (current-buffer))
9847 (expert (eq org-fast-tag-selection-single-key 'expert))
9848 (buffer-tags nil)
9849 (fwidth (+ maxlen 3 1 3))
9850 (ncol (/ (- (window-width) 4) fwidth))
9851 (i-face 'org-done)
9852 (c-face 'org-todo)
9853 tg cnt e c char c1 c2 ntable tbl rtn
9854 ov-start ov-end ov-prefix
9855 (exit-after-next org-fast-tag-selection-single-key)
9856 (done-keywords org-done-keywords)
9857 groups ingroup)
9858 (save-excursion
9859 (beginning-of-line 1)
9860 (if (looking-at
9861 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9862 (setq ov-start (match-beginning 1)
9863 ov-end (match-end 1)
9864 ov-prefix "")
9865 (setq ov-start (1- (point-at-eol))
9866 ov-end (1+ ov-start))
9867 (skip-chars-forward "^\n\r")
9868 (setq ov-prefix
9869 (concat
9870 (buffer-substring (1- (point)) (point))
9871 (if (> (current-column) org-tags-column)
9873 (make-string (- org-tags-column (current-column)) ?\ ))))))
9874 (org-move-overlay org-tags-overlay ov-start ov-end)
9875 (save-window-excursion
9876 (if expert
9877 (set-buffer (get-buffer-create " *Org tags*"))
9878 (delete-other-windows)
9879 (split-window-vertically)
9880 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9881 (erase-buffer)
9882 (org-set-local 'org-done-keywords done-keywords)
9883 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9884 (org-fast-tag-insert "Current" current c-face "\n\n")
9885 (org-fast-tag-show-exit exit-after-next)
9886 (org-set-current-tags-overlay current ov-prefix)
9887 (setq tbl fulltable char ?a cnt 0)
9888 (while (setq e (pop tbl))
9889 (cond
9890 ((equal e '(:startgroup))
9891 (push '() groups) (setq ingroup t)
9892 (when (not (= cnt 0))
9893 (setq cnt 0)
9894 (insert "\n"))
9895 (insert "{ "))
9896 ((equal e '(:endgroup))
9897 (setq ingroup nil cnt 0)
9898 (insert "}\n"))
9900 (setq tg (car e) c2 nil)
9901 (if (cdr e)
9902 (setq c (cdr e))
9903 ;; automatically assign a character.
9904 (setq c1 (string-to-char
9905 (downcase (substring
9906 tg (if (= (string-to-char tg) ?@) 1 0)))))
9907 (if (or (rassoc c1 ntable) (rassoc c1 table))
9908 (while (or (rassoc char ntable) (rassoc char table))
9909 (setq char (1+ char)))
9910 (setq c2 c1))
9911 (setq c (or c2 char)))
9912 (if ingroup (push tg (car groups)))
9913 (setq tg (org-add-props tg nil 'face
9914 (cond
9915 ((not (assoc tg table))
9916 (org-get-todo-face tg))
9917 ((member tg current) c-face)
9918 ((member tg inherited) i-face)
9919 (t nil))))
9920 (if (and (= cnt 0) (not ingroup)) (insert " "))
9921 (insert "[" c "] " tg (make-string
9922 (- fwidth 4 (length tg)) ?\ ))
9923 (push (cons tg c) ntable)
9924 (when (= (setq cnt (1+ cnt)) ncol)
9925 (insert "\n")
9926 (if ingroup (insert " "))
9927 (setq cnt 0)))))
9928 (setq ntable (nreverse ntable))
9929 (insert "\n")
9930 (goto-char (point-min))
9931 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9932 (fit-window-to-buffer))
9933 (setq rtn
9934 (catch 'exit
9935 (while t
9936 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9937 (if groups " [!] no groups" " [!]groups")
9938 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9939 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9940 (cond
9941 ((= c ?\r) (throw 'exit t))
9942 ((= c ?!)
9943 (setq groups (not groups))
9944 (goto-char (point-min))
9945 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9946 ((= c ?\C-c)
9947 (if (not expert)
9948 (org-fast-tag-show-exit
9949 (setq exit-after-next (not exit-after-next)))
9950 (setq expert nil)
9951 (delete-other-windows)
9952 (split-window-vertically)
9953 (org-switch-to-buffer-other-window " *Org tags*")
9954 (and (fboundp 'fit-window-to-buffer)
9955 (fit-window-to-buffer))))
9956 ((or (= c ?\C-g)
9957 (and (= c ?q) (not (rassoc c ntable))))
9958 (org-detach-overlay org-tags-overlay)
9959 (setq quit-flag t))
9960 ((= c ?\ )
9961 (setq current nil)
9962 (if exit-after-next (setq exit-after-next 'now)))
9963 ((= c ?\t)
9964 (condition-case nil
9965 (setq tg (completing-read
9966 "Tag: "
9967 (or buffer-tags
9968 (with-current-buffer buf
9969 (org-get-buffer-tags)))))
9970 (quit (setq tg "")))
9971 (when (string-match "\\S-" tg)
9972 (add-to-list 'buffer-tags (list tg))
9973 (if (member tg current)
9974 (setq current (delete tg current))
9975 (push tg current)))
9976 (if exit-after-next (setq exit-after-next 'now)))
9977 ((setq e (rassoc c todo-table) tg (car e))
9978 (with-current-buffer buf
9979 (save-excursion (org-todo tg)))
9980 (if exit-after-next (setq exit-after-next 'now)))
9981 ((setq e (rassoc c ntable) tg (car e))
9982 (if (member tg current)
9983 (setq current (delete tg current))
9984 (loop for g in groups do
9985 (if (member tg g)
9986 (mapc (lambda (x)
9987 (setq current (delete x current)))
9988 g)))
9989 (push tg current))
9990 (if exit-after-next (setq exit-after-next 'now))))
9992 ;; Create a sorted list
9993 (setq current
9994 (sort current
9995 (lambda (a b)
9996 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9997 (if (eq exit-after-next 'now) (throw 'exit t))
9998 (goto-char (point-min))
9999 (beginning-of-line 2)
10000 (delete-region (point) (point-at-eol))
10001 (org-fast-tag-insert "Current" current c-face)
10002 (org-set-current-tags-overlay current ov-prefix)
10003 (while (re-search-forward
10004 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10005 (setq tg (match-string 1))
10006 (add-text-properties
10007 (match-beginning 1) (match-end 1)
10008 (list 'face
10009 (cond
10010 ((member tg current) c-face)
10011 ((member tg inherited) i-face)
10012 (t (get-text-property (match-beginning 1) 'face))))))
10013 (goto-char (point-min)))))
10014 (org-detach-overlay org-tags-overlay)
10015 (if rtn
10016 (mapconcat 'identity current ":")
10017 nil))))
10019 (defun org-get-tags-string ()
10020 "Get the TAGS string in the current headline."
10021 (unless (org-on-heading-p t)
10022 (error "Not on a heading"))
10023 (save-excursion
10024 (beginning-of-line 1)
10025 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10026 (org-match-string-no-properties 1)
10027 "")))
10029 (defun org-get-tags ()
10030 "Get the list of tags specified in the current headline."
10031 (org-split-string (org-get-tags-string) ":"))
10033 (defun org-get-buffer-tags ()
10034 "Get a table of all tags used in the buffer, for completion."
10035 (let (tags)
10036 (save-excursion
10037 (goto-char (point-min))
10038 (while (re-search-forward
10039 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10040 (when (equal (char-after (point-at-bol 0)) ?*)
10041 (mapc (lambda (x) (add-to-list 'tags x))
10042 (org-split-string (org-match-string-no-properties 1) ":")))))
10043 (mapcar 'list tags)))
10045 ;;;; The mapping API
10047 ;;;###autoload
10048 (defun org-map-entries (func &optional match scope &rest skip)
10049 "Call FUNC at each headline selected by MATCH in SCOPE.
10051 FUNC is a function or a lisp form. The function will be called without
10052 arguments, with the cursor positioned at the beginning of the headline.
10053 The return values of all calls to the function will be collected and
10054 returned as a list.
10056 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10057 Only headlines that are matched by this query will be considered during
10058 the iteration. When MATCH is nil or t, all headlines will be
10059 visited by the iteration.
10061 SCOPE determines the scope of this command. It can be any of:
10063 nil The current buffer, respecting the restriction if any
10064 tree The subtree started with the entry at point
10065 file The current buffer, without restriction
10066 file-with-archives
10067 The current buffer, and any archives associated with it
10068 agenda All agenda files
10069 agenda-with-archives
10070 All agenda files with any archive files associated with them
10071 \(file1 file2 ...)
10072 If this is a list, all files in the list will be scanned
10074 The remaining args are treated as settings for the skipping facilities of
10075 the scanner. The following items can be given here:
10077 archive skip trees with the archive tag.
10078 comment skip trees with the COMMENT keyword
10079 function or Emacs Lisp form:
10080 will be used as value for `org-agenda-skip-function', so whenever
10081 the the function returns t, FUNC will not be called for that
10082 entry and search will continue from the point where the
10083 function leaves it."
10084 (let* ((org-agenda-archives-mode nil) ; just to make sure
10085 (org-agenda-skip-archived-trees (memq 'archive skip))
10086 (org-agenda-skip-comment-trees (memq 'comment skip))
10087 (org-agenda-skip-function
10088 (car (org-delete-all '(comment archive) skip)))
10089 (org-tags-match-list-sublevels t)
10090 matcher pos file)
10092 (cond
10093 ((eq match t) (setq matcher t))
10094 ((eq match nil) (setq matcher t))
10095 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10097 (when (eq scope 'tree)
10098 (org-back-to-heading t)
10099 (org-narrow-to-subtree)
10100 (setq scope nil))
10102 (if (not scope)
10103 (progn
10104 (org-prepare-agenda-buffers
10105 (list (buffer-file-name (current-buffer))))
10106 (org-scan-tags func matcher))
10107 ;; Get the right scope
10108 (setq pos (point))
10109 (cond
10110 ((and scope (listp scope) (symbolp (car scope)))
10111 (setq scope (eval scope)))
10112 ((eq scope 'agenda)
10113 (setq scope (org-agenda-files t)))
10114 ((eq scope 'agenda-with-archives)
10115 (setq scope (org-agenda-files t))
10116 (setq scope (org-add-archive-files scope)))
10117 ((eq scope 'file)
10118 (setq scope (list (buffer-file-name))))
10119 ((eq scope 'file-with-archives)
10120 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10121 (org-prepare-agenda-buffers scope)
10122 (while (setq file (pop scope))
10123 (with-current-buffer (org-find-base-buffer-visiting file)
10124 (save-excursion
10125 (save-restriction
10126 (widen)
10127 (goto-char (point-min))
10128 (org-scan-tags func matcher))))))))
10130 ;;;; Properties
10132 ;;; Setting and retrieving properties
10134 (defconst org-special-properties
10135 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10136 "TIMESTAMP" "TIMESTAMP_IA")
10137 "The special properties valid in Org-mode.
10139 These are properties that are not defined in the property drawer,
10140 but in some other way.")
10142 (defconst org-default-properties
10143 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10144 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10145 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10146 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10147 "Some properties that are used by Org-mode for various purposes.
10148 Being in this list makes sure that they are offered for completion.")
10150 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10151 "Regular expression matching the first line of a property drawer.")
10153 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10154 "Regular expression matching the first line of a property drawer.")
10156 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10157 "Regular expression matching the first line of a property drawer.")
10159 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10160 "Regular expression matching the first line of a property drawer.")
10162 (defconst org-property-drawer-re
10163 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10164 org-property-end-re "\\)\n?")
10165 "Matches an entire property drawer.")
10167 (defconst org-clock-drawer-re
10168 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10169 org-property-end-re "\\)\n?")
10170 "Matches an entire clock drawer.")
10172 (defun org-property-action ()
10173 "Do an action on properties."
10174 (interactive)
10175 (let (c)
10176 (org-at-property-p)
10177 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10178 (setq c (read-char-exclusive))
10179 (cond
10180 ((equal c ?s)
10181 (call-interactively 'org-set-property))
10182 ((equal c ?d)
10183 (call-interactively 'org-delete-property))
10184 ((equal c ?D)
10185 (call-interactively 'org-delete-property-globally))
10186 ((equal c ?c)
10187 (call-interactively 'org-compute-property-at-point))
10188 (t (error "No such property action %c" c)))))
10190 (defun org-at-property-p ()
10191 "Is the cursor in a property line?"
10192 ;; FIXME: Does not check if we are actually in the drawer.
10193 ;; FIXME: also returns true on any drawers.....
10194 ;; This is used by C-c C-c for property action.
10195 (save-excursion
10196 (beginning-of-line 1)
10197 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10199 (defun org-get-property-block (&optional beg end force)
10200 "Return the (beg . end) range of the body of the property drawer.
10201 BEG and END can be beginning and end of subtree, if not given
10202 they will be found.
10203 If the drawer does not exist and FORCE is non-nil, create the drawer."
10204 (catch 'exit
10205 (save-excursion
10206 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10207 (end (or end (progn (outline-next-heading) (point)))))
10208 (goto-char beg)
10209 (if (re-search-forward org-property-start-re end t)
10210 (setq beg (1+ (match-end 0)))
10211 (if force
10212 (save-excursion
10213 (org-insert-property-drawer)
10214 (setq end (progn (outline-next-heading) (point))))
10215 (throw 'exit nil))
10216 (goto-char beg)
10217 (if (re-search-forward org-property-start-re end t)
10218 (setq beg (1+ (match-end 0)))))
10219 (if (re-search-forward org-property-end-re end t)
10220 (setq end (match-beginning 0))
10221 (or force (throw 'exit nil))
10222 (goto-char beg)
10223 (setq end beg)
10224 (org-indent-line-function)
10225 (insert ":END:\n"))
10226 (cons beg end)))))
10228 (defun org-entry-properties (&optional pom which)
10229 "Get all properties of the entry at point-or-marker POM.
10230 This includes the TODO keyword, the tags, time strings for deadline,
10231 scheduled, and clocking, and any additional properties defined in the
10232 entry. The return value is an alist, keys may occur multiple times
10233 if the property key was used several times.
10234 POM may also be nil, in which case the current entry is used.
10235 If WHICH is nil or `all', get all properties. If WHICH is
10236 `special' or `standard', only get that subclass."
10237 (setq which (or which 'all))
10238 (org-with-point-at pom
10239 (let ((clockstr (substring org-clock-string 0 -1))
10240 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10241 beg end range props sum-props key value string clocksum)
10242 (save-excursion
10243 (when (condition-case nil (org-back-to-heading t) (error nil))
10244 (setq beg (point))
10245 (setq sum-props (get-text-property (point) 'org-summaries))
10246 (setq clocksum (get-text-property (point) :org-clock-minutes))
10247 (outline-next-heading)
10248 (setq end (point))
10249 (when (memq which '(all special))
10250 ;; Get the special properties, like TODO and tags
10251 (goto-char beg)
10252 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10253 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10254 (when (looking-at org-priority-regexp)
10255 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10256 (when (and (setq value (org-get-tags-string))
10257 (string-match "\\S-" value))
10258 (push (cons "TAGS" value) props))
10259 (when (setq value (org-get-tags-at))
10260 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10261 props))
10262 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10263 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10264 string (if (equal key clockstr)
10265 (org-no-properties
10266 (org-trim
10267 (buffer-substring
10268 (match-beginning 3) (goto-char (point-at-eol)))))
10269 (substring (org-match-string-no-properties 3) 1 -1)))
10270 (unless key
10271 (if (= (char-after (match-beginning 3)) ?\[)
10272 (setq key "TIMESTAMP_IA")
10273 (setq key "TIMESTAMP")))
10274 (when (or (equal key clockstr) (not (assoc key props)))
10275 (push (cons key string) props)))
10279 (when (memq which '(all standard))
10280 ;; Get the standard properties, like :PORP: ...
10281 (setq range (org-get-property-block beg end))
10282 (when range
10283 (goto-char (car range))
10284 (while (re-search-forward
10285 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10286 (cdr range) t)
10287 (setq key (org-match-string-no-properties 1)
10288 value (org-trim (or (org-match-string-no-properties 2) "")))
10289 (unless (member key excluded)
10290 (push (cons key (or value "")) props)))))
10291 (if clocksum
10292 (push (cons "CLOCKSUM"
10293 (org-columns-number-to-string (/ (float clocksum) 60.)
10294 'add_times))
10295 props))
10296 (append sum-props (nreverse props)))))))
10298 (defun org-entry-get (pom property &optional inherit)
10299 "Get value of PROPERTY for entry at point-or-marker POM.
10300 If INHERIT is non-nil and the entry does not have the property,
10301 then also check higher levels of the hierarchy.
10302 If INHERIT is the symbol `selective', use inheritance only if the setting
10303 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10304 If the property is present but empty, the return value is the empty string.
10305 If the property is not present at all, nil is returned."
10306 (org-with-point-at pom
10307 (if (and inherit (if (eq inherit 'selective)
10308 (org-property-inherit-p property)
10310 (org-entry-get-with-inheritance property)
10311 (if (member property org-special-properties)
10312 ;; We need a special property. Use brute force, get all properties.
10313 (cdr (assoc property (org-entry-properties nil 'special)))
10314 (let ((range (org-get-property-block)))
10315 (if (and range
10316 (goto-char (car range))
10317 (re-search-forward
10318 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10319 (cdr range) t))
10320 ;; Found the property, return it.
10321 (if (match-end 1)
10322 (org-match-string-no-properties 1)
10323 "")))))))
10325 (defun org-property-or-variable-value (var &optional inherit)
10326 "Check if there is a property fixing the value of VAR.
10327 If yes, return this value. If not, return the current value of the variable."
10328 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10329 (if (and prop (stringp prop) (string-match "\\S-" prop))
10330 (read prop)
10331 (symbol-value var))))
10333 (defun org-entry-delete (pom property)
10334 "Delete the property PROPERTY from entry at point-or-marker POM."
10335 (org-with-point-at pom
10336 (if (member property org-special-properties)
10337 nil ; cannot delete these properties.
10338 (let ((range (org-get-property-block)))
10339 (if (and range
10340 (goto-char (car range))
10341 (re-search-forward
10342 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10343 (cdr range) t))
10344 (progn
10345 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10347 nil)))))
10349 ;; Multi-values properties are properties that contain multiple values
10350 ;; These values are assumed to be single words, separated by whitespace.
10351 (defun org-entry-add-to-multivalued-property (pom property value)
10352 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10353 (let* ((old (org-entry-get pom property))
10354 (values (and old (org-split-string old "[ \t]"))))
10355 (unless (member value values)
10356 (setq values (cons value values))
10357 (org-entry-put pom property
10358 (mapconcat 'identity values " ")))))
10360 (defun org-entry-remove-from-multivalued-property (pom property value)
10361 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10362 (let* ((old (org-entry-get pom property))
10363 (values (and old (org-split-string old "[ \t]"))))
10364 (when (member value values)
10365 (setq values (delete value values))
10366 (org-entry-put pom property
10367 (mapconcat 'identity values " ")))))
10369 (defun org-entry-member-in-multivalued-property (pom property value)
10370 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10371 (let* ((old (org-entry-get pom property))
10372 (values (and old (org-split-string old "[ \t]"))))
10373 (member value values)))
10375 (defvar org-entry-property-inherited-from (make-marker))
10377 (defun org-entry-get-with-inheritance (property)
10378 "Get entry property, and search higher levels if not present."
10379 (let (tmp)
10380 (save-excursion
10381 (save-restriction
10382 (widen)
10383 (catch 'ex
10384 (while t
10385 (when (setq tmp (org-entry-get nil property))
10386 (org-back-to-heading t)
10387 (move-marker org-entry-property-inherited-from (point))
10388 (throw 'ex tmp))
10389 (or (org-up-heading-safe) (throw 'ex nil)))))
10390 (or tmp
10391 (cdr (assoc property org-file-properties))
10392 (cdr (assoc property org-global-properties))
10393 (cdr (assoc property org-global-properties-fixed))))))
10395 (defun org-entry-put (pom property value)
10396 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10397 (org-with-point-at pom
10398 (org-back-to-heading t)
10399 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10400 range)
10401 (cond
10402 ((equal property "TODO")
10403 (when (and (stringp value) (string-match "\\S-" value)
10404 (not (member value org-todo-keywords-1)))
10405 (error "\"%s\" is not a valid TODO state" value))
10406 (if (or (not value)
10407 (not (string-match "\\S-" value)))
10408 (setq value 'none))
10409 (org-todo value)
10410 (org-set-tags nil 'align))
10411 ((equal property "PRIORITY")
10412 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10413 (string-to-char value) ?\ ))
10414 (org-set-tags nil 'align))
10415 ((equal property "SCHEDULED")
10416 (if (re-search-forward org-scheduled-time-regexp end t)
10417 (cond
10418 ((eq value 'earlier) (org-timestamp-change -1 'day))
10419 ((eq value 'later) (org-timestamp-change 1 'day))
10420 (t (call-interactively 'org-schedule)))
10421 (call-interactively 'org-schedule)))
10422 ((equal property "DEADLINE")
10423 (if (re-search-forward org-deadline-time-regexp end t)
10424 (cond
10425 ((eq value 'earlier) (org-timestamp-change -1 'day))
10426 ((eq value 'later) (org-timestamp-change 1 'day))
10427 (t (call-interactively 'org-deadline)))
10428 (call-interactively 'org-deadline)))
10429 ((member property org-special-properties)
10430 (error "The %s property can not yet be set with `org-entry-put'"
10431 property))
10432 (t ; a non-special property
10433 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10434 (setq range (org-get-property-block beg end 'force))
10435 (goto-char (car range))
10436 (if (re-search-forward
10437 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10438 (progn
10439 (delete-region (match-beginning 1) (match-end 1))
10440 (goto-char (match-beginning 1)))
10441 (goto-char (cdr range))
10442 (insert "\n")
10443 (backward-char 1)
10444 (org-indent-line-function)
10445 (insert ":" property ":"))
10446 (and value (insert " " value))
10447 (org-indent-line-function)))))))
10449 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10450 "Get all property keys in the current buffer.
10451 With INCLUDE-SPECIALS, also list the special properties that relect things
10452 like tags and TODO state.
10453 With INCLUDE-DEFAULTS, also include properties that has special meaning
10454 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10455 With INCLUDE-COLUMNS, also include property names given in COLUMN
10456 formats in the current buffer."
10457 (let (rtn range cfmt cols s p)
10458 (save-excursion
10459 (save-restriction
10460 (widen)
10461 (goto-char (point-min))
10462 (while (re-search-forward org-property-start-re nil t)
10463 (setq range (org-get-property-block))
10464 (goto-char (car range))
10465 (while (re-search-forward
10466 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10467 (cdr range) t)
10468 (add-to-list 'rtn (org-match-string-no-properties 1)))
10469 (outline-next-heading))))
10471 (when include-specials
10472 (setq rtn (append org-special-properties rtn)))
10474 (when include-defaults
10475 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10477 (when include-columns
10478 (save-excursion
10479 (save-restriction
10480 (widen)
10481 (goto-char (point-min))
10482 (while (re-search-forward
10483 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10484 nil t)
10485 (setq cfmt (match-string 2) s 0)
10486 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10487 cfmt s)
10488 (setq s (match-end 0)
10489 p (match-string 1 cfmt))
10490 (unless (or (equal p "ITEM")
10491 (member p org-special-properties))
10492 (add-to-list 'rtn (match-string 1 cfmt))))))))
10494 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10496 (defun org-property-values (key)
10497 "Return a list of all values of property KEY."
10498 (save-excursion
10499 (save-restriction
10500 (widen)
10501 (goto-char (point-min))
10502 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10503 values)
10504 (while (re-search-forward re nil t)
10505 (add-to-list 'values (org-trim (match-string 1))))
10506 (delete "" values)))))
10508 (defun org-insert-property-drawer ()
10509 "Insert a property drawer into the current entry."
10510 (interactive)
10511 (org-back-to-heading t)
10512 (looking-at outline-regexp)
10513 (let ((indent (- (match-end 0)(match-beginning 0)))
10514 (beg (point))
10515 (re (concat "^[ \t]*" org-keyword-time-regexp))
10516 end hiddenp)
10517 (outline-next-heading)
10518 (setq end (point))
10519 (goto-char beg)
10520 (while (re-search-forward re end t))
10521 (setq hiddenp (org-invisible-p))
10522 (end-of-line 1)
10523 (and (equal (char-after) ?\n) (forward-char 1))
10524 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10525 (beginning-of-line 2))
10526 (org-skip-over-state-notes)
10527 (skip-chars-backward " \t\n\r")
10528 (if (eq (char-before) ?*) (forward-char 1))
10529 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10530 (beginning-of-line 0)
10531 (org-indent-to-column indent)
10532 (beginning-of-line 2)
10533 (org-indent-to-column indent)
10534 (beginning-of-line 0)
10535 (if hiddenp
10536 (save-excursion
10537 (org-back-to-heading t)
10538 (hide-entry))
10539 (org-flag-drawer t))))
10541 (defun org-set-property (property value)
10542 "In the current entry, set PROPERTY to VALUE.
10543 When called interactively, this will prompt for a property name, offering
10544 completion on existing and default properties. And then it will prompt
10545 for a value, offering competion either on allowed values (via an inherited
10546 xxx_ALL property) or on existing values in other instances of this property
10547 in the current file."
10548 (interactive
10549 (let* ((completion-ignore-case t)
10550 (keys (org-buffer-property-keys nil t t))
10551 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10552 (prop (if (member prop0 keys)
10553 prop0
10554 (or (cdr (assoc (downcase prop0)
10555 (mapcar (lambda (x) (cons (downcase x) x))
10556 keys)))
10557 prop0)))
10558 (cur (org-entry-get nil prop))
10559 (allowed (org-property-get-allowed-values nil prop 'table))
10560 (existing (mapcar 'list (org-property-values prop)))
10561 (val (if allowed
10562 (org-completing-read "Value: " allowed nil 'req-match)
10563 (org-completing-read
10564 (concat "Value" (if (and cur (string-match "\\S-" cur))
10565 (concat "[" cur "]") "")
10566 ": ")
10567 existing nil nil "" nil cur))))
10568 (list prop (if (equal val "") cur val))))
10569 (unless (equal (org-entry-get nil property) value)
10570 (org-entry-put nil property value)))
10572 (defun org-delete-property (property)
10573 "In the current entry, delete PROPERTY."
10574 (interactive
10575 (let* ((completion-ignore-case t)
10576 (prop (completing-read
10577 "Property: " (org-entry-properties nil 'standard))))
10578 (list prop)))
10579 (message "Property %s %s" property
10580 (if (org-entry-delete nil property)
10581 "deleted"
10582 "was not present in the entry")))
10584 (defun org-delete-property-globally (property)
10585 "Remove PROPERTY globally, from all entries."
10586 (interactive
10587 (let* ((completion-ignore-case t)
10588 (prop (completing-read
10589 "Globally remove property: "
10590 (mapcar 'list (org-buffer-property-keys)))))
10591 (list prop)))
10592 (save-excursion
10593 (save-restriction
10594 (widen)
10595 (goto-char (point-min))
10596 (let ((cnt 0))
10597 (while (re-search-forward
10598 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10599 nil t)
10600 (setq cnt (1+ cnt))
10601 (replace-match ""))
10602 (message "Property \"%s\" removed from %d entries" property cnt)))))
10604 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10606 (defun org-compute-property-at-point ()
10607 "Compute the property at point.
10608 This looks for an enclosing column format, extracts the operator and
10609 then applies it to the proerty in the column format's scope."
10610 (interactive)
10611 (unless (org-at-property-p)
10612 (error "Not at a property"))
10613 (let ((prop (org-match-string-no-properties 2)))
10614 (org-columns-get-format-and-top-level)
10615 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10616 (error "No operator defined for property %s" prop))
10617 (org-columns-compute prop)))
10619 (defun org-property-get-allowed-values (pom property &optional table)
10620 "Get allowed values for the property PROPERTY.
10621 When TABLE is non-nil, return an alist that can directly be used for
10622 completion."
10623 (let (vals)
10624 (cond
10625 ((equal property "TODO")
10626 (setq vals (org-with-point-at pom
10627 (append org-todo-keywords-1 '("")))))
10628 ((equal property "PRIORITY")
10629 (let ((n org-lowest-priority))
10630 (while (>= n org-highest-priority)
10631 (push (char-to-string n) vals)
10632 (setq n (1- n)))))
10633 ((member property org-special-properties))
10635 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10637 (when (and vals (string-match "\\S-" vals))
10638 (setq vals (car (read-from-string (concat "(" vals ")"))))
10639 (setq vals (mapcar (lambda (x)
10640 (cond ((stringp x) x)
10641 ((numberp x) (number-to-string x))
10642 ((symbolp x) (symbol-name x))
10643 (t "???")))
10644 vals)))))
10645 (if table (mapcar 'list vals) vals)))
10647 (defun org-property-previous-allowed-value (&optional previous)
10648 "Switch to the next allowed value for this property."
10649 (interactive)
10650 (org-property-next-allowed-value t))
10652 (defun org-property-next-allowed-value (&optional previous)
10653 "Switch to the next allowed value for this property."
10654 (interactive)
10655 (unless (org-at-property-p)
10656 (error "Not at a property"))
10657 (let* ((key (match-string 2))
10658 (value (match-string 3))
10659 (allowed (or (org-property-get-allowed-values (point) key)
10660 (and (member value '("[ ]" "[-]" "[X]"))
10661 '("[ ]" "[X]"))))
10662 nval)
10663 (unless allowed
10664 (error "Allowed values for this property have not been defined"))
10665 (if previous (setq allowed (reverse allowed)))
10666 (if (member value allowed)
10667 (setq nval (car (cdr (member value allowed)))))
10668 (setq nval (or nval (car allowed)))
10669 (if (equal nval value)
10670 (error "Only one allowed value for this property"))
10671 (org-at-property-p)
10672 (replace-match (concat " :" key ": " nval) t t)
10673 (org-indent-line-function)
10674 (beginning-of-line 1)
10675 (skip-chars-forward " \t")))
10677 (defun org-find-entry-with-id (ident)
10678 "Locate the entry that contains the ID property with exact value IDENT.
10679 IDENT can be a string, a symbol or a number, this function will search for
10680 the string representation of it.
10681 Return the position where this entry starts, or nil if there is no such entry."
10682 (let ((id (cond
10683 ((stringp ident) ident)
10684 ((symbol-name ident) (symbol-name ident))
10685 ((numberp ident) (number-to-string ident))
10686 (t (error "IDENT %s must be a string, symbol or number" ident))))
10687 (case-fold-search nil))
10688 (save-excursion
10689 (save-restriction
10690 (widen)
10691 (goto-char (point-min))
10692 (when (re-search-forward
10693 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10694 nil t)
10695 (org-back-to-heading)
10696 (point))))))
10698 ;;;; Timestamps
10700 (defvar org-last-changed-timestamp nil)
10701 (defvar org-last-inserted-timestamp nil
10702 "The last time stamp inserted with `org-insert-time-stamp'.")
10703 (defvar org-time-was-given) ; dynamically scoped parameter
10704 (defvar org-end-time-was-given) ; dynamically scoped parameter
10705 (defvar org-ts-what) ; dynamically scoped parameter
10707 (defun org-time-stamp (arg)
10708 "Prompt for a date/time and insert a time stamp.
10709 If the user specifies a time like HH:MM, or if this command is called
10710 with a prefix argument, the time stamp will contain date and time.
10711 Otherwise, only the date will be included. All parts of a date not
10712 specified by the user will be filled in from the current date/time.
10713 So if you press just return without typing anything, the time stamp
10714 will represent the current date/time. If there is already a timestamp
10715 at the cursor, it will be modified."
10716 (interactive "P")
10717 (let* ((ts nil)
10718 (default-time
10719 ;; Default time is either today, or, when entering a range,
10720 ;; the range start.
10721 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10722 (save-excursion
10723 (re-search-backward
10724 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10725 (- (point) 20) t)))
10726 (apply 'encode-time (org-parse-time-string (match-string 1)))
10727 (current-time)))
10728 (default-input (and ts (org-get-compact-tod ts)))
10729 org-time-was-given org-end-time-was-given time)
10730 (cond
10731 ((and (org-at-timestamp-p)
10732 (eq last-command 'org-time-stamp)
10733 (eq this-command 'org-time-stamp))
10734 (insert "--")
10735 (setq time (let ((this-command this-command))
10736 (org-read-date arg 'totime nil nil default-time default-input)))
10737 (org-insert-time-stamp time (or org-time-was-given arg)))
10738 ((org-at-timestamp-p)
10739 (setq time (let ((this-command this-command))
10740 (org-read-date arg 'totime nil nil default-time default-input)))
10741 (when (org-at-timestamp-p) ; just to get the match data
10742 (replace-match "")
10743 (setq org-last-changed-timestamp
10744 (org-insert-time-stamp
10745 time (or org-time-was-given arg)
10746 nil nil nil (list org-end-time-was-given))))
10747 (message "Timestamp updated"))
10749 (setq time (let ((this-command this-command))
10750 (org-read-date arg 'totime nil nil default-time default-input)))
10751 (org-insert-time-stamp time (or org-time-was-given arg)
10752 nil nil nil (list org-end-time-was-given))))))
10754 ;; FIXME: can we use this for something else, like computing time differences?
10755 (defun org-get-compact-tod (s)
10756 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10757 (let* ((t1 (match-string 1 s))
10758 (h1 (string-to-number (match-string 2 s)))
10759 (m1 (string-to-number (match-string 3 s)))
10760 (t2 (and (match-end 4) (match-string 5 s)))
10761 (h2 (and t2 (string-to-number (match-string 6 s))))
10762 (m2 (and t2 (string-to-number (match-string 7 s))))
10763 dh dm)
10764 (if (not t2)
10766 (setq dh (- h2 h1) dm (- m2 m1))
10767 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10768 (concat t1 "+" (number-to-string dh)
10769 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10771 (defun org-time-stamp-inactive (&optional arg)
10772 "Insert an inactive time stamp.
10773 An inactive time stamp is enclosed in square brackets instead of angle
10774 brackets. It is inactive in the sense that it does not trigger agenda entries,
10775 does not link to the calendar and cannot be changed with the S-cursor keys.
10776 So these are more for recording a certain time/date."
10777 (interactive "P")
10778 (let (org-time-was-given org-end-time-was-given time)
10779 (setq time (org-read-date arg 'totime))
10780 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10781 nil nil (list org-end-time-was-given))))
10783 (defvar org-date-ovl (org-make-overlay 1 1))
10784 (org-overlay-put org-date-ovl 'face 'org-warning)
10785 (org-detach-overlay org-date-ovl)
10787 (defvar org-ans1) ; dynamically scoped parameter
10788 (defvar org-ans2) ; dynamically scoped parameter
10790 (defvar org-plain-time-of-day-regexp) ; defined below
10792 (defvar org-overriding-default-time nil) ; dynamically scoped
10793 (defvar org-read-date-overlay nil)
10794 (defvar org-dcst nil) ; dynamically scoped
10796 (defun org-read-date (&optional with-time to-time from-string prompt
10797 default-time default-input)
10798 "Read a date, possibly a time, and make things smooth for the user.
10799 The prompt will suggest to enter an ISO date, but you can also enter anything
10800 which will at least partially be understood by `parse-time-string'.
10801 Unrecognized parts of the date will default to the current day, month, year,
10802 hour and minute. If this command is called to replace a timestamp at point,
10803 of to enter the second timestamp of a range, the default time is taken from the
10804 existing stamp. For example,
10805 3-2-5 --> 2003-02-05
10806 feb 15 --> currentyear-02-15
10807 sep 12 9 --> 2009-09-12
10808 12:45 --> today 12:45
10809 22 sept 0:34 --> currentyear-09-22 0:34
10810 12 --> currentyear-currentmonth-12
10811 Fri --> nearest Friday (today or later)
10812 etc.
10814 Furthermore you can specify a relative date by giving, as the *first* thing
10815 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10816 change in days weeks, months, years.
10817 With a single plus or minus, the date is relative to today. With a double
10818 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10819 +4d --> four days from today
10820 +4 --> same as above
10821 +2w --> two weeks from today
10822 ++5 --> five days from default date
10824 The function understands only English month and weekday abbreviations,
10825 but this can be configured with the variables `parse-time-months' and
10826 `parse-time-weekdays'.
10828 While prompting, a calendar is popped up - you can also select the
10829 date with the mouse (button 1). The calendar shows a period of three
10830 months. To scroll it to other months, use the keys `>' and `<'.
10831 If you don't like the calendar, turn it off with
10832 \(setq org-read-date-popup-calendar nil)
10834 With optional argument TO-TIME, the date will immediately be converted
10835 to an internal time.
10836 With an optional argument WITH-TIME, the prompt will suggest to also
10837 insert a time. Note that when WITH-TIME is not set, you can still
10838 enter a time, and this function will inform the calling routine about
10839 this change. The calling routine may then choose to change the format
10840 used to insert the time stamp into the buffer to include the time.
10841 With optional argument FROM-STRING, read from this string instead from
10842 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10843 the time/date that is used for everything that is not specified by the
10844 user."
10845 (require 'parse-time)
10846 (let* ((org-time-stamp-rounding-minutes
10847 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10848 (org-dcst org-display-custom-times)
10849 (ct (org-current-time))
10850 (def (or org-overriding-default-time default-time ct))
10851 (defdecode (decode-time def))
10852 (dummy (progn
10853 (when (< (nth 2 defdecode) org-extend-today-until)
10854 (setcar (nthcdr 2 defdecode) -1)
10855 (setcar (nthcdr 1 defdecode) 59)
10856 (setq def (apply 'encode-time defdecode)
10857 defdecode (decode-time def)))))
10858 (calendar-move-hook nil)
10859 (calendar-view-diary-initially-flag nil)
10860 (view-diary-entries-initially nil)
10861 (calendar-view-holidays-initially-flag nil)
10862 (view-calendar-holidays-initially nil)
10863 (timestr (format-time-string
10864 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10865 (prompt (concat (if prompt (concat prompt " ") "")
10866 (format "Date+time [%s]: " timestr)))
10867 ans (org-ans0 "") org-ans1 org-ans2 final)
10869 (cond
10870 (from-string (setq ans from-string))
10871 (org-read-date-popup-calendar
10872 (save-excursion
10873 (save-window-excursion
10874 (calendar)
10875 (calendar-forward-day (- (time-to-days def)
10876 (calendar-absolute-from-gregorian
10877 (calendar-current-date))))
10878 (org-eval-in-calendar nil t)
10879 (let* ((old-map (current-local-map))
10880 (map (copy-keymap calendar-mode-map))
10881 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10882 (org-defkey map (kbd "RET") 'org-calendar-select)
10883 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10884 'org-calendar-select-mouse)
10885 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10886 'org-calendar-select-mouse)
10887 (org-defkey minibuffer-local-map [(meta shift left)]
10888 (lambda () (interactive)
10889 (org-eval-in-calendar '(calendar-backward-month 1))))
10890 (org-defkey minibuffer-local-map [(meta shift right)]
10891 (lambda () (interactive)
10892 (org-eval-in-calendar '(calendar-forward-month 1))))
10893 (org-defkey minibuffer-local-map [(meta shift up)]
10894 (lambda () (interactive)
10895 (org-eval-in-calendar '(calendar-backward-year 1))))
10896 (org-defkey minibuffer-local-map [(meta shift down)]
10897 (lambda () (interactive)
10898 (org-eval-in-calendar '(calendar-forward-year 1))))
10899 (org-defkey minibuffer-local-map [(shift up)]
10900 (lambda () (interactive)
10901 (org-eval-in-calendar '(calendar-backward-week 1))))
10902 (org-defkey minibuffer-local-map [(shift down)]
10903 (lambda () (interactive)
10904 (org-eval-in-calendar '(calendar-forward-week 1))))
10905 (org-defkey minibuffer-local-map [(shift left)]
10906 (lambda () (interactive)
10907 (org-eval-in-calendar '(calendar-backward-day 1))))
10908 (org-defkey minibuffer-local-map [(shift right)]
10909 (lambda () (interactive)
10910 (org-eval-in-calendar '(calendar-forward-day 1))))
10911 (org-defkey minibuffer-local-map ">"
10912 (lambda () (interactive)
10913 (org-eval-in-calendar '(scroll-calendar-left 1))))
10914 (org-defkey minibuffer-local-map "<"
10915 (lambda () (interactive)
10916 (org-eval-in-calendar '(scroll-calendar-right 1))))
10917 (unwind-protect
10918 (progn
10919 (use-local-map map)
10920 (add-hook 'post-command-hook 'org-read-date-display)
10921 (setq org-ans0 (read-string prompt default-input nil nil))
10922 ;; org-ans0: from prompt
10923 ;; org-ans1: from mouse click
10924 ;; org-ans2: from calendar motion
10925 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10926 (remove-hook 'post-command-hook 'org-read-date-display)
10927 (use-local-map old-map)
10928 (when org-read-date-overlay
10929 (org-delete-overlay org-read-date-overlay)
10930 (setq org-read-date-overlay nil)))))))
10932 (t ; Naked prompt only
10933 (unwind-protect
10934 (setq ans (read-string prompt default-input nil timestr))
10935 (when org-read-date-overlay
10936 (org-delete-overlay org-read-date-overlay)
10937 (setq org-read-date-overlay nil)))))
10939 (setq final (org-read-date-analyze ans def defdecode))
10941 (if to-time
10942 (apply 'encode-time final)
10943 (if (and (boundp 'org-time-was-given) org-time-was-given)
10944 (format "%04d-%02d-%02d %02d:%02d"
10945 (nth 5 final) (nth 4 final) (nth 3 final)
10946 (nth 2 final) (nth 1 final))
10947 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10948 (defvar def)
10949 (defvar defdecode)
10950 (defvar with-time)
10951 (defun org-read-date-display ()
10952 "Display the currrent date prompt interpretation in the minibuffer."
10953 (when org-read-date-display-live
10954 (when org-read-date-overlay
10955 (org-delete-overlay org-read-date-overlay))
10956 (let ((p (point)))
10957 (end-of-line 1)
10958 (while (not (equal (buffer-substring
10959 (max (point-min) (- (point) 4)) (point))
10960 " "))
10961 (insert " "))
10962 (goto-char p))
10963 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10964 " " (or org-ans1 org-ans2)))
10965 (org-end-time-was-given nil)
10966 (f (org-read-date-analyze ans def defdecode))
10967 (fmts (if org-dcst
10968 org-time-stamp-custom-formats
10969 org-time-stamp-formats))
10970 (fmt (if (or with-time
10971 (and (boundp 'org-time-was-given) org-time-was-given))
10972 (cdr fmts)
10973 (car fmts)))
10974 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10975 (when (and org-end-time-was-given
10976 (string-match org-plain-time-of-day-regexp txt))
10977 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10978 org-end-time-was-given
10979 (substring txt (match-end 0)))))
10980 (setq org-read-date-overlay
10981 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10982 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10984 (defun org-read-date-analyze (ans def defdecode)
10985 "Analyze the combined answer of the date prompt."
10986 ;; FIXME: cleanup and comment
10987 (let (delta deltan deltaw deltadef year month day
10988 hour minute second wday pm h2 m2 tl wday1
10989 iso-year iso-weekday iso-week iso-year iso-date)
10991 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10992 (setq ans "+0"))
10994 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10995 (setq ans (replace-match "" t t ans)
10996 deltan (car delta)
10997 deltaw (nth 1 delta)
10998 deltadef (nth 2 delta)))
11000 ;; Check if there is an iso week date in there
11001 ;; If yes, sore the info and ostpone interpreting it until the rest
11002 ;; of the parsing is done
11003 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11004 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11005 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11006 iso-week (string-to-number (match-string 2 ans)))
11007 (setq ans (replace-match "" t t ans)))
11009 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11010 (when (string-match
11011 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11012 (setq year (if (match-end 2)
11013 (string-to-number (match-string 2 ans))
11014 (string-to-number (format-time-string "%Y")))
11015 month (string-to-number (match-string 3 ans))
11016 day (string-to-number (match-string 4 ans)))
11017 (if (< year 100) (setq year (+ 2000 year)))
11018 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11019 t nil ans)))
11020 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11021 ;; If there is a time with am/pm, and *no* time without it, we convert
11022 ;; so that matching will be successful.
11023 (loop for i from 1 to 2 do ; twice, for end time as well
11024 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11025 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11026 (setq hour (string-to-number (match-string 1 ans))
11027 minute (if (match-end 3)
11028 (string-to-number (match-string 3 ans))
11030 pm (equal ?p
11031 (string-to-char (downcase (match-string 4 ans)))))
11032 (if (and (= hour 12) (not pm))
11033 (setq hour 0)
11034 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11035 (setq ans (replace-match (format "%02d:%02d" hour minute)
11036 t t ans))))
11038 ;; Check if a time range is given as a duration
11039 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11040 (setq hour (string-to-number (match-string 1 ans))
11041 h2 (+ hour (string-to-number (match-string 3 ans)))
11042 minute (string-to-number (match-string 2 ans))
11043 m2 (+ minute (if (match-end 5) (string-to-number
11044 (match-string 5 ans))0)))
11045 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11046 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11047 t t ans)))
11049 ;; Check if there is a time range
11050 (when (boundp 'org-end-time-was-given)
11051 (setq org-time-was-given nil)
11052 (when (and (string-match org-plain-time-of-day-regexp ans)
11053 (match-end 8))
11054 (setq org-end-time-was-given (match-string 8 ans))
11055 (setq ans (concat (substring ans 0 (match-beginning 7))
11056 (substring ans (match-end 7))))))
11058 (setq tl (parse-time-string ans)
11059 day (or (nth 3 tl) (nth 3 defdecode))
11060 month (or (nth 4 tl)
11061 (if (and org-read-date-prefer-future
11062 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11063 (1+ (nth 4 defdecode))
11064 (nth 4 defdecode)))
11065 year (or (nth 5 tl)
11066 (if (and org-read-date-prefer-future
11067 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11068 (1+ (nth 5 defdecode))
11069 (nth 5 defdecode)))
11070 hour (or (nth 2 tl) (nth 2 defdecode))
11071 minute (or (nth 1 tl) (nth 1 defdecode))
11072 second (or (nth 0 tl) 0)
11073 wday (nth 6 tl))
11075 ;; Special date definitions below
11076 (cond
11077 (iso-week
11078 ;; There was an iso week
11079 (setq year (or iso-year year)
11080 day (or iso-weekday wday 1)
11081 wday nil ; to make sure that the trigger below does not match
11082 iso-date (calendar-gregorian-from-absolute
11083 (calendar-absolute-from-iso
11084 (list iso-week day year))))
11085 ; FIXME: Should we also push ISO weeks into the future?
11086 ; (when (and org-read-date-prefer-future
11087 ; (not iso-year)
11088 ; (< (calendar-absolute-from-gregorian iso-date)
11089 ; (time-to-days (current-time))))
11090 ; (setq year (1+ year)
11091 ; iso-date (calendar-gregorian-from-absolute
11092 ; (calendar-absolute-from-iso
11093 ; (list iso-week day year)))))
11094 (setq month (car iso-date)
11095 year (nth 2 iso-date)
11096 day (nth 1 iso-date)))
11097 (deltan
11098 (unless deltadef
11099 (let ((now (decode-time (current-time))))
11100 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11101 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11102 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11103 ((equal deltaw "m") (setq month (+ month deltan)))
11104 ((equal deltaw "y") (setq year (+ year deltan)))))
11105 ((and wday (not (nth 3 tl)))
11106 ;; Weekday was given, but no day, so pick that day in the week
11107 ;; on or after the derived date.
11108 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11109 (unless (equal wday wday1)
11110 (setq day (+ day (% (- wday wday1 -7) 7))))))
11111 (if (and (boundp 'org-time-was-given)
11112 (nth 2 tl))
11113 (setq org-time-was-given t))
11114 (if (< year 100) (setq year (+ 2000 year)))
11115 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11116 (list second minute hour day month year)))
11118 (defvar parse-time-weekdays)
11120 (defun org-read-date-get-relative (s today default)
11121 "Check string S for special relative date string.
11122 TODAY and DEFAULT are internal times, for today and for a default.
11123 Return shift list (N what def-flag)
11124 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11125 N is the number of WHATs to shift.
11126 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11127 the DEFAULT date rather than TODAY."
11128 (when (and
11129 (string-match
11130 (concat
11131 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11132 "\\([0-9]+\\)?"
11133 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11134 "\\([ \t]\\|$\\)") s)
11135 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11136 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11137 (string-to-char (substring (match-string 1 s) -1))
11138 ?+))
11139 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11140 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11141 (what (if (match-end 3) (match-string 3 s) "d"))
11142 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11143 (date (if rel default today))
11144 (wday (nth 6 (decode-time date)))
11145 delta)
11146 (if wday1
11147 (progn
11148 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11149 (if (= dir ?-) (setq delta (- delta 7)))
11150 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11151 (list delta "d" rel))
11152 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11154 (defun org-eval-in-calendar (form &optional keepdate)
11155 "Eval FORM in the calendar window and return to current window.
11156 Also, store the cursor date in variable org-ans2."
11157 (let ((sw (selected-window)))
11158 (select-window (get-buffer-window "*Calendar*"))
11159 (eval form)
11160 (when (and (not keepdate) (calendar-cursor-to-date))
11161 (let* ((date (calendar-cursor-to-date))
11162 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11163 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11164 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11165 (select-window sw)))
11167 ; ;; Update the prompt to show new default date
11168 ; (save-excursion
11169 ; (goto-char (point-min))
11170 ; (when (and org-ans2
11171 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11172 ; (get-text-property (match-end 0) 'field))
11173 ; (let ((inhibit-read-only t))
11174 ; (replace-match (concat "[" org-ans2 "]") t t)
11175 ; (add-text-properties (point-min) (1+ (match-end 0))
11176 ; (text-properties-at (1+ (point-min)))))))))
11178 (defun org-calendar-select ()
11179 "Return to `org-read-date' with the date currently selected.
11180 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11181 (interactive)
11182 (when (calendar-cursor-to-date)
11183 (let* ((date (calendar-cursor-to-date))
11184 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11185 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11186 (if (active-minibuffer-window) (exit-minibuffer))))
11188 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11189 "Insert a date stamp for the date given by the internal TIME.
11190 WITH-HM means, use the stamp format that includes the time of the day.
11191 INACTIVE means use square brackets instead of angular ones, so that the
11192 stamp will not contribute to the agenda.
11193 PRE and POST are optional strings to be inserted before and after the
11194 stamp.
11195 The command returns the inserted time stamp."
11196 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11197 stamp)
11198 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11199 (insert-before-markers (or pre ""))
11200 (insert-before-markers (setq stamp (format-time-string fmt time)))
11201 (when (listp extra)
11202 (setq extra (car extra))
11203 (if (and (stringp extra)
11204 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11205 (setq extra (format "-%02d:%02d"
11206 (string-to-number (match-string 1 extra))
11207 (string-to-number (match-string 2 extra))))
11208 (setq extra nil)))
11209 (when extra
11210 (backward-char 1)
11211 (insert-before-markers extra)
11212 (forward-char 1))
11213 (insert-before-markers (or post ""))
11214 (setq org-last-inserted-timestamp stamp)))
11216 (defun org-toggle-time-stamp-overlays ()
11217 "Toggle the use of custom time stamp formats."
11218 (interactive)
11219 (setq org-display-custom-times (not org-display-custom-times))
11220 (unless org-display-custom-times
11221 (let ((p (point-min)) (bmp (buffer-modified-p)))
11222 (while (setq p (next-single-property-change p 'display))
11223 (if (and (get-text-property p 'display)
11224 (eq (get-text-property p 'face) 'org-date))
11225 (remove-text-properties
11226 p (setq p (next-single-property-change p 'display))
11227 '(display t))))
11228 (set-buffer-modified-p bmp)))
11229 (if (featurep 'xemacs)
11230 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11231 (org-restart-font-lock)
11232 (setq org-table-may-need-update t)
11233 (if org-display-custom-times
11234 (message "Time stamps are overlayed with custom format")
11235 (message "Time stamp overlays removed")))
11237 (defun org-display-custom-time (beg end)
11238 "Overlay modified time stamp format over timestamp between BEG and END."
11239 (let* ((ts (buffer-substring beg end))
11240 t1 w1 with-hm tf time str w2 (off 0))
11241 (save-match-data
11242 (setq t1 (org-parse-time-string ts t))
11243 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11244 (setq off (- (match-end 0) (match-beginning 0)))))
11245 (setq end (- end off))
11246 (setq w1 (- end beg)
11247 with-hm (and (nth 1 t1) (nth 2 t1))
11248 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11249 time (org-fix-decoded-time t1)
11250 str (org-add-props
11251 (format-time-string
11252 (substring tf 1 -1) (apply 'encode-time time))
11253 nil 'mouse-face 'highlight)
11254 w2 (length str))
11255 (if (not (= w2 w1))
11256 (add-text-properties (1+ beg) (+ 2 beg)
11257 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11258 (if (featurep 'xemacs)
11259 (progn
11260 (put-text-property beg end 'invisible t)
11261 (put-text-property beg end 'end-glyph (make-glyph str)))
11262 (put-text-property beg end 'display str))))
11264 (defun org-translate-time (string)
11265 "Translate all timestamps in STRING to custom format.
11266 But do this only if the variable `org-display-custom-times' is set."
11267 (when org-display-custom-times
11268 (save-match-data
11269 (let* ((start 0)
11270 (re org-ts-regexp-both)
11271 t1 with-hm inactive tf time str beg end)
11272 (while (setq start (string-match re string start))
11273 (setq beg (match-beginning 0)
11274 end (match-end 0)
11275 t1 (save-match-data
11276 (org-parse-time-string (substring string beg end) t))
11277 with-hm (and (nth 1 t1) (nth 2 t1))
11278 inactive (equal (substring string beg (1+ beg)) "[")
11279 tf (funcall (if with-hm 'cdr 'car)
11280 org-time-stamp-custom-formats)
11281 time (org-fix-decoded-time t1)
11282 str (format-time-string
11283 (concat
11284 (if inactive "[" "<") (substring tf 1 -1)
11285 (if inactive "]" ">"))
11286 (apply 'encode-time time))
11287 string (replace-match str t t string)
11288 start (+ start (length str)))))))
11289 string)
11291 (defun org-fix-decoded-time (time)
11292 "Set 0 instead of nil for the first 6 elements of time.
11293 Don't touch the rest."
11294 (let ((n 0))
11295 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11297 (defun org-days-to-time (timestamp-string)
11298 "Difference between TIMESTAMP-STRING and now in days."
11299 (- (time-to-days (org-time-string-to-time timestamp-string))
11300 (time-to-days (current-time))))
11302 (defun org-deadline-close (timestamp-string &optional ndays)
11303 "Is the time in TIMESTAMP-STRING close to the current date?"
11304 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11305 (and (< (org-days-to-time timestamp-string) ndays)
11306 (not (org-entry-is-done-p))))
11308 (defun org-get-wdays (ts)
11309 "Get the deadline lead time appropriate for timestring TS."
11310 (cond
11311 ((<= org-deadline-warning-days 0)
11312 ;; 0 or negative, enforce this value no matter what
11313 (- org-deadline-warning-days))
11314 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11315 ;; lead time is specified.
11316 (floor (* (string-to-number (match-string 1 ts))
11317 (cdr (assoc (match-string 2 ts)
11318 '(("d" . 1) ("w" . 7)
11319 ("m" . 30.4) ("y" . 365.25)))))))
11320 ;; go for the default.
11321 (t org-deadline-warning-days)))
11323 (defun org-calendar-select-mouse (ev)
11324 "Return to `org-read-date' with the date currently selected.
11325 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11326 (interactive "e")
11327 (mouse-set-point ev)
11328 (when (calendar-cursor-to-date)
11329 (let* ((date (calendar-cursor-to-date))
11330 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11331 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11332 (if (active-minibuffer-window) (exit-minibuffer))))
11334 (defun org-check-deadlines (ndays)
11335 "Check if there are any deadlines due or past due.
11336 A deadline is considered due if it happens within `org-deadline-warning-days'
11337 days from today's date. If the deadline appears in an entry marked DONE,
11338 it is not shown. The prefix arg NDAYS can be used to test that many
11339 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11340 (interactive "P")
11341 (let* ((org-warn-days
11342 (cond
11343 ((equal ndays '(4)) 100000)
11344 (ndays (prefix-numeric-value ndays))
11345 (t (abs org-deadline-warning-days))))
11346 (case-fold-search nil)
11347 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11348 (callback
11349 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11351 (message "%d deadlines past-due or due within %d days"
11352 (org-occur regexp nil callback)
11353 org-warn-days)))
11355 (defun org-check-before-date (date)
11356 "Check if there are deadlines or scheduled entries before DATE."
11357 (interactive (list (org-read-date)))
11358 (let ((case-fold-search nil)
11359 (regexp (concat "\\<\\(" org-deadline-string
11360 "\\|" org-scheduled-string
11361 "\\) *<\\([^>]+\\)>"))
11362 (callback
11363 (lambda () (time-less-p
11364 (org-time-string-to-time (match-string 2))
11365 (org-time-string-to-time date)))))
11366 (message "%d entries before %s"
11367 (org-occur regexp nil callback) date)))
11369 (defun org-evaluate-time-range (&optional to-buffer)
11370 "Evaluate a time range by computing the difference between start and end.
11371 Normally the result is just printed in the echo area, but with prefix arg
11372 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11373 If the time range is actually in a table, the result is inserted into the
11374 next column.
11375 For time difference computation, a year is assumed to be exactly 365
11376 days in order to avoid rounding problems."
11377 (interactive "P")
11379 (org-clock-update-time-maybe)
11380 (save-excursion
11381 (unless (org-at-date-range-p t)
11382 (goto-char (point-at-bol))
11383 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11384 (if (not (org-at-date-range-p t))
11385 (error "Not at a time-stamp range, and none found in current line")))
11386 (let* ((ts1 (match-string 1))
11387 (ts2 (match-string 2))
11388 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11389 (match-end (match-end 0))
11390 (time1 (org-time-string-to-time ts1))
11391 (time2 (org-time-string-to-time ts2))
11392 (t1 (time-to-seconds time1))
11393 (t2 (time-to-seconds time2))
11394 (diff (abs (- t2 t1)))
11395 (negative (< (- t2 t1) 0))
11396 ;; (ys (floor (* 365 24 60 60)))
11397 (ds (* 24 60 60))
11398 (hs (* 60 60))
11399 (fy "%dy %dd %02d:%02d")
11400 (fy1 "%dy %dd")
11401 (fd "%dd %02d:%02d")
11402 (fd1 "%dd")
11403 (fh "%02d:%02d")
11404 y d h m align)
11405 (if havetime
11406 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11408 d (floor (/ diff ds)) diff (mod diff ds)
11409 h (floor (/ diff hs)) diff (mod diff hs)
11410 m (floor (/ diff 60)))
11411 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11413 d (floor (+ (/ diff ds) 0.5))
11414 h 0 m 0))
11415 (if (not to-buffer)
11416 (message "%s" (org-make-tdiff-string y d h m))
11417 (if (org-at-table-p)
11418 (progn
11419 (goto-char match-end)
11420 (setq align t)
11421 (and (looking-at " *|") (goto-char (match-end 0))))
11422 (goto-char match-end))
11423 (if (looking-at
11424 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11425 (replace-match ""))
11426 (if negative (insert " -"))
11427 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11428 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11429 (insert " " (format fh h m))))
11430 (if align (org-table-align))
11431 (message "Time difference inserted")))))
11433 (defun org-make-tdiff-string (y d h m)
11434 (let ((fmt "")
11435 (l nil))
11436 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11437 l (push y l)))
11438 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11439 l (push d l)))
11440 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11441 l (push h l)))
11442 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11443 l (push m l)))
11444 (apply 'format fmt (nreverse l))))
11446 (defun org-time-string-to-time (s)
11447 (apply 'encode-time (org-parse-time-string s)))
11449 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11450 "Convert a time stamp to an absolute day number.
11451 If there is a specifyer for a cyclic time stamp, get the closest date to
11452 DAYNR.
11453 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11454 (cond
11455 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11456 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11457 daynr
11458 (+ daynr 1000)))
11459 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11460 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11461 (time-to-days (current-time))) (match-string 0 s)
11462 prefer show-all))
11463 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11465 (defun org-days-to-iso-week (days)
11466 "Return the iso week number."
11467 (require 'cal-iso)
11468 (car (calendar-iso-from-absolute days)))
11470 (defun org-small-year-to-year (year)
11471 "Convert 2-digit years into 4-digit years.
11472 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11473 The year 2000 cannot be abbreviated. Any year lager than 99
11474 is retrned unchanged."
11475 (if (< year 38)
11476 (setq year (+ 2000 year))
11477 (if (< year 100)
11478 (setq year (+ 1900 year))))
11479 year)
11481 (defun org-time-from-absolute (d)
11482 "Return the time corresponding to date D.
11483 D may be an absolute day number, or a calendar-type list (month day year)."
11484 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11485 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11487 (defun org-calendar-holiday ()
11488 "List of holidays, for Diary display in Org-mode."
11489 (require 'holidays)
11490 (let ((hl (funcall
11491 (if (fboundp 'calendar-check-holidays)
11492 'calendar-check-holidays 'check-calendar-holidays) date)))
11493 (if hl (mapconcat 'identity hl "; "))))
11495 (defun org-diary-sexp-entry (sexp entry date)
11496 "Process a SEXP diary ENTRY for DATE."
11497 (require 'diary-lib)
11498 (let ((result (if calendar-debug-sexp
11499 (let ((stack-trace-on-error t))
11500 (eval (car (read-from-string sexp))))
11501 (condition-case nil
11502 (eval (car (read-from-string sexp)))
11503 (error
11504 (beep)
11505 (message "Bad sexp at line %d in %s: %s"
11506 (org-current-line)
11507 (buffer-file-name) sexp)
11508 (sleep-for 2))))))
11509 (cond ((stringp result) result)
11510 ((and (consp result)
11511 (stringp (cdr result))) (cdr result))
11512 (result entry)
11513 (t nil))))
11515 (defun org-diary-to-ical-string (frombuf)
11516 "Get iCalendar entries from diary entries in buffer FROMBUF.
11517 This uses the icalendar.el library."
11518 (let* ((tmpdir (if (featurep 'xemacs)
11519 (temp-directory)
11520 temporary-file-directory))
11521 (tmpfile (make-temp-name
11522 (expand-file-name "orgics" tmpdir)))
11523 buf rtn b e)
11524 (save-excursion
11525 (set-buffer frombuf)
11526 (icalendar-export-region (point-min) (point-max) tmpfile)
11527 (setq buf (find-buffer-visiting tmpfile))
11528 (set-buffer buf)
11529 (goto-char (point-min))
11530 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11531 (setq b (match-beginning 0)))
11532 (goto-char (point-max))
11533 (if (re-search-backward "^END:VEVENT" nil t)
11534 (setq e (match-end 0)))
11535 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11536 (kill-buffer buf)
11537 (delete-file tmpfile)
11538 rtn))
11540 (defun org-closest-date (start current change prefer show-all)
11541 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11542 When PREFER is `past' return a date that is either CURRENT or past.
11543 When PREFER is `future', return a date that is either CURRENT or future.
11544 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11545 ;; Make the proper lists from the dates
11546 (catch 'exit
11547 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11548 dn dw sday cday n1 n2
11549 d m y y1 y2 date1 date2 nmonths nm ny m2)
11551 (setq start (org-date-to-gregorian start)
11552 current (org-date-to-gregorian
11553 (if show-all
11554 current
11555 (time-to-days (current-time))))
11556 sday (calendar-absolute-from-gregorian start)
11557 cday (calendar-absolute-from-gregorian current))
11559 (if (<= cday sday) (throw 'exit sday))
11561 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11562 (setq dn (string-to-number (match-string 1 change))
11563 dw (cdr (assoc (match-string 2 change) a1)))
11564 (error "Invalid change specifyer: %s" change))
11565 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11566 (cond
11567 ((eq dw 'day)
11568 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11569 n2 (+ n1 dn)))
11570 ((eq dw 'year)
11571 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11572 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11573 (setq date1 (list m d y1)
11574 n1 (calendar-absolute-from-gregorian date1)
11575 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11576 n2 (calendar-absolute-from-gregorian date2)))
11577 ((eq dw 'month)
11578 ;; approx number of month between the two dates
11579 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11580 ;; How often does dn fit in there?
11581 (setq d (nth 1 start) m (car start) y (nth 2 start)
11582 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11583 m (+ m nm)
11584 ny (floor (/ m 12))
11585 y (+ y ny)
11586 m (- m (* ny 12)))
11587 (while (> m 12) (setq m (- m 12) y (1+ y)))
11588 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11589 (setq m2 (+ m dn) y2 y)
11590 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11591 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11592 (while (<= n2 cday)
11593 (setq n1 n2 m m2 y y2)
11594 (setq m2 (+ m dn) y2 y)
11595 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11596 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11597 (if show-all
11598 (cond
11599 ((eq prefer 'past) n1)
11600 ((eq prefer 'future) (if (= cday n1) n1 n2))
11601 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11602 (cond
11603 ((eq prefer 'past) n1)
11604 ((eq prefer 'future) (if (= cday n1) n1 n2))
11605 (t (if (= cday n1) n1 n2)))))))
11607 (defun org-date-to-gregorian (date)
11608 "Turn any specification of DATE into a gregorian date for the calendar."
11609 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11610 ((and (listp date) (= (length date) 3)) date)
11611 ((stringp date)
11612 (setq date (org-parse-time-string date))
11613 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11614 ((listp date)
11615 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11617 (defun org-parse-time-string (s &optional nodefault)
11618 "Parse the standard Org-mode time string.
11619 This should be a lot faster than the normal `parse-time-string'.
11620 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11621 hour and minute fields will be nil if not given."
11622 (if (string-match org-ts-regexp0 s)
11623 (list 0
11624 (if (or (match-beginning 8) (not nodefault))
11625 (string-to-number (or (match-string 8 s) "0")))
11626 (if (or (match-beginning 7) (not nodefault))
11627 (string-to-number (or (match-string 7 s) "0")))
11628 (string-to-number (match-string 4 s))
11629 (string-to-number (match-string 3 s))
11630 (string-to-number (match-string 2 s))
11631 nil nil nil)
11632 (make-list 9 0)))
11634 (defun org-timestamp-up (&optional arg)
11635 "Increase the date item at the cursor by one.
11636 If the cursor is on the year, change the year. If it is on the month or
11637 the day, change that.
11638 With prefix ARG, change by that many units."
11639 (interactive "p")
11640 (org-timestamp-change (prefix-numeric-value arg)))
11642 (defun org-timestamp-down (&optional arg)
11643 "Decrease the date item at the cursor by one.
11644 If the cursor is on the year, change the year. If it is on the month or
11645 the day, change that.
11646 With prefix ARG, change by that many units."
11647 (interactive "p")
11648 (org-timestamp-change (- (prefix-numeric-value arg))))
11650 (defun org-timestamp-up-day (&optional arg)
11651 "Increase the date in the time stamp by one day.
11652 With prefix ARG, change that many days."
11653 (interactive "p")
11654 (if (and (not (org-at-timestamp-p t))
11655 (org-on-heading-p))
11656 (org-todo 'up)
11657 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11659 (defun org-timestamp-down-day (&optional arg)
11660 "Decrease the date in the time stamp by one day.
11661 With prefix ARG, change that many days."
11662 (interactive "p")
11663 (if (and (not (org-at-timestamp-p t))
11664 (org-on-heading-p))
11665 (org-todo 'down)
11666 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11668 (defun org-at-timestamp-p (&optional inactive-ok)
11669 "Determine if the cursor is in or at a timestamp."
11670 (interactive)
11671 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11672 (pos (point))
11673 (ans (or (looking-at tsr)
11674 (save-excursion
11675 (skip-chars-backward "^[<\n\r\t")
11676 (if (> (point) (point-min)) (backward-char 1))
11677 (and (looking-at tsr)
11678 (> (- (match-end 0) pos) -1))))))
11679 (and ans
11680 (boundp 'org-ts-what)
11681 (setq org-ts-what
11682 (cond
11683 ((= pos (match-beginning 0)) 'bracket)
11684 ((= pos (1- (match-end 0))) 'bracket)
11685 ((org-pos-in-match-range pos 2) 'year)
11686 ((org-pos-in-match-range pos 3) 'month)
11687 ((org-pos-in-match-range pos 7) 'hour)
11688 ((org-pos-in-match-range pos 8) 'minute)
11689 ((or (org-pos-in-match-range pos 4)
11690 (org-pos-in-match-range pos 5)) 'day)
11691 ((and (> pos (or (match-end 8) (match-end 5)))
11692 (< pos (match-end 0)))
11693 (- pos (or (match-end 8) (match-end 5))))
11694 (t 'day))))
11695 ans))
11697 (defun org-toggle-timestamp-type ()
11698 "Toggle the type (<active> or [inactive]) of a time stamp."
11699 (interactive)
11700 (when (org-at-timestamp-p t)
11701 (save-excursion
11702 (goto-char (match-beginning 0))
11703 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11704 (goto-char (1- (match-end 0)))
11705 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11706 (message "Timestamp is now %sactive"
11707 (if (equal (char-before) ?>) "in" ""))))
11709 (defun org-timestamp-change (n &optional what)
11710 "Change the date in the time stamp at point.
11711 The date will be changed by N times WHAT. WHAT can be `day', `month',
11712 `year', `minute', `second'. If WHAT is not given, the cursor position
11713 in the timestamp determines what will be changed."
11714 (let ((pos (point))
11715 with-hm inactive
11716 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11717 org-ts-what
11718 extra rem
11719 ts time time0)
11720 (if (not (org-at-timestamp-p t))
11721 (error "Not at a timestamp"))
11722 (if (and (not what) (eq org-ts-what 'bracket))
11723 (org-toggle-timestamp-type)
11724 (if (and (not what) (not (eq org-ts-what 'day))
11725 org-display-custom-times
11726 (get-text-property (point) 'display)
11727 (not (get-text-property (1- (point)) 'display)))
11728 (setq org-ts-what 'day))
11729 (setq org-ts-what (or what org-ts-what)
11730 inactive (= (char-after (match-beginning 0)) ?\[)
11731 ts (match-string 0))
11732 (replace-match "")
11733 (if (string-match
11734 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11736 (setq extra (match-string 1 ts)))
11737 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11738 (setq with-hm t))
11739 (setq time0 (org-parse-time-string ts))
11740 (when (and (eq org-ts-what 'minute)
11741 (eq current-prefix-arg nil))
11742 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11743 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11744 (setcar (cdr time0) (+ (nth 1 time0)
11745 (if (> n 0) (- rem) (- dm rem))))))
11746 (setq time
11747 (encode-time (or (car time0) 0)
11748 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11749 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11750 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11751 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11752 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11753 (nthcdr 6 time0)))
11754 (when (integerp org-ts-what)
11755 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11756 (if (eq what 'calendar)
11757 (let ((cal-date (org-get-date-from-calendar)))
11758 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11759 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11760 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11761 (setcar time0 (or (car time0) 0))
11762 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11763 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11764 (setq time (apply 'encode-time time0))))
11765 (setq org-last-changed-timestamp
11766 (org-insert-time-stamp time with-hm inactive nil nil extra))
11767 (org-clock-update-time-maybe)
11768 (goto-char pos)
11769 ;; Try to recenter the calendar window, if any
11770 (if (and org-calendar-follow-timestamp-change
11771 (get-buffer-window "*Calendar*" t)
11772 (memq org-ts-what '(day month year)))
11773 (org-recenter-calendar (time-to-days time))))))
11775 (defun org-modify-ts-extra (s pos n dm)
11776 "Change the different parts of the lead-time and repeat fields in timestamp."
11777 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11778 ng h m new rem)
11779 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11780 (cond
11781 ((or (org-pos-in-match-range pos 2)
11782 (org-pos-in-match-range pos 3))
11783 (setq m (string-to-number (match-string 3 s))
11784 h (string-to-number (match-string 2 s)))
11785 (if (org-pos-in-match-range pos 2)
11786 (setq h (+ h n))
11787 (setq n (* dm (org-no-warnings (signum n))))
11788 (when (not (= 0 (setq rem (% m dm))))
11789 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11790 (setq m (+ m n)))
11791 (if (< m 0) (setq m (+ m 60) h (1- h)))
11792 (if (> m 59) (setq m (- m 60) h (1+ h)))
11793 (setq h (min 24 (max 0 h)))
11794 (setq ng 1 new (format "-%02d:%02d" h m)))
11795 ((org-pos-in-match-range pos 6)
11796 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11797 ((org-pos-in-match-range pos 5)
11798 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11800 ((org-pos-in-match-range pos 9)
11801 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11802 ((org-pos-in-match-range pos 8)
11803 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11805 (when ng
11806 (setq s (concat
11807 (substring s 0 (match-beginning ng))
11809 (substring s (match-end ng))))))
11812 (defun org-recenter-calendar (date)
11813 "If the calendar is visible, recenter it to DATE."
11814 (let* ((win (selected-window))
11815 (cwin (get-buffer-window "*Calendar*" t))
11816 (calendar-move-hook nil))
11817 (when cwin
11818 (select-window cwin)
11819 (calendar-goto-date (if (listp date) date
11820 (calendar-gregorian-from-absolute date)))
11821 (select-window win))))
11823 (defun org-goto-calendar (&optional arg)
11824 "Go to the Emacs calendar at the current date.
11825 If there is a time stamp in the current line, go to that date.
11826 A prefix ARG can be used to force the current date."
11827 (interactive "P")
11828 (let ((tsr org-ts-regexp) diff
11829 (calendar-move-hook nil)
11830 (calendar-view-holidays-initially-flag nil)
11831 (view-calendar-holidays-initially nil)
11832 (calendar-view-diary-initially-flag nil)
11833 (view-diary-entries-initially nil))
11834 (if (or (org-at-timestamp-p)
11835 (save-excursion
11836 (beginning-of-line 1)
11837 (looking-at (concat ".*" tsr))))
11838 (let ((d1 (time-to-days (current-time)))
11839 (d2 (time-to-days
11840 (org-time-string-to-time (match-string 1)))))
11841 (setq diff (- d2 d1))))
11842 (calendar)
11843 (calendar-goto-today)
11844 (if (and diff (not arg)) (calendar-forward-day diff))))
11846 (defun org-get-date-from-calendar ()
11847 "Return a list (month day year) of date at point in calendar."
11848 (with-current-buffer "*Calendar*"
11849 (save-match-data
11850 (calendar-cursor-to-date))))
11852 (defun org-date-from-calendar ()
11853 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11854 If there is already a time stamp at the cursor position, update it."
11855 (interactive)
11856 (if (org-at-timestamp-p t)
11857 (org-timestamp-change 0 'calendar)
11858 (let ((cal-date (org-get-date-from-calendar)))
11859 (org-insert-time-stamp
11860 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11862 (defun org-minutes-to-hh:mm-string (m)
11863 "Compute H:MM from a number of minutes."
11864 (let ((h (/ m 60)))
11865 (setq m (- m (* 60 h)))
11866 (format org-time-clocksum-format h m)))
11868 (defun org-hh:mm-string-to-minutes (s)
11869 "Convert a string H:MM to a number of minutes."
11870 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11871 (+ (* (string-to-number (match-string 1 s)) 60)
11872 (string-to-number (match-string 2 s)))
11875 ;;;; Agenda files
11877 ;;;###autoload
11878 (defun org-iswitchb (&optional arg)
11879 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11880 With a prefix argument, restrict available to files.
11881 With two prefix arguments, restrict available buffers to agenda files.
11883 Due to some yet unresolved reason, global function
11884 `iswitchb-mode' needs to be active for this function to work."
11885 (interactive "P")
11886 (require 'iswitchb)
11887 (let ((enabled iswitchb-mode) blist)
11888 (or enabled (iswitchb-mode 1))
11889 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11890 ((equal arg '(16)) (org-buffer-list 'agenda))
11891 (t (org-buffer-list))))
11892 (unwind-protect
11893 (let ((iswitchb-make-buflist-hook
11894 (lambda ()
11895 (setq iswitchb-temp-buflist
11896 (mapcar 'buffer-name blist)))))
11897 (switch-to-buffer
11898 (iswitchb-read-buffer
11899 "Switch-to: " nil t))
11900 (or enabled (iswitchb-mode -1))))))
11902 (defun org-buffer-list (&optional predicate tmp)
11903 "Return a list of Org buffers.
11904 PREDICATE can be either 'export, 'files or 'agenda.
11906 'export restrict the list to Export buffers.
11907 'files restrict the list to buffers visiting Org files.
11908 'agenda restrict the list to buffers visiting agenda files.
11910 If TMP is non-nil, don't include temporary buffers."
11911 (let (filter blist)
11912 (setq filter
11913 (cond ((eq predicate 'files) "\.org$")
11914 ((eq predicate 'export) "\*Org .*Export")
11915 (t "\*Org \\|\.org$")))
11916 (setq blist
11917 (mapcar
11918 (lambda(b)
11919 (let ((bname (buffer-name b))
11920 (bfile (buffer-file-name b)))
11921 (if (and (string-match filter bname)
11922 (if (eq predicate 'agenda)
11923 (member bfile
11924 (mapcar (lambda(f) (file-truename f))
11925 org-agenda-files)) t)
11926 (if tmp (not (string-match "tmp" bname)) t)) b)))
11927 (buffer-list)))
11928 (delete nil blist)))
11930 (defun org-agenda-files (&optional unrestricted archives)
11931 "Get the list of agenda files.
11932 Optional UNRESTRICTED means return the full list even if a restriction
11933 is currently in place.
11934 When ARCHIVES is t, include all archive files hat are really being
11935 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11936 `org-agenda-archives-mode' is t."
11937 (let ((files
11938 (cond
11939 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11940 ((stringp org-agenda-files) (org-read-agenda-file-list))
11941 ((listp org-agenda-files) org-agenda-files)
11942 (t (error "Invalid value of `org-agenda-files'")))))
11943 (setq files (apply 'append
11944 (mapcar (lambda (f)
11945 (if (file-directory-p f)
11946 (directory-files
11947 f t org-agenda-file-regexp)
11948 (list f)))
11949 files)))
11950 (when org-agenda-skip-unavailable-files
11951 (setq files (delq nil
11952 (mapcar (function
11953 (lambda (file)
11954 (and (file-readable-p file) file)))
11955 files))))
11956 (when (or (eq archives t)
11957 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11958 (setq files (org-add-archive-files files)))
11959 files))
11961 (defun org-edit-agenda-file-list ()
11962 "Edit the list of agenda files.
11963 Depending on setup, this either uses customize to edit the variable
11964 `org-agenda-files', or it visits the file that is holding the list. In the
11965 latter case, the buffer is set up in a way that saving it automatically kills
11966 the buffer and restores the previous window configuration."
11967 (interactive)
11968 (if (stringp org-agenda-files)
11969 (let ((cw (current-window-configuration)))
11970 (find-file org-agenda-files)
11971 (org-set-local 'org-window-configuration cw)
11972 (org-add-hook 'after-save-hook
11973 (lambda ()
11974 (set-window-configuration
11975 (prog1 org-window-configuration
11976 (kill-buffer (current-buffer))))
11977 (org-install-agenda-files-menu)
11978 (message "New agenda file list installed"))
11979 nil 'local)
11980 (message "%s" (substitute-command-keys
11981 "Edit list and finish with \\[save-buffer]")))
11982 (customize-variable 'org-agenda-files)))
11984 (defun org-store-new-agenda-file-list (list)
11985 "Set new value for the agenda file list and save it correcly."
11986 (if (stringp org-agenda-files)
11987 (let ((f org-agenda-files) b)
11988 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11989 (with-temp-file f
11990 (insert (mapconcat 'identity list "\n") "\n")))
11991 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11992 (setq org-agenda-files list)
11993 (customize-save-variable 'org-agenda-files org-agenda-files))))
11995 (defun org-read-agenda-file-list ()
11996 "Read the list of agenda files from a file."
11997 (when (file-directory-p org-agenda-files)
11998 (error "`org-agenda-files' cannot be a single directory"))
11999 (when (stringp org-agenda-files)
12000 (with-temp-buffer
12001 (insert-file-contents org-agenda-files)
12002 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12005 ;;;###autoload
12006 (defun org-cycle-agenda-files ()
12007 "Cycle through the files in `org-agenda-files'.
12008 If the current buffer visits an agenda file, find the next one in the list.
12009 If the current buffer does not, find the first agenda file."
12010 (interactive)
12011 (let* ((fs (org-agenda-files t))
12012 (files (append fs (list (car fs))))
12013 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12014 file)
12015 (unless files (error "No agenda files"))
12016 (catch 'exit
12017 (while (setq file (pop files))
12018 (if (equal (file-truename file) tcf)
12019 (when (car files)
12020 (find-file (car files))
12021 (throw 'exit t))))
12022 (find-file (car fs)))
12023 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12025 (defun org-agenda-file-to-front (&optional to-end)
12026 "Move/add the current file to the top of the agenda file list.
12027 If the file is not present in the list, it is added to the front. If it is
12028 present, it is moved there. With optional argument TO-END, add/move to the
12029 end of the list."
12030 (interactive "P")
12031 (let ((org-agenda-skip-unavailable-files nil)
12032 (file-alist (mapcar (lambda (x)
12033 (cons (file-truename x) x))
12034 (org-agenda-files t)))
12035 (ctf (file-truename buffer-file-name))
12036 x had)
12037 (setq x (assoc ctf file-alist) had x)
12039 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12040 (if to-end
12041 (setq file-alist (append (delq x file-alist) (list x)))
12042 (setq file-alist (cons x (delq x file-alist))))
12043 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12044 (org-install-agenda-files-menu)
12045 (message "File %s to %s of agenda file list"
12046 (if had "moved" "added") (if to-end "end" "front"))))
12048 (defun org-remove-file (&optional file)
12049 "Remove current file from the list of files in variable `org-agenda-files'.
12050 These are the files which are being checked for agenda entries.
12051 Optional argument FILE means, use this file instead of the current."
12052 (interactive)
12053 (let* ((org-agenda-skip-unavailable-files nil)
12054 (file (or file buffer-file-name))
12055 (true-file (file-truename file))
12056 (afile (abbreviate-file-name file))
12057 (files (delq nil (mapcar
12058 (lambda (x)
12059 (if (equal true-file
12060 (file-truename x))
12061 nil x))
12062 (org-agenda-files t)))))
12063 (if (not (= (length files) (length (org-agenda-files t))))
12064 (progn
12065 (org-store-new-agenda-file-list files)
12066 (org-install-agenda-files-menu)
12067 (message "Removed file: %s" afile))
12068 (message "File was not in list: %s (not removed)" afile))))
12070 (defun org-file-menu-entry (file)
12071 (vector file (list 'find-file file) t))
12073 (defun org-check-agenda-file (file)
12074 "Make sure FILE exists. If not, ask user what to do."
12075 (when (not (file-exists-p file))
12076 (message "non-existent file %s. [R]emove from list or [A]bort?"
12077 (abbreviate-file-name file))
12078 (let ((r (downcase (read-char-exclusive))))
12079 (cond
12080 ((equal r ?r)
12081 (org-remove-file file)
12082 (throw 'nextfile t))
12083 (t (error "Abort"))))))
12085 (defun org-get-agenda-file-buffer (file)
12086 "Get a buffer visiting FILE. If the buffer needs to be created, add
12087 it to the list of buffers which might be released later."
12088 (let ((buf (org-find-base-buffer-visiting file)))
12089 (if buf
12090 buf ; just return it
12091 ;; Make a new buffer and remember it
12092 (setq buf (find-file-noselect file))
12093 (if buf (push buf org-agenda-new-buffers))
12094 buf)))
12096 (defun org-release-buffers (blist)
12097 "Release all buffers in list, asking the user for confirmation when needed.
12098 When a buffer is unmodified, it is just killed. When modified, it is saved
12099 \(if the user agrees) and then killed."
12100 (let (buf file)
12101 (while (setq buf (pop blist))
12102 (setq file (buffer-file-name buf))
12103 (when (and (buffer-modified-p buf)
12104 file
12105 (y-or-n-p (format "Save file %s? " file)))
12106 (with-current-buffer buf (save-buffer)))
12107 (kill-buffer buf))))
12109 (defun org-prepare-agenda-buffers (files)
12110 "Create buffers for all agenda files, protect archived trees and comments."
12111 (interactive)
12112 (let ((pa '(:org-archived t))
12113 (pc '(:org-comment t))
12114 (pall '(:org-archived t :org-comment t))
12115 (inhibit-read-only t)
12116 (rea (concat ":" org-archive-tag ":"))
12117 bmp file re)
12118 (save-excursion
12119 (save-restriction
12120 (while (setq file (pop files))
12121 (if (bufferp file)
12122 (set-buffer file)
12123 (org-check-agenda-file file)
12124 (set-buffer (org-get-agenda-file-buffer file)))
12125 (widen)
12126 (setq bmp (buffer-modified-p))
12127 (org-refresh-category-properties)
12128 (setq org-todo-keywords-for-agenda
12129 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12130 (setq org-done-keywords-for-agenda
12131 (append org-done-keywords-for-agenda org-done-keywords))
12132 (save-excursion
12133 (remove-text-properties (point-min) (point-max) pall)
12134 (when org-agenda-skip-archived-trees
12135 (goto-char (point-min))
12136 (while (re-search-forward rea nil t)
12137 (if (org-on-heading-p t)
12138 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12139 (goto-char (point-min))
12140 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12141 (while (re-search-forward re nil t)
12142 (add-text-properties
12143 (match-beginning 0) (org-end-of-subtree t) pc)))
12144 (set-buffer-modified-p bmp))))))
12146 ;;;; Embedded LaTeX
12148 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12149 "Keymap for the minor `org-cdlatex-mode'.")
12151 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12152 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12153 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12154 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12155 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12157 (defvar org-cdlatex-texmathp-advice-is-done nil
12158 "Flag remembering if we have applied the advice to texmathp already.")
12160 (define-minor-mode org-cdlatex-mode
12161 "Toggle the minor `org-cdlatex-mode'.
12162 This mode supports entering LaTeX environment and math in LaTeX fragments
12163 in Org-mode.
12164 \\{org-cdlatex-mode-map}"
12165 nil " OCDL" nil
12166 (when org-cdlatex-mode (require 'cdlatex))
12167 (unless org-cdlatex-texmathp-advice-is-done
12168 (setq org-cdlatex-texmathp-advice-is-done t)
12169 (defadvice texmathp (around org-math-always-on activate)
12170 "Always return t in org-mode buffers.
12171 This is because we want to insert math symbols without dollars even outside
12172 the LaTeX math segments. If Orgmode thinks that point is actually inside
12173 en embedded LaTeX fragement, let texmathp do its job.
12174 \\[org-cdlatex-mode-map]"
12175 (interactive)
12176 (let (p)
12177 (cond
12178 ((not (org-mode-p)) ad-do-it)
12179 ((eq this-command 'cdlatex-math-symbol)
12180 (setq ad-return-value t
12181 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12183 (let ((p (org-inside-LaTeX-fragment-p)))
12184 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12185 (setq ad-return-value t
12186 texmathp-why '("Org-mode embedded math" . 0))
12187 (if p ad-do-it)))))))))
12189 (defun turn-on-org-cdlatex ()
12190 "Unconditionally turn on `org-cdlatex-mode'."
12191 (org-cdlatex-mode 1))
12193 (defun org-inside-LaTeX-fragment-p ()
12194 "Test if point is inside a LaTeX fragment.
12195 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12196 sequence appearing also before point.
12197 Even though the matchers for math are configurable, this function assumes
12198 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12199 delimiters are skipped when they have been removed by customization.
12200 The return value is nil, or a cons cell with the delimiter and
12201 and the position of this delimiter.
12203 This function does a reasonably good job, but can locally be fooled by
12204 for example currency specifications. For example it will assume being in
12205 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12206 fragments that are properly closed, but during editing, we have to live
12207 with the uncertainty caused by missing closing delimiters. This function
12208 looks only before point, not after."
12209 (catch 'exit
12210 (let ((pos (point))
12211 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12212 (lim (progn
12213 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12214 (point)))
12215 dd-on str (start 0) m re)
12216 (goto-char pos)
12217 (when dodollar
12218 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12219 re (nth 1 (assoc "$" org-latex-regexps)))
12220 (while (string-match re str start)
12221 (cond
12222 ((= (match-end 0) (length str))
12223 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12224 ((= (match-end 0) (- (length str) 5))
12225 (throw 'exit nil))
12226 (t (setq start (match-end 0))))))
12227 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12228 (goto-char pos)
12229 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12230 (and (match-beginning 2) (throw 'exit nil))
12231 ;; count $$
12232 (while (re-search-backward "\\$\\$" lim t)
12233 (setq dd-on (not dd-on)))
12234 (goto-char pos)
12235 (if dd-on (cons "$$" m))))))
12238 (defun org-try-cdlatex-tab ()
12239 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12240 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12241 - inside a LaTeX fragment, or
12242 - after the first word in a line, where an abbreviation expansion could
12243 insert a LaTeX environment."
12244 (when org-cdlatex-mode
12245 (cond
12246 ((save-excursion
12247 (skip-chars-backward "a-zA-Z0-9*")
12248 (skip-chars-backward " \t")
12249 (bolp))
12250 (cdlatex-tab) t)
12251 ((org-inside-LaTeX-fragment-p)
12252 (cdlatex-tab) t)
12253 (t nil))))
12255 (defun org-cdlatex-underscore-caret (&optional arg)
12256 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12257 Revert to the normal definition outside of these fragments."
12258 (interactive "P")
12259 (if (org-inside-LaTeX-fragment-p)
12260 (call-interactively 'cdlatex-sub-superscript)
12261 (let (org-cdlatex-mode)
12262 (call-interactively (key-binding (vector last-input-event))))))
12264 (defun org-cdlatex-math-modify (&optional arg)
12265 "Execute `cdlatex-math-modify' in LaTeX fragments.
12266 Revert to the normal definition outside of these fragments."
12267 (interactive "P")
12268 (if (org-inside-LaTeX-fragment-p)
12269 (call-interactively 'cdlatex-math-modify)
12270 (let (org-cdlatex-mode)
12271 (call-interactively (key-binding (vector last-input-event))))))
12273 (defvar org-latex-fragment-image-overlays nil
12274 "List of overlays carrying the images of latex fragments.")
12275 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12277 (defun org-remove-latex-fragment-image-overlays ()
12278 "Remove all overlays with LaTeX fragment images in current buffer."
12279 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12280 (setq org-latex-fragment-image-overlays nil))
12282 (defun org-preview-latex-fragment (&optional subtree)
12283 "Preview the LaTeX fragment at point, or all locally or globally.
12284 If the cursor is in a LaTeX fragment, create the image and overlay
12285 it over the source code. If there is no fragment at point, display
12286 all fragments in the current text, from one headline to the next. With
12287 prefix SUBTREE, display all fragments in the current subtree. With a
12288 double prefix `C-u C-u', or when the cursor is before the first headline,
12289 display all fragments in the buffer.
12290 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12291 (interactive "P")
12292 (org-remove-latex-fragment-image-overlays)
12293 (save-excursion
12294 (save-restriction
12295 (let (beg end at msg)
12296 (cond
12297 ((or (equal subtree '(16))
12298 (not (save-excursion
12299 (re-search-backward (concat "^" outline-regexp) nil t))))
12300 (setq beg (point-min) end (point-max)
12301 msg "Creating images for buffer...%s"))
12302 ((equal subtree '(4))
12303 (org-back-to-heading)
12304 (setq beg (point) end (org-end-of-subtree t)
12305 msg "Creating images for subtree...%s"))
12307 (if (setq at (org-inside-LaTeX-fragment-p))
12308 (goto-char (max (point-min) (- (cdr at) 2)))
12309 (org-back-to-heading))
12310 (setq beg (point) end (progn (outline-next-heading) (point))
12311 msg (if at "Creating image...%s"
12312 "Creating images for entry...%s"))))
12313 (message msg "")
12314 (narrow-to-region beg end)
12315 (goto-char beg)
12316 (org-format-latex
12317 (concat "ltxpng/" (file-name-sans-extension
12318 (file-name-nondirectory
12319 buffer-file-name)))
12320 default-directory 'overlays msg at 'forbuffer)
12321 (message msg "done. Use `C-c C-c' to remove images.")))))
12323 (defvar org-latex-regexps
12324 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12325 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12326 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12327 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12328 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12329 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12330 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12331 "Regular expressions for matching embedded LaTeX.")
12333 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12334 "Replace LaTeX fragments with links to an image, and produce images."
12335 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12336 (let* ((prefixnodir (file-name-nondirectory prefix))
12337 (absprefix (expand-file-name prefix dir))
12338 (todir (file-name-directory absprefix))
12339 (opt org-format-latex-options)
12340 (matchers (plist-get opt :matchers))
12341 (re-list org-latex-regexps)
12342 (cnt 0) txt link beg end re e checkdir
12343 m n block linkfile movefile ov)
12344 ;; Check if there are old images files with this prefix, and remove them
12345 (when (file-directory-p todir)
12346 (mapc 'delete-file
12347 (directory-files
12348 todir 'full
12349 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12350 ;; Check the different regular expressions
12351 (while (setq e (pop re-list))
12352 (setq m (car e) re (nth 1 e) n (nth 2 e)
12353 block (if (nth 3 e) "\n\n" ""))
12354 (when (member m matchers)
12355 (goto-char (point-min))
12356 (while (re-search-forward re nil t)
12357 (when (or (not at) (equal (cdr at) (match-beginning n)))
12358 (setq txt (match-string n)
12359 beg (match-beginning n) end (match-end n)
12360 cnt (1+ cnt)
12361 linkfile (format "%s_%04d.png" prefix cnt)
12362 movefile (format "%s_%04d.png" absprefix cnt)
12363 link (concat block "[[file:" linkfile "]]" block))
12364 (if msg (message msg cnt))
12365 (goto-char beg)
12366 (unless checkdir ; make sure the directory exists
12367 (setq checkdir t)
12368 (or (file-directory-p todir) (make-directory todir)))
12369 (org-create-formula-image
12370 txt movefile opt forbuffer)
12371 (if overlays
12372 (progn
12373 (setq ov (org-make-overlay beg end))
12374 (if (featurep 'xemacs)
12375 (progn
12376 (org-overlay-put ov 'invisible t)
12377 (org-overlay-put
12378 ov 'end-glyph
12379 (make-glyph (vector 'png :file movefile))))
12380 (org-overlay-put
12381 ov 'display
12382 (list 'image :type 'png :file movefile :ascent 'center)))
12383 (push ov org-latex-fragment-image-overlays)
12384 (goto-char end))
12385 (delete-region beg end)
12386 (insert link))))))))
12388 ;; This function borrows from Ganesh Swami's latex2png.el
12389 (defun org-create-formula-image (string tofile options buffer)
12390 (let* ((tmpdir (if (featurep 'xemacs)
12391 (temp-directory)
12392 temporary-file-directory))
12393 (texfilebase (make-temp-name
12394 (expand-file-name "orgtex" tmpdir)))
12395 (texfile (concat texfilebase ".tex"))
12396 (dvifile (concat texfilebase ".dvi"))
12397 (pngfile (concat texfilebase ".png"))
12398 (fnh (if (featurep 'xemacs)
12399 (font-height (get-face-font 'default))
12400 (face-attribute 'default :height nil)))
12401 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12402 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12403 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12404 "Black"))
12405 (bg (or (plist-get options (if buffer :background :html-background))
12406 "Transparent")))
12407 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12408 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12409 (with-temp-file texfile
12410 (insert org-format-latex-header
12411 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12412 (let ((dir default-directory))
12413 (condition-case nil
12414 (progn
12415 (cd tmpdir)
12416 (call-process "latex" nil nil nil texfile))
12417 (error nil))
12418 (cd dir))
12419 (if (not (file-exists-p dvifile))
12420 (progn (message "Failed to create dvi file from %s" texfile) nil)
12421 (condition-case nil
12422 (call-process "dvipng" nil nil nil
12423 "-E" "-fg" fg "-bg" bg
12424 "-D" dpi
12425 ;;"-x" scale "-y" scale
12426 "-T" "tight"
12427 "-o" pngfile
12428 dvifile)
12429 (error nil))
12430 (if (not (file-exists-p pngfile))
12431 (progn (message "Failed to create png file from %s" texfile) nil)
12432 ;; Use the requested file name and clean up
12433 (copy-file pngfile tofile 'replace)
12434 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12435 (delete-file (concat texfilebase e)))
12436 pngfile))))
12438 (defun org-dvipng-color (attr)
12439 "Return an rgb color specification for dvipng."
12440 (apply 'format "rgb %s %s %s"
12441 (mapcar 'org-normalize-color
12442 (color-values (face-attribute 'default attr nil)))))
12444 (defun org-normalize-color (value)
12445 "Return string to be used as color value for an RGB component."
12446 (format "%g" (/ value 65535.0)))
12449 ;;;; Key bindings
12451 ;; Make `C-c C-x' a prefix key
12452 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12454 ;; TAB key with modifiers
12455 (org-defkey org-mode-map "\C-i" 'org-cycle)
12456 (org-defkey org-mode-map [(tab)] 'org-cycle)
12457 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12458 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12459 (org-defkey org-mode-map "\M-\t" 'org-complete)
12460 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12461 ;; The following line is necessary under Suse GNU/Linux
12462 (unless (featurep 'xemacs)
12463 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12464 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12465 (define-key org-mode-map [backtab] 'org-shifttab)
12467 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12468 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12469 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12471 ;; Cursor keys with modifiers
12472 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12473 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12474 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12475 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12477 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12478 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12479 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12480 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12482 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12483 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12484 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12485 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12487 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12488 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12490 ;;; Extra keys for tty access.
12491 ;; We only set them when really needed because otherwise the
12492 ;; menus don't show the simple keys
12494 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12495 (not window-system))
12496 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12497 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12498 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12499 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12500 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12501 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12502 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12503 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12504 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12505 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12506 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12507 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12508 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12509 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12510 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12511 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12512 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12513 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12514 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12515 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12516 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12517 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12519 ;; All the other keys
12521 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12522 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12523 (if (boundp 'narrow-map)
12524 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12525 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12526 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12527 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12528 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12529 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12530 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12531 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12532 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12533 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12534 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12535 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12536 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12537 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12538 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12539 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12540 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12541 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12542 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12543 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12544 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12545 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12546 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12547 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12548 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12549 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12550 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12551 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12552 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12553 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12554 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12555 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12556 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12557 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12558 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12559 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12560 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12561 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12562 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12563 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12564 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12565 (org-defkey org-mode-map "\C-c^" 'org-sort)
12566 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12567 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12568 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12569 (org-defkey org-mode-map "\C-m" 'org-return)
12570 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12571 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12572 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12573 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12574 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12575 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12576 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12577 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12578 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12579 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12580 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12581 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12582 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12583 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12584 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12585 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12587 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12588 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12589 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12590 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12592 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12593 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12594 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12595 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12596 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12597 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12598 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12599 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12600 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12601 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12602 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12603 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12605 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12607 (when (featurep 'xemacs)
12608 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12610 (defvar org-table-auto-blank-field) ; defined in org-table.el
12611 (defun org-self-insert-command (N)
12612 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12613 If the cursor is in a table looking at whitespace, the whitespace is
12614 overwritten, and the table is not marked as requiring realignment."
12615 (interactive "p")
12616 (if (and (org-table-p)
12617 (progn
12618 ;; check if we blank the field, and if that triggers align
12619 (and (featurep 'org-table) org-table-auto-blank-field
12620 (member last-command
12621 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12622 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12623 ;; got extra space, this field does not determine column width
12624 (let (org-table-may-need-update) (org-table-blank-field))
12625 ;; no extra space, this field may determine column width
12626 (org-table-blank-field)))
12628 (eq N 1)
12629 (looking-at "[^|\n]* |"))
12630 (let (org-table-may-need-update)
12631 (goto-char (1- (match-end 0)))
12632 (delete-backward-char 1)
12633 (goto-char (match-beginning 0))
12634 (self-insert-command N))
12635 (setq org-table-may-need-update t)
12636 (self-insert-command N)
12637 (org-fix-tags-on-the-fly)))
12639 (defun org-fix-tags-on-the-fly ()
12640 (when (and (equal (char-after (point-at-bol)) ?*)
12641 (org-on-heading-p))
12642 (org-align-tags-here org-tags-column)))
12644 (defun org-delete-backward-char (N)
12645 "Like `delete-backward-char', insert whitespace at field end in tables.
12646 When deleting backwards, in tables this function will insert whitespace in
12647 front of the next \"|\" separator, to keep the table aligned. The table will
12648 still be marked for re-alignment if the field did fill the entire column,
12649 because, in this case the deletion might narrow the column."
12650 (interactive "p")
12651 (if (and (org-table-p)
12652 (eq N 1)
12653 (string-match "|" (buffer-substring (point-at-bol) (point)))
12654 (looking-at ".*?|"))
12655 (let ((pos (point))
12656 (noalign (looking-at "[^|\n\r]* |"))
12657 (c org-table-may-need-update))
12658 (backward-delete-char N)
12659 (skip-chars-forward "^|")
12660 (insert " ")
12661 (goto-char (1- pos))
12662 ;; noalign: if there were two spaces at the end, this field
12663 ;; does not determine the width of the column.
12664 (if noalign (setq org-table-may-need-update c)))
12665 (backward-delete-char N)
12666 (org-fix-tags-on-the-fly)))
12668 (defun org-delete-char (N)
12669 "Like `delete-char', but insert whitespace at field end in tables.
12670 When deleting characters, in tables this function will insert whitespace in
12671 front of the next \"|\" separator, to keep the table aligned. The table will
12672 still be marked for re-alignment if the field did fill the entire column,
12673 because, in this case the deletion might narrow the column."
12674 (interactive "p")
12675 (if (and (org-table-p)
12676 (not (bolp))
12677 (not (= (char-after) ?|))
12678 (eq N 1))
12679 (if (looking-at ".*?|")
12680 (let ((pos (point))
12681 (noalign (looking-at "[^|\n\r]* |"))
12682 (c org-table-may-need-update))
12683 (replace-match (concat
12684 (substring (match-string 0) 1 -1)
12685 " |"))
12686 (goto-char pos)
12687 ;; noalign: if there were two spaces at the end, this field
12688 ;; does not determine the width of the column.
12689 (if noalign (setq org-table-may-need-update c)))
12690 (delete-char N))
12691 (delete-char N)
12692 (org-fix-tags-on-the-fly)))
12694 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12695 (put 'org-self-insert-command 'delete-selection t)
12696 (put 'orgtbl-self-insert-command 'delete-selection t)
12697 (put 'org-delete-char 'delete-selection 'supersede)
12698 (put 'org-delete-backward-char 'delete-selection 'supersede)
12700 ;; Make `flyspell-mode' delay after some commands
12701 (put 'org-self-insert-command 'flyspell-delayed t)
12702 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12703 (put 'org-delete-char 'flyspell-delayed t)
12704 (put 'org-delete-backward-char 'flyspell-delayed t)
12706 ;; Make pabbrev-mode expand after org-mode commands
12707 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12708 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12710 ;; How to do this: Measure non-white length of current string
12711 ;; If equal to column width, we should realign.
12713 (defun org-remap (map &rest commands)
12714 "In MAP, remap the functions given in COMMANDS.
12715 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12716 (let (new old)
12717 (while commands
12718 (setq old (pop commands) new (pop commands))
12719 (if (fboundp 'command-remapping)
12720 (org-defkey map (vector 'remap old) new)
12721 (substitute-key-definition old new map global-map)))))
12723 (when (eq org-enable-table-editor 'optimized)
12724 ;; If the user wants maximum table support, we need to hijack
12725 ;; some standard editing functions
12726 (org-remap org-mode-map
12727 'self-insert-command 'org-self-insert-command
12728 'delete-char 'org-delete-char
12729 'delete-backward-char 'org-delete-backward-char)
12730 (org-defkey org-mode-map "|" 'org-force-self-insert))
12732 (defun org-shiftcursor-error ()
12733 "Throw an error because Shift-Cursor command was applied in wrong context."
12734 (error "This command is active in special context like tables, headlines or timestamps"))
12736 (defun org-shifttab (&optional arg)
12737 "Global visibility cycling or move to previous table field.
12738 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12739 on context.
12740 See the individual commands for more information."
12741 (interactive "P")
12742 (cond
12743 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12744 ((integerp arg)
12745 (message "Content view to level: %d" arg)
12746 (org-content (prefix-numeric-value arg))
12747 (setq org-cycle-global-status 'overview))
12748 (t (call-interactively 'org-global-cycle))))
12750 (defun org-shiftmetaleft ()
12751 "Promote subtree or delete table column.
12752 Calls `org-promote-subtree', `org-outdent-item',
12753 or `org-table-delete-column', depending on context.
12754 See the individual commands for more information."
12755 (interactive)
12756 (cond
12757 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12758 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12759 ((org-at-item-p) (call-interactively 'org-outdent-item))
12760 (t (org-shiftcursor-error))))
12762 (defun org-shiftmetaright ()
12763 "Demote subtree or insert table column.
12764 Calls `org-demote-subtree', `org-indent-item',
12765 or `org-table-insert-column', depending on context.
12766 See the individual commands for more information."
12767 (interactive)
12768 (cond
12769 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12770 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12771 ((org-at-item-p) (call-interactively 'org-indent-item))
12772 (t (org-shiftcursor-error))))
12774 (defun org-shiftmetaup (&optional arg)
12775 "Move subtree up or kill table row.
12776 Calls `org-move-subtree-up' or `org-table-kill-row' or
12777 `org-move-item-up' depending on context. See the individual commands
12778 for more information."
12779 (interactive "P")
12780 (cond
12781 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12782 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12783 ((org-at-item-p) (call-interactively 'org-move-item-up))
12784 (t (org-shiftcursor-error))))
12785 (defun org-shiftmetadown (&optional arg)
12786 "Move subtree down or insert table row.
12787 Calls `org-move-subtree-down' or `org-table-insert-row' or
12788 `org-move-item-down', depending on context. See the individual
12789 commands for more information."
12790 (interactive "P")
12791 (cond
12792 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12793 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12794 ((org-at-item-p) (call-interactively 'org-move-item-down))
12795 (t (org-shiftcursor-error))))
12797 (defun org-metaleft (&optional arg)
12798 "Promote heading or move table column to left.
12799 Calls `org-do-promote' or `org-table-move-column', depending on context.
12800 With no specific context, calls the Emacs default `backward-word'.
12801 See the individual commands for more information."
12802 (interactive "P")
12803 (cond
12804 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12805 ((or (org-on-heading-p) (org-region-active-p))
12806 (call-interactively 'org-do-promote))
12807 ((org-at-item-p) (call-interactively 'org-outdent-item))
12808 (t (call-interactively 'backward-word))))
12810 (defun org-metaright (&optional arg)
12811 "Demote subtree or move table column to right.
12812 Calls `org-do-demote' or `org-table-move-column', depending on context.
12813 With no specific context, calls the Emacs default `forward-word'.
12814 See the individual commands for more information."
12815 (interactive "P")
12816 (cond
12817 ((org-at-table-p) (call-interactively 'org-table-move-column))
12818 ((or (org-on-heading-p) (org-region-active-p))
12819 (call-interactively 'org-do-demote))
12820 ((org-at-item-p) (call-interactively 'org-indent-item))
12821 (t (call-interactively 'forward-word))))
12823 (defun org-metaup (&optional arg)
12824 "Move subtree up or move table row up.
12825 Calls `org-move-subtree-up' or `org-table-move-row' or
12826 `org-move-item-up', depending on context. See the individual commands
12827 for more information."
12828 (interactive "P")
12829 (cond
12830 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12831 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12832 ((org-at-item-p) (call-interactively 'org-move-item-up))
12833 (t (transpose-lines 1) (beginning-of-line -1))))
12835 (defun org-metadown (&optional arg)
12836 "Move subtree down or move table row down.
12837 Calls `org-move-subtree-down' or `org-table-move-row' or
12838 `org-move-item-down', depending on context. See the individual
12839 commands for more information."
12840 (interactive "P")
12841 (cond
12842 ((org-at-table-p) (call-interactively 'org-table-move-row))
12843 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12844 ((org-at-item-p) (call-interactively 'org-move-item-down))
12845 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12847 (defun org-shiftup (&optional arg)
12848 "Increase item in timestamp or increase priority of current headline.
12849 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12850 depending on context. See the individual commands for more information."
12851 (interactive "P")
12852 (cond
12853 ((org-at-timestamp-p t)
12854 (call-interactively (if org-edit-timestamp-down-means-later
12855 'org-timestamp-down 'org-timestamp-up)))
12856 ((org-on-heading-p) (call-interactively 'org-priority-up))
12857 ((org-at-item-p) (call-interactively 'org-previous-item))
12858 ((org-clocktable-try-shift 'up arg))
12859 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12861 (defun org-shiftdown (&optional arg)
12862 "Decrease item in timestamp or decrease priority of current headline.
12863 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12864 depending on context. See the individual commands for more information."
12865 (interactive "P")
12866 (cond
12867 ((org-at-timestamp-p t)
12868 (call-interactively (if org-edit-timestamp-down-means-later
12869 'org-timestamp-up 'org-timestamp-down)))
12870 ((org-on-heading-p) (call-interactively 'org-priority-down))
12871 ((org-clocktable-try-shift 'down arg))
12872 (t (call-interactively 'org-next-item))))
12874 (defun org-shiftright (&optional arg)
12875 "Next TODO keyword or timestamp one day later, depending on context."
12876 (interactive "P")
12877 (cond
12878 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12879 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12880 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12881 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12882 ((org-clocktable-try-shift 'right arg))
12883 (t (org-shiftcursor-error))))
12885 (defun org-shiftleft (&optional arg)
12886 "Previous TODO keyword or timestamp one day earlier, depending on context."
12887 (interactive "P")
12888 (cond
12889 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12890 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12891 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12892 ((org-at-property-p)
12893 (call-interactively 'org-property-previous-allowed-value))
12894 ((org-clocktable-try-shift 'left arg))
12895 (t (org-shiftcursor-error))))
12897 (defun org-shiftcontrolright ()
12898 "Switch to next TODO set."
12899 (interactive)
12900 (cond
12901 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12902 (t (org-shiftcursor-error))))
12904 (defun org-shiftcontrolleft ()
12905 "Switch to previous TODO set."
12906 (interactive)
12907 (cond
12908 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12909 (t (org-shiftcursor-error))))
12911 (defun org-ctrl-c-ret ()
12912 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12913 (interactive)
12914 (cond
12915 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12916 (t (call-interactively 'org-insert-heading))))
12918 (defun org-copy-special ()
12919 "Copy region in table or copy current subtree.
12920 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12921 See the individual commands for more information."
12922 (interactive)
12923 (call-interactively
12924 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12926 (defun org-cut-special ()
12927 "Cut region in table or cut current subtree.
12928 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12929 See the individual commands for more information."
12930 (interactive)
12931 (call-interactively
12932 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12934 (defun org-paste-special (arg)
12935 "Paste rectangular region into table, or past subtree relative to level.
12936 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12937 See the individual commands for more information."
12938 (interactive "P")
12939 (if (org-at-table-p)
12940 (org-table-paste-rectangle)
12941 (org-paste-subtree arg)))
12943 (defun org-edit-special ()
12944 "Call a special editor for the stuff at point.
12945 When at a table, call the formula editor with `org-table-edit-formulas'.
12946 When at the first line of an src example, call `org-edit-src-code'.
12947 When in an #+include line, visit the include file. Otherwise call
12948 `ffap' to visit the file at point."
12949 (interactive)
12950 (cond
12951 ((org-at-table-p)
12952 (call-interactively 'org-table-edit-formulas))
12953 ((save-excursion
12954 (beginning-of-line 1)
12955 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12956 (find-file (org-trim (match-string 1))))
12957 ((org-edit-src-code))
12958 (t (call-interactively 'ffap))))
12960 (defun org-ctrl-c-ctrl-c (&optional arg)
12961 "Set tags in headline, or update according to changed information at point.
12963 This command does many different things, depending on context:
12965 - If the cursor is in a headline, prompt for tags and insert them
12966 into the current line, aligned to `org-tags-column'. When called
12967 with prefix arg, realign all tags in the current buffer.
12969 - If the cursor is in one of the special #+KEYWORD lines, this
12970 triggers scanning the buffer for these lines and updating the
12971 information.
12973 - If the cursor is inside a table, realign the table. This command
12974 works even if the automatic table editor has been turned off.
12976 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12977 the entire table.
12979 - If the cursor is a the beginning of a dynamic block, update it.
12981 - If the cursor is inside a table created by the table.el package,
12982 activate that table.
12984 - If the current buffer is a remember buffer, close note and file it.
12985 with a prefix argument, file it without further interaction to the default
12986 location.
12988 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12989 links in this buffer.
12991 - If the cursor is on a numbered item in a plain list, renumber the
12992 ordered list.
12994 - If the cursor is on a checkbox, toggle it."
12995 (interactive "P")
12996 (let ((org-enable-table-editor t))
12997 (cond
12998 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12999 org-occur-highlights
13000 org-latex-fragment-image-overlays)
13001 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13002 (org-remove-occur-highlights)
13003 (org-remove-latex-fragment-image-overlays)
13004 (message "Temporary highlights/overlays removed from current buffer"))
13005 ((and (local-variable-p 'org-finish-function (current-buffer))
13006 (fboundp org-finish-function))
13007 (funcall org-finish-function))
13008 ((org-at-property-p)
13009 (call-interactively 'org-property-action))
13010 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13011 ((org-on-heading-p) (call-interactively 'org-set-tags))
13012 ((org-at-table.el-p)
13013 (require 'table)
13014 (beginning-of-line 1)
13015 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13016 (call-interactively 'table-recognize-table))
13017 ((org-at-table-p)
13018 (org-table-maybe-eval-formula)
13019 (if arg
13020 (call-interactively 'org-table-recalculate)
13021 (org-table-maybe-recalculate-line))
13022 (call-interactively 'org-table-align))
13023 ((org-at-item-checkbox-p)
13024 (call-interactively 'org-toggle-checkbox))
13025 ((org-at-item-p)
13026 (call-interactively 'org-maybe-renumber-ordered-list))
13027 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13028 ;; Dynamic block
13029 (beginning-of-line 1)
13030 (org-update-dblock))
13031 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13032 (cond
13033 ((equal (match-string 1) "TBLFM")
13034 ;; Recalculate the table before this line
13035 (save-excursion
13036 (beginning-of-line 1)
13037 (skip-chars-backward " \r\n\t")
13038 (if (org-at-table-p)
13039 (org-call-with-arg 'org-table-recalculate t))))
13041 ; (org-set-regexps-and-options)
13042 ; (org-restart-font-lock)
13043 (let ((org-inhibit-startup t)) (org-mode-restart))
13044 (message "Local setup has been refreshed"))))
13045 (t (error "C-c C-c can do nothing useful at this location.")))))
13047 (defun org-mode-restart ()
13048 "Restart Org-mode, to scan again for special lines.
13049 Also updates the keyword regular expressions."
13050 (interactive)
13051 (org-mode)
13052 (message "Org-mode restarted"))
13054 (defun org-kill-note-or-show-branches ()
13055 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13056 (interactive)
13057 (if (not org-finish-function)
13058 (call-interactively 'show-branches)
13059 (let ((org-note-abort t))
13060 (funcall org-finish-function))))
13062 (defun org-return (&optional indent)
13063 "Goto next table row or insert a newline.
13064 Calls `org-table-next-row' or `newline', depending on context.
13065 See the individual commands for more information."
13066 (interactive)
13067 (cond
13068 ((bobp) (if indent (newline-and-indent) (newline)))
13069 ((and (org-at-heading-p)
13070 (looking-at
13071 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13072 (org-show-entry)
13073 (end-of-line 1)
13074 (newline))
13075 ((org-at-table-p)
13076 (org-table-justify-field-maybe)
13077 (call-interactively 'org-table-next-row))
13078 (t (if indent (newline-and-indent) (newline)))))
13080 (defun org-return-indent ()
13081 "Goto next table row or insert a newline and indent.
13082 Calls `org-table-next-row' or `newline-and-indent', depending on
13083 context. See the individual commands for more information."
13084 (interactive)
13085 (org-return t))
13087 (defun org-ctrl-c-star ()
13088 "Compute table, or change heading status of lines.
13089 Calls `org-table-recalculate' or `org-toggle-region-headings',
13090 depending on context. This will also turn a plain list item or a normal
13091 line into a subheading."
13092 (interactive)
13093 (cond
13094 ((org-at-table-p)
13095 (call-interactively 'org-table-recalculate))
13096 ((org-region-active-p)
13097 ;; Convert all lines in region to list items
13098 (call-interactively 'org-toggle-region-headings))
13099 ((org-on-heading-p)
13100 (org-toggle-region-headings (point-at-bol)
13101 (min (1+ (point-at-eol)) (point-max))))
13102 ((org-at-item-p)
13103 ;; Convert to heading
13104 (let ((level (save-match-data
13105 (save-excursion
13106 (condition-case nil
13107 (progn
13108 (org-back-to-heading t)
13109 (funcall outline-level))
13110 (error 0))))))
13111 (replace-match
13112 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13113 (t (org-toggle-region-headings (point-at-bol)
13114 (min (1+ (point-at-eol)) (point-max))))))
13116 (defun org-ctrl-c-minus ()
13117 "Insert separator line in table or modify bullet status of line.
13118 Also turns a plain line or a region of lines into list items.
13119 Calls `org-table-insert-hline', `org-toggle-region-items', or
13120 `org-cycle-list-bullet', depending on context."
13121 (interactive)
13122 (cond
13123 ((org-at-table-p)
13124 (call-interactively 'org-table-insert-hline))
13125 ((org-on-heading-p)
13126 ;; Convert to item
13127 (save-excursion
13128 (beginning-of-line 1)
13129 (if (looking-at "\\*+ ")
13130 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13131 ((org-region-active-p)
13132 ;; Convert all lines in region to list items
13133 (call-interactively 'org-toggle-region-items))
13134 ((org-in-item-p)
13135 (call-interactively 'org-cycle-list-bullet))
13136 (t (org-toggle-region-items (point-at-bol)
13137 (min (1+ (point-at-eol)) (point-max))))))
13139 (defun org-toggle-region-items (beg end)
13140 "Convert all lines in region to list items.
13141 If the first line is already an item, convert all list items in the region
13142 to normal lines."
13143 (interactive "r")
13144 (let (l2 l)
13145 (save-excursion
13146 (goto-char end)
13147 (setq l2 (org-current-line))
13148 (goto-char beg)
13149 (beginning-of-line 1)
13150 (setq l (1- (org-current-line)))
13151 (if (org-at-item-p)
13152 ;; We already have items, de-itemize
13153 (while (< (setq l (1+ l)) l2)
13154 (when (org-at-item-p)
13155 (goto-char (match-beginning 2))
13156 (delete-region (match-beginning 2) (match-end 2))
13157 (and (looking-at "[ \t]+") (replace-match "")))
13158 (beginning-of-line 2))
13159 (while (< (setq l (1+ l)) l2)
13160 (unless (org-at-item-p)
13161 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13162 (replace-match "\\1- \\2")))
13163 (beginning-of-line 2))))))
13165 (defun org-toggle-region-headings (beg end)
13166 "Convert all lines in region to list items.
13167 If the first line is already an item, convert all list items in the region
13168 to normal lines."
13169 (interactive "r")
13170 (let (l2 l)
13171 (save-excursion
13172 (goto-char end)
13173 (setq l2 (org-current-line))
13174 (goto-char beg)
13175 (beginning-of-line 1)
13176 (setq l (1- (org-current-line)))
13177 (if (org-on-heading-p)
13178 ;; We already have headlines, de-star them
13179 (while (< (setq l (1+ l)) l2)
13180 (when (org-on-heading-p t)
13181 (and (looking-at outline-regexp) (replace-match "")))
13182 (beginning-of-line 2))
13183 (let* ((stars (save-excursion
13184 (re-search-backward org-complex-heading-regexp nil t)
13185 (or (match-string 1) "*")))
13186 (add-stars (if org-odd-levels-only "**" "*"))
13187 (rpl (concat stars add-stars " \\2")))
13188 (while (< (setq l (1+ l)) l2)
13189 (unless (org-on-heading-p)
13190 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13191 (replace-match rpl)))
13192 (beginning-of-line 2)))))))
13194 (defun org-meta-return (&optional arg)
13195 "Insert a new heading or wrap a region in a table.
13196 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13197 See the individual commands for more information."
13198 (interactive "P")
13199 (cond
13200 ((org-at-table-p)
13201 (call-interactively 'org-table-wrap-region))
13202 (t (call-interactively 'org-insert-heading))))
13204 ;;; Menu entries
13206 ;; Define the Org-mode menus
13207 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13208 '("Tbl"
13209 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13210 ["Next Field" org-cycle (org-at-table-p)]
13211 ["Previous Field" org-shifttab (org-at-table-p)]
13212 ["Next Row" org-return (org-at-table-p)]
13213 "--"
13214 ["Blank Field" org-table-blank-field (org-at-table-p)]
13215 ["Edit Field" org-table-edit-field (org-at-table-p)]
13216 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13217 "--"
13218 ("Column"
13219 ["Move Column Left" org-metaleft (org-at-table-p)]
13220 ["Move Column Right" org-metaright (org-at-table-p)]
13221 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13222 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13223 ("Row"
13224 ["Move Row Up" org-metaup (org-at-table-p)]
13225 ["Move Row Down" org-metadown (org-at-table-p)]
13226 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13227 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13228 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13229 "--"
13230 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13231 ("Rectangle"
13232 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13233 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13234 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13235 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13236 "--"
13237 ("Calculate"
13238 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13239 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13240 ["Edit Formulas" org-edit-special (org-at-table-p)]
13241 "--"
13242 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13243 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13244 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13245 "--"
13246 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13247 "--"
13248 ["Sum Column/Rectangle" org-table-sum
13249 (or (org-at-table-p) (org-region-active-p))]
13250 ["Which Column?" org-table-current-column (org-at-table-p)])
13251 ["Debug Formulas"
13252 org-table-toggle-formula-debugger
13253 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13254 ["Show Col/Row Numbers"
13255 org-table-toggle-coordinate-overlays
13256 :style toggle
13257 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13258 "--"
13259 ["Create" org-table-create (and (not (org-at-table-p))
13260 org-enable-table-editor)]
13261 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13262 ["Import from File" org-table-import (not (org-at-table-p))]
13263 ["Export to File" org-table-export (org-at-table-p)]
13264 "--"
13265 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13267 (easy-menu-define org-org-menu org-mode-map "Org menu"
13268 '("Org"
13269 ("Show/Hide"
13270 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13271 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13272 ["Sparse Tree..." org-sparse-tree t]
13273 ["Reveal Context" org-reveal t]
13274 ["Show All" show-all t]
13275 "--"
13276 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13277 "--"
13278 ["New Heading" org-insert-heading t]
13279 ("Navigate Headings"
13280 ["Up" outline-up-heading t]
13281 ["Next" outline-next-visible-heading t]
13282 ["Previous" outline-previous-visible-heading t]
13283 ["Next Same Level" outline-forward-same-level t]
13284 ["Previous Same Level" outline-backward-same-level t]
13285 "--"
13286 ["Jump" org-goto t])
13287 ("Edit Structure"
13288 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13289 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13290 "--"
13291 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13292 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13293 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13294 "--"
13295 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13296 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13297 ["Demote Heading" org-metaright (not (org-at-table-p))]
13298 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13299 "--"
13300 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13301 "--"
13302 ["Convert to odd levels" org-convert-to-odd-levels t]
13303 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13304 ("Editing"
13305 ["Emphasis..." org-emphasize t]
13306 ["Edit Source Example" org-edit-special t])
13307 ("Archive"
13308 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13309 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13310 ; :active t :keys "C-u C-c C-x C-a"]
13311 ["Sparse trees open ARCHIVE trees"
13312 (setq org-sparse-tree-open-archived-trees
13313 (not org-sparse-tree-open-archived-trees))
13314 :style toggle :selected org-sparse-tree-open-archived-trees]
13315 ["Cycling opens ARCHIVE trees"
13316 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13317 :style toggle :selected org-cycle-open-archived-trees]
13318 "--"
13319 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13320 ; ["Check and Move Children" (org-archive-subtree '(4))
13321 ; :active t :keys "C-u C-c C-x C-s"]
13323 "--"
13324 ("TODO Lists"
13325 ["TODO/DONE/-" org-todo t]
13326 ("Select keyword"
13327 ["Next keyword" org-shiftright (org-on-heading-p)]
13328 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13329 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13330 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13331 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13332 ["Show TODO Tree" org-show-todo-tree t]
13333 ["Global TODO list" org-todo-list t]
13334 "--"
13335 ["Set Priority" org-priority t]
13336 ["Priority Up" org-shiftup t]
13337 ["Priority Down" org-shiftdown t])
13338 ("TAGS and Properties"
13339 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13340 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13341 "--"
13342 ["Set property" 'org-set-property t]
13343 ["Column view of properties" org-columns t]
13344 ["Insert Column View DBlock" org-insert-columns-dblock t])
13345 ("Dates and Scheduling"
13346 ["Timestamp" org-time-stamp t]
13347 ["Timestamp (inactive)" org-time-stamp-inactive t]
13348 ("Change Date"
13349 ["1 Day Later" org-shiftright t]
13350 ["1 Day Earlier" org-shiftleft t]
13351 ["1 ... Later" org-shiftup t]
13352 ["1 ... Earlier" org-shiftdown t])
13353 ["Compute Time Range" org-evaluate-time-range t]
13354 ["Schedule Item" org-schedule t]
13355 ["Deadline" org-deadline t]
13356 "--"
13357 ["Custom time format" org-toggle-time-stamp-overlays
13358 :style radio :selected org-display-custom-times]
13359 "--"
13360 ["Goto Calendar" org-goto-calendar t]
13361 ["Date from Calendar" org-date-from-calendar t])
13362 ("Logging work"
13363 ["Clock in" org-clock-in t]
13364 ["Clock out" org-clock-out t]
13365 ["Clock cancel" org-clock-cancel t]
13366 ["Goto running clock" org-clock-goto t]
13367 ["Display times" org-clock-display t]
13368 ["Create clock table" org-clock-report t]
13369 "--"
13370 ["Record DONE time"
13371 (progn (setq org-log-done (not org-log-done))
13372 (message "Switching to %s will %s record a timestamp"
13373 (car org-done-keywords)
13374 (if org-log-done "automatically" "not")))
13375 :style toggle :selected org-log-done])
13376 "--"
13377 ["Agenda Command..." org-agenda t]
13378 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13379 ("File List for Agenda")
13380 ("Special views current file"
13381 ["TODO Tree" org-show-todo-tree t]
13382 ["Check Deadlines" org-check-deadlines t]
13383 ["Timeline" org-timeline t]
13384 ["Tags Tree" org-tags-sparse-tree t])
13385 "--"
13386 ("Hyperlinks"
13387 ["Store Link (Global)" org-store-link t]
13388 ["Insert Link" org-insert-link t]
13389 ["Follow Link" org-open-at-point t]
13390 "--"
13391 ["Next link" org-next-link t]
13392 ["Previous link" org-previous-link t]
13393 "--"
13394 ["Descriptive Links"
13395 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13396 :style radio
13397 :selected (member '(org-link) buffer-invisibility-spec)]
13398 ["Literal Links"
13399 (progn
13400 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13401 :style radio
13402 :selected (not (member '(org-link) buffer-invisibility-spec))])
13403 "--"
13404 ["Export/Publish..." org-export t]
13405 ("LaTeX"
13406 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13407 :selected org-cdlatex-mode]
13408 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13409 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13410 ["Modify math symbol" org-cdlatex-math-modify
13411 (org-inside-LaTeX-fragment-p)]
13412 ["Export LaTeX fragments as images"
13413 (if (featurep 'org-exp)
13414 (setq org-export-with-LaTeX-fragments
13415 (not org-export-with-LaTeX-fragments))
13416 (require 'org-exp))
13417 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13418 org-export-with-LaTeX-fragments)])
13419 "--"
13420 ("Documentation"
13421 ["Show Version" org-version t]
13422 ["Info Documentation" org-info t])
13423 ("Customize"
13424 ["Browse Org Group" org-customize t]
13425 "--"
13426 ["Expand This Menu" org-create-customize-menu
13427 (fboundp 'customize-menu-create)])
13428 "--"
13429 ["Refresh setup" org-mode-restart t]
13432 (defun org-info (&optional node)
13433 "Read documentation for Org-mode in the info system.
13434 With optional NODE, go directly to that node."
13435 (interactive)
13436 (info (format "(org)%s" (or node ""))))
13438 (defun org-install-agenda-files-menu ()
13439 (let ((bl (buffer-list)))
13440 (save-excursion
13441 (while bl
13442 (set-buffer (pop bl))
13443 (if (org-mode-p) (setq bl nil)))
13444 (when (org-mode-p)
13445 (easy-menu-change
13446 '("Org") "File List for Agenda"
13447 (append
13448 (list
13449 ["Edit File List" (org-edit-agenda-file-list) t]
13450 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13451 ["Remove Current File from List" org-remove-file t]
13452 ["Cycle through agenda files" org-cycle-agenda-files t]
13453 ["Occur in all agenda files" org-occur-in-agenda-files t]
13454 "--")
13455 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13457 ;;;; Documentation
13459 ;;;###autoload
13460 (defun org-require-autoloaded-modules ()
13461 (interactive)
13462 (mapc 'require
13463 '(org-agenda org-archive org-clock org-colview
13464 org-exp org-id org-export-latex org-publish
13465 org-remember org-table)))
13467 ;;;###autoload
13468 (defun org-customize ()
13469 "Call the customize function with org as argument."
13470 (interactive)
13471 (org-load-modules-maybe)
13472 (org-require-autoloaded-modules)
13473 (customize-browse 'org))
13475 (defun org-create-customize-menu ()
13476 "Create a full customization menu for Org-mode, insert it into the menu."
13477 (interactive)
13478 (org-load-modules-maybe)
13479 (org-require-autoloaded-modules)
13480 (if (fboundp 'customize-menu-create)
13481 (progn
13482 (easy-menu-change
13483 '("Org") "Customize"
13484 `(["Browse Org group" org-customize t]
13485 "--"
13486 ,(customize-menu-create 'org)
13487 ["Set" Custom-set t]
13488 ["Save" Custom-save t]
13489 ["Reset to Current" Custom-reset-current t]
13490 ["Reset to Saved" Custom-reset-saved t]
13491 ["Reset to Standard Settings" Custom-reset-standard t]))
13492 (message "\"Org\"-menu now contains full customization menu"))
13493 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13495 ;;;; Miscellaneous stuff
13497 ;;; Generally useful functions
13499 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13500 "Display the given MESSAGE as a warning."
13501 (if (fboundp 'display-warning)
13502 (display-warning 'org message
13503 (if (featurep 'xemacs)
13504 'warning
13505 :warning))
13506 (let ((buf (get-buffer-create "*Org warnings*")))
13507 (with-current-buffer buf
13508 (goto-char (point-max))
13509 (insert "Warning (Org): " message)
13510 (unless (bolp)
13511 (newline)))
13512 (display-buffer buf)
13513 (sit-for 0))))
13515 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13516 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13517 (if (and marker (marker-buffer marker)
13518 (buffer-live-p (marker-buffer marker)))
13519 (progn
13520 (switch-to-buffer (marker-buffer marker))
13521 (if (or (> marker (point-max)) (< marker (point-min)))
13522 (widen))
13523 (goto-char marker))
13524 (if bookmark
13525 (bookmark-jump bookmark)
13526 (error "Cannot find location"))))
13528 (defun org-quote-csv-field (s)
13529 "Quote field for inclusion in CSV material."
13530 (if (string-match "[\",]" s)
13531 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13534 (defun org-plist-delete (plist property)
13535 "Delete PROPERTY from PLIST.
13536 This is in contrast to merely setting it to 0."
13537 (let (p)
13538 (while plist
13539 (if (not (eq property (car plist)))
13540 (setq p (plist-put p (car plist) (nth 1 plist))))
13541 (setq plist (cddr plist)))
13544 (defun org-force-self-insert (N)
13545 "Needed to enforce self-insert under remapping."
13546 (interactive "p")
13547 (self-insert-command N))
13549 (defun org-string-width (s)
13550 "Compute width of string, ignoring invisible characters.
13551 This ignores character with invisibility property `org-link', and also
13552 characters with property `org-cwidth', because these will become invisible
13553 upon the next fontification round."
13554 (let (b l)
13555 (when (or (eq t buffer-invisibility-spec)
13556 (assq 'org-link buffer-invisibility-spec))
13557 (while (setq b (text-property-any 0 (length s)
13558 'invisible 'org-link s))
13559 (setq s (concat (substring s 0 b)
13560 (substring s (or (next-single-property-change
13561 b 'invisible s) (length s)))))))
13562 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13563 (setq s (concat (substring s 0 b)
13564 (substring s (or (next-single-property-change
13565 b 'org-cwidth s) (length s))))))
13566 (setq l (string-width s) b -1)
13567 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13568 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13571 (defun org-base-buffer (buffer)
13572 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13573 (if (not buffer)
13574 buffer
13575 (or (buffer-base-buffer buffer)
13576 buffer)))
13578 (defun org-trim (s)
13579 "Remove whitespace at beginning and end of string."
13580 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13581 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13584 (defun org-wrap (string &optional width lines)
13585 "Wrap string to either a number of lines, or a width in characters.
13586 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13587 that costs. If there is a word longer than WIDTH, the text is actually
13588 wrapped to the length of that word.
13589 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13590 many lines, whatever width that takes.
13591 The return value is a list of lines, without newlines at the end."
13592 (let* ((words (org-split-string string "[ \t\n]+"))
13593 (maxword (apply 'max (mapcar 'org-string-width words)))
13594 w ll)
13595 (cond (width
13596 (org-do-wrap words (max maxword width)))
13597 (lines
13598 (setq w maxword)
13599 (setq ll (org-do-wrap words maxword))
13600 (if (<= (length ll) lines)
13602 (setq ll words)
13603 (while (> (length ll) lines)
13604 (setq w (1+ w))
13605 (setq ll (org-do-wrap words w)))
13606 ll))
13607 (t (error "Cannot wrap this")))))
13609 (defun org-do-wrap (words width)
13610 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13611 (let (lines line)
13612 (while words
13613 (setq line (pop words))
13614 (while (and words (< (+ (length line) (length (car words))) width))
13615 (setq line (concat line " " (pop words))))
13616 (setq lines (push line lines)))
13617 (nreverse lines)))
13619 (defun org-split-string (string &optional separators)
13620 "Splits STRING into substrings at SEPARATORS.
13621 No empty strings are returned if there are matches at the beginning
13622 and end of string."
13623 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13624 (start 0)
13625 notfirst
13626 (list nil))
13627 (while (and (string-match rexp string
13628 (if (and notfirst
13629 (= start (match-beginning 0))
13630 (< start (length string)))
13631 (1+ start) start))
13632 (< (match-beginning 0) (length string)))
13633 (setq notfirst t)
13634 (or (eq (match-beginning 0) 0)
13635 (and (eq (match-beginning 0) (match-end 0))
13636 (eq (match-beginning 0) start))
13637 (setq list
13638 (cons (substring string start (match-beginning 0))
13639 list)))
13640 (setq start (match-end 0)))
13641 (or (eq start (length string))
13642 (setq list
13643 (cons (substring string start)
13644 list)))
13645 (nreverse list)))
13647 (defun org-context ()
13648 "Return a list of contexts of the current cursor position.
13649 If several contexts apply, all are returned.
13650 Each context entry is a list with a symbol naming the context, and
13651 two positions indicating start and end of the context. Possible
13652 contexts are:
13654 :headline anywhere in a headline
13655 :headline-stars on the leading stars in a headline
13656 :todo-keyword on a TODO keyword (including DONE) in a headline
13657 :tags on the TAGS in a headline
13658 :priority on the priority cookie in a headline
13659 :item on the first line of a plain list item
13660 :item-bullet on the bullet/number of a plain list item
13661 :checkbox on the checkbox in a plain list item
13662 :table in an org-mode table
13663 :table-special on a special filed in a table
13664 :table-table in a table.el table
13665 :link on a hyperlink
13666 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13667 :target on a <<target>>
13668 :radio-target on a <<<radio-target>>>
13669 :latex-fragment on a LaTeX fragment
13670 :latex-preview on a LaTeX fragment with overlayed preview image
13672 This function expects the position to be visible because it uses font-lock
13673 faces as a help to recognize the following contexts: :table-special, :link,
13674 and :keyword."
13675 (let* ((f (get-text-property (point) 'face))
13676 (faces (if (listp f) f (list f)))
13677 (p (point)) clist o)
13678 ;; First the large context
13679 (cond
13680 ((org-on-heading-p t)
13681 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13682 (when (progn
13683 (beginning-of-line 1)
13684 (looking-at org-todo-line-tags-regexp))
13685 (push (org-point-in-group p 1 :headline-stars) clist)
13686 (push (org-point-in-group p 2 :todo-keyword) clist)
13687 (push (org-point-in-group p 4 :tags) clist))
13688 (goto-char p)
13689 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13690 (if (looking-at "\\[#[A-Z0-9]\\]")
13691 (push (org-point-in-group p 0 :priority) clist)))
13693 ((org-at-item-p)
13694 (push (org-point-in-group p 2 :item-bullet) clist)
13695 (push (list :item (point-at-bol)
13696 (save-excursion (org-end-of-item) (point)))
13697 clist)
13698 (and (org-at-item-checkbox-p)
13699 (push (org-point-in-group p 0 :checkbox) clist)))
13701 ((org-at-table-p)
13702 (push (list :table (org-table-begin) (org-table-end)) clist)
13703 (if (memq 'org-formula faces)
13704 (push (list :table-special
13705 (previous-single-property-change p 'face)
13706 (next-single-property-change p 'face)) clist)))
13707 ((org-at-table-p 'any)
13708 (push (list :table-table) clist)))
13709 (goto-char p)
13711 ;; Now the small context
13712 (cond
13713 ((org-at-timestamp-p)
13714 (push (org-point-in-group p 0 :timestamp) clist))
13715 ((memq 'org-link faces)
13716 (push (list :link
13717 (previous-single-property-change p 'face)
13718 (next-single-property-change p 'face)) clist))
13719 ((memq 'org-special-keyword faces)
13720 (push (list :keyword
13721 (previous-single-property-change p 'face)
13722 (next-single-property-change p 'face)) clist))
13723 ((org-on-target-p)
13724 (push (org-point-in-group p 0 :target) clist)
13725 (goto-char (1- (match-beginning 0)))
13726 (if (looking-at org-radio-target-regexp)
13727 (push (org-point-in-group p 0 :radio-target) clist))
13728 (goto-char p))
13729 ((setq o (car (delq nil
13730 (mapcar
13731 (lambda (x)
13732 (if (memq x org-latex-fragment-image-overlays) x))
13733 (org-overlays-at (point))))))
13734 (push (list :latex-fragment
13735 (org-overlay-start o) (org-overlay-end o)) clist)
13736 (push (list :latex-preview
13737 (org-overlay-start o) (org-overlay-end o)) clist))
13738 ((org-inside-LaTeX-fragment-p)
13739 ;; FIXME: positions wrong.
13740 (push (list :latex-fragment (point) (point)) clist)))
13742 (setq clist (nreverse (delq nil clist)))
13743 clist))
13745 ;; FIXME: Compare with at-regexp-p Do we need both?
13746 (defun org-in-regexp (re &optional nlines visually)
13747 "Check if point is inside a match of regexp.
13748 Normally only the current line is checked, but you can include NLINES extra
13749 lines both before and after point into the search.
13750 If VISUALLY is set, require that the cursor is not after the match but
13751 really on, so that the block visually is on the match."
13752 (catch 'exit
13753 (let ((pos (point))
13754 (eol (point-at-eol (+ 1 (or nlines 0))))
13755 (inc (if visually 1 0)))
13756 (save-excursion
13757 (beginning-of-line (- 1 (or nlines 0)))
13758 (while (re-search-forward re eol t)
13759 (if (and (<= (match-beginning 0) pos)
13760 (>= (+ inc (match-end 0)) pos))
13761 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13763 (defun org-at-regexp-p (regexp)
13764 "Is point inside a match of REGEXP in the current line?"
13765 (catch 'exit
13766 (save-excursion
13767 (let ((pos (point)) (end (point-at-eol)))
13768 (beginning-of-line 1)
13769 (while (re-search-forward regexp end t)
13770 (if (and (<= (match-beginning 0) pos)
13771 (>= (match-end 0) pos))
13772 (throw 'exit t)))
13773 nil))))
13775 (defun org-occur-in-agenda-files (regexp &optional nlines)
13776 "Call `multi-occur' with buffers for all agenda files."
13777 (interactive "sOrg-files matching: \np")
13778 (let* ((files (org-agenda-files))
13779 (tnames (mapcar 'file-truename files))
13780 (extra org-agenda-text-search-extra-files)
13782 (when (eq (car extra) 'agenda-archives)
13783 (setq extra (cdr extra))
13784 (setq files (org-add-archive-files files)))
13785 (while (setq f (pop extra))
13786 (unless (member (file-truename f) tnames)
13787 (add-to-list 'files f 'append)
13788 (add-to-list 'tnames (file-truename f) 'append)))
13789 (multi-occur
13790 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13791 regexp)))
13793 (if (boundp 'occur-mode-find-occurrence-hook)
13794 ;; Emacs 23
13795 (add-hook 'occur-mode-find-occurrence-hook
13796 (lambda ()
13797 (when (org-mode-p)
13798 (org-reveal))))
13799 ;; Emacs 22
13800 (defadvice occur-mode-goto-occurrence
13801 (after org-occur-reveal activate)
13802 (and (org-mode-p) (org-reveal)))
13803 (defadvice occur-mode-goto-occurrence-other-window
13804 (after org-occur-reveal activate)
13805 (and (org-mode-p) (org-reveal)))
13806 (defadvice occur-mode-display-occurrence
13807 (after org-occur-reveal activate)
13808 (when (org-mode-p)
13809 (let ((pos (occur-mode-find-occurrence)))
13810 (with-current-buffer (marker-buffer pos)
13811 (save-excursion
13812 (goto-char pos)
13813 (org-reveal)))))))
13815 (defun org-uniquify (list)
13816 "Remove duplicate elements from LIST."
13817 (let (res)
13818 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13819 res))
13821 (defun org-delete-all (elts list)
13822 "Remove all elements in ELTS from LIST."
13823 (while elts
13824 (setq list (delete (pop elts) list)))
13825 list)
13827 (defun org-back-over-empty-lines ()
13828 "Move backwards over witespace, to the beginning of the first empty line.
13829 Returns the number of empty lines passed."
13830 (let ((pos (point)))
13831 (skip-chars-backward " \t\n\r")
13832 (beginning-of-line 2)
13833 (goto-char (min (point) pos))
13834 (count-lines (point) pos)))
13836 (defun org-skip-whitespace ()
13837 (skip-chars-forward " \t\n\r"))
13839 (defun org-point-in-group (point group &optional context)
13840 "Check if POINT is in match-group GROUP.
13841 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13842 match. If the match group does ot exist or point is not inside it,
13843 return nil."
13844 (and (match-beginning group)
13845 (>= point (match-beginning group))
13846 (<= point (match-end group))
13847 (if context
13848 (list context (match-beginning group) (match-end group))
13849 t)))
13851 (defun org-switch-to-buffer-other-window (&rest args)
13852 "Switch to buffer in a second window on the current frame.
13853 In particular, do not allow pop-up frames."
13854 (let (pop-up-frames special-display-buffer-names special-display-regexps
13855 special-display-function)
13856 (apply 'switch-to-buffer-other-window args)))
13858 (defun org-combine-plists (&rest plists)
13859 "Create a single property list from all plists in PLISTS.
13860 The process starts by copying the first list, and then setting properties
13861 from the other lists. Settings in the last list are the most significant
13862 ones and overrule settings in the other lists."
13863 (let ((rtn (copy-sequence (pop plists)))
13864 p v ls)
13865 (while plists
13866 (setq ls (pop plists))
13867 (while ls
13868 (setq p (pop ls) v (pop ls))
13869 (setq rtn (plist-put rtn p v))))
13870 rtn))
13872 (defun org-move-line-down (arg)
13873 "Move the current line down. With prefix argument, move it past ARG lines."
13874 (interactive "p")
13875 (let ((col (current-column))
13876 beg end pos)
13877 (beginning-of-line 1) (setq beg (point))
13878 (beginning-of-line 2) (setq end (point))
13879 (beginning-of-line (+ 1 arg))
13880 (setq pos (move-marker (make-marker) (point)))
13881 (insert (delete-and-extract-region beg end))
13882 (goto-char pos)
13883 (org-move-to-column col)))
13885 (defun org-move-line-up (arg)
13886 "Move the current line up. With prefix argument, move it past ARG lines."
13887 (interactive "p")
13888 (let ((col (current-column))
13889 beg end pos)
13890 (beginning-of-line 1) (setq beg (point))
13891 (beginning-of-line 2) (setq end (point))
13892 (beginning-of-line (- arg))
13893 (setq pos (move-marker (make-marker) (point)))
13894 (insert (delete-and-extract-region beg end))
13895 (goto-char pos)
13896 (org-move-to-column col)))
13898 (defun org-replace-escapes (string table)
13899 "Replace %-escapes in STRING with values in TABLE.
13900 TABLE is an association list with keys like \"%a\" and string values.
13901 The sequences in STRING may contain normal field width and padding information,
13902 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13903 so values can contain further %-escapes if they are define later in TABLE."
13904 (let ((case-fold-search nil)
13905 e re rpl)
13906 (while (setq e (pop table))
13907 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13908 (while (string-match re string)
13909 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13910 (cdr e)))
13911 (setq string (replace-match rpl t t string))))
13912 string))
13915 (defun org-sublist (list start end)
13916 "Return a section of LIST, from START to END.
13917 Counting starts at 1."
13918 (let (rtn (c start))
13919 (setq list (nthcdr (1- start) list))
13920 (while (and list (<= c end))
13921 (push (pop list) rtn)
13922 (setq c (1+ c)))
13923 (nreverse rtn)))
13925 (defun org-find-base-buffer-visiting (file)
13926 "Like `find-buffer-visiting' but alway return the base buffer and
13927 not an indirect buffer."
13928 (let ((buf (find-buffer-visiting file)))
13929 (if buf
13930 (or (buffer-base-buffer buf) buf)
13931 nil)))
13933 (defun org-image-file-name-regexp ()
13934 "Return regexp matching the file names of images."
13935 (if (fboundp 'image-file-name-regexp)
13936 (image-file-name-regexp)
13937 (let ((image-file-name-extensions
13938 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13939 "xbm" "xpm" "pbm" "pgm" "ppm")))
13940 (concat "\\."
13941 (regexp-opt (nconc (mapcar 'upcase
13942 image-file-name-extensions)
13943 image-file-name-extensions)
13945 "\\'"))))
13947 (defun org-file-image-p (file)
13948 "Return non-nil if FILE is an image."
13949 (save-match-data
13950 (string-match (org-image-file-name-regexp) file)))
13952 (defun org-get-cursor-date ()
13953 "Return the date at cursor in as a time.
13954 This works in the calendar and in the agenda, anywhere else it just
13955 returns the current time."
13956 (let (date day defd)
13957 (cond
13958 ((eq major-mode 'calendar-mode)
13959 (setq date (calendar-cursor-to-date)
13960 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13961 ((eq major-mode 'org-agenda-mode)
13962 (setq day (get-text-property (point) 'day))
13963 (if day
13964 (setq date (calendar-gregorian-from-absolute day)
13965 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13966 (nth 2 date))))))
13967 (or defd (current-time))))
13969 (defvar org-agenda-action-marker (make-marker)
13970 "Marker pointing to the entry for the next agenda action.")
13972 (defun org-mark-entry-for-agenda-action ()
13973 "Mark the current entry as target of an agenda action.
13974 Agenda actions are actions executed from the agenda with the key `k',
13975 which make use of the date at the cursor."
13976 (interactive)
13977 (move-marker org-agenda-action-marker
13978 (save-excursion (org-back-to-heading t) (point))
13979 (current-buffer))
13980 (message
13981 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13983 ;;; Paragraph filling stuff.
13984 ;; We want this to be just right, so use the full arsenal.
13986 (defun org-indent-line-function ()
13987 "Indent line like previous, but further if previous was headline or item."
13988 (interactive)
13989 (let* ((pos (point))
13990 (itemp (org-at-item-p))
13991 column bpos bcol tpos tcol bullet btype bullet-type)
13992 ;; Find the previous relevant line
13993 (beginning-of-line 1)
13994 (cond
13995 ((looking-at "#") (setq column 0))
13996 ((looking-at "\\*+ ") (setq column 0))
13998 (beginning-of-line 0)
13999 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14000 (beginning-of-line 0))
14001 (cond
14002 ((looking-at "\\*+[ \t]+")
14003 (if (not org-adapt-indentation)
14004 (setq column 0)
14005 (goto-char (match-end 0))
14006 (setq column (current-column))))
14007 ((org-in-item-p)
14008 (org-beginning-of-item)
14009 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14010 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14011 (setq bpos (match-beginning 1) tpos (match-end 0)
14012 bcol (progn (goto-char bpos) (current-column))
14013 tcol (progn (goto-char tpos) (current-column))
14014 bullet (match-string 1)
14015 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14016 (if (> tcol (+ bcol org-description-max-indent))
14017 (setq tcol (+ bcol 5)))
14018 (if (not itemp)
14019 (setq column tcol)
14020 (goto-char pos)
14021 (beginning-of-line 1)
14022 (if (looking-at "\\S-")
14023 (progn
14024 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14025 (setq bullet (match-string 1)
14026 btype (if (string-match "[0-9]" bullet) "n" bullet))
14027 (setq column (if (equal btype bullet-type) bcol tcol)))
14028 (setq column (org-get-indentation)))))
14029 (t (setq column (org-get-indentation))))))
14030 (goto-char pos)
14031 (if (<= (current-column) (current-indentation))
14032 (org-indent-line-to column)
14033 (save-excursion (org-indent-line-to column)))
14034 (setq column (current-column))
14035 (beginning-of-line 1)
14036 (if (looking-at
14037 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14038 (replace-match (concat "\\1" (format org-property-format
14039 (match-string 2) (match-string 3)))
14040 t nil))
14041 (org-move-to-column column)))
14043 (defun org-set-autofill-regexps ()
14044 (interactive)
14045 ;; In the paragraph separator we include headlines, because filling
14046 ;; text in a line directly attached to a headline would otherwise
14047 ;; fill the headline as well.
14048 (org-set-local 'comment-start-skip "^#+[ \t]*")
14049 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14050 ;; The paragraph starter includes hand-formatted lists.
14051 (org-set-local 'paragraph-start
14052 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14053 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14054 ;; But only if the user has not turned off tables or fixed-width regions
14055 (org-set-local
14056 'auto-fill-inhibit-regexp
14057 (concat "\\*+ \\|#\\+"
14058 "\\|[ \t]*" org-keyword-time-regexp
14059 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14060 (concat
14061 "\\|[ \t]*["
14062 (if org-enable-table-editor "|" "")
14063 (if org-enable-fixed-width-editor ":" "")
14064 "]"))))
14065 ;; We use our own fill-paragraph function, to make sure that tables
14066 ;; and fixed-width regions are not wrapped. That function will pass
14067 ;; through to `fill-paragraph' when appropriate.
14068 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14069 ; Adaptive filling: To get full control, first make sure that
14070 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14071 (org-set-local 'adaptive-fill-regexp "\000")
14072 (org-set-local 'adaptive-fill-function
14073 'org-adaptive-fill-function)
14074 (org-set-local
14075 'align-mode-rules-list
14076 '((org-in-buffer-settings
14077 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14078 (modes . '(org-mode))))))
14080 (defun org-fill-paragraph (&optional justify)
14081 "Re-align a table, pass through to fill-paragraph if no table."
14082 (let ((table-p (org-at-table-p))
14083 (table.el-p (org-at-table.el-p)))
14084 (cond ((and (equal (char-after (point-at-bol)) ?*)
14085 (save-excursion (goto-char (point-at-bol))
14086 (looking-at outline-regexp)))
14087 t) ; skip headlines
14088 (table.el-p t) ; skip table.el tables
14089 (table-p (org-table-align) t) ; align org-mode tables
14090 (t nil)))) ; call paragraph-fill
14092 ;; For reference, this is the default value of adaptive-fill-regexp
14093 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14095 (defun org-adaptive-fill-function ()
14096 "Return a fill prefix for org-mode files.
14097 In particular, this makes sure hanging paragraphs for hand-formatted lists
14098 work correctly."
14099 (cond ((looking-at "#[ \t]+")
14100 (match-string 0))
14101 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14102 (save-excursion
14103 (if (> (match-end 1) (+ (match-beginning 1)
14104 org-description-max-indent))
14105 (goto-char (+ (match-beginning 1) 5))
14106 (goto-char (match-end 0)))
14107 (make-string (current-column) ?\ )))
14108 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14109 (save-excursion
14110 (goto-char (match-end 0))
14111 (make-string (current-column) ?\ )))
14112 (t nil)))
14114 ;;; Other stuff.
14116 (defun org-toggle-fixed-width-section (arg)
14117 "Toggle the fixed-width export.
14118 If there is no active region, the QUOTE keyword at the current headline is
14119 inserted or removed. When present, it causes the text between this headline
14120 and the next to be exported as fixed-width text, and unmodified.
14121 If there is an active region, this command adds or removes a colon as the
14122 first character of this line. If the first character of a line is a colon,
14123 this line is also exported in fixed-width font."
14124 (interactive "P")
14125 (let* ((cc 0)
14126 (regionp (org-region-active-p))
14127 (beg (if regionp (region-beginning) (point)))
14128 (end (if regionp (region-end)))
14129 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14130 (case-fold-search nil)
14131 (re "[ \t]*\\(:\\)")
14132 off)
14133 (if regionp
14134 (save-excursion
14135 (goto-char beg)
14136 (setq cc (current-column))
14137 (beginning-of-line 1)
14138 (setq off (looking-at re))
14139 (while (> nlines 0)
14140 (setq nlines (1- nlines))
14141 (beginning-of-line 1)
14142 (cond
14143 (arg
14144 (org-move-to-column cc t)
14145 (insert ":\n")
14146 (forward-line -1))
14147 ((and off (looking-at re))
14148 (replace-match "" t t nil 1))
14149 ((not off) (org-move-to-column cc t) (insert ":")))
14150 (forward-line 1)))
14151 (save-excursion
14152 (org-back-to-heading)
14153 (if (looking-at (concat outline-regexp
14154 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14155 (replace-match "" t t nil 1)
14156 (if (looking-at outline-regexp)
14157 (progn
14158 (goto-char (match-end 0))
14159 (insert org-quote-string " "))))))))
14161 ;;;; Functions extending outline functionality
14163 (defun org-beginning-of-line (&optional arg)
14164 "Go to the beginning of the current line. If that is invisible, continue
14165 to a visible line beginning. This makes the function of C-a more intuitive.
14166 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14167 first attempt, and only move to after the tags when the cursor is already
14168 beyond the end of the headline."
14169 (interactive "P")
14170 (let ((pos (point)) refpos)
14171 (beginning-of-line 1)
14172 (if (bobp)
14174 (backward-char 1)
14175 (if (org-invisible-p)
14176 (while (and (not (bobp)) (org-invisible-p))
14177 (backward-char 1)
14178 (beginning-of-line 1))
14179 (forward-char 1)))
14180 (when org-special-ctrl-a/e
14181 (cond
14182 ((and (looking-at org-complex-heading-regexp)
14183 (= (char-after (match-end 1)) ?\ ))
14184 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14185 (point-at-eol)))
14186 (goto-char
14187 (if (eq org-special-ctrl-a/e t)
14188 (cond ((> pos refpos) refpos)
14189 ((= pos (point)) refpos)
14190 (t (point)))
14191 (cond ((> pos (point)) (point))
14192 ((not (eq last-command this-command)) (point))
14193 (t refpos)))))
14194 ((org-at-item-p)
14195 (goto-char
14196 (if (eq org-special-ctrl-a/e t)
14197 (cond ((> pos (match-end 4)) (match-end 4))
14198 ((= pos (point)) (match-end 4))
14199 (t (point)))
14200 (cond ((> pos (point)) (point))
14201 ((not (eq last-command this-command)) (point))
14202 (t (match-end 4))))))))
14203 (org-no-warnings
14204 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14206 (defun org-end-of-line (&optional arg)
14207 "Go to the end of the line.
14208 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14209 first attempt, and only move to after the tags when the cursor is already
14210 beyond the end of the headline."
14211 (interactive "P")
14212 (if (or (not org-special-ctrl-a/e)
14213 (not (org-on-heading-p)))
14214 (end-of-line arg)
14215 (let ((pos (point)))
14216 (beginning-of-line 1)
14217 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14218 (if (eq org-special-ctrl-a/e t)
14219 (if (or (< pos (match-beginning 1))
14220 (= pos (match-end 0)))
14221 (goto-char (match-beginning 1))
14222 (goto-char (match-end 0)))
14223 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14224 (goto-char (match-end 0))
14225 (goto-char (match-beginning 1))))
14226 (end-of-line arg))))
14227 (org-no-warnings
14228 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14231 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14232 (define-key org-mode-map "\C-e" 'org-end-of-line)
14234 (defun org-kill-line (&optional arg)
14235 "Kill line, to tags or end of line."
14236 (interactive "P")
14237 (cond
14238 ((or (not org-special-ctrl-k)
14239 (bolp)
14240 (not (org-on-heading-p)))
14241 (call-interactively 'kill-line))
14242 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14243 (kill-region (point) (match-beginning 1))
14244 (org-set-tags nil t))
14245 (t (kill-region (point) (point-at-eol)))))
14247 (define-key org-mode-map "\C-k" 'org-kill-line)
14249 (defun org-invisible-p ()
14250 "Check if point is at a character currently not visible."
14251 ;; Early versions of noutline don't have `outline-invisible-p'.
14252 (if (fboundp 'outline-invisible-p)
14253 (outline-invisible-p)
14254 (get-char-property (point) 'invisible)))
14256 (defun org-invisible-p2 ()
14257 "Check if point is at a character currently not visible."
14258 (save-excursion
14259 (if (and (eolp) (not (bobp))) (backward-char 1))
14260 ;; Early versions of noutline don't have `outline-invisible-p'.
14261 (if (fboundp 'outline-invisible-p)
14262 (outline-invisible-p)
14263 (get-char-property (point) 'invisible))))
14265 (defalias 'org-back-to-heading 'outline-back-to-heading)
14266 (defalias 'org-on-heading-p 'outline-on-heading-p)
14267 (defalias 'org-at-heading-p 'outline-on-heading-p)
14268 (defun org-at-heading-or-item-p ()
14269 (or (org-on-heading-p) (org-at-item-p)))
14271 (defun org-on-target-p ()
14272 (or (org-in-regexp org-radio-target-regexp)
14273 (org-in-regexp org-target-regexp)))
14275 (defun org-up-heading-all (arg)
14276 "Move to the heading line of which the present line is a subheading.
14277 This function considers both visible and invisible heading lines.
14278 With argument, move up ARG levels."
14279 (if (fboundp 'outline-up-heading-all)
14280 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14281 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14283 (defun org-up-heading-safe ()
14284 "Move to the heading line of which the present line is a subheading.
14285 This version will not throw an error. It will return the level of the
14286 headline found, or nil if no higher level is found."
14287 (let ((pos (point)) start-level level
14288 (re (concat "^" outline-regexp)))
14289 (catch 'exit
14290 (outline-back-to-heading t)
14291 (setq start-level (funcall outline-level))
14292 (if (equal start-level 1) (throw 'exit nil))
14293 (while (re-search-backward re nil t)
14294 (setq level (funcall outline-level))
14295 (if (< level start-level) (throw 'exit level)))
14296 nil)))
14298 (defun org-first-sibling-p ()
14299 "Is this heading the first child of its parents?"
14300 (interactive)
14301 (let ((re (concat "^" outline-regexp))
14302 level l)
14303 (unless (org-at-heading-p t)
14304 (error "Not at a heading"))
14305 (setq level (funcall outline-level))
14306 (save-excursion
14307 (if (not (re-search-backward re nil t))
14309 (setq l (funcall outline-level))
14310 (< l level)))))
14312 (defun org-goto-sibling (&optional previous)
14313 "Goto the next sibling, even if it is invisible.
14314 When PREVIOUS is set, go to the previous sibling instead. Returns t
14315 when a sibling was found. When none is found, return nil and don't
14316 move point."
14317 (let ((fun (if previous 're-search-backward 're-search-forward))
14318 (pos (point))
14319 (re (concat "^" outline-regexp))
14320 level l)
14321 (when (condition-case nil (org-back-to-heading t) (error nil))
14322 (setq level (funcall outline-level))
14323 (catch 'exit
14324 (or previous (forward-char 1))
14325 (while (funcall fun re nil t)
14326 (setq l (funcall outline-level))
14327 (when (< l level) (goto-char pos) (throw 'exit nil))
14328 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14329 (goto-char pos)
14330 nil))))
14332 (defun org-show-siblings ()
14333 "Show all siblings of the current headline."
14334 (save-excursion
14335 (while (org-goto-sibling) (org-flag-heading nil)))
14336 (save-excursion
14337 (while (org-goto-sibling 'previous)
14338 (org-flag-heading nil))))
14340 (defun org-show-hidden-entry ()
14341 "Show an entry where even the heading is hidden."
14342 (save-excursion
14343 (org-show-entry)))
14345 (defun org-flag-heading (flag &optional entry)
14346 "Flag the current heading. FLAG non-nil means make invisible.
14347 When ENTRY is non-nil, show the entire entry."
14348 (save-excursion
14349 (org-back-to-heading t)
14350 ;; Check if we should show the entire entry
14351 (if entry
14352 (progn
14353 (org-show-entry)
14354 (save-excursion
14355 (and (outline-next-heading)
14356 (org-flag-heading nil))))
14357 (outline-flag-region (max (point-min) (1- (point)))
14358 (save-excursion (outline-end-of-heading) (point))
14359 flag))))
14361 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14362 ;; This is an exact copy of the original function, but it uses
14363 ;; `org-back-to-heading', to make it work also in invisible
14364 ;; trees. And is uses an invisible-OK argument.
14365 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14366 (org-back-to-heading invisible-OK)
14367 (let ((first t)
14368 (level (funcall outline-level)))
14369 (while (and (not (eobp))
14370 (or first (> (funcall outline-level) level)))
14371 (setq first nil)
14372 (outline-next-heading))
14373 (unless to-heading
14374 (if (memq (preceding-char) '(?\n ?\^M))
14375 (progn
14376 ;; Go to end of line before heading
14377 (forward-char -1)
14378 (if (memq (preceding-char) '(?\n ?\^M))
14379 ;; leave blank line before heading
14380 (forward-char -1))))))
14381 (point))
14383 (defun org-show-subtree ()
14384 "Show everything after this heading at deeper levels."
14385 (outline-flag-region
14386 (point)
14387 (save-excursion
14388 (outline-end-of-subtree) (outline-next-heading) (point))
14389 nil))
14391 (defun org-show-entry ()
14392 "Show the body directly following this heading.
14393 Show the heading too, if it is currently invisible."
14394 (interactive)
14395 (save-excursion
14396 (condition-case nil
14397 (progn
14398 (org-back-to-heading t)
14399 (outline-flag-region
14400 (max (point-min) (1- (point)))
14401 (save-excursion
14402 (re-search-forward
14403 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14404 (or (match-beginning 1) (point-max)))
14405 nil))
14406 (error nil))))
14408 (defun org-make-options-regexp (kwds)
14409 "Make a regular expression for keyword lines."
14410 (concat
14412 "#?[ \t]*\\+\\("
14413 (mapconcat 'regexp-quote kwds "\\|")
14414 "\\):[ \t]*"
14415 "\\(.+\\)"))
14417 ;; Make isearch reveal the necessary context
14418 (defun org-isearch-end ()
14419 "Reveal context after isearch exits."
14420 (when isearch-success ; only if search was successful
14421 (if (featurep 'xemacs)
14422 ;; Under XEmacs, the hook is run in the correct place,
14423 ;; we directly show the context.
14424 (org-show-context 'isearch)
14425 ;; In Emacs the hook runs *before* restoring the overlays.
14426 ;; So we have to use a one-time post-command-hook to do this.
14427 ;; (Emacs 22 has a special variable, see function `org-mode')
14428 (unless (and (boundp 'isearch-mode-end-hook-quit)
14429 isearch-mode-end-hook-quit)
14430 ;; Only when the isearch was not quitted.
14431 (org-add-hook 'post-command-hook 'org-isearch-post-command
14432 'append 'local)))))
14434 (defun org-isearch-post-command ()
14435 "Remove self from hook, and show context."
14436 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14437 (org-show-context 'isearch))
14440 ;;;; Integration with and fixes for other packages
14442 ;;; Imenu support
14444 (defvar org-imenu-markers nil
14445 "All markers currently used by Imenu.")
14446 (make-variable-buffer-local 'org-imenu-markers)
14448 (defun org-imenu-new-marker (&optional pos)
14449 "Return a new marker for use by Imenu, and remember the marker."
14450 (let ((m (make-marker)))
14451 (move-marker m (or pos (point)))
14452 (push m org-imenu-markers)
14455 (defun org-imenu-get-tree ()
14456 "Produce the index for Imenu."
14457 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14458 (setq org-imenu-markers nil)
14459 (let* ((n org-imenu-depth)
14460 (re (concat "^" outline-regexp))
14461 (subs (make-vector (1+ n) nil))
14462 (last-level 0)
14463 m tree level head)
14464 (save-excursion
14465 (save-restriction
14466 (widen)
14467 (goto-char (point-max))
14468 (while (re-search-backward re nil t)
14469 (setq level (org-reduced-level (funcall outline-level)))
14470 (when (<= level n)
14471 (looking-at org-complex-heading-regexp)
14472 (setq head (org-match-string-no-properties 4)
14473 m (org-imenu-new-marker))
14474 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14475 (if (>= level last-level)
14476 (push (cons head m) (aref subs level))
14477 (push (cons head (aref subs (1+ level))) (aref subs level))
14478 (loop for i from (1+ level) to n do (aset subs i nil)))
14479 (setq last-level level)))))
14480 (aref subs 1)))
14482 (eval-after-load "imenu"
14483 '(progn
14484 (add-hook 'imenu-after-jump-hook
14485 (lambda ()
14486 (if (eq major-mode 'org-mode)
14487 (org-show-context 'org-goto))))))
14489 ;; Speedbar support
14491 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14492 "Overlay marking the agenda restriction line in speedbar.")
14493 (org-overlay-put org-speedbar-restriction-lock-overlay
14494 'face 'org-agenda-restriction-lock)
14495 (org-overlay-put org-speedbar-restriction-lock-overlay
14496 'help-echo "Agendas are currently limited to this item.")
14497 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14499 (defun org-speedbar-set-agenda-restriction ()
14500 "Restrict future agenda commands to the location at point in speedbar.
14501 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14502 (interactive)
14503 (require 'org-agenda)
14504 (let (p m tp np dir txt w)
14505 (cond
14506 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14507 'org-imenu t))
14508 (setq m (get-text-property p 'org-imenu-marker))
14509 (save-excursion
14510 (save-restriction
14511 (set-buffer (marker-buffer m))
14512 (goto-char m)
14513 (org-agenda-set-restriction-lock 'subtree))))
14514 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14515 'speedbar-function 'speedbar-find-file))
14516 (setq tp (previous-single-property-change
14517 (1+ p) 'speedbar-function)
14518 np (next-single-property-change
14519 tp 'speedbar-function)
14520 dir (speedbar-line-directory)
14521 txt (buffer-substring-no-properties (or tp (point-min))
14522 (or np (point-max))))
14523 (save-excursion
14524 (save-restriction
14525 (set-buffer (find-file-noselect
14526 (let ((default-directory dir))
14527 (expand-file-name txt))))
14528 (unless (org-mode-p)
14529 (error "Cannot restrict to non-Org-mode file"))
14530 (org-agenda-set-restriction-lock 'file))))
14531 (t (error "Don't know how to restrict Org-mode's agenda")))
14532 (org-move-overlay org-speedbar-restriction-lock-overlay
14533 (point-at-bol) (point-at-eol))
14534 (setq current-prefix-arg nil)
14535 (org-agenda-maybe-redo)))
14537 (eval-after-load "speedbar"
14538 '(progn
14539 (speedbar-add-supported-extension ".org")
14540 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14541 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14542 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14543 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14544 (add-hook 'speedbar-visiting-tag-hook
14545 (lambda () (org-show-context 'org-goto)))))
14548 ;;; Fixes and Hacks for problems with other packages
14550 ;; Make flyspell not check words in links, to not mess up our keymap
14551 (defun org-mode-flyspell-verify ()
14552 "Don't let flyspell put overlays at active buttons."
14553 (not (get-text-property (point) 'keymap)))
14555 ;; Make `bookmark-jump' show the jump location if it was hidden.
14556 (eval-after-load "bookmark"
14557 '(if (boundp 'bookmark-after-jump-hook)
14558 ;; We can use the hook
14559 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14560 ;; Hook not available, use advice
14561 (defadvice bookmark-jump (after org-make-visible activate)
14562 "Make the position visible."
14563 (org-bookmark-jump-unhide))))
14565 (defun org-bookmark-jump-unhide ()
14566 "Unhide the current position, to show the bookmark location."
14567 (and (org-mode-p)
14568 (or (org-invisible-p)
14569 (save-excursion (goto-char (max (point-min) (1- (point))))
14570 (org-invisible-p)))
14571 (org-show-context 'bookmark-jump)))
14573 ;; Make session.el ignore our circular variable
14574 (eval-after-load "session"
14575 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14577 ;;;; Experimental code
14579 (defun org-closed-in-range ()
14580 "Sparse tree of items closed in a certain time range.
14581 Still experimental, may disappear in the future."
14582 (interactive)
14583 ;; Get the time interval from the user.
14584 (let* ((time1 (time-to-seconds
14585 (org-read-date nil 'to-time nil "Starting date: ")))
14586 (time2 (time-to-seconds
14587 (org-read-date nil 'to-time nil "End date:")))
14588 ;; callback function
14589 (callback (lambda ()
14590 (let ((time
14591 (time-to-seconds
14592 (apply 'encode-time
14593 (org-parse-time-string
14594 (match-string 1))))))
14595 ;; check if time in interval
14596 (and (>= time time1) (<= time time2))))))
14597 ;; make tree, check each match with the callback
14598 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14601 ;;;; Finish up
14603 (provide 'org)
14605 (run-hooks 'org-load-hook)
14607 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14609 ;;; org.el ends here