Implement include files for export.
[org-mode/org-tableheadings.git] / lisp / org.el
blobbc8ac0c8ed42dd12942b27e3215f6821dbeb203b
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.02b
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.02b"
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 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
142 "Modules that should always be loaded together with org.el.
143 If a description starts with <C>, the file is not part of emacs
144 and loading it will require that you have downloaded and properly installed
145 the org-mode distribution.
147 You can also use this system to load external packages (i.e. neither Org
148 core modules, not modules from the CONTRIB directory). Just add symbols
149 to the end of the list. If the package is called org-xyz.e, then you need
150 to add the symbol `xyz', and the package must have a call to
152 (provide 'org-xyz)"
153 :group 'org
154 :set 'org-set-modules
155 :type
156 '(set :greedy t
157 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
158 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
159 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
160 (const :tag " info: Links to Info nodes" org-info)
161 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
162 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
163 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
164 (const :tag " mew Links to Mew folders/messages" org-mew)
165 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
166 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
167 (const :tag " vm: Links to VM folders/messages" org-vm)
168 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
169 (const :tag " mouse: Additional mouse support" org-mouse)
171 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
172 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
173 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
174 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
175 (const :tag "C eval: Include command output as text" org-eval)
176 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
177 (const :tag "C id: Global id's for identifying entries" org-id)
178 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
179 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
180 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
181 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
182 (const :tag "C registry: A registry for Org links" org-registry)
183 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
184 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
185 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
186 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
187 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
190 (defgroup org-startup nil
191 "Options concerning startup of Org-mode."
192 :tag "Org Startup"
193 :group 'org)
195 (defcustom org-startup-folded t
196 "Non-nil means, entering Org-mode will switch to OVERVIEW.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
200 #+STARTUP: fold
201 #+STARTUP: nofold
202 #+STARTUP: content"
203 :group 'org-startup
204 :type '(choice
205 (const :tag "nofold: show all" nil)
206 (const :tag "fold: overview" t)
207 (const :tag "content: all headlines" content)))
209 (defcustom org-startup-truncated t
210 "Non-nil means, entering Org-mode will set `truncate-lines'.
211 This is useful since some lines containing links can be very long and
212 uninteresting. Also tables look terrible when wrapped."
213 :group 'org-startup
214 :type 'boolean)
216 (defcustom org-startup-align-all-tables nil
217 "Non-nil means, align all tables when visiting a file.
218 This is useful when the column width in tables is forced with <N> cookies
219 in table fields. Such tables will look correct only after the first re-align.
220 This can also be configured on a per-file basis by adding one of
221 the following lines anywhere in the buffer:
222 #+STARTUP: align
223 #+STARTUP: noalign"
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-insert-mode-line-in-empty-file nil
228 "Non-nil means insert the first line setting Org-mode in empty files.
229 When the function `org-mode' is called interactively in an empty file, this
230 normally means that the file name does not automatically trigger Org-mode.
231 To ensure that the file will always be in Org-mode in the future, a
232 line enforcing Org-mode will be inserted into the buffer, if this option
233 has been set."
234 :group 'org-startup
235 :type 'boolean)
237 (defcustom org-replace-disputed-keys nil
238 "Non-nil means use alternative key bindings for some keys.
239 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
240 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
241 If you want to use Org-mode together with one of these other modes,
242 or more generally if you would like to move some Org-mode commands to
243 other keys, set this variable and configure the keys with the variable
244 `org-disputed-keys'.
246 This option is only relevant at load-time of Org-mode, and must be set
247 *before* org.el is loaded. Changing it requires a restart of Emacs to
248 become effective."
249 :group 'org-startup
250 :type 'boolean)
252 (if (fboundp 'defvaralias)
253 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
255 (defcustom org-disputed-keys
256 '(([(shift up)] . [(meta p)])
257 ([(shift down)] . [(meta n)])
258 ([(shift left)] . [(meta -)])
259 ([(shift right)] . [(meta +)])
260 ([(control shift right)] . [(meta shift +)])
261 ([(control shift left)] . [(meta shift -)]))
262 "Keys for which Org-mode and other modes compete.
263 This is an alist, cars are the default keys, second element specifies
264 the alternative to use when `org-replace-disputed-keys' is t.
266 Keys can be specified in any syntax supported by `define-key'.
267 The value of this option takes effect only at Org-mode's startup,
268 therefore you'll have to restart Emacs to apply it after changing."
269 :group 'org-startup
270 :type 'alist)
272 (defun org-key (key)
273 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
274 Or return the original if not disputed."
275 (if org-replace-disputed-keys
276 (let* ((nkey (key-description key))
277 (x (org-find-if (lambda (x)
278 (equal (key-description (car x)) nkey))
279 org-disputed-keys)))
280 (if x (cdr x) key))
281 key))
283 (defun org-find-if (predicate seq)
284 (catch 'exit
285 (while seq
286 (if (funcall predicate (car seq))
287 (throw 'exit (car seq))
288 (pop seq)))))
290 (defun org-defkey (keymap key def)
291 "Define a key, possibly translated, as returned by `org-key'."
292 (define-key keymap (org-key key) def))
294 (defcustom org-ellipsis nil
295 "The ellipsis to use in the Org-mode outline.
296 When nil, just use the standard three dots. When a string, use that instead,
297 When a face, use the standart 3 dots, but with the specified face.
298 The change affects only Org-mode (which will then use its own display table).
299 Changing this requires executing `M-x org-mode' in a buffer to become
300 effective."
301 :group 'org-startup
302 :type '(choice (const :tag "Default" nil)
303 (face :tag "Face" :value org-warning)
304 (string :tag "String" :value "...#")))
306 (defvar org-display-table nil
307 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
309 (defgroup org-keywords nil
310 "Keywords in Org-mode."
311 :tag "Org Keywords"
312 :group 'org)
314 (defcustom org-deadline-string "DEADLINE:"
315 "String to mark deadline entries.
316 A deadline is this string, followed by a time stamp. Should be a word,
317 terminated by a colon. You can insert a schedule keyword and
318 a timestamp with \\[org-deadline].
319 Changes become only effective after restarting Emacs."
320 :group 'org-keywords
321 :type 'string)
323 (defcustom org-scheduled-string "SCHEDULED:"
324 "String to mark scheduled TODO entries.
325 A schedule is this string, followed by a time stamp. Should be a word,
326 terminated by a colon. You can insert a schedule keyword and
327 a timestamp with \\[org-schedule].
328 Changes become only effective after restarting Emacs."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-closed-string "CLOSED:"
333 "String used as the prefix for timestamps logging closing a TODO entry."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-clock-string "CLOCK:"
338 "String used as prefix for timestamps clocking work hours on an item."
339 :group 'org-keywords
340 :type 'string)
342 (defcustom org-comment-string "COMMENT"
343 "Entries starting with this keyword will never be exported.
344 An entry can be toggled between COMMENT and normal with
345 \\[org-toggle-comment].
346 Changes become only effective after restarting Emacs."
347 :group 'org-keywords
348 :type 'string)
350 (defcustom org-quote-string "QUOTE"
351 "Entries starting with this keyword will be exported in fixed-width font.
352 Quoting applies only to the text in the entry following the headline, and does
353 not extend beyond the next headline, even if that is lower level.
354 An entry can be toggled between QUOTE and normal with
355 \\[org-toggle-fixed-width-section]."
356 :group 'org-keywords
357 :type 'string)
359 (defconst org-repeat-re
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defcustom org-indirect-buffer-display 'other-window
455 "How should indirect tree buffers be displayed?
456 This applies to indirect buffers created with the commands
457 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
458 Valid values are:
459 current-window Display in the current window
460 other-window Just display in another window.
461 dedicated-frame Create one new frame, and re-use it each time.
462 new-frame Make a new frame each time. Note that in this case
463 previously-made indirect buffers are kept, and you need to
464 kill these buffers yourself."
465 :group 'org-structure
466 :group 'org-agenda-windows
467 :type '(choice
468 (const :tag "In current window" current-window)
469 (const :tag "In current frame, other window" other-window)
470 (const :tag "Each time a new frame" new-frame)
471 (const :tag "One dedicated frame" dedicated-frame)))
473 (defgroup org-cycle nil
474 "Options concerning visibility cycling in Org-mode."
475 :tag "Org Cycle"
476 :group 'org-structure)
478 (defcustom org-drawers '("PROPERTIES" "CLOCK")
479 "Names of drawers. Drawers are not opened by cycling on the headline above.
480 Drawers only open with a TAB on the drawer line itself. A drawer looks like
481 this:
482 :DRAWERNAME:
483 .....
484 :END:
485 The drawer \"PROPERTIES\" is special for capturing properties through
486 the property API.
488 Drawers can be defined on the per-file basis with a line like:
490 #+DRAWERS: HIDDEN STATE PROPERTIES"
491 :group 'org-structure
492 :type '(repeat (string :tag "Drawer Name")))
494 (defcustom org-cycle-global-at-bob nil
495 "Cycle globally if cursor is at beginning of buffer and not at a headline.
496 This makes it possible to do global cycling without having to use S-TAB or
497 C-u TAB. For this special case to work, the first line of the buffer
498 must not be a headline - it may be empty ot some other text. When used in
499 this way, `org-cycle-hook' is disables temporarily, to make sure the
500 cursor stays at the beginning of the buffer.
501 When this option is nil, don't do anything special at the beginning
502 of the buffer."
503 :group 'org-cycle
504 :type 'boolean)
506 (defcustom org-cycle-emulate-tab t
507 "Where should `org-cycle' emulate TAB.
508 nil Never
509 white Only in completely white lines
510 whitestart Only at the beginning of lines, before the first non-white char
511 t Everywhere except in headlines
512 exc-hl-bol Everywhere except at the start of a headline
513 If TAB is used in a place where it does not emulate TAB, the current subtree
514 visibility is cycled."
515 :group 'org-cycle
516 :type '(choice (const :tag "Never" nil)
517 (const :tag "Only in completely white lines" white)
518 (const :tag "Before first char in a line" whitestart)
519 (const :tag "Everywhere except in headlines" t)
520 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
523 (defcustom org-cycle-separator-lines 2
524 "Number of empty lines needed to keep an empty line between collapsed trees.
525 If you leave an empty line between the end of a subtree and the following
526 headline, this empty line is hidden when the subtree is folded.
527 Org-mode will leave (exactly) one empty line visible if the number of
528 empty lines is equal or larger to the number given in this variable.
529 So the default 2 means, at least 2 empty lines after the end of a subtree
530 are needed to produce free space between a collapsed subtree and the
531 following headline.
533 Special case: when 0, never leave empty lines in collapsed view."
534 :group 'org-cycle
535 :type 'integer)
537 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
538 org-cycle-hide-drawers
539 org-cycle-show-empty-lines
540 org-optimize-window-after-visibility-change)
541 "Hook that is run after `org-cycle' has changed the buffer visibility.
542 The function(s) in this hook must accept a single argument which indicates
543 the new state that was set by the most recent `org-cycle' command. The
544 argument is a symbol. After a global state change, it can have the values
545 `overview', `content', or `all'. After a local state change, it can have
546 the values `folded', `children', or `subtree'."
547 :group 'org-cycle
548 :type 'hook)
550 (defgroup org-edit-structure nil
551 "Options concerning structure editing in Org-mode."
552 :tag "Org Edit Structure"
553 :group 'org-structure)
555 (defcustom org-odd-levels-only nil
556 "Non-nil means, skip even levels and only use odd levels for the outline.
557 This has the effect that two stars are being added/taken away in
558 promotion/demotion commands. It also influences how levels are
559 handled by the exporters.
560 Changing it requires restart of `font-lock-mode' to become effective
561 for fontification also in regions already fontified.
562 You may also set this on a per-file basis by adding one of the following
563 lines to the buffer:
565 #+STARTUP: odd
566 #+STARTUP: oddeven"
567 :group 'org-edit-structure
568 :group 'org-font-lock
569 :type 'boolean)
571 (defcustom org-adapt-indentation t
572 "Non-nil means, adapt indentation when promoting and demoting.
573 When this is set and the *entire* text in an entry is indented, the
574 indentation is increased by one space in a demotion command, and
575 decreased by one in a promotion command. If any line in the entry
576 body starts at column 0, indentation is not changed at all."
577 :group 'org-edit-structure
578 :type 'boolean)
580 (defcustom org-special-ctrl-a/e nil
581 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
582 When t, `C-a' will bring back the cursor to the beginning of the
583 headline text, i.e. after the stars and after a possible TODO keyword.
584 In an item, this will be the position after the bullet.
585 When the cursor is already at that position, another `C-a' will bring
586 it to the beginning of the line.
587 `C-e' will jump to the end of the headline, ignoring the presence of tags
588 in the headline. A second `C-e' will then jump to the true end of the
589 line, after any tags.
590 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
591 and only a directly following, identical keypress will bring the cursor
592 to the special positions."
593 :group 'org-edit-structure
594 :type '(choice
595 (const :tag "off" nil)
596 (const :tag "after bullet first" t)
597 (const :tag "border first" reversed)))
599 (if (fboundp 'defvaralias)
600 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
602 (defcustom org-special-ctrl-k nil
603 "Non-nil means `C-k' will behave specially in headlines.
604 When nil, `C-k' will call the default `kill-line' command.
605 When t, the following will happen while the cursor is in the headline:
607 - When the cursor is at the beginning of a headline, kill the entire
608 line and possible the folded subtree below the line.
609 - When in the middle of the headline text, kill the headline up to the tags.
610 - When after the headline text, kill the tags."
611 :group 'org-edit-structure
612 :type 'boolean)
614 (defcustom org-M-RET-may-split-line '((default . t))
615 "Non-nil means, M-RET will split the line at the cursor position.
616 When nil, it will go to the end of the line before making a
617 new line.
618 You may also set this option in a different way for different
619 contexts. Valid contexts are:
621 headline when creating a new headline
622 item when creating a new item
623 table in a table field
624 default the value to be used for all contexts not explicitly
625 customized"
626 :group 'org-structure
627 :group 'org-table
628 :type '(choice
629 (const :tag "Always" t)
630 (const :tag "Never" nil)
631 (repeat :greedy t :tag "Individual contexts"
632 (cons
633 (choice :tag "Context"
634 (const headline)
635 (const item)
636 (const table)
637 (const default))
638 (boolean)))))
641 (defcustom org-blank-before-new-entry '((heading . nil)
642 (plain-list-item . nil))
643 "Should `org-insert-heading' leave a blank line before new heading/item?
644 The value is an alist, with `heading' and `plain-list-item' as car,
645 and a boolean flag as cdr."
646 :group 'org-edit-structure
647 :type '(list
648 (cons (const heading) (boolean))
649 (cons (const plain-list-item) (boolean))))
651 (defcustom org-insert-heading-hook nil
652 "Hook being run after inserting a new heading."
653 :group 'org-edit-structure
654 :type 'hook)
656 (defcustom org-enable-fixed-width-editor t
657 "Non-nil means, lines starting with \":\" are treated as fixed-width.
658 This currently only means, they are never auto-wrapped.
659 When nil, such lines will be treated like ordinary lines.
660 See also the QUOTE keyword."
661 :group 'org-edit-structure
662 :type 'boolean)
664 (defcustom org-goto-auto-isearch t
665 "Non-nil means, typing characters in org-goto starts incremental search."
666 :group 'org-edit-structure
667 :type 'boolean)
669 (defgroup org-sparse-trees nil
670 "Options concerning sparse trees in Org-mode."
671 :tag "Org Sparse Trees"
672 :group 'org-structure)
674 (defcustom org-highlight-sparse-tree-matches t
675 "Non-nil means, highlight all matches that define a sparse tree.
676 The highlights will automatically disappear the next time the buffer is
677 changed by an edit command."
678 :group 'org-sparse-trees
679 :type 'boolean)
681 (defcustom org-remove-highlights-with-change t
682 "Non-nil means, any change to the buffer will remove temporary highlights.
683 Such highlights are created by `org-occur' and `org-clock-display'.
684 When nil, `C-c C-c needs to be used to get rid of the highlights.
685 The highlights created by `org-preview-latex-fragment' always need
686 `C-c C-c' to be removed."
687 :group 'org-sparse-trees
688 :group 'org-time
689 :type 'boolean)
692 (defcustom org-occur-hook '(org-first-headline-recenter)
693 "Hook that is run after `org-occur' has constructed a sparse tree.
694 This can be used to recenter the window to show as much of the structure
695 as possible."
696 :group 'org-sparse-trees
697 :type 'hook)
699 (defgroup org-plain-lists nil
700 "Options concerning plain lists in Org-mode."
701 :tag "Org Plain lists"
702 :group 'org-structure)
704 (defcustom org-cycle-include-plain-lists nil
705 "Non-nil means, include plain lists into visibility cycling.
706 This means that during cycling, plain list items will *temporarily* be
707 interpreted as outline headlines with a level given by 1000+i where i is the
708 indentation of the bullet. In all other operations, plain list items are
709 not seen as headlines. For example, you cannot assign a TODO keyword to
710 such an item."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-plain-list-ordered-item-terminator t
715 "The character that makes a line with leading number an ordered list item.
716 Valid values are ?. and ?\). To get both terminators, use t. While
717 ?. may look nicer, it creates the danger that a line with leading
718 number may be incorrectly interpreted as an item. ?\) therefore is
719 the safe choice."
720 :group 'org-plain-lists
721 :type '(choice (const :tag "dot like in \"2.\"" ?.)
722 (const :tag "paren like in \"2)\"" ?\))
723 (const :tab "both" t)))
725 (defcustom org-empty-line-terminates-plain-lists nil
726 "Non-nil means, an empty line ends all plain list levels.
727 When nil, empty lines are part of the preceeding item."
728 :group 'org-plain-lists
729 :type 'boolean)
731 (defcustom org-auto-renumber-ordered-lists t
732 "Non-nil means, automatically renumber ordered plain lists.
733 Renumbering happens when the sequence have been changed with
734 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
735 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
736 :group 'org-plain-lists
737 :type 'boolean)
739 (defcustom org-provide-checkbox-statistics t
740 "Non-nil means, update checkbox statistics after insert and toggle.
741 When this is set, checkbox statistics is updated each time you either insert
742 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
743 with \\[org-ctrl-c-ctrl-c\\]."
744 :group 'org-plain-lists
745 :type 'boolean)
748 (defgroup org-imenu-and-speedbar nil
749 "Options concerning imenu and speedbar in Org-mode."
750 :tag "Org Imenu and Speedbar"
751 :group 'org-structure)
753 (defcustom org-imenu-depth 2
754 "The maximum level for Imenu access to Org-mode headlines.
755 This also applied for speedbar access."
756 :group 'org-imenu-and-speedbar
757 :type 'number)
759 (defgroup org-table nil
760 "Options concerning tables in Org-mode."
761 :tag "Org Table"
762 :group 'org)
764 (defcustom org-enable-table-editor 'optimized
765 "Non-nil means, lines starting with \"|\" are handled by the table editor.
766 When nil, such lines will be treated like ordinary lines.
768 When equal to the symbol `optimized', the table editor will be optimized to
769 do the following:
770 - Automatic overwrite mode in front of whitespace in table fields.
771 This makes the structure of the table stay in tact as long as the edited
772 field does not exceed the column width.
773 - Minimize the number of realigns. Normally, the table is aligned each time
774 TAB or RET are pressed to move to another field. With optimization this
775 happens only if changes to a field might have changed the column width.
776 Optimization requires replacing the functions `self-insert-command',
777 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
778 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
779 very good at guessing when a re-align will be necessary, but you can always
780 force one with \\[org-ctrl-c-ctrl-c].
782 If you would like to use the optimized version in Org-mode, but the
783 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
785 This variable can be used to turn on and off the table editor during a session,
786 but in order to toggle optimization, a restart is required.
788 See also the variable `org-table-auto-blank-field'."
789 :group 'org-table
790 :type '(choice
791 (const :tag "off" nil)
792 (const :tag "on" t)
793 (const :tag "on, optimized" optimized)))
795 (defcustom org-table-tab-recognizes-table.el t
796 "Non-nil means, TAB will automatically notice a table.el table.
797 When it sees such a table, it moves point into it and - if necessary -
798 calls `table-recognize-table'."
799 :group 'org-table-editing
800 :type 'boolean)
802 (defgroup org-link nil
803 "Options concerning links in Org-mode."
804 :tag "Org Link"
805 :group 'org)
807 (defvar org-link-abbrev-alist-local nil
808 "Buffer-local version of `org-link-abbrev-alist', which see.
809 The value of this is taken from the #+LINK lines.")
810 (make-variable-buffer-local 'org-link-abbrev-alist-local)
812 (defcustom org-link-abbrev-alist nil
813 "Alist of link abbreviations.
814 The car of each element is a string, to be replaced at the start of a link.
815 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
816 links in Org-mode buffers can have an optional tag after a double colon, e.g.
818 [[linkkey:tag][description]]
820 If REPLACE is a string, the tag will simply be appended to create the link.
821 If the string contains \"%s\", the tag will be inserted there.
823 REPLACE may also be a function that will be called with the tag as the
824 only argument to create the link, which should be returned as a string.
826 See the manual for examples."
827 :group 'org-link
828 :type 'alist)
830 (defcustom org-descriptive-links t
831 "Non-nil means, hide link part and only show description of bracket links.
832 Bracket links are like [[link][descritpion]]. This variable sets the initial
833 state in new org-mode buffers. The setting can then be toggled on a
834 per-buffer basis from the Org->Hyperlinks menu."
835 :group 'org-link
836 :type 'boolean)
838 (defcustom org-link-file-path-type 'adaptive
839 "How the path name in file links should be stored.
840 Valid values are:
842 relative Relative to the current directory, i.e. the directory of the file
843 into which the link is being inserted.
844 absolute Absolute path, if possible with ~ for home directory.
845 noabbrev Absolute path, no abbreviation of home directory.
846 adaptive Use relative path for files in the current directory and sub-
847 directories of it. For other files, use an absolute path."
848 :group 'org-link
849 :type '(choice
850 (const relative)
851 (const absolute)
852 (const noabbrev)
853 (const adaptive)))
855 (defcustom org-activate-links '(bracket angle plain radio tag date)
856 "Types of links that should be activated in Org-mode files.
857 This is a list of symbols, each leading to the activation of a certain link
858 type. In principle, it does not hurt to turn on most link types - there may
859 be a small gain when turning off unused link types. The types are:
861 bracket The recommended [[link][description]] or [[link]] links with hiding.
862 angular Links in angular brackes that may contain whitespace like
863 <bbdb:Carsten Dominik>.
864 plain Plain links in normal text, no whitespace, like http://google.com.
865 radio Text that is matched by a radio target, see manual for details.
866 tag Tag settings in a headline (link to tag search).
867 date Time stamps (link to calendar).
869 Changing this variable requires a restart of Emacs to become effective."
870 :group 'org-link
871 :type '(set (const :tag "Double bracket links (new style)" bracket)
872 (const :tag "Angular bracket links (old style)" angular)
873 (const :tag "Plain text links" plain)
874 (const :tag "Radio target matches" radio)
875 (const :tag "Tags" tag)
876 (const :tag "Timestamps" date)))
878 (defcustom org-make-link-description-function nil
879 "Function to use to generate link descriptions from links. If
880 nil the link location will be used. This function must take two
881 parameters; the first is the link and the second the description
882 org-insert-link has generated, and should return the description
883 to use."
884 :group 'org-link
885 :type 'function)
887 (defgroup org-link-store nil
888 "Options concerning storing links in Org-mode."
889 :tag "Org Store Link"
890 :group 'org-link)
892 (defcustom org-email-link-description-format "Email %c: %.30s"
893 "Format of the description part of a link to an email or usenet message.
894 The following %-excapes will be replaced by corresponding information:
896 %F full \"From\" field
897 %f name, taken from \"From\" field, address if no name
898 %T full \"To\" field
899 %t first name in \"To\" field, address if no name
900 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
901 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
902 %s subject
903 %m message-id.
905 You may use normal field width specification between the % and the letter.
906 This is for example useful to limit the length of the subject.
908 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
909 :group 'org-link-store
910 :type 'string)
912 (defcustom org-from-is-user-regexp
913 (let (r1 r2)
914 (when (and user-mail-address (not (string= user-mail-address "")))
915 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
916 (when (and user-full-name (not (string= user-full-name "")))
917 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
918 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
919 "Regexp mached against the \"From:\" header of an email or usenet message.
920 It should match if the message is from the user him/herself."
921 :group 'org-link-store
922 :type 'regexp)
924 (defcustom org-context-in-file-links t
925 "Non-nil means, file links from `org-store-link' contain context.
926 A search string will be added to the file name with :: as separator and
927 used to find the context when the link is activated by the command
928 `org-open-at-point'.
929 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
930 negates this setting for the duration of the command."
931 :group 'org-link-store
932 :type 'boolean)
934 (defcustom org-keep-stored-link-after-insertion nil
935 "Non-nil means, keep link in list for entire session.
937 The command `org-store-link' adds a link pointing to the current
938 location to an internal list. These links accumulate during a session.
939 The command `org-insert-link' can be used to insert links into any
940 Org-mode file (offering completion for all stored links). When this
941 option is nil, every link which has been inserted once using \\[org-insert-link]
942 will be removed from the list, to make completing the unused links
943 more efficient."
944 :group 'org-link-store
945 :type 'boolean)
947 (defgroup org-link-follow nil
948 "Options concerning following links in Org-mode."
949 :tag "Org Follow Link"
950 :group 'org-link)
952 (defcustom org-follow-link-hook nil
953 "Hook that is run after a link has been followed."
954 :group 'org-link-follow
955 :type 'hook)
957 (defcustom org-tab-follows-link nil
958 "Non-nil means, on links TAB will follow the link.
959 Needs to be set before org.el is loaded."
960 :group 'org-link-follow
961 :type 'boolean)
963 (defcustom org-return-follows-link nil
964 "Non-nil means, on links RET will follow the link.
965 Needs to be set before org.el is loaded."
966 :group 'org-link-follow
967 :type 'boolean)
969 (defcustom org-mouse-1-follows-link
970 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
971 "Non-nil means, mouse-1 on a link will follow the link.
972 A longer mouse click will still set point. Does not work on XEmacs.
973 Needs to be set before org.el is loaded."
974 :group 'org-link-follow
975 :type 'boolean)
977 (defcustom org-mark-ring-length 4
978 "Number of different positions to be recorded in the ring
979 Changing this requires a restart of Emacs to work correctly."
980 :group 'org-link-follow
981 :type 'interger)
983 (defcustom org-link-frame-setup
984 '((vm . vm-visit-folder-other-frame)
985 (gnus . gnus-other-frame)
986 (file . find-file-other-window))
987 "Setup the frame configuration for following links.
988 When following a link with Emacs, it may often be useful to display
989 this link in another window or frame. This variable can be used to
990 set this up for the different types of links.
991 For VM, use any of
992 `vm-visit-folder'
993 `vm-visit-folder-other-frame'
994 For Gnus, use any of
995 `gnus'
996 `gnus-other-frame'
997 For FILE, use any of
998 `find-file'
999 `find-file-other-window'
1000 `find-file-other-frame'
1001 For the calendar, use the variable `calendar-setup'.
1002 For BBDB, it is currently only possible to display the matches in
1003 another window."
1004 :group 'org-link-follow
1005 :type '(list
1006 (cons (const vm)
1007 (choice
1008 (const vm-visit-folder)
1009 (const vm-visit-folder-other-window)
1010 (const vm-visit-folder-other-frame)))
1011 (cons (const gnus)
1012 (choice
1013 (const gnus)
1014 (const gnus-other-frame)))
1015 (cons (const file)
1016 (choice
1017 (const find-file)
1018 (const find-file-other-window)
1019 (const find-file-other-frame)))))
1021 (defcustom org-display-internal-link-with-indirect-buffer nil
1022 "Non-nil means, use indirect buffer to display infile links.
1023 Activating internal links (from one location in a file to another location
1024 in the same file) normally just jumps to the location. When the link is
1025 activated with a C-u prefix (or with mouse-3), the link is displayed in
1026 another window. When this option is set, the other window actually displays
1027 an indirect buffer clone of the current buffer, to avoid any visibility
1028 changes to the current buffer."
1029 :group 'org-link-follow
1030 :type 'boolean)
1032 (defcustom org-open-non-existing-files nil
1033 "Non-nil means, `org-open-file' will open non-existing files.
1034 When nil, an error will be generated."
1035 :group 'org-link-follow
1036 :type 'boolean)
1038 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1039 "Function and arguments to call for following mailto links.
1040 This is a list with the first element being a lisp function, and the
1041 remaining elements being arguments to the function. In string arguments,
1042 %a will be replaced by the address, and %s will be replaced by the subject
1043 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1044 :group 'org-link-follow
1045 :type '(choice
1046 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1047 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1048 (const :tag "message-mail" (message-mail "%a" "%s"))
1049 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1051 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1052 "Non-nil means, ask for confirmation before executing shell links.
1053 Shell links can be dangerous: just think about a link
1055 [[shell:rm -rf ~/*][Google Search]]
1057 This link would show up in your Org-mode document as \"Google Search\",
1058 but really it would remove your entire home directory.
1059 Therefore we advise against setting this variable to nil.
1060 Just change it to `y-or-n-p' of you want to confirm with a
1061 single keystroke rather than having to type \"yes\"."
1062 :group 'org-link-follow
1063 :type '(choice
1064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1065 (const :tag "with y-or-n (faster)" y-or-n-p)
1066 (const :tag "no confirmation (dangerous)" nil)))
1068 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1069 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1070 Elisp links can be dangerous: just think about a link
1072 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1074 This link would show up in your Org-mode document as \"Google Search\",
1075 but really it would remove your entire home directory.
1076 Therefore we advise against setting this variable to nil.
1077 Just change it to `y-or-n-p' of you want to confirm with a
1078 single keystroke rather than having to type \"yes\"."
1079 :group 'org-link-follow
1080 :type '(choice
1081 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1082 (const :tag "with y-or-n (faster)" y-or-n-p)
1083 (const :tag "no confirmation (dangerous)" nil)))
1085 (defconst org-file-apps-defaults-gnu
1086 '((remote . emacs)
1087 (t . mailcap))
1088 "Default file applications on a UNIX or GNU/Linux system.
1089 See `org-file-apps'.")
1091 (defconst org-file-apps-defaults-macosx
1092 '((remote . emacs)
1093 (t . "open %s")
1094 ("ps" . "gv %s")
1095 ("ps.gz" . "gv %s")
1096 ("eps" . "gv %s")
1097 ("eps.gz" . "gv %s")
1098 ("dvi" . "xdvi %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1105 (defconst org-file-apps-defaults-windowsnt
1106 (list
1107 '(remote . emacs)
1108 (cons t
1109 (list (if (featurep 'xemacs)
1110 'mswindows-shell-execute
1111 'w32-shell-execute)
1112 "open" 'file)))
1113 "Default file applications on a Windows NT system.
1114 The system \"open\" is used for most files.
1115 See `org-file-apps'.")
1117 (defcustom org-file-apps
1119 ("txt" . emacs)
1120 ("tex" . emacs)
1121 ("ltx" . emacs)
1122 ("org" . emacs)
1123 ("el" . emacs)
1124 ("bib" . emacs)
1126 "External applications for opening `file:path' items in a document.
1127 Org-mode uses system defaults for different file types, but
1128 you can use this variable to set the application for a given file
1129 extension. The entries in this list are cons cells where the car identifies
1130 files and the cdr the corresponding command. Possible values for the
1131 file identifier are
1132 \"ext\" A string identifying an extension
1133 `directory' Matches a directory
1134 `remote' Matches a remote file, accessible through tramp or efs.
1135 Remote files most likely should be visited through Emacs
1136 because external applications cannot handle such paths.
1137 t Default for all remaining files
1139 Possible values for the command are:
1140 `emacs' The file will be visited by the current Emacs process.
1141 `default' Use the default application for this file type.
1142 string A command to be executed by a shell; %s will be replaced
1143 by the path to the file.
1144 sexp A Lisp form which will be evaluated. The file path will
1145 be available in the Lisp variable `file'.
1146 For more examples, see the system specific constants
1147 `org-file-apps-defaults-macosx'
1148 `org-file-apps-defaults-windowsnt'
1149 `org-file-apps-defaults-gnu'."
1150 :group 'org-link-follow
1151 :type '(repeat
1152 (cons (choice :value ""
1153 (string :tag "Extension")
1154 (const :tag "Default for unrecognized files" t)
1155 (const :tag "Remote file" remote)
1156 (const :tag "Links to a directory" directory))
1157 (choice :value ""
1158 (const :tag "Visit with Emacs" emacs)
1159 (const :tag "Use system default" default)
1160 (string :tag "Command")
1161 (sexp :tag "Lisp form")))))
1163 (defgroup org-refile nil
1164 "Options concerning refiling entries in Org-mode."
1165 :tag "Org Remember"
1166 :group 'org)
1168 (defcustom org-directory "~/org"
1169 "Directory with org files.
1170 This directory will be used as default to prompt for org files.
1171 Used by the hooks for remember.el."
1172 :group 'org-refile
1173 :group 'org-remember
1174 :type 'directory)
1176 (defcustom org-default-notes-file "~/.notes"
1177 "Default target for storing notes.
1178 Used by the hooks for remember.el. This can be a string, or nil to mean
1179 the value of `remember-data-file'.
1180 You can set this on a per-template basis with the variable
1181 `org-remember-templates'."
1182 :group 'org-refile
1183 :group 'org-remember
1184 :type '(choice
1185 (const :tag "Default from remember-data-file" nil)
1186 file))
1188 (defcustom org-goto-interface 'outline
1189 "The default interface to be used for `org-goto'.
1190 Allowed vaues are:
1191 outline The interface shows an outline of the relevant file
1192 and the correct heading is found by moving through
1193 the outline or by searching with incremental search.
1194 outline-path-completion Headlines in the current buffer are offered via
1195 completion."
1196 :group 'org-refile
1197 :type '(choice
1198 (const :tag "Outline" outline)
1199 (const :tag "Outline-path-completion" outline-path-completion)))
1201 (defcustom org-reverse-note-order nil
1202 "Non-nil means, store new notes at the beginning of a file or entry.
1203 When nil, new notes will be filed to the end of a file or entry.
1204 This can also be a list with cons cells of regular expressions that
1205 are matched against file names, and values."
1206 :group 'org-remember
1207 :type '(choice
1208 (const :tag "Reverse always" t)
1209 (const :tag "Reverse never" nil)
1210 (repeat :tag "By file name regexp"
1211 (cons regexp boolean))))
1213 (defcustom org-refile-targets nil
1214 "Targets for refiling entries with \\[org-refile].
1215 This is list of cons cells. Each cell contains:
1216 - a specification of the files to be considered, either a list of files,
1217 or a symbol whose function or variable value will be used to retrieve
1218 a file name or a list of file names. Nil means, refile to a different
1219 heading in the current buffer.
1220 - A specification of how to find candidate refile targets. This may be
1221 any of
1222 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1223 This tag has to be present in all target headlines, inheritance will
1224 not be considered.
1225 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1226 todo keyword.
1227 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1228 headlines that are refiling targets.
1229 - a cons cell (:level . N). Any headline of level N is considered a target.
1230 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1231 :group 'org-remember
1232 :type '(repeat
1233 (cons
1234 (choice :value org-agenda-files
1235 (const :tag "All agenda files" org-agenda-files)
1236 (const :tag "Current buffer" nil)
1237 (function) (variable) (file))
1238 (choice :tag "Identify target headline by"
1239 (cons :tag "Specific tag" (const :tag) (string))
1240 (cons :tag "TODO keyword" (const :todo) (string))
1241 (cons :tag "Regular expression" (const :regexp) (regexp))
1242 (cons :tag "Level number" (const :level) (integer))
1243 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1245 (defcustom org-refile-use-outline-path nil
1246 "Non-nil means, provide refile targets as paths.
1247 So a level 3 headline will be available as level1/level2/level3.
1248 When the value is `file', also include the file name (without directory)
1249 into the path. When `full-file-path', include the full file path."
1250 :group 'org-remember
1251 :type '(choice
1252 (const :tag "Not" nil)
1253 (const :tag "Yes" t)
1254 (const :tag "Start with file name" file)
1255 (const :tag "Start with full file path" full-file-path)))
1257 (defgroup org-todo nil
1258 "Options concerning TODO items in Org-mode."
1259 :tag "Org TODO"
1260 :group 'org)
1262 (defgroup org-progress nil
1263 "Options concerning Progress logging in Org-mode."
1264 :tag "Org Progress"
1265 :group 'org-time)
1267 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1268 "List of TODO entry keyword sequences and their interpretation.
1269 \\<org-mode-map>This is a list of sequences.
1271 Each sequence starts with a symbol, either `sequence' or `type',
1272 indicating if the keywords should be interpreted as a sequence of
1273 action steps, or as different types of TODO items. The first
1274 keywords are states requiring action - these states will select a headline
1275 for inclusion into the global TODO list Org-mode produces. If one of
1276 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1277 signify that no further action is necessary. If \"|\" is not found,
1278 the last keyword is treated as the only DONE state of the sequence.
1280 The command \\[org-todo] cycles an entry through these states, and one
1281 additional state where no keyword is present. For details about this
1282 cycling, see the manual.
1284 TODO keywords and interpretation can also be set on a per-file basis with
1285 the special #+SEQ_TODO and #+TYP_TODO lines.
1287 Each keyword can optionally specify a character for fast state selection
1288 \(in combination with the variable `org-use-fast-todo-selection')
1289 and specifiers for state change logging, using the same syntax
1290 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1291 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1292 indicates to record a time stamp each time this state is selected.
1294 Each keyword may also specify if a timestamp or a note should be
1295 recorded when entering or leaving the state, by adding additional
1296 characters in the parenthesis after the keyword. This looks like this:
1297 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1298 record only the time of the state change. With X and Y being either
1299 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1300 Y when leaving the state if and only if the *target* state does not
1301 define X. You may omit any of the fast-selection key or X or /Y,
1302 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1304 For backward compatibility, this variable may also be just a list
1305 of keywords - in this case the interptetation (sequence or type) will be
1306 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1307 :group 'org-todo
1308 :group 'org-keywords
1309 :type '(choice
1310 (repeat :tag "Old syntax, just keywords"
1311 (string :tag "Keyword"))
1312 (repeat :tag "New syntax"
1313 (cons
1314 (choice
1315 :tag "Interpretation"
1316 (const :tag "Sequence (cycling hits every state)" sequence)
1317 (const :tag "Type (cycling directly to DONE)" type))
1318 (repeat
1319 (string :tag "Keyword"))))))
1321 (defvar org-todo-keywords-1 nil
1322 "All TODO and DONE keywords active in a buffer.")
1323 (make-variable-buffer-local 'org-todo-keywords-1)
1324 (defvar org-todo-keywords-for-agenda nil)
1325 (defvar org-done-keywords-for-agenda nil)
1326 (defvar org-agenda-contributing-files nil)
1327 (defvar org-not-done-keywords nil)
1328 (make-variable-buffer-local 'org-not-done-keywords)
1329 (defvar org-done-keywords nil)
1330 (make-variable-buffer-local 'org-done-keywords)
1331 (defvar org-todo-heads nil)
1332 (make-variable-buffer-local 'org-todo-heads)
1333 (defvar org-todo-sets nil)
1334 (make-variable-buffer-local 'org-todo-sets)
1335 (defvar org-todo-log-states nil)
1336 (make-variable-buffer-local 'org-todo-log-states)
1337 (defvar org-todo-kwd-alist nil)
1338 (make-variable-buffer-local 'org-todo-kwd-alist)
1339 (defvar org-todo-key-alist nil)
1340 (make-variable-buffer-local 'org-todo-key-alist)
1341 (defvar org-todo-key-trigger nil)
1342 (make-variable-buffer-local 'org-todo-key-trigger)
1344 (defcustom org-todo-interpretation 'sequence
1345 "Controls how TODO keywords are interpreted.
1346 This variable is in principle obsolete and is only used for
1347 backward compatibility, if the interpretation of todo keywords is
1348 not given already in `org-todo-keywords'. See that variable for
1349 more information."
1350 :group 'org-todo
1351 :group 'org-keywords
1352 :type '(choice (const sequence)
1353 (const type)))
1355 (defcustom org-use-fast-todo-selection 'prefix
1356 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1357 This variable describes if and under what circumstances the cycling
1358 mechanism for TODO keywords will be replaced by a single-key, direct
1359 selection scheme.
1361 When nil, fast selection is never used.
1363 When the symbol `prefix', it will be used when `org-todo' is called with
1364 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1365 in an agenda buffer.
1367 When t, fast selection is used by default. In this case, the prefix
1368 argument forces cycling instead.
1370 In all cases, the special interface is only used if access keys have actually
1371 been assigned by the user, i.e. if keywords in the configuration are followed
1372 by a letter in parenthesis, like TODO(t)."
1373 :group 'org-todo
1374 :type '(choice
1375 (const :tag "Never" nil)
1376 (const :tag "By default" t)
1377 (const :tag "Only with C-u C-c C-t" prefix)))
1379 (defcustom org-after-todo-state-change-hook nil
1380 "Hook which is run after the state of a TODO item was changed.
1381 The new state (a string with a TODO keyword, or nil) is available in the
1382 Lisp variable `state'."
1383 :group 'org-todo
1384 :type 'hook)
1386 (defcustom org-log-done nil
1387 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1388 When equal to the list (done), also prompt for a closing note.
1389 This can also be configured on a per-file basis by adding one of
1390 the following lines anywhere in the buffer:
1392 #+STARTUP: logdone
1393 #+STARTUP: lognotedone
1394 #+STARTUP: nologdone"
1395 :group 'org-todo
1396 :group 'org-progress
1397 :type '(choice
1398 (const :tag "No logging" nil)
1399 (const :tag "Record CLOSED timestamp" time)
1400 (const :tag "Record CLOSED timestamp with closing note." note)))
1402 ;; Normalize old uses of org-log-done.
1403 (cond
1404 ((eq org-log-done t) (setq org-log-done 'time))
1405 ((and (listp org-log-done) (memq 'done org-log-done))
1406 (setq org-log-done 'note)))
1408 (defcustom org-log-note-clock-out nil
1409 "Non-nil means, recored a note when clocking out of an item.
1410 This can also be configured on a per-file basis by adding one of
1411 the following lines anywhere in the buffer:
1413 #+STARTUP: lognoteclock-out
1414 #+STARTUP: nolognoteclock-out"
1415 :group 'org-todo
1416 :group 'org-progress
1417 :type 'boolean)
1419 (defcustom org-log-done-with-time t
1420 "Non-nil means, the CLOSED time stamp will contain date and time.
1421 When nil, only the date will be recorded."
1422 :group 'org-progress
1423 :type 'boolean)
1425 (defcustom org-log-note-headings
1426 '((done . "CLOSING NOTE %t")
1427 (state . "State %-12s %t")
1428 (note . "Note taken on %t")
1429 (clock-out . ""))
1430 "Headings for notes added to entries.
1431 The value is an alist, with the car being a symbol indicating the note
1432 context, and the cdr is the heading to be used. The heading may also be the
1433 empty string.
1434 %t in the heading will be replaced by a time stamp.
1435 %s will be replaced by the new TODO state, in double quotes.
1436 %u will be replaced by the user name.
1437 %U will be replaced by the full user name."
1438 :group 'org-todo
1439 :group 'org-progress
1440 :type '(list :greedy t
1441 (cons (const :tag "Heading when closing an item" done) string)
1442 (cons (const :tag
1443 "Heading when changing todo state (todo sequence only)"
1444 state) string)
1445 (cons (const :tag "Heading when just taking a note" note) string)
1446 (cons (const :tag "Heading when clocking out" clock-out) string)))
1448 (unless (assq 'note org-log-note-headings)
1449 (push '(note . "%t") org-log-note-headings))
1451 (defcustom org-log-states-order-reversed t
1452 "Non-nil means, the latest state change note will be directly after heading.
1453 When nil, the notes will be orderer according to time."
1454 :group 'org-todo
1455 :group 'org-progress
1456 :type 'boolean)
1458 (defcustom org-log-repeat 'time
1459 "Non-nil means, record moving through the DONE state when triggering repeat.
1460 An auto-repeating tasks is immediately switched back to TODO when marked
1461 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1462 the TODO keyword definition, or recording a closing note by setting
1463 `org-log-done', there will be no record of the task moving through DONE.
1464 This variable forces taking a note anyway. Possible values are:
1466 nil Don't force a record
1467 time Record a time stamp
1468 note Record a note
1470 This option can also be set with on a per-file-basis with
1472 #+STARTUP: logrepeat
1473 #+STARTUP: lognoterepeat
1474 #+STARTUP: nologrepeat
1476 You can have local logging settings for a subtree by setting the LOGGING
1477 property to one or more of these keywords."
1478 :group 'org-todo
1479 :group 'org-progress
1480 :type '(choice
1481 (const :tag "Don't force a record" nil)
1482 (const :tag "Force recording the DONE state" time)
1483 (const :tag "Force recording a note with the DONE state" note)))
1486 (defgroup org-priorities nil
1487 "Priorities in Org-mode."
1488 :tag "Org Priorities"
1489 :group 'org-todo)
1491 (defcustom org-highest-priority ?A
1492 "The highest priority of TODO items. A character like ?A, ?B etc.
1493 Must have a smaller ASCII number than `org-lowest-priority'."
1494 :group 'org-priorities
1495 :type 'character)
1497 (defcustom org-lowest-priority ?C
1498 "The lowest priority of TODO items. A character like ?A, ?B etc.
1499 Must have a larger ASCII number than `org-highest-priority'."
1500 :group 'org-priorities
1501 :type 'character)
1503 (defcustom org-default-priority ?B
1504 "The default priority of TODO items.
1505 This is the priority an item get if no explicit priority is given."
1506 :group 'org-priorities
1507 :type 'character)
1509 (defcustom org-priority-start-cycle-with-default t
1510 "Non-nil means, start with default priority when starting to cycle.
1511 When this is nil, the first step in the cycle will be (depending on the
1512 command used) one higher or lower that the default priority."
1513 :group 'org-priorities
1514 :type 'boolean)
1516 (defgroup org-time nil
1517 "Options concerning time stamps and deadlines in Org-mode."
1518 :tag "Org Time"
1519 :group 'org)
1521 (defcustom org-insert-labeled-timestamps-at-point nil
1522 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1523 When nil, these labeled time stamps are forces into the second line of an
1524 entry, just after the headline. When scheduling from the global TODO list,
1525 the time stamp will always be forced into the second line."
1526 :group 'org-time
1527 :type 'boolean)
1529 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1530 "Formats for `format-time-string' which are used for time stamps.
1531 It is not recommended to change this constant.")
1533 (defcustom org-time-stamp-rounding-minutes '(0 5)
1534 "Number of minutes to round time stamps to.
1535 These are two values, the first applies when first creating a time stamp.
1536 The second applies when changing it with the commands `S-up' and `S-down'.
1537 When changing the time stamp, this means that it will change in steps
1538 of N minutes, as given by the second value.
1540 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1541 numbers should be factors of 60, so for example 5, 10, 15.
1543 When this is larger than 1, you can still force an exact time-stamp by using
1544 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1545 and by using a prefix arg to `S-up/down' to specify the exact number
1546 of minutes to shift."
1547 :group 'org-time
1548 :get '(lambda (var) ; Make sure all entries have 5 elements
1549 (if (integerp (default-value var))
1550 (list (default-value var) 5)
1551 (default-value var)))
1552 :type '(list
1553 (integer :tag "when inserting times")
1554 (integer :tag "when modifying times")))
1556 ;; Normalize old customizations of this variable.
1557 (when (integerp org-time-stamp-rounding-minutes)
1558 (setq org-time-stamp-rounding-minutes
1559 (list org-time-stamp-rounding-minutes
1560 org-time-stamp-rounding-minutes)))
1562 (defcustom org-display-custom-times nil
1563 "Non-nil means, overlay custom formats over all time stamps.
1564 The formats are defined through the variable `org-time-stamp-custom-formats'.
1565 To turn this on on a per-file basis, insert anywhere in the file:
1566 #+STARTUP: customtime"
1567 :group 'org-time
1568 :set 'set-default
1569 :type 'sexp)
1570 (make-variable-buffer-local 'org-display-custom-times)
1572 (defcustom org-time-stamp-custom-formats
1573 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1574 "Custom formats for time stamps. See `format-time-string' for the syntax.
1575 These are overlayed over the default ISO format if the variable
1576 `org-display-custom-times' is set. Time like %H:%M should be at the
1577 end of the second format."
1578 :group 'org-time
1579 :type 'sexp)
1581 (defun org-time-stamp-format (&optional long inactive)
1582 "Get the right format for a time string."
1583 (let ((f (if long (cdr org-time-stamp-formats)
1584 (car org-time-stamp-formats))))
1585 (if inactive
1586 (concat "[" (substring f 1 -1) "]")
1587 f)))
1589 (defcustom org-deadline-warning-days 14
1590 "No. of days before expiration during which a deadline becomes active.
1591 This variable governs the display in sparse trees and in the agenda.
1592 When 0 or negative, it means use this number (the absolute value of it)
1593 even if a deadline has a different individual lead time specified."
1594 :group 'org-time
1595 :group 'org-agenda-daily/weekly
1596 :type 'number)
1598 (defcustom org-read-date-prefer-future t
1599 "Non-nil means, assume future for incomplete date input from user.
1600 This affects the following situations:
1601 1. The user gives a day, but no month.
1602 For example, if today is the 15th, and you enter \"3\", Org-mode will
1603 read this as the third of *next* month. However, if you enter \"17\",
1604 it will be considered as *this* month.
1605 2. The user gives a month but not a year.
1606 For example, if it is april and you enter \"feb 2\", this will be read
1607 as feb 2, *next* year. \"May 5\", however, will be this year.
1609 Currently this does not work for ISO week specifications.
1611 When this option is nil, the current month and year will always be used
1612 as defaults."
1613 :group 'org-time
1614 :type 'boolean)
1616 (defcustom org-read-date-display-live t
1617 "Non-nil means, display current interpretation of date prompt live.
1618 This display will be in an overlay, in the minibuffer."
1619 :group 'org-time
1620 :type 'boolean)
1622 (defcustom org-read-date-popup-calendar t
1623 "Non-nil means, pop up a calendar when prompting for a date.
1624 In the calendar, the date can be selected with mouse-1. However, the
1625 minibuffer will also be active, and you can simply enter the date as well.
1626 When nil, only the minibuffer will be available."
1627 :group 'org-time
1628 :type 'boolean)
1629 (if (fboundp 'defvaralias)
1630 (defvaralias 'org-popup-calendar-for-date-prompt
1631 'org-read-date-popup-calendar))
1633 (defcustom org-extend-today-until 0
1634 "The hour when your day really ends.
1635 This has influence for the following applications:
1636 - When switching the agenda to \"today\". It it is still earlier than
1637 the time given here, the day recognized as TODAY is actually yesterday.
1638 - When a date is read from the user and it is still before the time given
1639 here, the current date and time will be assumed to be yesterday, 23:59.
1641 FIXME:
1642 IMPORTANT: This is still a very experimental feature, it may disappear
1643 again or it may be extended to mean more things."
1644 :group 'org-time
1645 :type 'number)
1647 (defcustom org-edit-timestamp-down-means-later nil
1648 "Non-nil means, S-down will increase the time in a time stamp.
1649 When nil, S-up will increase."
1650 :group 'org-time
1651 :type 'boolean)
1653 (defcustom org-calendar-follow-timestamp-change t
1654 "Non-nil means, make the calendar window follow timestamp changes.
1655 When a timestamp is modified and the calendar window is visible, it will be
1656 moved to the new date."
1657 :group 'org-time
1658 :type 'boolean)
1660 (defgroup org-tags nil
1661 "Options concerning tags in Org-mode."
1662 :tag "Org Tags"
1663 :group 'org)
1665 (defcustom org-tag-alist nil
1666 "List of tags allowed in Org-mode files.
1667 When this list is nil, Org-mode will base TAG input on what is already in the
1668 buffer.
1669 The value of this variable is an alist, the car of each entry must be a
1670 keyword as a string, the cdr may be a character that is used to select
1671 that tag through the fast-tag-selection interface.
1672 See the manual for details."
1673 :group 'org-tags
1674 :type '(repeat
1675 (choice
1676 (cons (string :tag "Tag name")
1677 (character :tag "Access char"))
1678 (const :tag "Start radio group" (:startgroup))
1679 (const :tag "End radio group" (:endgroup)))))
1681 (defcustom org-use-fast-tag-selection 'auto
1682 "Non-nil means, use fast tag selection scheme.
1683 This is a special interface to select and deselect tags with single keys.
1684 When nil, fast selection is never used.
1685 When the symbol `auto', fast selection is used if and only if selection
1686 characters for tags have been configured, either through the variable
1687 `org-tag-alist' or through a #+TAGS line in the buffer.
1688 When t, fast selection is always used and selection keys are assigned
1689 automatically if necessary."
1690 :group 'org-tags
1691 :type '(choice
1692 (const :tag "Always" t)
1693 (const :tag "Never" nil)
1694 (const :tag "When selection characters are configured" 'auto)))
1696 (defcustom org-fast-tag-selection-single-key nil
1697 "Non-nil means, fast tag selection exits after first change.
1698 When nil, you have to press RET to exit it.
1699 During fast tag selection, you can toggle this flag with `C-c'.
1700 This variable can also have the value `expert'. In this case, the window
1701 displaying the tags menu is not even shown, until you press C-c again."
1702 :group 'org-tags
1703 :type '(choice
1704 (const :tag "No" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Expert" expert)))
1708 (defvar org-fast-tag-selection-include-todo nil
1709 "Non-nil means, fast tags selection interface will also offer TODO states.
1710 This is an undocumented feature, you should not rely on it.")
1712 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1713 "The column to which tags should be indented in a headline.
1714 If this number is positive, it specifies the column. If it is negative,
1715 it means that the tags should be flushright to that column. For example,
1716 -80 works well for a normal 80 character screen."
1717 :group 'org-tags
1718 :type 'integer)
1720 (defcustom org-auto-align-tags t
1721 "Non-nil means, realign tags after pro/demotion of TODO state change.
1722 These operations change the length of a headline and therefore shift
1723 the tags around. With this options turned on, after each such operation
1724 the tags are again aligned to `org-tags-column'."
1725 :group 'org-tags
1726 :type 'boolean)
1728 (defcustom org-use-tag-inheritance t
1729 "Non-nil means, tags in levels apply also for sublevels.
1730 When nil, only the tags directly given in a specific line apply there.
1731 If you turn off this option, you very likely want to turn on the
1732 companion option `org-tags-match-list-sublevels'.
1734 This may also be a list of tags that should be inherited, or a regexp that
1735 matches tags that should be inherited."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Not" nil)
1739 (const :tag "Always" t)
1740 (repeat :tag "Specific tags" (string :tag "Tag"))
1741 (regexp :tag "Tags matched by regexp")))
1743 (defun org-tag-inherit-p (tag)
1744 "Check if TAG is one that should be inherited."
1745 (cond
1746 ((eq org-use-tag-inheritance t) t)
1747 ((not org-use-tag-inheritance) nil)
1748 ((stringp org-use-tag-inheritance)
1749 (string-match org-use-tag-inheritance tag))
1750 ((listp org-use-tag-inheritance)
1751 (member tag org-use-tag-inheritance))
1752 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1754 (defcustom org-tags-match-list-sublevels nil
1755 "Non-nil means list also sublevels of headlines matching tag search.
1756 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1757 the sublevels of a headline matching a tag search often also match
1758 the same search. Listing all of them can create very long lists.
1759 Setting this variable to nil causes subtrees of a match to be skipped.
1760 This option is off by default, because inheritance in on. If you turn
1761 inheritance off, you very likely want to turn this option on.
1763 As a special case, if the tag search is restricted to TODO items, the
1764 value of this variable is ignored and sublevels are always checked, to
1765 make sure all corresponding TODO items find their way into the list."
1766 :group 'org-tags
1767 :type 'boolean)
1769 (defvar org-tags-history nil
1770 "History of minibuffer reads for tags.")
1771 (defvar org-last-tags-completion-table nil
1772 "The last used completion table for tags.")
1773 (defvar org-after-tags-change-hook nil
1774 "Hook that is run after the tags in a line have changed.")
1776 (defgroup org-properties nil
1777 "Options concerning properties in Org-mode."
1778 :tag "Org Properties"
1779 :group 'org)
1781 (defcustom org-property-format "%-10s %s"
1782 "How property key/value pairs should be formatted by `indent-line'.
1783 When `indent-line' hits a property definition, it will format the line
1784 according to this format, mainly to make sure that the values are
1785 lined-up with respect to each other."
1786 :group 'org-properties
1787 :type 'string)
1789 (defcustom org-use-property-inheritance nil
1790 "Non-nil means, properties apply also for sublevels.
1792 This setting is chiefly used during property searches. Turning it on can
1793 cause significant overhead when doing a search, which is why it is not
1794 on by default.
1796 When nil, only the properties directly given in the current entry count.
1797 When t, every property is inherited. The value may also be a list of
1798 properties that should have inheritance, or a regular expression matching
1799 properties that should be inherited.
1801 However, note that some special properties use inheritance under special
1802 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1803 and the properties ending in \"_ALL\" when they are used as descriptor
1804 for valid values of a property.
1806 Note for programmers:
1807 When querying an entry with `org-entry-get', you can control if inheritance
1808 should be used. By default, `org-entry-get' looks only at the local
1809 properties. You can request inheritance by setting the inherit argument
1810 to t (to force inheritance) or to `selective' (to respect the setting
1811 in this variable)."
1812 :group 'org-properties
1813 :type '(choice
1814 (const :tag "Not" nil)
1815 (const :tag "Always" t)
1816 (repeat :tag "Specific properties" (string :tag "Property"))
1817 (regexp :tag "Properties matched by regexp")))
1819 (defun org-property-inherit-p (property)
1820 "Check if PROPERTY is one that should be inherited."
1821 (cond
1822 ((eq org-use-property-inheritance t) t)
1823 ((not org-use-property-inheritance) nil)
1824 ((stringp org-use-property-inheritance)
1825 (string-match org-use-property-inheritance property))
1826 ((listp org-use-property-inheritance)
1827 (member property org-use-property-inheritance))
1828 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1830 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1831 "The default column format, if no other format has been defined.
1832 This variable can be set on the per-file basis by inserting a line
1834 #+COLUMNS: %25ITEM ....."
1835 :group 'org-properties
1836 :type 'string)
1838 (defcustom org-effort-property "Effort"
1839 "The property that is being used to keep track of effort estimates.
1840 Effort estimates given in this property need to have the format H:MM."
1841 :group 'org-properties
1842 :group 'org-progress
1843 :type '(string :tag "Property"))
1845 (defcustom org-global-properties nil
1846 "List of property/value pairs that can be inherited by any entry.
1847 You can set buffer-local values for this by adding lines like
1849 #+PROPERTY: NAME VALUE"
1850 :group 'org-properties
1851 :type '(repeat
1852 (cons (string :tag "Property")
1853 (string :tag "Value"))))
1855 (defvar org-local-properties nil
1856 "List of property/value pairs that can be inherited by any entry.
1857 Valid for the current buffer.
1858 This variable is populated from #+PROPERTY lines.")
1860 (defgroup org-agenda nil
1861 "Options concerning agenda views in Org-mode."
1862 :tag "Org Agenda"
1863 :group 'org)
1865 (defvar org-category nil
1866 "Variable used by org files to set a category for agenda display.
1867 Such files should use a file variable to set it, for example
1869 # -*- mode: org; org-category: \"ELisp\"
1871 or contain a special line
1873 #+CATEGORY: ELisp
1875 If the file does not specify a category, then file's base name
1876 is used instead.")
1877 (make-variable-buffer-local 'org-category)
1879 (defcustom org-agenda-files nil
1880 "The files to be used for agenda display.
1881 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1882 \\[org-remove-file]. You can also use customize to edit the list.
1884 If an entry is a directory, all files in that directory that are matched by
1885 `org-agenda-file-regexp' will be part of the file list.
1887 If the value of the variable is not a list but a single file name, then
1888 the list of agenda files is actually stored and maintained in that file, one
1889 agenda file per line."
1890 :group 'org-agenda
1891 :type '(choice
1892 (repeat :tag "List of files and directories" file)
1893 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1895 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1896 "Regular expression to match files for `org-agenda-files'.
1897 If any element in the list in that variable contains a directory instead
1898 of a normal file, all files in that directory that are matched by this
1899 regular expression will be included."
1900 :group 'org-agenda
1901 :type 'regexp)
1903 (defcustom org-agenda-text-search-extra-files nil
1904 "List of extra files to be searched by text search commands.
1905 These files will be search in addition to the agenda files by the
1906 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1907 Note that these files will only be searched for text search commands,
1908 not for the other agenda views like todo lists, tag searches or the weekly
1909 agenda. This variable is intended to list notes and possibly archive files
1910 that should also be searched by these two commands.
1911 In fact, if the first element in the list is the symbol `agenda-archives',
1912 than all archive files of all agenda files will be added to the search
1913 scope."
1914 :group 'org-agenda
1915 :type '(set :greedy t
1916 (const :tag "Agenda Archives" agenda-archives)
1917 (repeat :inline t (file))))
1919 (if (fboundp 'defvaralias)
1920 (defvaralias 'org-agenda-multi-occur-extra-files
1921 'org-agenda-text-search-extra-files))
1923 (defcustom org-agenda-skip-unavailable-files nil
1924 "t means to just skip non-reachable files in `org-agenda-files'.
1925 Nil means to remove them, after a query, from the list."
1926 :group 'org-agenda
1927 :type 'boolean)
1929 (defcustom org-calendar-to-agenda-key [?c]
1930 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1931 The command `org-calendar-goto-agenda' will be bound to this key. The
1932 default is the character `c' because then `c' can be used to switch back and
1933 forth between agenda and calendar."
1934 :group 'org-agenda
1935 :type 'sexp)
1937 (eval-after-load "calendar"
1938 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1939 'org-calendar-goto-agenda))
1941 (defgroup org-latex nil
1942 "Options for embedding LaTeX code into Org-mode."
1943 :tag "Org LaTeX"
1944 :group 'org)
1946 (defcustom org-format-latex-options
1947 '(:foreground default :background default :scale 1.0
1948 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1949 :matchers ("begin" "$" "$$" "\\(" "\\["))
1950 "Options for creating images from LaTeX fragments.
1951 This is a property list with the following properties:
1952 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1953 `default' means use the forground of the default face.
1954 :background the background color, or \"Transparent\".
1955 `default' means use the background of the default face.
1956 :scale a scaling factor for the size of the images
1957 :html-foreground, :html-background, :html-scale
1958 The same numbers for HTML export.
1959 :matchers a list indicating which matchers should be used to
1960 find LaTeX fragments. Valid members of this list are:
1961 \"begin\" find environments
1962 \"$\" find math expressions surrounded by $...$
1963 \"$$\" find math expressions surrounded by $$....$$
1964 \"\\(\" find math expressions surrounded by \\(...\\)
1965 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1966 :group 'org-latex
1967 :type 'plist)
1969 (defcustom org-format-latex-header "\\documentclass{article}
1970 \\usepackage{fullpage} % do not remove
1971 \\usepackage{amssymb}
1972 \\usepackage[usenames]{color}
1973 \\usepackage{amsmath}
1974 \\usepackage{latexsym}
1975 \\usepackage[mathscr]{eucal}
1976 \\pagestyle{empty} % do not remove"
1977 "The document header used for processing LaTeX fragments."
1978 :group 'org-latex
1979 :type 'string)
1982 (defgroup org-font-lock nil
1983 "Font-lock settings for highlighting in Org-mode."
1984 :tag "Org Font Lock"
1985 :group 'org)
1987 (defcustom org-level-color-stars-only nil
1988 "Non-nil means fontify only the stars in each headline.
1989 When nil, the entire headline is fontified.
1990 Changing it requires restart of `font-lock-mode' to become effective
1991 also in regions already fontified."
1992 :group 'org-font-lock
1993 :type 'boolean)
1995 (defcustom org-hide-leading-stars nil
1996 "Non-nil means, hide the first N-1 stars in a headline.
1997 This works by using the face `org-hide' for these stars. This
1998 face is white for a light background, and black for a dark
1999 background. You may have to customize the face `org-hide' to
2000 make this work.
2001 Changing it requires restart of `font-lock-mode' to become effective
2002 also in regions already fontified.
2003 You may also set this on a per-file basis by adding one of the following
2004 lines to the buffer:
2006 #+STARTUP: hidestars
2007 #+STARTUP: showstars"
2008 :group 'org-font-lock
2009 :type 'boolean)
2011 (defcustom org-fontify-done-headline nil
2012 "Non-nil means, change the face of a headline if it is marked DONE.
2013 Normally, only the TODO/DONE keyword indicates the state of a headline.
2014 When this is non-nil, the headline after the keyword is set to the
2015 `org-headline-done' as an additional indication."
2016 :group 'org-font-lock
2017 :type 'boolean)
2019 (defcustom org-fontify-emphasized-text t
2020 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2021 Changing this variable requires a restart of Emacs to take effect."
2022 :group 'org-font-lock
2023 :type 'boolean)
2025 (defcustom org-highlight-latex-fragments-and-specials nil
2026 "Non-nil means, fontify what is treated specially by the exporters."
2027 :group 'org-font-lock
2028 :type 'boolean)
2030 (defcustom org-hide-emphasis-markers nil
2031 "Non-nil mean font-lock should hide the emphasis marker characters."
2032 :group 'org-font-lock
2033 :type 'boolean)
2035 (defvar org-emph-re nil
2036 "Regular expression for matching emphasis.")
2037 (defvar org-verbatim-re nil
2038 "Regular expression for matching verbatim text.")
2039 (defvar org-emphasis-regexp-components) ; defined just below
2040 (defvar org-emphasis-alist) ; defined just below
2041 (defun org-set-emph-re (var val)
2042 "Set variable and compute the emphasis regular expression."
2043 (set var val)
2044 (when (and (boundp 'org-emphasis-alist)
2045 (boundp 'org-emphasis-regexp-components)
2046 org-emphasis-alist org-emphasis-regexp-components)
2047 (let* ((e org-emphasis-regexp-components)
2048 (pre (car e))
2049 (post (nth 1 e))
2050 (border (nth 2 e))
2051 (body (nth 3 e))
2052 (nl (nth 4 e))
2053 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2054 (body1 (concat body "*?"))
2055 (markers (mapconcat 'car org-emphasis-alist ""))
2056 (vmarkers (mapconcat
2057 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2058 org-emphasis-alist "")))
2059 ;; make sure special characters appear at the right position in the class
2060 (if (string-match "\\^" markers)
2061 (setq markers (concat (replace-match "" t t markers) "^")))
2062 (if (string-match "-" markers)
2063 (setq markers (concat (replace-match "" t t markers) "-")))
2064 (if (string-match "\\^" vmarkers)
2065 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2066 (if (string-match "-" vmarkers)
2067 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2068 (if (> nl 0)
2069 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2070 (int-to-string nl) "\\}")))
2071 ;; Make the regexp
2072 (setq org-emph-re
2073 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2074 "\\("
2075 "\\([" markers "]\\)"
2076 "\\("
2077 "[^" border "]\\|"
2078 "[^" border (if (and nil stacked) markers) "]"
2079 body1
2080 "[^" border (if (and nil stacked) markers) "]"
2081 "\\)"
2082 "\\3\\)"
2083 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2084 (setq org-verbatim-re
2085 (concat "\\([" pre "]\\|^\\)"
2086 "\\("
2087 "\\([" vmarkers "]\\)"
2088 "\\("
2089 "[^" border "]\\|"
2090 "[^" border "]"
2091 body1
2092 "[^" border "]"
2093 "\\)"
2094 "\\3\\)"
2095 "\\([" post "]\\|$\\)")))))
2097 (defcustom org-emphasis-regexp-components
2098 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2099 "Components used to build the regular expression for emphasis.
2100 This is a list with 6 entries. Terminology: In an emphasis string
2101 like \" *strong word* \", we call the initial space PREMATCH, the final
2102 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2103 and \"trong wor\" is the body. The different components in this variable
2104 specify what is allowed/forbidden in each part:
2106 pre Chars allowed as prematch. Beginning of line will be allowed too.
2107 post Chars allowed as postmatch. End of line will be allowed too.
2108 border The chars *forbidden* as border characters.
2109 body-regexp A regexp like \".\" to match a body character. Don't use
2110 non-shy groups here, and don't allow newline here.
2111 newline The maximum number of newlines allowed in an emphasis exp.
2113 Use customize to modify this, or restart Emacs after changing it."
2114 :group 'org-font-lock
2115 :set 'org-set-emph-re
2116 :type '(list
2117 (sexp :tag "Allowed chars in pre ")
2118 (sexp :tag "Allowed chars in post ")
2119 (sexp :tag "Forbidden chars in border ")
2120 (sexp :tag "Regexp for body ")
2121 (integer :tag "number of newlines allowed")
2122 (option (boolean :tag "Stacking (DISABLED) "))))
2124 (defcustom org-emphasis-alist
2125 `(("*" bold "<b>" "</b>")
2126 ("/" italic "<i>" "</i>")
2127 ("_" underline "<u>" "</u>")
2128 ("=" org-code "<code>" "</code>" verbatim)
2129 ("~" org-verbatim "" "" verbatim)
2130 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2131 "<del>" "</del>")
2133 "Special syntax for emphasized text.
2134 Text starting and ending with a special character will be emphasized, for
2135 example *bold*, _underlined_ and /italic/. This variable sets the marker
2136 characters, the face to be used by font-lock for highlighting in Org-mode
2137 Emacs buffers, and the HTML tags to be used for this.
2138 Use customize to modify this, or restart Emacs after changing it."
2139 :group 'org-font-lock
2140 :set 'org-set-emph-re
2141 :type '(repeat
2142 (list
2143 (string :tag "Marker character")
2144 (choice
2145 (face :tag "Font-lock-face")
2146 (plist :tag "Face property list"))
2147 (string :tag "HTML start tag")
2148 (string :tag "HTML end tag")
2149 (option (const verbatim)))))
2151 ;;; Miscellaneous options
2153 (defgroup org-completion nil
2154 "Completion in Org-mode."
2155 :tag "Org Completion"
2156 :group 'org)
2158 (defcustom org-completion-fallback-command 'hippie-expand
2159 "The expansion command called by \\[org-complete] in normal context.
2160 Normal means, no org-mode-specific context."
2161 :group 'org-completion
2162 :type 'function)
2164 ;;; Functions and variables from ther packages
2165 ;; Declared here to avoid compiler warnings
2167 ;; XEmacs only
2168 (defvar outline-mode-menu-heading)
2169 (defvar outline-mode-menu-show)
2170 (defvar outline-mode-menu-hide)
2171 (defvar zmacs-regions) ; XEmacs regions
2173 ;; Emacs only
2174 (defvar mark-active)
2176 ;; Various packages
2177 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2178 (declare-function calendar-forward-day "cal-move" (arg))
2179 (declare-function calendar-goto-date "cal-move" (date))
2180 (declare-function calendar-goto-today "cal-move" ())
2181 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2182 (defvar calc-embedded-close-formula)
2183 (defvar calc-embedded-open-formula)
2184 (declare-function cdlatex-tab "ext:cdlatex" ())
2185 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2186 (defvar font-lock-unfontify-region-function)
2187 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2188 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2189 (defvar iswitchb-temp-buflist)
2190 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2191 (declare-function org-agenda-skip "org-agenda" ())
2192 (declare-function org-format-agenda-item "org-agenda"
2193 (extra txt &optional category tags dotime noprefix remove-re))
2194 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2195 (declare-function org-agenda-change-all-lines "org-agenda"
2196 (newhead hdmarker &optional fixface))
2197 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2198 (declare-function org-agenda-maybe-redo "org-agenda" ())
2199 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2200 (beg end))
2201 (declare-function parse-time-string "parse-time" (string))
2202 (declare-function remember "remember" (&optional initial))
2203 (declare-function remember-buffer-desc "remember" ())
2204 (declare-function remember-finalize "remember" ())
2205 (defvar remember-save-after-remembering)
2206 (defvar remember-data-file)
2207 (defvar remember-register)
2208 (defvar remember-buffer)
2209 (defvar remember-handler-functions)
2210 (defvar remember-annotation-functions)
2211 (defvar texmathp-why)
2212 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2213 (declare-function table--at-cell-p "table" (position &optional object at-column))
2215 (defvar w3m-current-url)
2216 (defvar w3m-current-title)
2218 (defvar org-latex-regexps)
2220 ;;; Autoload and prepare some org modules
2222 ;; Some table stuff that needs to be defined here, because it is used
2223 ;; by the functions setting up org-mode or checking for table context.
2225 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2226 "Detects an org-type or table-type table.")
2227 (defconst org-table-line-regexp "^[ \t]*|"
2228 "Detects an org-type table line.")
2229 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2230 "Detects an org-type table line.")
2231 (defconst org-table-hline-regexp "^[ \t]*|-"
2232 "Detects an org-type table hline.")
2233 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2234 "Detects a table-type table hline.")
2235 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2236 "Searching from within a table (any type) this finds the first line
2237 outside the table.")
2239 ;; Autoload the functions in org-table.el that are needed by functions here.
2241 (eval-and-compile
2242 (org-autoload "org-table"
2243 '(org-table-align org-table-begin org-table-blank-field
2244 org-table-convert org-table-convert-region org-table-copy-down
2245 org-table-copy-region org-table-create
2246 org-table-create-or-convert-from-region
2247 org-table-create-with-table.el org-table-current-dline
2248 org-table-cut-region org-table-delete-column org-table-edit-field
2249 org-table-edit-formulas org-table-end org-table-eval-formula
2250 org-table-export org-table-field-info
2251 org-table-get-stored-formulas org-table-goto-column
2252 org-table-hline-and-move org-table-import org-table-insert-column
2253 org-table-insert-hline org-table-insert-row org-table-iterate
2254 org-table-justify-field-maybe org-table-kill-row
2255 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2256 org-table-move-column org-table-move-column-left
2257 org-table-move-column-right org-table-move-row
2258 org-table-move-row-down org-table-move-row-up
2259 org-table-next-field org-table-next-row org-table-paste-rectangle
2260 org-table-previous-field org-table-recalculate
2261 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2262 org-table-toggle-coordinate-overlays
2263 org-table-toggle-formula-debugger org-table-wrap-region
2264 orgtbl-mode turn-on-orgtbl)))
2266 (defun org-at-table-p (&optional table-type)
2267 "Return t if the cursor is inside an org-type table.
2268 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2269 (if org-enable-table-editor
2270 (save-excursion
2271 (beginning-of-line 1)
2272 (looking-at (if table-type org-table-any-line-regexp
2273 org-table-line-regexp)))
2274 nil))
2275 (defsubst org-table-p () (org-at-table-p))
2277 (defun org-at-table.el-p ()
2278 "Return t if and only if we are at a table.el table."
2279 (and (org-at-table-p 'any)
2280 (save-excursion
2281 (goto-char (org-table-begin 'any))
2282 (looking-at org-table1-hline-regexp))))
2283 (defun org-table-recognize-table.el ()
2284 "If there is a table.el table nearby, recognize it and move into it."
2285 (if org-table-tab-recognizes-table.el
2286 (if (org-at-table.el-p)
2287 (progn
2288 (beginning-of-line 1)
2289 (if (looking-at org-table-dataline-regexp)
2291 (if (looking-at org-table1-hline-regexp)
2292 (progn
2293 (beginning-of-line 2)
2294 (if (looking-at org-table-any-border-regexp)
2295 (beginning-of-line -1)))))
2296 (if (re-search-forward "|" (org-table-end t) t)
2297 (progn
2298 (require 'table)
2299 (if (table--at-cell-p (point))
2301 (message "recognizing table.el table...")
2302 (table-recognize-table)
2303 (message "recognizing table.el table...done")))
2304 (error "This should not happen..."))
2306 nil)
2307 nil))
2309 (defun org-at-table-hline-p ()
2310 "Return t if the cursor is inside a hline in a table."
2311 (if org-enable-table-editor
2312 (save-excursion
2313 (beginning-of-line 1)
2314 (looking-at org-table-hline-regexp))
2315 nil))
2317 (defvar org-table-clean-did-remove-column nil)
2319 (defun org-table-map-tables (function)
2320 "Apply FUNCTION to the start of all tables in the buffer."
2321 (save-excursion
2322 (save-restriction
2323 (widen)
2324 (goto-char (point-min))
2325 (while (re-search-forward org-table-any-line-regexp nil t)
2326 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2327 (beginning-of-line 1)
2328 (if (looking-at org-table-line-regexp)
2329 (save-excursion (funcall function)))
2330 (re-search-forward org-table-any-border-regexp nil 1))))
2331 (message "Mapping tables: done"))
2333 ;; Declare and autoload functions from org-exp.el
2335 (declare-function org-default-export-plist "org-exp")
2336 (declare-function org-infile-export-plist "org-exp")
2337 (declare-function org-get-current-options "org-exp")
2338 (eval-and-compile
2339 (org-autoload "org-exp"
2340 '(org-export org-export-as-ascii org-export-visible
2341 org-insert-export-options-template org-export-as-html-and-open
2342 org-export-as-html-batch org-export-as-html-to-buffer
2343 org-replace-region-by-html org-export-region-as-html
2344 org-export-as-html org-export-icalendar-this-file
2345 org-export-icalendar-all-agenda-files
2346 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2348 ;; Declare and autoload functions from org-exp.el
2350 (eval-and-compile
2351 (org-autoload "org-exp"
2352 '(org-agenda org-agenda-list org-search-view
2353 org-todo-list org-tags-view org-agenda-list-stuck-projects
2354 org-diary org-agenda-to-appt)))
2356 ;; Autoload org-remember
2358 (eval-and-compile
2359 (org-autoload "org-remember"
2360 '(org-remember-insinuate org-remember-annotation
2361 org-remember-apply-template org-remember org-remember-handler)))
2363 ;; Autoload org-clock.el
2366 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2367 (beg end))
2368 (defvar org-clock-marker (make-marker)
2369 "Marker recording the last clock-in.")
2371 (eval-and-compile
2372 (org-autoload
2373 "org-clock"
2374 '(org-clock-in org-clock-out org-clock-cancel
2375 org-clock-goto org-clock-sum org-clock-display
2376 org-remove-clock-overlays org-clock-report
2377 org-clocktable-shift org-dblock-write:clocktable
2378 org-get-clocktable)))
2380 (defun org-clock-update-time-maybe ()
2381 "If this is a CLOCK line, update it and return t.
2382 Otherwise, return nil."
2383 (interactive)
2384 (save-excursion
2385 (beginning-of-line 1)
2386 (skip-chars-forward " \t")
2387 (when (looking-at org-clock-string)
2388 (let ((re (concat "[ \t]*" org-clock-string
2389 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2390 "\\([ \t]*=>.*\\)?"))
2391 ts te h m s)
2392 (if (not (looking-at re))
2394 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2395 (end-of-line 1)
2396 (setq ts (match-string 1)
2397 te (match-string 2))
2398 (setq s (- (time-to-seconds
2399 (apply 'encode-time (org-parse-time-string te)))
2400 (time-to-seconds
2401 (apply 'encode-time (org-parse-time-string ts))))
2402 h (floor (/ s 3600))
2403 s (- s (* 3600 h))
2404 m (floor (/ s 60))
2405 s (- s (* 60 s)))
2406 (insert " => " (format "%2d:%02d" h m))
2407 t)))))
2409 (defun org-check-running-clock ()
2410 "Check if the current buffer contains the running clock.
2411 If yes, offer to stop it and to save the buffer with the changes."
2412 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2413 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2414 (buffer-name))))
2415 (org-clock-out)
2416 (when (y-or-n-p "Save changed buffer?")
2417 (save-buffer))))
2419 (defun org-clocktable-try-shift (dir n)
2420 "Check if this line starts a clock table, if yes, shift the time block."
2421 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2422 (org-clocktable-shift dir n)))
2424 ;; Autoload archiving code
2425 ;; The stuff that is needed for cycling and tags has to be defined here.
2427 (defgroup org-archive nil
2428 "Options concerning archiving in Org-mode."
2429 :tag "Org Archive"
2430 :group 'org-structure)
2432 (defcustom org-archive-location "%s_archive::"
2433 "The location where subtrees should be archived.
2435 Otherwise, the value of this variable is a string, consisting of two
2436 parts, separated by a double-colon.
2438 The first part is a file name - when omitted, archiving happens in the same
2439 file. %s will be replaced by the current file name (without directory part).
2440 Archiving to a different file is useful to keep archived entries from
2441 contributing to the Org-mode Agenda.
2443 The part after the double colon is a headline. The archived entries will be
2444 filed under that headline. When omitted, the subtrees are simply filed away
2445 at the end of the file, as top-level entries.
2447 Here are a few examples:
2448 \"%s_archive::\"
2449 If the current file is Projects.org, archive in file
2450 Projects.org_archive, as top-level trees. This is the default.
2452 \"::* Archived Tasks\"
2453 Archive in the current file, under the top-level headline
2454 \"* Archived Tasks\".
2456 \"~/org/archive.org::\"
2457 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2459 \"basement::** Finished Tasks\"
2460 Archive in file ./basement (relative path), as level 3 trees
2461 below the level 2 heading \"** Finished Tasks\".
2463 You may set this option on a per-file basis by adding to the buffer a
2464 line like
2466 #+ARCHIVE: basement::** Finished Tasks
2468 You may also define it locally for a subtree by setting an ARCHIVE property
2469 in the entry. If such a property is found in an entry, or anywhere up
2470 the hierarchy, it will be used."
2471 :group 'org-archive
2472 :type 'string)
2474 (defcustom org-archive-tag "ARCHIVE"
2475 "The tag that marks a subtree as archived.
2476 An archived subtree does not open during visibility cycling, and does
2477 not contribute to the agenda listings.
2478 After changing this, font-lock must be restarted in the relevant buffers to
2479 get the proper fontification."
2480 :group 'org-archive
2481 :group 'org-keywords
2482 :type 'string)
2484 (defcustom org-agenda-skip-archived-trees t
2485 "Non-nil means, the agenda will skip any items located in archived trees.
2486 An archived tree is a tree marked with the tag ARCHIVE."
2487 :group 'org-archive
2488 :group 'org-agenda-skip
2489 :type 'boolean)
2491 (defcustom org-cycle-open-archived-trees nil
2492 "Non-nil means, `org-cycle' will open archived trees.
2493 An archived tree is a tree marked with the tag ARCHIVE.
2494 When nil, archived trees will stay folded. You can still open them with
2495 normal outline commands like `show-all', but not with the cycling commands."
2496 :group 'org-archive
2497 :group 'org-cycle
2498 :type 'boolean)
2500 (defcustom org-sparse-tree-open-archived-trees nil
2501 "Non-nil means sparse tree construction shows matches in archived trees.
2502 When nil, matches in these trees are highlighted, but the trees are kept in
2503 collapsed state."
2504 :group 'org-archive
2505 :group 'org-sparse-trees
2506 :type 'boolean)
2508 (defun org-cycle-hide-archived-subtrees (state)
2509 "Re-hide all archived subtrees after a visibility state change."
2510 (when (and (not org-cycle-open-archived-trees)
2511 (not (memq state '(overview folded))))
2512 (save-excursion
2513 (let* ((globalp (memq state '(contents all)))
2514 (beg (if globalp (point-min) (point)))
2515 (end (if globalp (point-max) (org-end-of-subtree t))))
2516 (org-hide-archived-subtrees beg end)
2517 (goto-char beg)
2518 (if (looking-at (concat ".*:" org-archive-tag ":"))
2519 (message "%s" (substitute-command-keys
2520 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2522 (defun org-force-cycle-archived ()
2523 "Cycle subtree even if it is archived."
2524 (interactive)
2525 (setq this-command 'org-cycle)
2526 (let ((org-cycle-open-archived-trees t))
2527 (call-interactively 'org-cycle)))
2529 (defun org-hide-archived-subtrees (beg end)
2530 "Re-hide all archived subtrees after a visibility state change."
2531 (save-excursion
2532 (let* ((re (concat ":" org-archive-tag ":")))
2533 (goto-char beg)
2534 (while (re-search-forward re end t)
2535 (and (org-on-heading-p) (hide-subtree))
2536 (org-end-of-subtree t)))))
2538 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2540 (eval-and-compile
2541 (org-autoload "org-archive"
2542 '(org-add-archive-files org-archive-subtree
2543 org-archive-to-archive-sibling org-toggle-archive-tag)))
2545 ;; Autoload Column View Code
2547 (declare-function org-columns-number-to-string "org-colview")
2548 (declare-function org-columns-get-format-and-top-level "org-colview")
2549 (declare-function org-columns-compute "org-colview")
2551 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2552 '(org-columns-number-to-string org-columns-get-format-and-top-level
2553 org-columns-compute org-agenda-columns org-columns-remove-overlays
2554 org-columns org-insert-columns-dblock))
2556 ;;; Variables for pre-computed regular expressions, all buffer local
2558 (defvar org-drawer-regexp nil
2559 "Matches first line of a hidden block.")
2560 (make-variable-buffer-local 'org-drawer-regexp)
2561 (defvar org-todo-regexp nil
2562 "Matches any of the TODO state keywords.")
2563 (make-variable-buffer-local 'org-todo-regexp)
2564 (defvar org-not-done-regexp nil
2565 "Matches any of the TODO state keywords except the last one.")
2566 (make-variable-buffer-local 'org-not-done-regexp)
2567 (defvar org-todo-line-regexp nil
2568 "Matches a headline and puts TODO state into group 2 if present.")
2569 (make-variable-buffer-local 'org-todo-line-regexp)
2570 (defvar org-complex-heading-regexp nil
2571 "Matches a headline and puts everything into groups:
2572 group 1: the stars
2573 group 2: The todo keyword, maybe
2574 group 3: Priority cookie
2575 group 4: True headline
2576 group 5: Tags")
2577 (make-variable-buffer-local 'org-complex-heading-regexp)
2578 (defvar org-todo-line-tags-regexp nil
2579 "Matches a headline and puts TODO state into group 2 if present.
2580 Also put tags into group 4 if tags are present.")
2581 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2582 (defvar org-nl-done-regexp nil
2583 "Matches newline followed by a headline with the DONE keyword.")
2584 (make-variable-buffer-local 'org-nl-done-regexp)
2585 (defvar org-looking-at-done-regexp nil
2586 "Matches the DONE keyword a point.")
2587 (make-variable-buffer-local 'org-looking-at-done-regexp)
2588 (defvar org-ds-keyword-length 12
2589 "Maximum length of the Deadline and SCHEDULED keywords.")
2590 (make-variable-buffer-local 'org-ds-keyword-length)
2591 (defvar org-deadline-regexp nil
2592 "Matches the DEADLINE keyword.")
2593 (make-variable-buffer-local 'org-deadline-regexp)
2594 (defvar org-deadline-time-regexp nil
2595 "Matches the DEADLINE keyword together with a time stamp.")
2596 (make-variable-buffer-local 'org-deadline-time-regexp)
2597 (defvar org-deadline-line-regexp nil
2598 "Matches the DEADLINE keyword and the rest of the line.")
2599 (make-variable-buffer-local 'org-deadline-line-regexp)
2600 (defvar org-scheduled-regexp nil
2601 "Matches the SCHEDULED keyword.")
2602 (make-variable-buffer-local 'org-scheduled-regexp)
2603 (defvar org-scheduled-time-regexp nil
2604 "Matches the SCHEDULED keyword together with a time stamp.")
2605 (make-variable-buffer-local 'org-scheduled-time-regexp)
2606 (defvar org-closed-time-regexp nil
2607 "Matches the CLOSED keyword together with a time stamp.")
2608 (make-variable-buffer-local 'org-closed-time-regexp)
2610 (defvar org-keyword-time-regexp nil
2611 "Matches any of the 4 keywords, together with the time stamp.")
2612 (make-variable-buffer-local 'org-keyword-time-regexp)
2613 (defvar org-keyword-time-not-clock-regexp nil
2614 "Matches any of the 3 keywords, together with the time stamp.")
2615 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2616 (defvar org-maybe-keyword-time-regexp nil
2617 "Matches a timestamp, possibly preceeded by a keyword.")
2618 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2619 (defvar org-planning-or-clock-line-re nil
2620 "Matches a line with planning or clock info.")
2621 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2623 (defconst org-plain-time-of-day-regexp
2624 (concat
2625 "\\(\\<[012]?[0-9]"
2626 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2627 "\\(--?"
2628 "\\(\\<[012]?[0-9]"
2629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2630 "\\)?")
2631 "Regular expression to match a plain time or time range.
2632 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2633 groups carry important information:
2634 0 the full match
2635 1 the first time, range or not
2636 8 the second time, if it is a range.")
2638 (defconst org-plain-time-extension-regexp
2639 (concat
2640 "\\(\\<[012]?[0-9]"
2641 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2642 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2643 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2644 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2645 groups carry important information:
2646 0 the full match
2647 7 hours of duration
2648 9 minutes of duration")
2650 (defconst org-stamp-time-of-day-regexp
2651 (concat
2652 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2653 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2654 "\\(--?"
2655 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2656 "Regular expression to match a timestamp time or time range.
2657 After a match, the following groups carry important information:
2658 0 the full match
2659 1 date plus weekday, for backreferencing to make sure both times on same day
2660 2 the first time, range or not
2661 4 the second time, if it is a range.")
2663 (defconst org-startup-options
2664 '(("fold" org-startup-folded t)
2665 ("overview" org-startup-folded t)
2666 ("nofold" org-startup-folded nil)
2667 ("showall" org-startup-folded nil)
2668 ("content" org-startup-folded content)
2669 ("hidestars" org-hide-leading-stars t)
2670 ("showstars" org-hide-leading-stars nil)
2671 ("odd" org-odd-levels-only t)
2672 ("oddeven" org-odd-levels-only nil)
2673 ("align" org-startup-align-all-tables t)
2674 ("noalign" org-startup-align-all-tables nil)
2675 ("customtime" org-display-custom-times t)
2676 ("logdone" org-log-done time)
2677 ("lognotedone" org-log-done note)
2678 ("nologdone" org-log-done nil)
2679 ("lognoteclock-out" org-log-note-clock-out t)
2680 ("nolognoteclock-out" org-log-note-clock-out nil)
2681 ("logrepeat" org-log-repeat state)
2682 ("lognoterepeat" org-log-repeat note)
2683 ("nologrepeat" org-log-repeat nil)
2684 ("constcgs" constants-unit-system cgs)
2685 ("constSI" constants-unit-system SI))
2686 "Variable associated with STARTUP options for org-mode.
2687 Each element is a list of three items: The startup options as written
2688 in the #+STARTUP line, the corresponding variable, and the value to
2689 set this variable to if the option is found. An optional forth element PUSH
2690 means to push this value onto the list in the variable.")
2692 (defun org-set-regexps-and-options ()
2693 "Precompute regular expressions for current buffer."
2694 (when (org-mode-p)
2695 (org-set-local 'org-todo-kwd-alist nil)
2696 (org-set-local 'org-todo-key-alist nil)
2697 (org-set-local 'org-todo-key-trigger nil)
2698 (org-set-local 'org-todo-keywords-1 nil)
2699 (org-set-local 'org-done-keywords nil)
2700 (org-set-local 'org-todo-heads nil)
2701 (org-set-local 'org-todo-sets nil)
2702 (org-set-local 'org-todo-log-states nil)
2703 (let ((re (org-make-options-regexp
2704 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2705 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2706 "CONSTANTS" "PROPERTY" "DRAWERS")))
2707 (splitre "[ \t]+")
2708 kwds kws0 kwsa key log value cat arch tags const links hw dws
2709 tail sep kws1 prio props drawers)
2710 (save-excursion
2711 (save-restriction
2712 (widen)
2713 (goto-char (point-min))
2714 (while (re-search-forward re nil t)
2715 (setq key (upcase (match-string 1))
2716 value (org-match-string-no-properties 2))
2717 (cond
2718 ((equal key "CATEGORY")
2719 (if (string-match "[ \t]+$" value)
2720 (setq value (replace-match "" t t value)))
2721 (setq cat value))
2722 ((member key '("SEQ_TODO" "TODO"))
2723 (push (cons 'sequence (org-split-string value splitre)) kwds))
2724 ((equal key "TYP_TODO")
2725 (push (cons 'type (org-split-string value splitre)) kwds))
2726 ((equal key "TAGS")
2727 (setq tags (append tags (org-split-string value splitre))))
2728 ((equal key "COLUMNS")
2729 (org-set-local 'org-columns-default-format value))
2730 ((equal key "LINK")
2731 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2732 (push (cons (match-string 1 value)
2733 (org-trim (match-string 2 value)))
2734 links)))
2735 ((equal key "PRIORITIES")
2736 (setq prio (org-split-string value " +")))
2737 ((equal key "PROPERTY")
2738 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2739 (push (cons (match-string 1 value) (match-string 2 value))
2740 props)))
2741 ((equal key "DRAWERS")
2742 (setq drawers (org-split-string value splitre)))
2743 ((equal key "CONSTANTS")
2744 (setq const (append const (org-split-string value splitre))))
2745 ((equal key "STARTUP")
2746 (let ((opts (org-split-string value splitre))
2747 l var val)
2748 (while (setq l (pop opts))
2749 (when (setq l (assoc l org-startup-options))
2750 (setq var (nth 1 l) val (nth 2 l))
2751 (if (not (nth 3 l))
2752 (set (make-local-variable var) val)
2753 (if (not (listp (symbol-value var)))
2754 (set (make-local-variable var) nil))
2755 (set (make-local-variable var) (symbol-value var))
2756 (add-to-list var val))))))
2757 ((equal key "ARCHIVE")
2758 (string-match " *$" value)
2759 (setq arch (replace-match "" t t value))
2760 (remove-text-properties 0 (length arch)
2761 '(face t fontified t) arch)))
2763 (when cat
2764 (org-set-local 'org-category (intern cat))
2765 (push (cons "CATEGORY" cat) props))
2766 (when prio
2767 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2768 (setq prio (mapcar 'string-to-char prio))
2769 (org-set-local 'org-highest-priority (nth 0 prio))
2770 (org-set-local 'org-lowest-priority (nth 1 prio))
2771 (org-set-local 'org-default-priority (nth 2 prio)))
2772 (and props (org-set-local 'org-local-properties (nreverse props)))
2773 (and drawers (org-set-local 'org-drawers drawers))
2774 (and arch (org-set-local 'org-archive-location arch))
2775 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2776 ;; Process the TODO keywords
2777 (unless kwds
2778 ;; Use the global values as if they had been given locally.
2779 (setq kwds (default-value 'org-todo-keywords))
2780 (if (stringp (car kwds))
2781 (setq kwds (list (cons org-todo-interpretation
2782 (default-value 'org-todo-keywords)))))
2783 (setq kwds (reverse kwds)))
2784 (setq kwds (nreverse kwds))
2785 (let (inter kws kw)
2786 (while (setq kws (pop kwds))
2787 (setq inter (pop kws) sep (member "|" kws)
2788 kws0 (delete "|" (copy-sequence kws))
2789 kwsa nil
2790 kws1 (mapcar
2791 (lambda (x)
2792 ;; 1 2
2793 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2794 (progn
2795 (setq kw (match-string 1 x)
2796 key (and (match-end 2) (match-string 2 x))
2797 log (org-extract-log-state-settings x))
2798 (push (cons kw (and key (string-to-char key))) kwsa)
2799 (and log (push log org-todo-log-states))
2801 (error "Invalid TODO keyword %s" x)))
2802 kws0)
2803 kwsa (if kwsa (append '((:startgroup))
2804 (nreverse kwsa)
2805 '((:endgroup))))
2806 hw (car kws1)
2807 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2808 tail (list inter hw (car dws) (org-last dws)))
2809 (add-to-list 'org-todo-heads hw 'append)
2810 (push kws1 org-todo-sets)
2811 (setq org-done-keywords (append org-done-keywords dws nil))
2812 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2813 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2814 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2815 (setq org-todo-sets (nreverse org-todo-sets)
2816 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2817 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2818 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2819 ;; Process the constants
2820 (when const
2821 (let (e cst)
2822 (while (setq e (pop const))
2823 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2824 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2825 (setq org-table-formula-constants-local cst)))
2827 ;; Process the tags.
2828 (when tags
2829 (let (e tgs)
2830 (while (setq e (pop tags))
2831 (cond
2832 ((equal e "{") (push '(:startgroup) tgs))
2833 ((equal e "}") (push '(:endgroup) tgs))
2834 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2835 (push (cons (match-string 1 e)
2836 (string-to-char (match-string 2 e)))
2837 tgs))
2838 (t (push (list e) tgs))))
2839 (org-set-local 'org-tag-alist nil)
2840 (while (setq e (pop tgs))
2841 (or (and (stringp (car e))
2842 (assoc (car e) org-tag-alist))
2843 (push e org-tag-alist))))))
2845 ;; Compute the regular expressions and other local variables
2846 (if (not org-done-keywords)
2847 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2848 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2849 (length org-scheduled-string)
2850 (length org-clock-string)
2851 (length org-closed-string)))
2852 org-drawer-regexp
2853 (concat "^[ \t]*:\\("
2854 (mapconcat 'regexp-quote org-drawers "\\|")
2855 "\\):[ \t]*$")
2856 org-not-done-keywords
2857 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2858 org-todo-regexp
2859 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2860 "\\|") "\\)\\>")
2861 org-not-done-regexp
2862 (concat "\\<\\("
2863 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2864 "\\)\\>")
2865 org-todo-line-regexp
2866 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2867 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2868 "\\)\\>\\)?[ \t]*\\(.*\\)")
2869 org-complex-heading-regexp
2870 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2871 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2872 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2873 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2874 org-nl-done-regexp
2875 (concat "\n\\*+[ \t]+"
2876 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2877 "\\)" "\\>")
2878 org-todo-line-tags-regexp
2879 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2880 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2881 (org-re
2882 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2883 org-looking-at-done-regexp
2884 (concat "^" "\\(?:"
2885 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2886 "\\>")
2887 org-deadline-regexp (concat "\\<" org-deadline-string)
2888 org-deadline-time-regexp
2889 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2890 org-deadline-line-regexp
2891 (concat "\\<\\(" org-deadline-string "\\).*")
2892 org-scheduled-regexp
2893 (concat "\\<" org-scheduled-string)
2894 org-scheduled-time-regexp
2895 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2896 org-closed-time-regexp
2897 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2898 org-keyword-time-regexp
2899 (concat "\\<\\(" org-scheduled-string
2900 "\\|" org-deadline-string
2901 "\\|" org-closed-string
2902 "\\|" org-clock-string "\\)"
2903 " *[[<]\\([^]>]+\\)[]>]")
2904 org-keyword-time-not-clock-regexp
2905 (concat "\\<\\(" org-scheduled-string
2906 "\\|" org-deadline-string
2907 "\\|" org-closed-string
2908 "\\)"
2909 " *[[<]\\([^]>]+\\)[]>]")
2910 org-maybe-keyword-time-regexp
2911 (concat "\\(\\<\\(" org-scheduled-string
2912 "\\|" org-deadline-string
2913 "\\|" org-closed-string
2914 "\\|" org-clock-string "\\)\\)?"
2915 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2916 org-planning-or-clock-line-re
2917 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2918 "\\|" org-deadline-string
2919 "\\|" org-closed-string "\\|" org-clock-string
2920 "\\)\\>\\)")
2922 (org-compute-latex-and-specials-regexp)
2923 (org-set-font-lock-defaults)))
2925 (defun org-extract-log-state-settings (x)
2926 "Extract the log state setting from a TODO keyword string.
2927 This will extract info from a string like \"WAIT(w@/!)\"."
2928 (let (kw key log1 log2)
2929 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2930 (setq kw (match-string 1 x)
2931 key (and (match-end 2) (match-string 2 x))
2932 log1 (and (match-end 3) (match-string 3 x))
2933 log2 (and (match-end 4) (match-string 4 x)))
2934 (and (or log1 log2)
2935 (list kw
2936 (and log1 (if (equal log1 "!") 'time 'note))
2937 (and log2 (if (equal log2 "!") 'time 'note)))))))
2939 (defun org-remove-keyword-keys (list)
2940 "Remove a pair of parenthesis at the end of each string in LIST."
2941 (mapcar (lambda (x)
2942 (if (string-match "(.*)$" x)
2943 (substring x 0 (match-beginning 0))
2945 list))
2947 ;; FIXME: this could be done much better, using second characters etc.
2948 (defun org-assign-fast-keys (alist)
2949 "Assign fast keys to a keyword-key alist.
2950 Respect keys that are already there."
2951 (let (new e k c c1 c2 (char ?a))
2952 (while (setq e (pop alist))
2953 (cond
2954 ((equal e '(:startgroup)) (push e new))
2955 ((equal e '(:endgroup)) (push e new))
2957 (setq k (car e) c2 nil)
2958 (if (cdr e)
2959 (setq c (cdr e))
2960 ;; automatically assign a character.
2961 (setq c1 (string-to-char
2962 (downcase (substring
2963 k (if (= (string-to-char k) ?@) 1 0)))))
2964 (if (or (rassoc c1 new) (rassoc c1 alist))
2965 (while (or (rassoc char new) (rassoc char alist))
2966 (setq char (1+ char)))
2967 (setq c2 c1))
2968 (setq c (or c2 char)))
2969 (push (cons k c) new))))
2970 (nreverse new)))
2972 ;;; Some variables used in various places
2974 (defvar org-window-configuration nil
2975 "Used in various places to store a window configuration.")
2976 (defvar org-finish-function nil
2977 "Function to be called when `C-c C-c' is used.
2978 This is for getting out of special buffers like remember.")
2981 ;; FIXME: Occasionally check by commenting these, to make sure
2982 ;; no other functions uses these, forgetting to let-bind them.
2983 (defvar entry)
2984 (defvar state)
2985 (defvar last-state)
2986 (defvar date)
2987 (defvar description)
2989 ;; Defined somewhere in this file, but used before definition.
2990 (defvar org-html-entities)
2991 (defvar org-struct-menu)
2992 (defvar org-org-menu)
2993 (defvar org-tbl-menu)
2994 (defvar org-agenda-keymap)
2996 ;;;; Define the Org-mode
2998 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2999 (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."))
3002 ;; We use a before-change function to check if a table might need
3003 ;; an update.
3004 (defvar org-table-may-need-update t
3005 "Indicates that a table might need an update.
3006 This variable is set by `org-before-change-function'.
3007 `org-table-align' sets it back to nil.")
3008 (defun org-before-change-function (beg end)
3009 "Every change indicates that a table might need an update."
3010 (setq org-table-may-need-update t))
3011 (defvar org-mode-map)
3012 (defvar org-mode-hook nil)
3013 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3014 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3015 (defvar org-table-buffer-is-an nil)
3016 (defconst org-outline-regexp "\\*+ ")
3018 ;;;###autoload
3019 (define-derived-mode org-mode outline-mode "Org"
3020 "Outline-based notes management and organizer, alias
3021 \"Carsten's outline-mode for keeping track of everything.\"
3023 Org-mode develops organizational tasks around a NOTES file which
3024 contains information about projects as plain text. Org-mode is
3025 implemented on top of outline-mode, which is ideal to keep the content
3026 of large files well structured. It supports ToDo items, deadlines and
3027 time stamps, which magically appear in the diary listing of the Emacs
3028 calendar. Tables are easily created with a built-in table editor.
3029 Plain text URL-like links connect to websites, emails (VM), Usenet
3030 messages (Gnus), BBDB entries, and any files related to the project.
3031 For printing and sharing of notes, an Org-mode file (or a part of it)
3032 can be exported as a structured ASCII or HTML file.
3034 The following commands are available:
3036 \\{org-mode-map}"
3038 ;; Get rid of Outline menus, they are not needed
3039 ;; Need to do this here because define-derived-mode sets up
3040 ;; the keymap so late. Still, it is a waste to call this each time
3041 ;; we switch another buffer into org-mode.
3042 (if (featurep 'xemacs)
3043 (when (boundp 'outline-mode-menu-heading)
3044 ;; Assume this is Greg's port, it used easymenu
3045 (easy-menu-remove outline-mode-menu-heading)
3046 (easy-menu-remove outline-mode-menu-show)
3047 (easy-menu-remove outline-mode-menu-hide))
3048 (define-key org-mode-map [menu-bar headings] 'undefined)
3049 (define-key org-mode-map [menu-bar hide] 'undefined)
3050 (define-key org-mode-map [menu-bar show] 'undefined))
3052 (org-load-modules-maybe)
3053 (easy-menu-add org-org-menu)
3054 (easy-menu-add org-tbl-menu)
3055 (org-install-agenda-files-menu)
3056 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3057 (org-add-to-invisibility-spec '(org-cwidth))
3058 (when (featurep 'xemacs)
3059 (org-set-local 'line-move-ignore-invisible t))
3060 (org-set-local 'outline-regexp org-outline-regexp)
3061 (org-set-local 'outline-level 'org-outline-level)
3062 (when (and org-ellipsis
3063 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3064 (fboundp 'make-glyph-code))
3065 (unless org-display-table
3066 (setq org-display-table (make-display-table)))
3067 (set-display-table-slot
3068 org-display-table 4
3069 (vconcat (mapcar
3070 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3071 org-ellipsis)))
3072 (if (stringp org-ellipsis) org-ellipsis "..."))))
3073 (setq buffer-display-table org-display-table))
3074 (org-set-regexps-and-options)
3075 ;; Calc embedded
3076 (org-set-local 'calc-embedded-open-mode "# ")
3077 (modify-syntax-entry ?# "<")
3078 (modify-syntax-entry ?@ "w")
3079 (if org-startup-truncated (setq truncate-lines t))
3080 (org-set-local 'font-lock-unfontify-region-function
3081 'org-unfontify-region)
3082 ;; Activate before-change-function
3083 (org-set-local 'org-table-may-need-update t)
3084 (org-add-hook 'before-change-functions 'org-before-change-function nil
3085 'local)
3086 ;; Check for running clock before killing a buffer
3087 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3088 ;; Paragraphs and auto-filling
3089 (org-set-autofill-regexps)
3090 (setq indent-line-function 'org-indent-line-function)
3091 (org-update-radio-target-regexp)
3093 ;; Comment characters
3094 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3095 (org-set-local 'comment-padding " ")
3097 ;; Align options lines
3098 (org-set-local
3099 'align-mode-rules-list
3100 '((org-in-buffer-settings
3101 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3102 (modes . '(org-mode)))))
3104 ;; Imenu
3105 (org-set-local 'imenu-create-index-function
3106 'org-imenu-get-tree)
3108 ;; Make isearch reveal context
3109 (if (or (featurep 'xemacs)
3110 (not (boundp 'outline-isearch-open-invisible-function)))
3111 ;; Emacs 21 and XEmacs make use of the hook
3112 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3113 ;; Emacs 22 deals with this through a special variable
3114 (org-set-local 'outline-isearch-open-invisible-function
3115 (lambda (&rest ignore) (org-show-context 'isearch))))
3117 ;; If empty file that did not turn on org-mode automatically, make it to.
3118 (if (and org-insert-mode-line-in-empty-file
3119 (interactive-p)
3120 (= (point-min) (point-max)))
3121 (insert "# -*- mode: org -*-\n\n"))
3123 (unless org-inhibit-startup
3124 (when org-startup-align-all-tables
3125 (let ((bmp (buffer-modified-p)))
3126 (org-table-map-tables 'org-table-align)
3127 (set-buffer-modified-p bmp)))
3128 (org-cycle-hide-drawers 'all)
3129 (cond
3130 ((eq org-startup-folded t)
3131 (org-cycle '(4)))
3132 ((eq org-startup-folded 'content)
3133 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3134 (org-cycle '(4)) (org-cycle '(4)))))))
3136 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3138 (defun org-current-time ()
3139 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3140 (if (> (car org-time-stamp-rounding-minutes) 1)
3141 (let ((r (car org-time-stamp-rounding-minutes))
3142 (time (decode-time)))
3143 (apply 'encode-time
3144 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3145 (nthcdr 2 time))))
3146 (current-time)))
3148 ;;;; Font-Lock stuff, including the activators
3150 (defvar org-mouse-map (make-sparse-keymap))
3151 (org-defkey org-mouse-map
3152 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3153 (org-defkey org-mouse-map
3154 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3155 (when org-mouse-1-follows-link
3156 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3157 (when org-tab-follows-link
3158 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3159 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3160 (when org-return-follows-link
3161 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3162 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3164 (require 'font-lock)
3166 (defconst org-non-link-chars "]\t\n\r<>")
3167 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3168 "shell" "elisp"))
3169 (defvar org-link-types-re nil
3170 "Matches a link that has a url-like prefix like \"http:\"")
3171 (defvar org-link-re-with-space nil
3172 "Matches a link with spaces, optional angular brackets around it.")
3173 (defvar org-link-re-with-space2 nil
3174 "Matches a link with spaces, optional angular brackets around it.")
3175 (defvar org-angle-link-re nil
3176 "Matches link with angular brackets, spaces are allowed.")
3177 (defvar org-plain-link-re nil
3178 "Matches plain link, without spaces.")
3179 (defvar org-bracket-link-regexp nil
3180 "Matches a link in double brackets.")
3181 (defvar org-bracket-link-analytic-regexp nil
3182 "Regular expression used to analyze links.
3183 Here is what the match groups contain after a match:
3184 1: http:
3185 2: http
3186 3: path
3187 4: [desc]
3188 5: desc")
3189 (defvar org-any-link-re nil
3190 "Regular expression matching any link.")
3192 (defun org-make-link-regexps ()
3193 "Update the link regular expressions.
3194 This should be called after the variable `org-link-types' has changed."
3195 (setq org-link-types-re
3196 (concat
3197 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3198 org-link-re-with-space
3199 (concat
3200 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3201 "\\([^" org-non-link-chars " ]"
3202 "[^" org-non-link-chars "]*"
3203 "[^" org-non-link-chars " ]\\)>?")
3204 org-link-re-with-space2
3205 (concat
3206 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3207 "\\([^" org-non-link-chars " ]"
3208 "[^]\t\n\r]*"
3209 "[^" org-non-link-chars " ]\\)>?")
3210 org-angle-link-re
3211 (concat
3212 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3213 "\\([^" org-non-link-chars " ]"
3214 "[^" org-non-link-chars "]*"
3215 "\\)>")
3216 org-plain-link-re
3217 (concat
3218 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3219 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3220 org-bracket-link-regexp
3221 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3222 org-bracket-link-analytic-regexp
3223 (concat
3224 "\\[\\["
3225 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3226 "\\([^]]+\\)"
3227 "\\]"
3228 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3229 "\\]")
3230 org-any-link-re
3231 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3232 org-angle-link-re "\\)\\|\\("
3233 org-plain-link-re "\\)")))
3235 (org-make-link-regexps)
3237 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3238 "Regular expression for fast time stamp matching.")
3239 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3240 "Regular expression for fast time stamp matching.")
3241 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3242 "Regular expression matching time strings for analysis.
3243 This one does not require the space after the date, so it can be used
3244 on a string that terminates immediately after the date.")
3245 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3246 "Regular expression matching time strings for analysis.")
3247 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3248 "Regular expression matching time stamps, with groups.")
3249 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3250 "Regular expression matching time stamps (also [..]), with groups.")
3251 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3252 "Regular expression matching a time stamp range.")
3253 (defconst org-tr-regexp-both
3254 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3255 "Regular expression matching a time stamp range.")
3256 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3257 org-ts-regexp "\\)?")
3258 "Regular expression matching a time stamp or time stamp range.")
3259 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3260 org-ts-regexp-both "\\)?")
3261 "Regular expression matching a time stamp or time stamp range.
3262 The time stamps may be either active or inactive.")
3264 (defvar org-emph-face nil)
3266 (defun org-do-emphasis-faces (limit)
3267 "Run through the buffer and add overlays to links."
3268 (let (rtn)
3269 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3270 (if (not (= (char-after (match-beginning 3))
3271 (char-after (match-beginning 4))))
3272 (progn
3273 (setq rtn t)
3274 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3275 'face
3276 (nth 1 (assoc (match-string 3)
3277 org-emphasis-alist)))
3278 (add-text-properties (match-beginning 2) (match-end 2)
3279 '(font-lock-multiline t))
3280 (when org-hide-emphasis-markers
3281 (add-text-properties (match-end 4) (match-beginning 5)
3282 '(invisible org-link))
3283 (add-text-properties (match-beginning 3) (match-end 3)
3284 '(invisible org-link)))))
3285 (backward-char 1))
3286 rtn))
3288 (defun org-emphasize (&optional char)
3289 "Insert or change an emphasis, i.e. a font like bold or italic.
3290 If there is an active region, change that region to a new emphasis.
3291 If there is no region, just insert the marker characters and position
3292 the cursor between them.
3293 CHAR should be either the marker character, or the first character of the
3294 HTML tag associated with that emphasis. If CHAR is a space, the means
3295 to remove the emphasis of the selected region.
3296 If char is not given (for example in an interactive call) it
3297 will be prompted for."
3298 (interactive)
3299 (let ((eal org-emphasis-alist) e det
3300 (erc org-emphasis-regexp-components)
3301 (prompt "")
3302 (string "") beg end move tag c s)
3303 (if (org-region-active-p)
3304 (setq beg (region-beginning) end (region-end)
3305 string (buffer-substring beg end))
3306 (setq move t))
3308 (while (setq e (pop eal))
3309 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3310 c (aref tag 0))
3311 (push (cons c (string-to-char (car e))) det)
3312 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3313 (substring tag 1)))))
3314 (unless char
3315 (message "%s" (concat "Emphasis marker or tag:" prompt))
3316 (setq char (read-char-exclusive)))
3317 (setq char (or (cdr (assoc char det)) char))
3318 (if (equal char ?\ )
3319 (setq s "" move nil)
3320 (unless (assoc (char-to-string char) org-emphasis-alist)
3321 (error "No such emphasis marker: \"%c\"" char))
3322 (setq s (char-to-string char)))
3323 (while (and (> (length string) 1)
3324 (equal (substring string 0 1) (substring string -1))
3325 (assoc (substring string 0 1) org-emphasis-alist))
3326 (setq string (substring string 1 -1)))
3327 (setq string (concat s string s))
3328 (if beg (delete-region beg end))
3329 (unless (or (bolp)
3330 (string-match (concat "[" (nth 0 erc) "\n]")
3331 (char-to-string (char-before (point)))))
3332 (insert " "))
3333 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3334 (char-to-string (char-after (point))))
3335 (insert " ") (backward-char 1))
3336 (insert string)
3337 (and move (backward-char 1))))
3339 (defconst org-nonsticky-props
3340 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3343 (defun org-activate-plain-links (limit)
3344 "Run through the buffer and add overlays to links."
3345 (catch 'exit
3346 (let (f)
3347 (while (re-search-forward org-plain-link-re limit t)
3348 (setq f (get-text-property (match-beginning 0) 'face))
3349 (if (or (eq f 'org-tag)
3350 (and (listp f) (memq 'org-tag f)))
3352 (add-text-properties (match-beginning 0) (match-end 0)
3353 (list 'mouse-face 'highlight
3354 'rear-nonsticky org-nonsticky-props
3355 'keymap org-mouse-map
3357 (throw 'exit t))))))
3359 (defun org-activate-code (limit)
3360 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3361 (unless (get-text-property (match-beginning 1) 'face)
3362 (remove-text-properties (match-beginning 0) (match-end 0)
3363 '(display t invisible t intangible t))
3364 t)))
3366 (defun org-activate-angle-links (limit)
3367 "Run through the buffer and add overlays to links."
3368 (if (re-search-forward org-angle-link-re limit t)
3369 (progn
3370 (add-text-properties (match-beginning 0) (match-end 0)
3371 (list 'mouse-face 'highlight
3372 'rear-nonsticky org-nonsticky-props
3373 'keymap org-mouse-map
3375 t)))
3377 (defun org-activate-bracket-links (limit)
3378 "Run through the buffer and add overlays to bracketed links."
3379 (if (re-search-forward org-bracket-link-regexp limit t)
3380 (let* ((help (concat "LINK: "
3381 (org-match-string-no-properties 1)))
3382 ;; FIXME: above we should remove the escapes.
3383 ;; but that requires another match, protecting match data,
3384 ;; a lot of overhead for font-lock.
3385 (ip (org-maybe-intangible
3386 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3387 'keymap org-mouse-map 'mouse-face 'highlight
3388 'font-lock-multiline t 'help-echo help)))
3389 (vp (list 'rear-nonsticky org-nonsticky-props
3390 'keymap org-mouse-map 'mouse-face 'highlight
3391 ' font-lock-multiline t 'help-echo help)))
3392 ;; We need to remove the invisible property here. Table narrowing
3393 ;; may have made some of this invisible.
3394 (remove-text-properties (match-beginning 0) (match-end 0)
3395 '(invisible nil))
3396 (if (match-end 3)
3397 (progn
3398 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3399 (add-text-properties (match-beginning 3) (match-end 3) vp)
3400 (add-text-properties (match-end 3) (match-end 0) ip))
3401 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3402 (add-text-properties (match-beginning 1) (match-end 1) vp)
3403 (add-text-properties (match-end 1) (match-end 0) ip))
3404 t)))
3406 (defun org-activate-dates (limit)
3407 "Run through the buffer and add overlays to dates."
3408 (if (re-search-forward org-tsr-regexp-both limit t)
3409 (progn
3410 (add-text-properties (match-beginning 0) (match-end 0)
3411 (list 'mouse-face 'highlight
3412 'rear-nonsticky org-nonsticky-props
3413 'keymap org-mouse-map))
3414 (when org-display-custom-times
3415 (if (match-end 3)
3416 (org-display-custom-time (match-beginning 3) (match-end 3)))
3417 (org-display-custom-time (match-beginning 1) (match-end 1)))
3418 t)))
3420 (defvar org-target-link-regexp nil
3421 "Regular expression matching radio targets in plain text.")
3422 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3423 "Regular expression matching a link target.")
3424 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3425 "Regular expression matching a radio target.")
3426 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3427 "Regular expression matching any target.")
3429 (defun org-activate-target-links (limit)
3430 "Run through the buffer and add overlays to target matches."
3431 (when org-target-link-regexp
3432 (let ((case-fold-search t))
3433 (if (re-search-forward org-target-link-regexp limit t)
3434 (progn
3435 (add-text-properties (match-beginning 0) (match-end 0)
3436 (list 'mouse-face 'highlight
3437 'rear-nonsticky org-nonsticky-props
3438 'keymap org-mouse-map
3439 'help-echo "Radio target link"
3440 'org-linked-text t))
3441 t)))))
3443 (defun org-update-radio-target-regexp ()
3444 "Find all radio targets in this file and update the regular expression."
3445 (interactive)
3446 (when (memq 'radio org-activate-links)
3447 (setq org-target-link-regexp
3448 (org-make-target-link-regexp (org-all-targets 'radio)))
3449 (org-restart-font-lock)))
3451 (defun org-hide-wide-columns (limit)
3452 (let (s e)
3453 (setq s (text-property-any (point) (or limit (point-max))
3454 'org-cwidth t))
3455 (when s
3456 (setq e (next-single-property-change s 'org-cwidth))
3457 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3458 (goto-char e)
3459 t)))
3461 (defvar org-latex-and-specials-regexp nil
3462 "Regular expression for highlighting export special stuff.")
3463 (defvar org-match-substring-regexp)
3464 (defvar org-match-substring-with-braces-regexp)
3465 (defvar org-export-html-special-string-regexps)
3467 (defun org-compute-latex-and-specials-regexp ()
3468 "Compute regular expression for stuff treated specially by exporters."
3469 (if (not org-highlight-latex-fragments-and-specials)
3470 (org-set-local 'org-latex-and-specials-regexp nil)
3471 (require 'org-exp)
3472 (let*
3473 ((matchers (plist-get org-format-latex-options :matchers))
3474 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3475 org-latex-regexps)))
3476 (options (org-combine-plists (org-default-export-plist)
3477 (org-infile-export-plist)))
3478 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3479 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3480 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3481 (org-export-html-expand (plist-get options :expand-quoted-html))
3482 (org-export-with-special-strings (plist-get options :special-strings))
3483 (re-sub
3484 (cond
3485 ((equal org-export-with-sub-superscripts '{})
3486 (list org-match-substring-with-braces-regexp))
3487 (org-export-with-sub-superscripts
3488 (list org-match-substring-regexp))
3489 (t nil)))
3490 (re-latex
3491 (if org-export-with-LaTeX-fragments
3492 (mapcar (lambda (x) (nth 1 x)) latexs)))
3493 (re-macros
3494 (if org-export-with-TeX-macros
3495 (list (concat "\\\\"
3496 (regexp-opt
3497 (append (mapcar 'car org-html-entities)
3498 (if (boundp 'org-latex-entities)
3499 org-latex-entities nil))
3500 'words))) ; FIXME
3502 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3503 (re-special (if org-export-with-special-strings
3504 (mapcar (lambda (x) (car x))
3505 org-export-html-special-string-regexps)))
3506 (re-rest
3507 (delq nil
3508 (list
3509 (if org-export-html-expand "@<[^>\n]+>")
3510 ))))
3511 (org-set-local
3512 'org-latex-and-specials-regexp
3513 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3514 re-rest) "\\|")))))
3516 (defun org-do-latex-and-special-faces (limit)
3517 "Run through the buffer and add overlays to links."
3518 (when org-latex-and-specials-regexp
3519 (let (rtn d)
3520 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3521 limit t))
3522 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3523 'face))
3524 '(org-code org-verbatim underline)))
3525 (progn
3526 (setq rtn t
3527 d (cond ((member (char-after (1+ (match-beginning 0)))
3528 '(?_ ?^)) 1)
3529 (t 0)))
3530 (font-lock-prepend-text-property
3531 (+ d (match-beginning 0)) (match-end 0)
3532 'face 'org-latex-and-export-specials)
3533 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3534 '(font-lock-multiline t)))))
3535 rtn)))
3537 (defun org-restart-font-lock ()
3538 "Restart font-lock-mode, to force refontification."
3539 (when (and (boundp 'font-lock-mode) font-lock-mode)
3540 (font-lock-mode -1)
3541 (font-lock-mode 1)))
3543 (defun org-all-targets (&optional radio)
3544 "Return a list of all targets in this file.
3545 With optional argument RADIO, only find radio targets."
3546 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3547 rtn)
3548 (save-excursion
3549 (goto-char (point-min))
3550 (while (re-search-forward re nil t)
3551 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3552 rtn)))
3554 (defun org-make-target-link-regexp (targets)
3555 "Make regular expression matching all strings in TARGETS.
3556 The regular expression finds the targets also if there is a line break
3557 between words."
3558 (and targets
3559 (concat
3560 "\\<\\("
3561 (mapconcat
3562 (lambda (x)
3563 (while (string-match " +" x)
3564 (setq x (replace-match "\\s-+" t t x)))
3566 targets
3567 "\\|")
3568 "\\)\\>")))
3570 (defun org-activate-tags (limit)
3571 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3572 (progn
3573 (add-text-properties (match-beginning 1) (match-end 1)
3574 (list 'mouse-face 'highlight
3575 'rear-nonsticky org-nonsticky-props
3576 'keymap org-mouse-map))
3577 t)))
3579 (defun org-outline-level ()
3580 (save-excursion
3581 (looking-at outline-regexp)
3582 (if (match-beginning 1)
3583 (+ (org-get-string-indentation (match-string 1)) 1000)
3584 (1- (- (match-end 0) (match-beginning 0))))))
3586 (defvar org-font-lock-keywords nil)
3588 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3589 "Regular expression matching a property line.")
3591 (defvar org-font-lock-hook nil
3592 "Functions to be called for special font loch stuff.")
3594 (defun org-font-lock-hook (limit)
3595 (run-hook-with-args 'org-font-lock-hook limit))
3597 (defun org-set-font-lock-defaults ()
3598 (let* ((em org-fontify-emphasized-text)
3599 (lk org-activate-links)
3600 (org-font-lock-extra-keywords
3601 (list
3602 ;; Call the hook
3603 '(org-font-lock-hook)
3604 ;; Headlines
3605 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3606 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3607 ;; Table lines
3608 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3609 (1 'org-table t))
3610 ;; Table internals
3611 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3612 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3613 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3614 ;; Drawers
3615 (list org-drawer-regexp '(0 'org-special-keyword t))
3616 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3617 ;; Properties
3618 (list org-property-re
3619 '(1 'org-special-keyword t)
3620 '(3 'org-property-value t))
3621 (if org-format-transports-properties-p
3622 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3623 ;; Links
3624 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3625 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3626 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3627 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3628 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3629 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3630 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3631 '(org-hide-wide-columns (0 nil append))
3632 ;; TODO lines
3633 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3634 '(1 (org-get-todo-face 1) t))
3635 ;; DONE
3636 (if org-fontify-done-headline
3637 (list (concat "^[*]+ +\\<\\("
3638 (mapconcat 'regexp-quote org-done-keywords "\\|")
3639 "\\)\\(.*\\)")
3640 '(2 'org-headline-done t))
3641 nil)
3642 ;; Priorities
3643 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3644 ;; Special keywords
3645 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3646 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3647 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3648 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3649 ;; Emphasis
3650 (if em
3651 (if (featurep 'xemacs)
3652 '(org-do-emphasis-faces (0 nil append))
3653 '(org-do-emphasis-faces)))
3654 ;; Checkboxes
3655 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3656 2 'bold prepend)
3657 (if org-provide-checkbox-statistics
3658 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3659 (0 (org-get-checkbox-statistics-face) t)))
3660 ;; Description list items
3661 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*?\\) ::"
3662 2 'bold prepend)
3663 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3664 '(1 'org-archived prepend))
3665 ;; Specials
3666 '(org-do-latex-and-special-faces)
3667 ;; Code
3668 '(org-activate-code (1 'org-code t))
3669 ;; COMMENT
3670 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3671 "\\|" org-quote-string "\\)\\>")
3672 '(1 'org-special-keyword t))
3673 '("^#.*" (0 'font-lock-comment-face t))
3675 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3676 ;; Now set the full font-lock-keywords
3677 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3678 (org-set-local 'font-lock-defaults
3679 '(org-font-lock-keywords t nil nil backward-paragraph))
3680 (kill-local-variable 'font-lock-keywords) nil))
3682 (defvar org-m nil)
3683 (defvar org-l nil)
3684 (defvar org-f nil)
3685 (defun org-get-level-face (n)
3686 "Get the right face for match N in font-lock matching of healdines."
3687 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3688 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3689 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3690 (cond
3691 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3692 ((eq n 2) org-f)
3693 (t (if org-level-color-stars-only nil org-f))))
3695 (defun org-get-todo-face (kwd)
3696 "Get the right face for a TODO keyword KWD.
3697 If KWD is a number, get the corresponding match group."
3698 (if (numberp kwd) (setq kwd (match-string kwd)))
3699 (or (cdr (assoc kwd org-todo-keyword-faces))
3700 (and (member kwd org-done-keywords) 'org-done)
3701 'org-todo))
3703 (defun org-unfontify-region (beg end &optional maybe_loudly)
3704 "Remove fontification and activation overlays from links."
3705 (font-lock-default-unfontify-region beg end)
3706 (let* ((buffer-undo-list t)
3707 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3708 (inhibit-modification-hooks t)
3709 deactivate-mark buffer-file-name buffer-file-truename)
3710 (remove-text-properties beg end
3711 '(mouse-face t keymap t org-linked-text t
3712 invisible t intangible t))))
3714 ;;;; Visibility cycling, including org-goto and indirect buffer
3716 ;;; Cycling
3718 (defvar org-cycle-global-status nil)
3719 (make-variable-buffer-local 'org-cycle-global-status)
3720 (defvar org-cycle-subtree-status nil)
3721 (make-variable-buffer-local 'org-cycle-subtree-status)
3723 ;;;###autoload
3724 (defun org-cycle (&optional arg)
3725 "Visibility cycling for Org-mode.
3727 - When this function is called with a prefix argument, rotate the entire
3728 buffer through 3 states (global cycling)
3729 1. OVERVIEW: Show only top-level headlines.
3730 2. CONTENTS: Show all headlines of all levels, but no body text.
3731 3. SHOW ALL: Show everything.
3733 - When point is at the beginning of a headline, rotate the subtree started
3734 by this line through 3 different states (local cycling)
3735 1. FOLDED: Only the main headline is shown.
3736 2. CHILDREN: The main headline and the direct children are shown.
3737 From this state, you can move to one of the children
3738 and zoom in further.
3739 3. SUBTREE: Show the entire subtree, including body text.
3741 - When there is a numeric prefix, go up to a heading with level ARG, do
3742 a `show-subtree' and return to the previous cursor position. If ARG
3743 is negative, go up that many levels.
3745 - When point is not at the beginning of a headline, execute
3746 `indent-relative', like TAB normally does. See the option
3747 `org-cycle-emulate-tab' for details.
3749 - Special case: if point is at the beginning of the buffer and there is
3750 no headline in line 1, this function will act as if called with prefix arg.
3751 But only if also the variable `org-cycle-global-at-bob' is t."
3752 (interactive "P")
3753 (org-load-modules-maybe)
3754 (let* ((outline-regexp
3755 (if (and (org-mode-p) org-cycle-include-plain-lists)
3756 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3757 outline-regexp))
3758 (bob-special (and org-cycle-global-at-bob (bobp)
3759 (not (looking-at outline-regexp))))
3760 (org-cycle-hook
3761 (if bob-special
3762 (delq 'org-optimize-window-after-visibility-change
3763 (copy-sequence org-cycle-hook))
3764 org-cycle-hook))
3765 (pos (point)))
3767 (if (or bob-special (equal arg '(4)))
3768 ;; special case: use global cycling
3769 (setq arg t))
3771 (cond
3773 ((org-at-table-p 'any)
3774 ;; Enter the table or move to the next field in the table
3775 (or (org-table-recognize-table.el)
3776 (progn
3777 (if arg (org-table-edit-field t)
3778 (org-table-justify-field-maybe)
3779 (call-interactively 'org-table-next-field)))))
3781 ((eq arg t) ;; Global cycling
3783 (cond
3784 ((and (eq last-command this-command)
3785 (eq org-cycle-global-status 'overview))
3786 ;; We just created the overview - now do table of contents
3787 ;; This can be slow in very large buffers, so indicate action
3788 (message "CONTENTS...")
3789 (org-content)
3790 (message "CONTENTS...done")
3791 (setq org-cycle-global-status 'contents)
3792 (run-hook-with-args 'org-cycle-hook 'contents))
3794 ((and (eq last-command this-command)
3795 (eq org-cycle-global-status 'contents))
3796 ;; We just showed the table of contents - now show everything
3797 (show-all)
3798 (message "SHOW ALL")
3799 (setq org-cycle-global-status 'all)
3800 (run-hook-with-args 'org-cycle-hook 'all))
3803 ;; Default action: go to overview
3804 (org-overview)
3805 (message "OVERVIEW")
3806 (setq org-cycle-global-status 'overview)
3807 (run-hook-with-args 'org-cycle-hook 'overview))))
3809 ((and org-drawers org-drawer-regexp
3810 (save-excursion
3811 (beginning-of-line 1)
3812 (looking-at org-drawer-regexp)))
3813 ;; Toggle block visibility
3814 (org-flag-drawer
3815 (not (get-char-property (match-end 0) 'invisible))))
3817 ((integerp arg)
3818 ;; Show-subtree, ARG levels up from here.
3819 (save-excursion
3820 (org-back-to-heading)
3821 (outline-up-heading (if (< arg 0) (- arg)
3822 (- (funcall outline-level) arg)))
3823 (org-show-subtree)))
3825 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3826 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3827 ;; At a heading: rotate between three different views
3828 (org-back-to-heading)
3829 (let ((goal-column 0) eoh eol eos)
3830 ;; First, some boundaries
3831 (save-excursion
3832 (org-back-to-heading)
3833 (save-excursion
3834 (beginning-of-line 2)
3835 (while (and (not (eobp)) ;; this is like `next-line'
3836 (get-char-property (1- (point)) 'invisible))
3837 (beginning-of-line 2)) (setq eol (point)))
3838 (outline-end-of-heading) (setq eoh (point))
3839 (org-end-of-subtree t)
3840 (unless (eobp)
3841 (skip-chars-forward " \t\n")
3842 (beginning-of-line 1) ; in case this is an item
3844 (setq eos (1- (point))))
3845 ;; Find out what to do next and set `this-command'
3846 (cond
3847 ((= eos eoh)
3848 ;; Nothing is hidden behind this heading
3849 (message "EMPTY ENTRY")
3850 (setq org-cycle-subtree-status nil)
3851 (save-excursion
3852 (goto-char eos)
3853 (outline-next-heading)
3854 (if (org-invisible-p) (org-flag-heading nil))))
3855 ((or (>= eol eos)
3856 (not (string-match "\\S-" (buffer-substring eol eos))))
3857 ;; Entire subtree is hidden in one line: open it
3858 (org-show-entry)
3859 (show-children)
3860 (message "CHILDREN")
3861 (save-excursion
3862 (goto-char eos)
3863 (outline-next-heading)
3864 (if (org-invisible-p) (org-flag-heading nil)))
3865 (setq org-cycle-subtree-status 'children)
3866 (run-hook-with-args 'org-cycle-hook 'children))
3867 ((and (eq last-command this-command)
3868 (eq org-cycle-subtree-status 'children))
3869 ;; We just showed the children, now show everything.
3870 (org-show-subtree)
3871 (message "SUBTREE")
3872 (setq org-cycle-subtree-status 'subtree)
3873 (run-hook-with-args 'org-cycle-hook 'subtree))
3875 ;; Default action: hide the subtree.
3876 (hide-subtree)
3877 (message "FOLDED")
3878 (setq org-cycle-subtree-status 'folded)
3879 (run-hook-with-args 'org-cycle-hook 'folded)))))
3881 ;; TAB emulation
3882 (buffer-read-only (org-back-to-heading))
3884 ((org-try-cdlatex-tab))
3886 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3887 (or (not (bolp))
3888 (not (looking-at outline-regexp))))
3889 (call-interactively (global-key-binding "\t")))
3891 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3892 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3893 (or (and (eq org-cycle-emulate-tab 'white)
3894 (= (match-end 0) (point-at-eol)))
3895 (and (eq org-cycle-emulate-tab 'whitestart)
3896 (>= (match-end 0) pos))))
3898 (eq org-cycle-emulate-tab t))
3899 (call-interactively (global-key-binding "\t")))
3901 (t (save-excursion
3902 (org-back-to-heading)
3903 (org-cycle))))))
3905 ;;;###autoload
3906 (defun org-global-cycle (&optional arg)
3907 "Cycle the global visibility. For details see `org-cycle'."
3908 (interactive "P")
3909 (let ((org-cycle-include-plain-lists
3910 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3911 (if (integerp arg)
3912 (progn
3913 (show-all)
3914 (hide-sublevels arg)
3915 (setq org-cycle-global-status 'contents))
3916 (org-cycle '(4)))))
3918 (defun org-overview ()
3919 "Switch to overview mode, shoing only top-level headlines.
3920 Really, this shows all headlines with level equal or greater than the level
3921 of the first headline in the buffer. This is important, because if the
3922 first headline is not level one, then (hide-sublevels 1) gives confusing
3923 results."
3924 (interactive)
3925 (let ((level (save-excursion
3926 (goto-char (point-min))
3927 (if (re-search-forward (concat "^" outline-regexp) nil t)
3928 (progn
3929 (goto-char (match-beginning 0))
3930 (funcall outline-level))))))
3931 (and level (hide-sublevels level))))
3933 (defun org-content (&optional arg)
3934 "Show all headlines in the buffer, like a table of contents.
3935 With numerical argument N, show content up to level N."
3936 (interactive "P")
3937 (save-excursion
3938 ;; Visit all headings and show their offspring
3939 (and (integerp arg) (org-overview))
3940 (goto-char (point-max))
3941 (catch 'exit
3942 (while (and (progn (condition-case nil
3943 (outline-previous-visible-heading 1)
3944 (error (goto-char (point-min))))
3946 (looking-at outline-regexp))
3947 (if (integerp arg)
3948 (show-children (1- arg))
3949 (show-branches))
3950 (if (bobp) (throw 'exit nil))))))
3953 (defun org-optimize-window-after-visibility-change (state)
3954 "Adjust the window after a change in outline visibility.
3955 This function is the default value of the hook `org-cycle-hook'."
3956 (when (get-buffer-window (current-buffer))
3957 (cond
3958 ; ((eq state 'overview) (org-first-headline-recenter 1))
3959 ; ((eq state 'overview) (org-beginning-of-line))
3960 ((eq state 'content) nil)
3961 ((eq state 'all) nil)
3962 ((eq state 'folded) nil)
3963 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3964 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3966 (defun org-compact-display-after-subtree-move ()
3967 (let (beg end)
3968 (save-excursion
3969 (if (org-up-heading-safe)
3970 (progn
3971 (hide-subtree)
3972 (show-entry)
3973 (show-children)
3974 (org-cycle-show-empty-lines 'children)
3975 (org-cycle-hide-drawers 'children))
3976 (org-overview)))))
3978 (defun org-cycle-show-empty-lines (state)
3979 "Show empty lines above all visible headlines.
3980 The region to be covered depends on STATE when called through
3981 `org-cycle-hook'. Lisp program can use t for STATE to get the
3982 entire buffer covered. Note that an empty line is only shown if there
3983 are at least `org-cycle-separator-lines' empty lines before the headeline."
3984 (when (> org-cycle-separator-lines 0)
3985 (save-excursion
3986 (let* ((n org-cycle-separator-lines)
3987 (re (cond
3988 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3989 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3990 (t (let ((ns (number-to-string (- n 2))))
3991 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3992 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3993 beg end)
3994 (cond
3995 ((memq state '(overview contents t))
3996 (setq beg (point-min) end (point-max)))
3997 ((memq state '(children folded))
3998 (setq beg (point) end (progn (org-end-of-subtree t t)
3999 (beginning-of-line 2)
4000 (point)))))
4001 (when beg
4002 (goto-char beg)
4003 (while (re-search-forward re end t)
4004 (if (not (get-char-property (match-end 1) 'invisible))
4005 (outline-flag-region
4006 (match-beginning 1) (match-end 1) nil)))))))
4007 ;; Never hide empty lines at the end of the file.
4008 (save-excursion
4009 (goto-char (point-max))
4010 (outline-previous-heading)
4011 (outline-end-of-heading)
4012 (if (and (looking-at "[ \t\n]+")
4013 (= (match-end 0) (point-max)))
4014 (outline-flag-region (point) (match-end 0) nil))))
4016 (defun org-cycle-hide-drawers (state)
4017 "Re-hide all drawers after a visibility state change."
4018 (when (and (org-mode-p)
4019 (not (memq state '(overview folded))))
4020 (save-excursion
4021 (let* ((globalp (memq state '(contents all)))
4022 (beg (if globalp (point-min) (point)))
4023 (end (if globalp (point-max) (org-end-of-subtree t))))
4024 (goto-char beg)
4025 (while (re-search-forward org-drawer-regexp end t)
4026 (org-flag-drawer t))))))
4028 (defun org-flag-drawer (flag)
4029 (save-excursion
4030 (beginning-of-line 1)
4031 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4032 (let ((b (match-end 0))
4033 (outline-regexp org-outline-regexp))
4034 (if (re-search-forward
4035 "^[ \t]*:END:"
4036 (save-excursion (outline-next-heading) (point)) t)
4037 (outline-flag-region b (point-at-eol) flag)
4038 (error ":END: line missing"))))))
4040 (defun org-subtree-end-visible-p ()
4041 "Is the end of the current subtree visible?"
4042 (pos-visible-in-window-p
4043 (save-excursion (org-end-of-subtree t) (point))))
4045 (defun org-first-headline-recenter (&optional N)
4046 "Move cursor to the first headline and recenter the headline.
4047 Optional argument N means, put the headline into the Nth line of the window."
4048 (goto-char (point-min))
4049 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4050 (beginning-of-line)
4051 (recenter (prefix-numeric-value N))))
4053 ;;; Org-goto
4055 (defvar org-goto-window-configuration nil)
4056 (defvar org-goto-marker nil)
4057 (defvar org-goto-map
4058 (let ((map (make-sparse-keymap)))
4059 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4060 (while (setq cmd (pop cmds))
4061 (substitute-key-definition cmd cmd map global-map)))
4062 (suppress-keymap map)
4063 (org-defkey map "\C-m" 'org-goto-ret)
4064 (org-defkey map [(return)] 'org-goto-ret)
4065 (org-defkey map [(left)] 'org-goto-left)
4066 (org-defkey map [(right)] 'org-goto-right)
4067 (org-defkey map [(control ?g)] 'org-goto-quit)
4068 (org-defkey map "\C-i" 'org-cycle)
4069 (org-defkey map [(tab)] 'org-cycle)
4070 (org-defkey map [(down)] 'outline-next-visible-heading)
4071 (org-defkey map [(up)] 'outline-previous-visible-heading)
4072 (if org-goto-auto-isearch
4073 (if (fboundp 'define-key-after)
4074 (define-key-after map [t] 'org-goto-local-auto-isearch)
4075 nil)
4076 (org-defkey map "q" 'org-goto-quit)
4077 (org-defkey map "n" 'outline-next-visible-heading)
4078 (org-defkey map "p" 'outline-previous-visible-heading)
4079 (org-defkey map "f" 'outline-forward-same-level)
4080 (org-defkey map "b" 'outline-backward-same-level)
4081 (org-defkey map "u" 'outline-up-heading))
4082 (org-defkey map "/" 'org-occur)
4083 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4084 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4085 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4086 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4087 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4088 map))
4090 (defconst org-goto-help
4091 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4092 RET=jump to location [Q]uit and return to previous location
4093 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4095 (defvar org-goto-start-pos) ; dynamically scoped parameter
4097 (defun org-goto (&optional alternative-interface)
4098 "Look up a different location in the current file, keeping current visibility.
4100 When you want look-up or go to a different location in a document, the
4101 fastest way is often to fold the entire buffer and then dive into the tree.
4102 This method has the disadvantage, that the previous location will be folded,
4103 which may not be what you want.
4105 This command works around this by showing a copy of the current buffer
4106 in an indirect buffer, in overview mode. You can dive into the tree in
4107 that copy, use org-occur and incremental search to find a location.
4108 When pressing RET or `Q', the command returns to the original buffer in
4109 which the visibility is still unchanged. After RET is will also jump to
4110 the location selected in the indirect buffer and expose the
4111 the headline hierarchy above."
4112 (interactive "P")
4113 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4114 (org-refile-use-outline-path t)
4115 (interface
4116 (if (not alternative-interface)
4117 org-goto-interface
4118 (if (eq org-goto-interface 'outline)
4119 'outline-path-completion
4120 'outline)))
4121 (org-goto-start-pos (point))
4122 (selected-point
4123 (if (eq interface 'outline)
4124 (car (org-get-location (current-buffer) org-goto-help))
4125 (nth 3 (org-refile-get-location "Goto: ")))))
4126 (if selected-point
4127 (progn
4128 (org-mark-ring-push org-goto-start-pos)
4129 (goto-char selected-point)
4130 (if (or (org-invisible-p) (org-invisible-p2))
4131 (org-show-context 'org-goto)))
4132 (message "Quit"))))
4134 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4135 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4136 (defvar org-goto-local-auto-isearch-map) ; defined below
4138 (defun org-get-location (buf help)
4139 "Let the user select a location in the Org-mode buffer BUF.
4140 This function uses a recursive edit. It returns the selected position
4141 or nil."
4142 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4143 (isearch-hide-immediately nil)
4144 (isearch-search-fun-function
4145 (lambda () 'org-goto-local-search-forward-headings))
4146 (org-goto-selected-point org-goto-exit-command))
4147 (save-excursion
4148 (save-window-excursion
4149 (delete-other-windows)
4150 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4151 (switch-to-buffer
4152 (condition-case nil
4153 (make-indirect-buffer (current-buffer) "*org-goto*")
4154 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4155 (with-output-to-temp-buffer "*Help*"
4156 (princ help))
4157 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4158 (setq buffer-read-only nil)
4159 (let ((org-startup-truncated t)
4160 (org-startup-folded nil)
4161 (org-startup-align-all-tables nil))
4162 (org-mode)
4163 (org-overview))
4164 (setq buffer-read-only t)
4165 (if (and (boundp 'org-goto-start-pos)
4166 (integer-or-marker-p org-goto-start-pos))
4167 (let ((org-show-hierarchy-above t)
4168 (org-show-siblings t)
4169 (org-show-following-heading t))
4170 (goto-char org-goto-start-pos)
4171 (and (org-invisible-p) (org-show-context)))
4172 (goto-char (point-min)))
4173 (org-beginning-of-line)
4174 (message "Select location and press RET")
4175 (use-local-map org-goto-map)
4176 (recursive-edit)
4178 (kill-buffer "*org-goto*")
4179 (cons org-goto-selected-point org-goto-exit-command)))
4181 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4182 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4183 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4184 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4186 (defun org-goto-local-search-forward-headings (string bound noerror)
4187 "Search and make sure that anu matches are in headlines."
4188 (catch 'return
4189 (while (search-forward string bound noerror)
4190 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4191 (and (member :headline context)
4192 (not (member :tags context))))
4193 (throw 'return (point))))))
4195 (defun org-goto-local-auto-isearch ()
4196 "Start isearch."
4197 (interactive)
4198 (goto-char (point-min))
4199 (let ((keys (this-command-keys)))
4200 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4201 (isearch-mode t)
4202 (isearch-process-search-char (string-to-char keys)))))
4204 (defun org-goto-ret (&optional arg)
4205 "Finish `org-goto' by going to the new location."
4206 (interactive "P")
4207 (setq org-goto-selected-point (point)
4208 org-goto-exit-command 'return)
4209 (throw 'exit nil))
4211 (defun org-goto-left ()
4212 "Finish `org-goto' by going to the new location."
4213 (interactive)
4214 (if (org-on-heading-p)
4215 (progn
4216 (beginning-of-line 1)
4217 (setq org-goto-selected-point (point)
4218 org-goto-exit-command 'left)
4219 (throw 'exit nil))
4220 (error "Not on a heading")))
4222 (defun org-goto-right ()
4223 "Finish `org-goto' by going to the new location."
4224 (interactive)
4225 (if (org-on-heading-p)
4226 (progn
4227 (setq org-goto-selected-point (point)
4228 org-goto-exit-command 'right)
4229 (throw 'exit nil))
4230 (error "Not on a heading")))
4232 (defun org-goto-quit ()
4233 "Finish `org-goto' without cursor motion."
4234 (interactive)
4235 (setq org-goto-selected-point nil)
4236 (setq org-goto-exit-command 'quit)
4237 (throw 'exit nil))
4239 ;;; Indirect buffer display of subtrees
4241 (defvar org-indirect-dedicated-frame nil
4242 "This is the frame being used for indirect tree display.")
4243 (defvar org-last-indirect-buffer nil)
4245 (defun org-tree-to-indirect-buffer (&optional arg)
4246 "Create indirect buffer and narrow it to current subtree.
4247 With numerical prefix ARG, go up to this level and then take that tree.
4248 If ARG is negative, go up that many levels.
4249 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4250 indirect buffer previously made with this command, to avoid proliferation of
4251 indirect buffers. However, when you call the command with a `C-u' prefix, or
4252 when `org-indirect-buffer-display' is `new-frame', the last buffer
4253 is kept so that you can work with several indirect buffers at the same time.
4254 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4255 requests that a new frame be made for the new buffer, so that the dedicated
4256 frame is not changed."
4257 (interactive "P")
4258 (let ((cbuf (current-buffer))
4259 (cwin (selected-window))
4260 (pos (point))
4261 beg end level heading ibuf)
4262 (save-excursion
4263 (org-back-to-heading t)
4264 (when (numberp arg)
4265 (setq level (org-outline-level))
4266 (if (< arg 0) (setq arg (+ level arg)))
4267 (while (> (setq level (org-outline-level)) arg)
4268 (outline-up-heading 1 t)))
4269 (setq beg (point)
4270 heading (org-get-heading))
4271 (org-end-of-subtree t) (setq end (point)))
4272 (if (and (buffer-live-p org-last-indirect-buffer)
4273 (not (eq org-indirect-buffer-display 'new-frame))
4274 (not arg))
4275 (kill-buffer org-last-indirect-buffer))
4276 (setq ibuf (org-get-indirect-buffer cbuf)
4277 org-last-indirect-buffer ibuf)
4278 (cond
4279 ((or (eq org-indirect-buffer-display 'new-frame)
4280 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4281 (select-frame (make-frame))
4282 (delete-other-windows)
4283 (switch-to-buffer ibuf)
4284 (org-set-frame-title heading))
4285 ((eq org-indirect-buffer-display 'dedicated-frame)
4286 (raise-frame
4287 (select-frame (or (and org-indirect-dedicated-frame
4288 (frame-live-p org-indirect-dedicated-frame)
4289 org-indirect-dedicated-frame)
4290 (setq org-indirect-dedicated-frame (make-frame)))))
4291 (delete-other-windows)
4292 (switch-to-buffer ibuf)
4293 (org-set-frame-title (concat "Indirect: " heading)))
4294 ((eq org-indirect-buffer-display 'current-window)
4295 (switch-to-buffer ibuf))
4296 ((eq org-indirect-buffer-display 'other-window)
4297 (pop-to-buffer ibuf))
4298 (t (error "Invalid value.")))
4299 (if (featurep 'xemacs)
4300 (save-excursion (org-mode) (turn-on-font-lock)))
4301 (narrow-to-region beg end)
4302 (show-all)
4303 (goto-char pos)
4304 (and (window-live-p cwin) (select-window cwin))))
4306 (defun org-get-indirect-buffer (&optional buffer)
4307 (setq buffer (or buffer (current-buffer)))
4308 (let ((n 1) (base (buffer-name buffer)) bname)
4309 (while (buffer-live-p
4310 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4311 (setq n (1+ n)))
4312 (condition-case nil
4313 (make-indirect-buffer buffer bname 'clone)
4314 (error (make-indirect-buffer buffer bname)))))
4316 (defun org-set-frame-title (title)
4317 "Set the title of the current frame to the string TITLE."
4318 ;; FIXME: how to name a single frame in XEmacs???
4319 (unless (featurep 'xemacs)
4320 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4322 ;;;; Structure editing
4324 ;;; Inserting headlines
4326 (defun org-insert-heading (&optional force-heading)
4327 "Insert a new heading or item with same depth at point.
4328 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4329 If point is at the beginning of a headline, insert a sibling before the
4330 current headline. If point is not at the beginning, do not split the line,
4331 but create the new hedline after the current line."
4332 (interactive "P")
4333 (if (= (buffer-size) 0)
4334 (insert "\n* ")
4335 (when (or force-heading (not (org-insert-item)))
4336 (let* ((head (save-excursion
4337 (condition-case nil
4338 (progn
4339 (org-back-to-heading)
4340 (match-string 0))
4341 (error "*"))))
4342 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4343 pos)
4344 (cond
4345 ((and (org-on-heading-p) (bolp)
4346 (or (bobp)
4347 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4348 ;; insert before the current line
4349 (open-line (if blank 2 1)))
4350 ((and (bolp)
4351 (or (bobp)
4352 (save-excursion
4353 (backward-char 1) (not (org-invisible-p)))))
4354 ;; insert right here
4355 nil)
4357 ;; in the middle of the line
4358 (org-show-entry)
4359 (let ((split
4360 (org-get-alist-option org-M-RET-may-split-line 'headline))
4361 tags pos)
4362 (if (org-on-heading-p)
4363 (progn
4364 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4365 (setq tags (and (match-end 2) (match-string 2)))
4366 (and (match-end 1)
4367 (delete-region (match-beginning 1) (match-end 1)))
4368 (setq pos (point-at-bol))
4369 (or split (end-of-line 1))
4370 (delete-horizontal-space)
4371 (newline (if blank 2 1))
4372 (when tags
4373 (save-excursion
4374 (goto-char pos)
4375 (end-of-line 1)
4376 (insert " " tags)
4377 (org-set-tags nil 'align))))
4378 (or split (end-of-line 1))
4379 (newline (if blank 2 1))))))
4380 (insert head) (just-one-space)
4381 (setq pos (point))
4382 (end-of-line 1)
4383 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4384 (run-hooks 'org-insert-heading-hook)))))
4386 (defun org-get-heading (&optional no-tags)
4387 "Return the heading of the current entry, without the stars."
4388 (save-excursion
4389 (org-back-to-heading t)
4390 (if (looking-at
4391 (if no-tags
4392 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4393 "\\*+[ \t]+\\([^\r\n]*\\)"))
4394 (match-string 1) "")))
4396 (defun org-insert-heading-after-current ()
4397 "Insert a new heading with same level as current, after current subtree."
4398 (interactive)
4399 (org-back-to-heading)
4400 (org-insert-heading)
4401 (org-move-subtree-down)
4402 (end-of-line 1))
4404 (defun org-insert-todo-heading (arg)
4405 "Insert a new heading with the same level and TODO state as current heading.
4406 If the heading has no TODO state, or if the state is DONE, use the first
4407 state (TODO by default). Also with prefix arg, force first state."
4408 (interactive "P")
4409 (when (not (org-insert-item 'checkbox))
4410 (org-insert-heading)
4411 (save-excursion
4412 (org-back-to-heading)
4413 (outline-previous-heading)
4414 (looking-at org-todo-line-regexp))
4415 (if (or arg
4416 (not (match-beginning 2))
4417 (member (match-string 2) org-done-keywords))
4418 (insert (car org-todo-keywords-1) " ")
4419 (insert (match-string 2) " "))))
4421 (defun org-insert-subheading (arg)
4422 "Insert a new subheading and demote it.
4423 Works for outline headings and for plain lists alike."
4424 (interactive "P")
4425 (org-insert-heading arg)
4426 (cond
4427 ((org-on-heading-p) (org-do-demote))
4428 ((org-at-item-p) (org-indent-item 1))))
4430 (defun org-insert-todo-subheading (arg)
4431 "Insert a new subheading with TODO keyword or checkbox and demote it.
4432 Works for outline headings and for plain lists alike."
4433 (interactive "P")
4434 (org-insert-todo-heading arg)
4435 (cond
4436 ((org-on-heading-p) (org-do-demote))
4437 ((org-at-item-p) (org-indent-item 1))))
4439 ;;; Promotion and Demotion
4441 (defun org-promote-subtree ()
4442 "Promote the entire subtree.
4443 See also `org-promote'."
4444 (interactive)
4445 (save-excursion
4446 (org-map-tree 'org-promote))
4447 (org-fix-position-after-promote))
4449 (defun org-demote-subtree ()
4450 "Demote the entire subtree. See `org-demote'.
4451 See also `org-promote'."
4452 (interactive)
4453 (save-excursion
4454 (org-map-tree 'org-demote))
4455 (org-fix-position-after-promote))
4458 (defun org-do-promote ()
4459 "Promote the current heading higher up the tree.
4460 If the region is active in `transient-mark-mode', promote all headings
4461 in the region."
4462 (interactive)
4463 (save-excursion
4464 (if (org-region-active-p)
4465 (org-map-region 'org-promote (region-beginning) (region-end))
4466 (org-promote)))
4467 (org-fix-position-after-promote))
4469 (defun org-do-demote ()
4470 "Demote the current heading lower down the tree.
4471 If the region is active in `transient-mark-mode', demote all headings
4472 in the region."
4473 (interactive)
4474 (save-excursion
4475 (if (org-region-active-p)
4476 (org-map-region 'org-demote (region-beginning) (region-end))
4477 (org-demote)))
4478 (org-fix-position-after-promote))
4480 (defun org-fix-position-after-promote ()
4481 "Make sure that after pro/demotion cursor position is right."
4482 (let ((pos (point)))
4483 (when (save-excursion
4484 (beginning-of-line 1)
4485 (looking-at org-todo-line-regexp)
4486 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4487 (cond ((eobp) (insert " "))
4488 ((eolp) (insert " "))
4489 ((equal (char-after) ?\ ) (forward-char 1))))))
4491 (defun org-reduced-level (l)
4492 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4494 (defun org-get-valid-level (level &optional change)
4495 "Rectify a level change under the influence of `org-odd-levels-only'
4496 LEVEL is a current level, CHANGE is by how much the level should be
4497 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4498 even level numbers will become the next higher odd number."
4499 (if org-odd-levels-only
4500 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4501 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4502 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4503 (max 1 (+ level change))))
4505 (if (boundp 'define-obsolete-function-alias)
4506 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4507 (define-obsolete-function-alias 'org-get-legal-level
4508 'org-get-valid-level)
4509 (define-obsolete-function-alias 'org-get-legal-level
4510 'org-get-valid-level "23.1")))
4512 (defun org-promote ()
4513 "Promote the current heading higher up the tree.
4514 If the region is active in `transient-mark-mode', promote all headings
4515 in the region."
4516 (org-back-to-heading t)
4517 (let* ((level (save-match-data (funcall outline-level)))
4518 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4519 (diff (abs (- level (length up-head) -1))))
4520 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4521 (replace-match up-head nil t)
4522 ;; Fixup tag positioning
4523 (and org-auto-align-tags (org-set-tags nil t))
4524 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4526 (defun org-demote ()
4527 "Demote the current heading lower down the tree.
4528 If the region is active in `transient-mark-mode', demote all headings
4529 in the region."
4530 (org-back-to-heading t)
4531 (let* ((level (save-match-data (funcall outline-level)))
4532 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4533 (diff (abs (- level (length down-head) -1))))
4534 (replace-match down-head nil t)
4535 ;; Fixup tag positioning
4536 (and org-auto-align-tags (org-set-tags nil t))
4537 (if org-adapt-indentation (org-fixup-indentation diff))))
4539 (defun org-map-tree (fun)
4540 "Call FUN for every heading underneath the current one."
4541 (org-back-to-heading)
4542 (let ((level (funcall outline-level)))
4543 (save-excursion
4544 (funcall fun)
4545 (while (and (progn
4546 (outline-next-heading)
4547 (> (funcall outline-level) level))
4548 (not (eobp)))
4549 (funcall fun)))))
4551 (defun org-map-region (fun beg end)
4552 "Call FUN for every heading between BEG and END."
4553 (let ((org-ignore-region t))
4554 (save-excursion
4555 (setq end (copy-marker end))
4556 (goto-char beg)
4557 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4558 (< (point) end))
4559 (funcall fun))
4560 (while (and (progn
4561 (outline-next-heading)
4562 (< (point) end))
4563 (not (eobp)))
4564 (funcall fun)))))
4566 (defun org-fixup-indentation (diff)
4567 "Change the indentation in the current entry by DIFF
4568 However, if any line in the current entry has no indentation, or if it
4569 would end up with no indentation after the change, nothing at all is done."
4570 (save-excursion
4571 (let ((end (save-excursion (outline-next-heading)
4572 (point-marker)))
4573 (prohibit (if (> diff 0)
4574 "^\\S-"
4575 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4576 col)
4577 (unless (save-excursion (end-of-line 1)
4578 (re-search-forward prohibit end t))
4579 (while (and (< (point) end)
4580 (re-search-forward "^[ \t]+" end t))
4581 (goto-char (match-end 0))
4582 (setq col (current-column))
4583 (if (< diff 0) (replace-match ""))
4584 (indent-to (+ diff col))))
4585 (move-marker end nil))))
4587 (defun org-convert-to-odd-levels ()
4588 "Convert an org-mode file with all levels allowed to one with odd levels.
4589 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4590 level 5 etc."
4591 (interactive)
4592 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4593 (let ((org-odd-levels-only nil) n)
4594 (save-excursion
4595 (goto-char (point-min))
4596 (while (re-search-forward "^\\*\\*+ " nil t)
4597 (setq n (- (length (match-string 0)) 2))
4598 (while (>= (setq n (1- n)) 0)
4599 (org-demote))
4600 (end-of-line 1))))))
4603 (defun org-convert-to-oddeven-levels ()
4604 "Convert an org-mode file with only odd levels to one with odd and even levels.
4605 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4606 section with an even level, conversion would destroy the structure of the file. An error
4607 is signaled in this case."
4608 (interactive)
4609 (goto-char (point-min))
4610 ;; First check if there are no even levels
4611 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4612 (org-show-context t)
4613 (error "Not all levels are odd in this file. Conversion not possible."))
4614 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4615 (let ((org-odd-levels-only nil) n)
4616 (save-excursion
4617 (goto-char (point-min))
4618 (while (re-search-forward "^\\*\\*+ " nil t)
4619 (setq n (/ (1- (length (match-string 0))) 2))
4620 (while (>= (setq n (1- n)) 0)
4621 (org-promote))
4622 (end-of-line 1))))))
4624 (defun org-tr-level (n)
4625 "Make N odd if required."
4626 (if org-odd-levels-only (1+ (/ n 2)) n))
4628 ;;; Vertical tree motion, cutting and pasting of subtrees
4630 (defun org-move-subtree-up (&optional arg)
4631 "Move the current subtree up past ARG headlines of the same level."
4632 (interactive "p")
4633 (org-move-subtree-down (- (prefix-numeric-value arg))))
4635 (defun org-move-subtree-down (&optional arg)
4636 "Move the current subtree down past ARG headlines of the same level."
4637 (interactive "p")
4638 (setq arg (prefix-numeric-value arg))
4639 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4640 'outline-get-last-sibling))
4641 (ins-point (make-marker))
4642 (cnt (abs arg))
4643 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4644 ;; Select the tree
4645 (org-back-to-heading)
4646 (setq beg0 (point))
4647 (save-excursion
4648 (setq ne-beg (org-back-over-empty-lines))
4649 (setq beg (point)))
4650 (save-match-data
4651 (save-excursion (outline-end-of-heading)
4652 (setq folded (org-invisible-p)))
4653 (outline-end-of-subtree))
4654 (outline-next-heading)
4655 (setq ne-end (org-back-over-empty-lines))
4656 (setq end (point))
4657 (goto-char beg0)
4658 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4659 ;; include less whitespace
4660 (save-excursion
4661 (goto-char beg)
4662 (forward-line (- ne-beg ne-end))
4663 (setq beg (point))))
4664 ;; Find insertion point, with error handling
4665 (while (> cnt 0)
4666 (or (and (funcall movfunc) (looking-at outline-regexp))
4667 (progn (goto-char beg0)
4668 (error "Cannot move past superior level or buffer limit")))
4669 (setq cnt (1- cnt)))
4670 (if (> arg 0)
4671 ;; Moving forward - still need to move over subtree
4672 (progn (org-end-of-subtree t t)
4673 (save-excursion
4674 (org-back-over-empty-lines)
4675 (or (bolp) (newline)))))
4676 (setq ne-ins (org-back-over-empty-lines))
4677 (move-marker ins-point (point))
4678 (setq txt (buffer-substring beg end))
4679 (org-save-markers-in-region beg end)
4680 (delete-region beg end)
4681 (outline-flag-region (1- beg) beg nil)
4682 (outline-flag-region (1- (point)) (point) nil)
4683 (let ((bbb (point)))
4684 (insert-before-markers txt)
4685 (org-reinstall-markers-in-region bbb)
4686 (move-marker ins-point bbb))
4687 (or (bolp) (insert "\n"))
4688 (setq ins-end (point))
4689 (goto-char ins-point)
4690 (org-skip-whitespace)
4691 (when (and (< arg 0)
4692 (org-first-sibling-p)
4693 (> ne-ins ne-beg))
4694 ;; Move whitespace back to beginning
4695 (save-excursion
4696 (goto-char ins-end)
4697 (let ((kill-whole-line t))
4698 (kill-line (- ne-ins ne-beg)) (point)))
4699 (insert (make-string (- ne-ins ne-beg) ?\n)))
4700 (move-marker ins-point nil)
4701 (org-compact-display-after-subtree-move)
4702 (unless folded
4703 (org-show-entry)
4704 (show-children)
4705 (org-cycle-hide-drawers 'children))))
4707 (defvar org-subtree-clip ""
4708 "Clipboard for cut and paste of subtrees.
4709 This is actually only a copy of the kill, because we use the normal kill
4710 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4712 (defvar org-subtree-clip-folded nil
4713 "Was the last copied subtree folded?
4714 This is used to fold the tree back after pasting.")
4716 (defun org-cut-subtree (&optional n)
4717 "Cut the current subtree into the clipboard.
4718 With prefix arg N, cut this many sequential subtrees.
4719 This is a short-hand for marking the subtree and then cutting it."
4720 (interactive "p")
4721 (org-copy-subtree n 'cut))
4723 (defun org-copy-subtree (&optional n cut force-store-markers)
4724 "Cut the current subtree into the clipboard.
4725 With prefix arg N, cut this many sequential subtrees.
4726 This is a short-hand for marking the subtree and then copying it.
4727 If CUT is non-nil, actually cut the subtree.
4728 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4729 of some markers in the region, even if CUT is non-nil. This is
4730 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4731 (interactive "p")
4732 (let (beg end folded (beg0 (point)))
4733 (if (interactive-p)
4734 (org-back-to-heading nil) ; take what looks like a subtree
4735 (org-back-to-heading t)) ; take what is really there
4736 (org-back-over-empty-lines)
4737 (setq beg (point))
4738 (skip-chars-forward " \t\r\n")
4739 (save-match-data
4740 (save-excursion (outline-end-of-heading)
4741 (setq folded (org-invisible-p)))
4742 (condition-case nil
4743 (outline-forward-same-level (1- n))
4744 (error nil))
4745 (org-end-of-subtree t t))
4746 (org-back-over-empty-lines)
4747 (setq end (point))
4748 (goto-char beg0)
4749 (when (> end beg)
4750 (setq org-subtree-clip-folded folded)
4751 (when (or cut force-store-markers)
4752 (org-save-markers-in-region beg end))
4753 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4754 (setq org-subtree-clip (current-kill 0))
4755 (message "%s: Subtree(s) with %d characters"
4756 (if cut "Cut" "Copied")
4757 (length org-subtree-clip)))))
4759 (defun org-paste-subtree (&optional level tree)
4760 "Paste the clipboard as a subtree, with modification of headline level.
4761 The entire subtree is promoted or demoted in order to match a new headline
4762 level. By default, the new level is derived from the visible headings
4763 before and after the insertion point, and taken to be the inferior headline
4764 level of the two. So if the previous visible heading is level 3 and the
4765 next is level 4 (or vice versa), level 4 will be used for insertion.
4766 This makes sure that the subtree remains an independent subtree and does
4767 not swallow low level entries.
4769 You can also force a different level, either by using a numeric prefix
4770 argument, or by inserting the heading marker by hand. For example, if the
4771 cursor is after \"*****\", then the tree will be shifted to level 5.
4773 If you want to insert the tree as is, just use \\[yank].
4775 If optional TREE is given, use this text instead of the kill ring."
4776 (interactive "P")
4777 (unless (org-kill-is-subtree-p tree)
4778 (error "%s"
4779 (substitute-command-keys
4780 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4781 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4782 (^re (concat "^\\(" outline-regexp "\\)"))
4783 (re (concat "\\(" outline-regexp "\\)"))
4784 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4786 (old-level (if (string-match ^re txt)
4787 (- (match-end 0) (match-beginning 0) 1)
4788 -1))
4789 (force-level (cond (level (prefix-numeric-value level))
4790 ((string-match
4791 ^re_ (buffer-substring (point-at-bol) (point)))
4792 (- (match-end 1) (match-beginning 1)))
4793 (t nil)))
4794 (previous-level (save-excursion
4795 (condition-case nil
4796 (progn
4797 (outline-previous-visible-heading 1)
4798 (if (looking-at re)
4799 (- (match-end 0) (match-beginning 0) 1)
4801 (error 1))))
4802 (next-level (save-excursion
4803 (condition-case nil
4804 (progn
4805 (or (looking-at outline-regexp)
4806 (outline-next-visible-heading 1))
4807 (if (looking-at re)
4808 (- (match-end 0) (match-beginning 0) 1)
4810 (error 1))))
4811 (new-level (or force-level (max previous-level next-level)))
4812 (shift (if (or (= old-level -1)
4813 (= new-level -1)
4814 (= old-level new-level))
4816 (- new-level old-level)))
4817 (delta (if (> shift 0) -1 1))
4818 (func (if (> shift 0) 'org-demote 'org-promote))
4819 (org-odd-levels-only nil)
4820 beg end)
4821 ;; Remove the forced level indicator
4822 (if force-level
4823 (delete-region (point-at-bol) (point)))
4824 ;; Paste
4825 (beginning-of-line 1)
4826 (org-back-over-empty-lines)
4827 (setq beg (point))
4828 (insert-before-markers txt)
4829 (unless (string-match "\n\\'" txt) (insert "\n"))
4830 (org-reinstall-markers-in-region beg)
4831 (setq end (point))
4832 (goto-char beg)
4833 (skip-chars-forward " \t\n\r")
4834 (setq beg (point))
4835 ;; Shift if necessary
4836 (unless (= shift 0)
4837 (save-restriction
4838 (narrow-to-region beg end)
4839 (while (not (= shift 0))
4840 (org-map-region func (point-min) (point-max))
4841 (setq shift (+ delta shift)))
4842 (goto-char (point-min))))
4843 (when (interactive-p)
4844 (message "Clipboard pasted as level %d subtree" new-level))
4845 (if (and kill-ring
4846 (eq org-subtree-clip (current-kill 0))
4847 org-subtree-clip-folded)
4848 ;; The tree was folded before it was killed/copied
4849 (hide-subtree))))
4851 (defun org-kill-is-subtree-p (&optional txt)
4852 "Check if the current kill is an outline subtree, or a set of trees.
4853 Returns nil if kill does not start with a headline, or if the first
4854 headline level is not the largest headline level in the tree.
4855 So this will actually accept several entries of equal levels as well,
4856 which is OK for `org-paste-subtree'.
4857 If optional TXT is given, check this string instead of the current kill."
4858 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4859 (start-level (and kill
4860 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4861 org-outline-regexp "\\)")
4862 kill)
4863 (- (match-end 2) (match-beginning 2) 1)))
4864 (re (concat "^" org-outline-regexp))
4865 (start (1+ (match-beginning 2))))
4866 (if (not start-level)
4867 (progn
4868 nil) ;; does not even start with a heading
4869 (catch 'exit
4870 (while (setq start (string-match re kill (1+ start)))
4871 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4872 (throw 'exit nil)))
4873 t))))
4875 (defvar org-markers-to-move nil
4876 "Markers that should be moved with a cut-and-paste operation.
4877 Those markers are stored together with their positions relative to
4878 the start of the region.")
4880 (defun org-save-markers-in-region (beg end)
4881 "Check markers in region.
4882 If these markers are between BEG and END, record their position relative
4883 to BEG, so that after moving the block of text, we can put the markers back
4884 into place.
4885 This function gets called just before an entry or tree gets cut from the
4886 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4887 called immediately, to move the markers with the entries."
4888 (setq org-markers-to-move nil)
4889 (when (featurep 'org-clock)
4890 (org-clock-save-markers-for-cut-and-paste beg end))
4891 (when (featurep 'org-agenda)
4892 (org-agenda-save-markers-for-cut-and-paste beg end)))
4894 (defun org-check-and-save-marker (marker beg end)
4895 "Check if MARKER is between BEG and END.
4896 If yes, remember the marker and the distance to BEG."
4897 (when (and (marker-buffer marker)
4898 (equal (marker-buffer marker) (current-buffer)))
4899 (if (and (>= marker beg) (< marker end))
4900 (push (cons marker (- marker beg)) org-markers-to-move))))
4902 (defun org-reinstall-markers-in-region (beg)
4903 "Move all remembered markers to their position relative to BEG."
4904 (mapc (lambda (x)
4905 (move-marker (car x) (+ beg (cdr x))))
4906 org-markers-to-move)
4907 (setq org-markers-to-move nil))
4909 (defun org-narrow-to-subtree ()
4910 "Narrow buffer to the current subtree."
4911 (interactive)
4912 (save-excursion
4913 (save-match-data
4914 (narrow-to-region
4915 (progn (org-back-to-heading) (point))
4916 (progn (org-end-of-subtree t t) (point))))))
4919 ;;; Outline Sorting
4921 (defun org-sort (with-case)
4922 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4923 Optional argument WITH-CASE means sort case-sensitively."
4924 (interactive "P")
4925 (if (org-at-table-p)
4926 (org-call-with-arg 'org-table-sort-lines with-case)
4927 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4929 (defun org-sort-remove-invisible (s)
4930 (remove-text-properties 0 (length s) org-rm-props s)
4931 (while (string-match org-bracket-link-regexp s)
4932 (setq s (replace-match (if (match-end 2)
4933 (match-string 3 s)
4934 (match-string 1 s)) t t s)))
4937 (defvar org-priority-regexp) ; defined later in the file
4939 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4940 "Sort entries on a certain level of an outline tree.
4941 If there is an active region, the entries in the region are sorted.
4942 Else, if the cursor is before the first entry, sort the top-level items.
4943 Else, the children of the entry at point are sorted.
4945 Sorting can be alphabetically, numerically, and by date/time as given by
4946 the first time stamp in the entry. The command prompts for the sorting
4947 type unless it has been given to the function through the SORTING-TYPE
4948 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4949 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4950 called with point at the beginning of the record. It must return either
4951 a string or a number that should serve as the sorting key for that record.
4953 Comparing entries ignores case by default. However, with an optional argument
4954 WITH-CASE, the sorting considers case as well."
4955 (interactive "P")
4956 (let ((case-func (if with-case 'identity 'downcase))
4957 start beg end stars re re2
4958 txt what tmp plain-list-p)
4959 ;; Find beginning and end of region to sort
4960 (cond
4961 ((org-region-active-p)
4962 ;; we will sort the region
4963 (setq end (region-end)
4964 what "region")
4965 (goto-char (region-beginning))
4966 (if (not (org-on-heading-p)) (outline-next-heading))
4967 (setq start (point)))
4968 ((org-at-item-p)
4969 ;; we will sort this plain list
4970 (org-beginning-of-item-list) (setq start (point))
4971 (org-end-of-item-list) (setq end (point))
4972 (goto-char start)
4973 (setq plain-list-p t
4974 what "plain list"))
4975 ((or (org-on-heading-p)
4976 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4977 ;; we will sort the children of the current headline
4978 (org-back-to-heading)
4979 (setq start (point)
4980 end (progn (org-end-of-subtree t t)
4981 (org-back-over-empty-lines)
4982 (point))
4983 what "children")
4984 (goto-char start)
4985 (show-subtree)
4986 (outline-next-heading))
4988 ;; we will sort the top-level entries in this file
4989 (goto-char (point-min))
4990 (or (org-on-heading-p) (outline-next-heading))
4991 (setq start (point) end (point-max) what "top-level")
4992 (goto-char start)
4993 (show-all)))
4995 (setq beg (point))
4996 (if (>= beg end) (error "Nothing to sort"))
4998 (unless plain-list-p
4999 (looking-at "\\(\\*+\\)")
5000 (setq stars (match-string 1)
5001 re (concat "^" (regexp-quote stars) " +")
5002 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5003 txt (buffer-substring beg end))
5004 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5005 (if (and (not (equal stars "*")) (string-match re2 txt))
5006 (error "Region to sort contains a level above the first entry")))
5008 (unless sorting-type
5009 (message
5010 (if plain-list-p
5011 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5012 "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:")
5013 what)
5014 (setq sorting-type (read-char-exclusive))
5016 (and (= (downcase sorting-type) ?f)
5017 (setq getkey-func
5018 (completing-read "Sort using function: "
5019 obarray 'fboundp t nil nil))
5020 (setq getkey-func (intern getkey-func)))
5022 (and (= (downcase sorting-type) ?r)
5023 (setq property
5024 (completing-read "Property: "
5025 (mapcar 'list (org-buffer-property-keys t))
5026 nil t))))
5028 (message "Sorting entries...")
5030 (save-restriction
5031 (narrow-to-region start end)
5033 (let ((dcst (downcase sorting-type))
5034 (now (current-time)))
5035 (sort-subr
5036 (/= dcst sorting-type)
5037 ;; This function moves to the beginning character of the "record" to
5038 ;; be sorted.
5039 (if plain-list-p
5040 (lambda nil
5041 (if (org-at-item-p) t (goto-char (point-max))))
5042 (lambda nil
5043 (if (re-search-forward re nil t)
5044 (goto-char (match-beginning 0))
5045 (goto-char (point-max)))))
5046 ;; This function moves to the last character of the "record" being
5047 ;; sorted.
5048 (if plain-list-p
5049 'org-end-of-item
5050 (lambda nil
5051 (save-match-data
5052 (condition-case nil
5053 (outline-forward-same-level 1)
5054 (error
5055 (goto-char (point-max)))))))
5057 ;; This function returns the value that gets sorted against.
5058 (if plain-list-p
5059 (lambda nil
5060 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5061 (cond
5062 ((= dcst ?n)
5063 (string-to-number (buffer-substring (match-end 0)
5064 (point-at-eol))))
5065 ((= dcst ?a)
5066 (buffer-substring (match-end 0) (point-at-eol)))
5067 ((= dcst ?t)
5068 (if (re-search-forward org-ts-regexp
5069 (point-at-eol) t)
5070 (org-time-string-to-time (match-string 0))
5071 now))
5072 ((= dcst ?f)
5073 (if getkey-func
5074 (progn
5075 (setq tmp (funcall getkey-func))
5076 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5077 tmp)
5078 (error "Invalid key function `%s'" getkey-func)))
5079 (t (error "Invalid sorting type `%c'" sorting-type)))))
5080 (lambda nil
5081 (cond
5082 ((= dcst ?n)
5083 (if (looking-at outline-regexp)
5084 (string-to-number (buffer-substring (match-end 0)
5085 (point-at-eol)))
5086 nil))
5087 ((= dcst ?a)
5088 (funcall case-func (buffer-substring (point-at-bol)
5089 (point-at-eol))))
5090 ((= dcst ?t)
5091 (if (re-search-forward org-ts-regexp
5092 (save-excursion
5093 (forward-line 2)
5094 (point)) t)
5095 (org-time-string-to-time (match-string 0))
5096 now))
5097 ((= dcst ?p)
5098 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5099 (string-to-char (match-string 2))
5100 org-default-priority))
5101 ((= dcst ?r)
5102 (or (org-entry-get nil property) ""))
5103 ((= dcst ?o)
5104 (if (looking-at org-complex-heading-regexp)
5105 (- 9999 (length (member (match-string 2)
5106 org-todo-keywords-1)))))
5107 ((= dcst ?f)
5108 (if getkey-func
5109 (progn
5110 (setq tmp (funcall getkey-func))
5111 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5112 tmp)
5113 (error "Invalid key function `%s'" getkey-func)))
5114 (t (error "Invalid sorting type `%c'" sorting-type)))))
5116 (cond
5117 ((= dcst ?a) 'string<)
5118 ((= dcst ?t) 'time-less-p)
5119 (t nil)))))
5120 (message "Sorting entries...done")))
5122 (defun org-do-sort (table what &optional with-case sorting-type)
5123 "Sort TABLE of WHAT according to SORTING-TYPE.
5124 The user will be prompted for the SORTING-TYPE if the call to this
5125 function does not specify it. WHAT is only for the prompt, to indicate
5126 what is being sorted. The sorting key will be extracted from
5127 the car of the elements of the table.
5128 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5129 (unless sorting-type
5130 (message
5131 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5132 what)
5133 (setq sorting-type (read-char-exclusive)))
5134 (let ((dcst (downcase sorting-type))
5135 extractfun comparefun)
5136 ;; Define the appropriate functions
5137 (cond
5138 ((= dcst ?n)
5139 (setq extractfun 'string-to-number
5140 comparefun (if (= dcst sorting-type) '< '>)))
5141 ((= dcst ?a)
5142 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5143 (lambda(x) (downcase (org-sort-remove-invisible x))))
5144 comparefun (if (= dcst sorting-type)
5145 'string<
5146 (lambda (a b) (and (not (string< a b))
5147 (not (string= a b)))))))
5148 ((= dcst ?t)
5149 (setq extractfun
5150 (lambda (x)
5151 (if (string-match org-ts-regexp x)
5152 (time-to-seconds
5153 (org-time-string-to-time (match-string 0 x)))
5155 comparefun (if (= dcst sorting-type) '< '>)))
5156 (t (error "Invalid sorting type `%c'" sorting-type)))
5158 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5159 table)
5160 (lambda (a b) (funcall comparefun (car a) (car b))))))
5162 ;;;; Plain list items, including checkboxes
5164 ;;; Plain list items
5166 (defun org-at-item-p ()
5167 "Is point in a line starting a hand-formatted item?"
5168 (let ((llt org-plain-list-ordered-item-terminator))
5169 (save-excursion
5170 (goto-char (point-at-bol))
5171 (looking-at
5172 (cond
5173 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5174 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5175 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5176 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5178 (defun org-in-item-p ()
5179 "It the cursor inside a plain list item.
5180 Does not have to be the first line."
5181 (save-excursion
5182 (condition-case nil
5183 (progn
5184 (org-beginning-of-item)
5185 (org-at-item-p)
5187 (error nil))))
5189 (defun org-insert-item (&optional checkbox)
5190 "Insert a new item at the current level.
5191 Return t when things worked, nil when we are not in an item."
5192 (when (save-excursion
5193 (condition-case nil
5194 (progn
5195 (org-beginning-of-item)
5196 (org-at-item-p)
5197 (if (org-invisible-p) (error "Invisible item"))
5199 (error nil)))
5200 (let* ((bul (match-string 0))
5201 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5202 (match-end 0)))
5203 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5204 pos)
5205 (cond
5206 ((and (org-at-item-p) (<= (point) eow))
5207 ;; before the bullet
5208 (beginning-of-line 1)
5209 (open-line (if blank 2 1)))
5210 ((<= (point) eow)
5211 (beginning-of-line 1))
5213 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5214 (end-of-line 1)
5215 (delete-horizontal-space))
5216 (newline (if blank 2 1))))
5217 (insert bul (if checkbox "[ ]" ""))
5218 (just-one-space)
5219 (setq pos (point))
5220 (end-of-line 1)
5221 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5222 (org-maybe-renumber-ordered-list)
5223 (and checkbox (org-update-checkbox-count-maybe))
5226 ;;; Checkboxes
5228 (defun org-at-item-checkbox-p ()
5229 "Is point at a line starting a plain-list item with a checklet?"
5230 (and (org-at-item-p)
5231 (save-excursion
5232 (goto-char (match-end 0))
5233 (skip-chars-forward " \t")
5234 (looking-at "\\[[- X]\\]"))))
5236 (defun org-toggle-checkbox (&optional arg)
5237 "Toggle the checkbox in the current line."
5238 (interactive "P")
5239 (catch 'exit
5240 (let (beg end status (firstnew 'unknown))
5241 (cond
5242 ((org-region-active-p)
5243 (setq beg (region-beginning) end (region-end)))
5244 ((org-on-heading-p)
5245 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5246 ((org-at-item-checkbox-p)
5247 (let ((pos (point)))
5248 (replace-match
5249 (cond (arg "[-]")
5250 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5251 (t "[ ]"))
5252 t t)
5253 (goto-char pos))
5254 (throw 'exit t))
5255 (t (error "Not at a checkbox or heading, and no active region")))
5256 (save-excursion
5257 (goto-char beg)
5258 (while (< (point) end)
5259 (when (org-at-item-checkbox-p)
5260 (setq status (equal (match-string 0) "[X]"))
5261 (when (eq firstnew 'unknown)
5262 (setq firstnew (not status)))
5263 (replace-match
5264 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5265 (beginning-of-line 2)))))
5266 (org-update-checkbox-count-maybe))
5268 (defun org-update-checkbox-count-maybe ()
5269 "Update checkbox statistics unless turned off by user."
5270 (when org-provide-checkbox-statistics
5271 (org-update-checkbox-count)))
5273 (defun org-update-checkbox-count (&optional all)
5274 "Update the checkbox statistics in the current section.
5275 This will find all statistic cookies like [57%] and [6/12] and update them
5276 with the current numbers. With optional prefix argument ALL, do this for
5277 the whole buffer."
5278 (interactive "P")
5279 (save-excursion
5280 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5281 (beg (condition-case nil
5282 (progn (outline-back-to-heading) (point))
5283 (error (point-min))))
5284 (end (move-marker (make-marker)
5285 (progn (outline-next-heading) (point))))
5286 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5287 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5288 (re-find (concat re "\\|" re-box))
5289 beg-cookie end-cookie is-percent c-on c-off lim
5290 eline curr-ind next-ind continue-from startsearch
5291 (cstat 0)
5293 (when all
5294 (goto-char (point-min))
5295 (outline-next-heading)
5296 (setq beg (point) end (point-max)))
5297 (goto-char end)
5298 ;; find each statistic cookie
5299 (while (re-search-backward re-find beg t)
5300 (setq beg-cookie (match-beginning 1)
5301 end-cookie (match-end 1)
5302 cstat (+ cstat (if end-cookie 1 0))
5303 startsearch (point-at-eol)
5304 continue-from (point-at-bol)
5305 is-percent (match-beginning 2)
5306 lim (cond
5307 ((org-on-heading-p) (outline-next-heading) (point))
5308 ((org-at-item-p) (org-end-of-item) (point))
5309 (t nil))
5310 c-on 0
5311 c-off 0)
5312 (when lim
5313 ;; find first checkbox for this cookie and gather
5314 ;; statistics from all that are at this indentation level
5315 (goto-char startsearch)
5316 (if (re-search-forward re-box lim t)
5317 (progn
5318 (org-beginning-of-item)
5319 (setq curr-ind (org-get-indentation))
5320 (setq next-ind curr-ind)
5321 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5322 (save-excursion (end-of-line) (setq eline (point)))
5323 (if (re-search-forward re-box eline t)
5324 (if (member (match-string 2) '("[ ]" "[-]"))
5325 (setq c-off (1+ c-off))
5326 (setq c-on (1+ c-on))
5329 (org-end-of-item)
5330 (setq next-ind (org-get-indentation))
5332 (goto-char continue-from)
5333 ;; update cookie
5334 (when end-cookie
5335 (delete-region beg-cookie end-cookie)
5336 (goto-char beg-cookie)
5337 (insert
5338 (if is-percent
5339 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5340 (format "[%d/%d]" c-on (+ c-on c-off)))))
5341 ;; update items checkbox if it has one
5342 (when (org-at-item-p)
5343 (org-beginning-of-item)
5344 (when (and (> (+ c-on c-off) 0)
5345 (re-search-forward re-box (point-at-eol) t))
5346 (setq beg-cookie (match-beginning 2)
5347 end-cookie (match-end 2))
5348 (delete-region beg-cookie end-cookie)
5349 (goto-char beg-cookie)
5350 (cond ((= c-off 0) (insert "[X]"))
5351 ((= c-on 0) (insert "[ ]"))
5352 (t (insert "[-]")))
5354 (goto-char continue-from))
5355 (when (interactive-p)
5356 (message "Checkbox satistics updated %s (%d places)"
5357 (if all "in entire file" "in current outline entry") cstat)))))
5359 (defun org-get-checkbox-statistics-face ()
5360 "Select the face for checkbox statistics.
5361 The face will be `org-done' when all relevant boxes are checked. Otherwise
5362 it will be `org-todo'."
5363 (if (match-end 1)
5364 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5365 (if (and (> (match-end 2) (match-beginning 2))
5366 (equal (match-string 2) (match-string 3)))
5367 'org-done
5368 'org-todo)))
5370 (defun org-get-indentation (&optional line)
5371 "Get the indentation of the current line, interpreting tabs.
5372 When LINE is given, assume it represents a line and compute its indentation."
5373 (if line
5374 (if (string-match "^ *" (org-remove-tabs line))
5375 (match-end 0))
5376 (save-excursion
5377 (beginning-of-line 1)
5378 (skip-chars-forward " \t")
5379 (current-column))))
5381 (defun org-remove-tabs (s &optional width)
5382 "Replace tabulators in S with spaces.
5383 Assumes that s is a single line, starting in column 0."
5384 (setq width (or width tab-width))
5385 (while (string-match "\t" s)
5386 (setq s (replace-match
5387 (make-string
5388 (- (* width (/ (+ (match-beginning 0) width) width))
5389 (match-beginning 0)) ?\ )
5390 t t s)))
5393 (defun org-fix-indentation (line ind)
5394 "Fix indentation in LINE.
5395 IND is a cons cell with target and minimum indentation.
5396 If the current indenation in LINE is smaller than the minimum,
5397 leave it alone. If it is larger than ind, set it to the target."
5398 (let* ((l (org-remove-tabs line))
5399 (i (org-get-indentation l))
5400 (i1 (car ind)) (i2 (cdr ind)))
5401 (if (>= i i2) (setq l (substring line i2)))
5402 (if (> i1 0)
5403 (concat (make-string i1 ?\ ) l)
5404 l)))
5406 (defun org-beginning-of-item ()
5407 "Go to the beginning of the current hand-formatted item.
5408 If the cursor is not in an item, throw an error."
5409 (interactive)
5410 (let ((pos (point))
5411 (limit (save-excursion
5412 (condition-case nil
5413 (progn
5414 (org-back-to-heading)
5415 (beginning-of-line 2) (point))
5416 (error (point-min)))))
5417 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5418 ind ind1)
5419 (if (org-at-item-p)
5420 (beginning-of-line 1)
5421 (beginning-of-line 1)
5422 (skip-chars-forward " \t")
5423 (setq ind (current-column))
5424 (if (catch 'exit
5425 (while t
5426 (beginning-of-line 0)
5427 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5429 (if (looking-at "[ \t]*$")
5430 (setq ind1 ind-empty)
5431 (skip-chars-forward " \t")
5432 (setq ind1 (current-column)))
5433 (if (< ind1 ind)
5434 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5436 (goto-char pos)
5437 (error "Not in an item")))))
5439 (defun org-end-of-item ()
5440 "Go to the end of the current hand-formatted item.
5441 If the cursor is not in an item, throw an error."
5442 (interactive)
5443 (let* ((pos (point))
5444 ind1
5445 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5446 (limit (save-excursion (outline-next-heading) (point)))
5447 (ind (save-excursion
5448 (org-beginning-of-item)
5449 (skip-chars-forward " \t")
5450 (current-column)))
5451 (end (catch 'exit
5452 (while t
5453 (beginning-of-line 2)
5454 (if (eobp) (throw 'exit (point)))
5455 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5456 (if (looking-at "[ \t]*$")
5457 (setq ind1 ind-empty)
5458 (skip-chars-forward " \t")
5459 (setq ind1 (current-column)))
5460 (if (<= ind1 ind)
5461 (throw 'exit (point-at-bol)))))))
5462 (if end
5463 (goto-char end)
5464 (goto-char pos)
5465 (error "Not in an item"))))
5467 (defun org-next-item ()
5468 "Move to the beginning of the next item in the current plain list.
5469 Error if not at a plain list, or if this is the last item in the list."
5470 (interactive)
5471 (let (ind ind1 (pos (point)))
5472 (org-beginning-of-item)
5473 (setq ind (org-get-indentation))
5474 (org-end-of-item)
5475 (setq ind1 (org-get-indentation))
5476 (unless (and (org-at-item-p) (= ind ind1))
5477 (goto-char pos)
5478 (error "On last item"))))
5480 (defun org-previous-item ()
5481 "Move to the beginning of the previous item in the current plain list.
5482 Error if not at a plain list, or if this is the first item in the list."
5483 (interactive)
5484 (let (beg ind ind1 (pos (point)))
5485 (org-beginning-of-item)
5486 (setq beg (point))
5487 (setq ind (org-get-indentation))
5488 (goto-char beg)
5489 (catch 'exit
5490 (while t
5491 (beginning-of-line 0)
5492 (if (looking-at "[ \t]*$")
5494 (if (<= (setq ind1 (org-get-indentation)) ind)
5495 (throw 'exit t)))))
5496 (condition-case nil
5497 (if (or (not (org-at-item-p))
5498 (< ind1 (1- ind)))
5499 (error "")
5500 (org-beginning-of-item))
5501 (error (goto-char pos)
5502 (error "On first item")))))
5504 (defun org-first-list-item-p ()
5505 "Is this heading the item in a plain list?"
5506 (unless (org-at-item-p)
5507 (error "Not at a plain list item"))
5508 (org-beginning-of-item)
5509 (= (point) (save-excursion (org-beginning-of-item-list))))
5511 (defun org-move-item-down ()
5512 "Move the plain list item at point down, i.e. swap with following item.
5513 Subitems (items with larger indentation) are considered part of the item,
5514 so this really moves item trees."
5515 (interactive)
5516 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5517 (org-beginning-of-item)
5518 (setq beg0 (point))
5519 (save-excursion
5520 (setq ne-beg (org-back-over-empty-lines))
5521 (setq beg (point)))
5522 (goto-char beg0)
5523 (setq ind (org-get-indentation))
5524 (org-end-of-item)
5525 (setq end0 (point))
5526 (setq ind1 (org-get-indentation))
5527 (setq ne-end (org-back-over-empty-lines))
5528 (setq end (point))
5529 (goto-char beg0)
5530 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5531 ;; include less whitespace
5532 (save-excursion
5533 (goto-char beg)
5534 (forward-line (- ne-beg ne-end))
5535 (setq beg (point))))
5536 (goto-char end0)
5537 (if (and (org-at-item-p) (= ind ind1))
5538 (progn
5539 (org-end-of-item)
5540 (org-back-over-empty-lines)
5541 (setq txt (buffer-substring beg end))
5542 (save-excursion
5543 (delete-region beg end))
5544 (setq pos (point))
5545 (insert txt)
5546 (goto-char pos) (org-skip-whitespace)
5547 (org-maybe-renumber-ordered-list))
5548 (goto-char pos)
5549 (error "Cannot move this item further down"))))
5551 (defun org-move-item-up (arg)
5552 "Move the plain list item at point up, i.e. swap with previous item.
5553 Subitems (items with larger indentation) are considered part of the item,
5554 so this really moves item trees."
5555 (interactive "p")
5556 (let (beg beg0 end ind ind1 (pos (point)) txt
5557 ne-beg ne-ins ins-end)
5558 (org-beginning-of-item)
5559 (setq beg0 (point))
5560 (setq ind (org-get-indentation))
5561 (save-excursion
5562 (setq ne-beg (org-back-over-empty-lines))
5563 (setq beg (point)))
5564 (goto-char beg0)
5565 (org-end-of-item)
5566 (setq end (point))
5567 (goto-char beg0)
5568 (catch 'exit
5569 (while t
5570 (beginning-of-line 0)
5571 (if (looking-at "[ \t]*$")
5572 (if org-empty-line-terminates-plain-lists
5573 (progn
5574 (goto-char pos)
5575 (error "Cannot move this item further up"))
5576 nil)
5577 (if (<= (setq ind1 (org-get-indentation)) ind)
5578 (throw 'exit t)))))
5579 (condition-case nil
5580 (org-beginning-of-item)
5581 (error (goto-char beg)
5582 (error "Cannot move this item further up")))
5583 (setq ind1 (org-get-indentation))
5584 (if (and (org-at-item-p) (= ind ind1))
5585 (progn
5586 (setq ne-ins (org-back-over-empty-lines))
5587 (setq txt (buffer-substring beg end))
5588 (save-excursion
5589 (delete-region beg end))
5590 (setq pos (point))
5591 (insert txt)
5592 (setq ins-end (point))
5593 (goto-char pos) (org-skip-whitespace)
5595 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5596 ;; Move whitespace back to beginning
5597 (save-excursion
5598 (goto-char ins-end)
5599 (let ((kill-whole-line t))
5600 (kill-line (- ne-ins ne-beg)) (point)))
5601 (insert (make-string (- ne-ins ne-beg) ?\n)))
5603 (org-maybe-renumber-ordered-list))
5604 (goto-char pos)
5605 (error "Cannot move this item further up"))))
5607 (defun org-maybe-renumber-ordered-list ()
5608 "Renumber the ordered list at point if setup allows it.
5609 This tests the user option `org-auto-renumber-ordered-lists' before
5610 doing the renumbering."
5611 (interactive)
5612 (when (and org-auto-renumber-ordered-lists
5613 (org-at-item-p))
5614 (if (match-beginning 3)
5615 (org-renumber-ordered-list 1)
5616 (org-fix-bullet-type))))
5618 (defun org-maybe-renumber-ordered-list-safe ()
5619 (condition-case nil
5620 (save-excursion
5621 (org-maybe-renumber-ordered-list))
5622 (error nil)))
5624 (defun org-cycle-list-bullet (&optional which)
5625 "Cycle through the different itemize/enumerate bullets.
5626 This cycle the entire list level through the sequence:
5628 `-' -> `+' -> `*' -> `1.' -> `1)'
5630 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5631 0 meand `-', 1 means `+' etc."
5632 (interactive "P")
5633 (org-preserve-lc
5634 (org-beginning-of-item-list)
5635 (org-at-item-p)
5636 (beginning-of-line 1)
5637 (let ((current (match-string 0))
5638 (prevp (eq which 'previous))
5639 new)
5640 (setq new (cond
5641 ((and (numberp which)
5642 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5643 ((string-match "-" current) (if prevp "1)" "+"))
5644 ((string-match "\\+" current)
5645 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5646 ((string-match "\\*" current) (if prevp "+" "1."))
5647 ((string-match "\\." current) (if prevp "*" "1)"))
5648 ((string-match ")" current) (if prevp "1." "-"))
5649 (t (error "This should not happen"))))
5650 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5651 (org-fix-bullet-type)
5652 (org-maybe-renumber-ordered-list))))
5654 (defun org-get-string-indentation (s)
5655 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5656 (let ((n -1) (i 0) (w tab-width) c)
5657 (catch 'exit
5658 (while (< (setq n (1+ n)) (length s))
5659 (setq c (aref s n))
5660 (cond ((= c ?\ ) (setq i (1+ i)))
5661 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5662 (t (throw 'exit t)))))
5665 (defun org-renumber-ordered-list (arg)
5666 "Renumber an ordered plain list.
5667 Cursor needs to be in the first line of an item, the line that starts
5668 with something like \"1.\" or \"2)\"."
5669 (interactive "p")
5670 (unless (and (org-at-item-p)
5671 (match-beginning 3))
5672 (error "This is not an ordered list"))
5673 (let ((line (org-current-line))
5674 (col (current-column))
5675 (ind (org-get-string-indentation
5676 (buffer-substring (point-at-bol) (match-beginning 3))))
5677 ;; (term (substring (match-string 3) -1))
5678 ind1 (n (1- arg))
5679 fmt)
5680 ;; find where this list begins
5681 (org-beginning-of-item-list)
5682 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5683 (setq fmt (concat "%d" (match-string 1)))
5684 (beginning-of-line 0)
5685 ;; walk forward and replace these numbers
5686 (catch 'exit
5687 (while t
5688 (catch 'next
5689 (beginning-of-line 2)
5690 (if (eobp) (throw 'exit nil))
5691 (if (looking-at "[ \t]*$") (throw 'next nil))
5692 (skip-chars-forward " \t") (setq ind1 (current-column))
5693 (if (> ind1 ind) (throw 'next t))
5694 (if (< ind1 ind) (throw 'exit t))
5695 (if (not (org-at-item-p)) (throw 'exit nil))
5696 (delete-region (match-beginning 2) (match-end 2))
5697 (goto-char (match-beginning 2))
5698 (insert (format fmt (setq n (1+ n)))))))
5699 (goto-line line)
5700 (org-move-to-column col)))
5702 (defun org-fix-bullet-type ()
5703 "Make sure all items in this list have the same bullet as the firsst item."
5704 (interactive)
5705 (unless (org-at-item-p) (error "This is not a list"))
5706 (let ((line (org-current-line))
5707 (col (current-column))
5708 (ind (current-indentation))
5709 ind1 bullet)
5710 ;; find where this list begins
5711 (org-beginning-of-item-list)
5712 (beginning-of-line 1)
5713 ;; find out what the bullet type is
5714 (looking-at "[ \t]*\\(\\S-+\\)")
5715 (setq bullet (match-string 1))
5716 ;; walk forward and replace these numbers
5717 (beginning-of-line 0)
5718 (catch 'exit
5719 (while t
5720 (catch 'next
5721 (beginning-of-line 2)
5722 (if (eobp) (throw 'exit nil))
5723 (if (looking-at "[ \t]*$") (throw 'next nil))
5724 (skip-chars-forward " \t") (setq ind1 (current-column))
5725 (if (> ind1 ind) (throw 'next t))
5726 (if (< ind1 ind) (throw 'exit t))
5727 (if (not (org-at-item-p)) (throw 'exit nil))
5728 (skip-chars-forward " \t")
5729 (looking-at "\\S-+")
5730 (replace-match bullet))))
5731 (goto-line line)
5732 (org-move-to-column col)
5733 (if (string-match "[0-9]" bullet)
5734 (org-renumber-ordered-list 1))))
5736 (defun org-beginning-of-item-list ()
5737 "Go to the beginning of the current item list.
5738 I.e. to the first item in this list."
5739 (interactive)
5740 (org-beginning-of-item)
5741 (let ((pos (point-at-bol))
5742 (ind (org-get-indentation))
5743 ind1)
5744 ;; find where this list begins
5745 (catch 'exit
5746 (while t
5747 (catch 'next
5748 (beginning-of-line 0)
5749 (if (looking-at "[ \t]*$")
5750 (throw (if (bobp) 'exit 'next) t))
5751 (skip-chars-forward " \t") (setq ind1 (current-column))
5752 (if (or (< ind1 ind)
5753 (and (= ind1 ind)
5754 (not (org-at-item-p)))
5755 (bobp))
5756 (throw 'exit t)
5757 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5758 (goto-char pos)))
5761 (defun org-end-of-item-list ()
5762 "Go to the end of the current item list.
5763 I.e. to the text after the last item."
5764 (interactive)
5765 (org-beginning-of-item)
5766 (let ((pos (point-at-bol))
5767 (ind (org-get-indentation))
5768 ind1)
5769 ;; find where this list begins
5770 (catch 'exit
5771 (while t
5772 (catch 'next
5773 (beginning-of-line 2)
5774 (if (looking-at "[ \t]*$")
5775 (throw (if (eobp) 'exit 'next) t))
5776 (skip-chars-forward " \t") (setq ind1 (current-column))
5777 (if (or (< ind1 ind)
5778 (and (= ind1 ind)
5779 (not (org-at-item-p)))
5780 (eobp))
5781 (progn
5782 (setq pos (point-at-bol))
5783 (throw 'exit t))))))
5784 (goto-char pos)))
5787 (defvar org-last-indent-begin-marker (make-marker))
5788 (defvar org-last-indent-end-marker (make-marker))
5790 (defun org-outdent-item (arg)
5791 "Outdent a local list item."
5792 (interactive "p")
5793 (org-indent-item (- arg)))
5795 (defun org-indent-item (arg)
5796 "Indent a local list item."
5797 (interactive "p")
5798 (unless (org-at-item-p)
5799 (error "Not on an item"))
5800 (save-excursion
5801 (let (beg end ind ind1 tmp delta ind-down ind-up)
5802 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5803 (setq beg org-last-indent-begin-marker
5804 end org-last-indent-end-marker)
5805 (org-beginning-of-item)
5806 (setq beg (move-marker org-last-indent-begin-marker (point)))
5807 (org-end-of-item)
5808 (setq end (move-marker org-last-indent-end-marker (point))))
5809 (goto-char beg)
5810 (setq tmp (org-item-indent-positions)
5811 ind (car tmp)
5812 ind-down (nth 2 tmp)
5813 ind-up (nth 1 tmp)
5814 delta (if (> arg 0)
5815 (if ind-down (- ind-down ind) 2)
5816 (if ind-up (- ind-up ind) -2)))
5817 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5818 (while (< (point) end)
5819 (beginning-of-line 1)
5820 (skip-chars-forward " \t") (setq ind1 (current-column))
5821 (delete-region (point-at-bol) (point))
5822 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5823 (beginning-of-line 2))))
5824 (org-fix-bullet-type)
5825 (org-maybe-renumber-ordered-list-safe)
5826 (save-excursion
5827 (beginning-of-line 0)
5828 (condition-case nil (org-beginning-of-item) (error nil))
5829 (org-maybe-renumber-ordered-list-safe)))
5831 (defun org-item-indent-positions ()
5832 "Return indentation for plain list items.
5833 This returns a list with three values: The current indentation, the
5834 parent indentation and the indentation a child should habe.
5835 Assumes cursor in item line."
5836 (let* ((bolpos (point-at-bol))
5837 (ind (org-get-indentation))
5838 ind-down ind-up pos)
5839 (save-excursion
5840 (org-beginning-of-item-list)
5841 (skip-chars-backward "\n\r \t")
5842 (when (org-in-item-p)
5843 (org-beginning-of-item)
5844 (setq ind-up (org-get-indentation))))
5845 (setq pos (point))
5846 (save-excursion
5847 (cond
5848 ((and (condition-case nil (progn (org-previous-item) t)
5849 (error nil))
5850 (or (forward-char 1) t)
5851 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5852 (setq ind-down (org-get-indentation)))
5853 ((and (goto-char pos)
5854 (org-at-item-p))
5855 (goto-char (match-end 0))
5856 (skip-chars-forward " \t")
5857 (setq ind-down (current-column)))))
5858 (list ind ind-up ind-down)))
5860 ;;; The orgstruct minor mode
5862 ;; Define a minor mode which can be used in other modes in order to
5863 ;; integrate the org-mode structure editing commands.
5865 ;; This is really a hack, because the org-mode structure commands use
5866 ;; keys which normally belong to the major mode. Here is how it
5867 ;; works: The minor mode defines all the keys necessary to operate the
5868 ;; structure commands, but wraps the commands into a function which
5869 ;; tests if the cursor is currently at a headline or a plain list
5870 ;; item. If that is the case, the structure command is used,
5871 ;; temporarily setting many Org-mode variables like regular
5872 ;; expressions for filling etc. However, when any of those keys is
5873 ;; used at a different location, function uses `key-binding' to look
5874 ;; up if the key has an associated command in another currently active
5875 ;; keymap (minor modes, major mode, global), and executes that
5876 ;; command. There might be problems if any of the keys is otherwise
5877 ;; used as a prefix key.
5879 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5880 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5881 ;; addresses this by checking explicitly for both bindings.
5883 (defvar orgstruct-mode-map (make-sparse-keymap)
5884 "Keymap for the minor `orgstruct-mode'.")
5886 (defvar org-local-vars nil
5887 "List of local variables, for use by `orgstruct-mode'")
5889 ;;;###autoload
5890 (define-minor-mode orgstruct-mode
5891 "Toggle the minor more `orgstruct-mode'.
5892 This mode is for using Org-mode structure commands in other modes.
5893 The following key behave as if Org-mode was active, if the cursor
5894 is on a headline, or on a plain list item (both in the definition
5895 of Org-mode).
5897 M-up Move entry/item up
5898 M-down Move entry/item down
5899 M-left Promote
5900 M-right Demote
5901 M-S-up Move entry/item up
5902 M-S-down Move entry/item down
5903 M-S-left Promote subtree
5904 M-S-right Demote subtree
5905 M-q Fill paragraph and items like in Org-mode
5906 C-c ^ Sort entries
5907 C-c - Cycle list bullet
5908 TAB Cycle item visibility
5909 M-RET Insert new heading/item
5910 S-M-RET Insert new TODO heading / Chekbox item
5911 C-c C-c Set tags / toggle checkbox"
5912 nil " OrgStruct" nil
5913 (org-load-modules-maybe)
5914 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5916 ;;;###autoload
5917 (defun turn-on-orgstruct ()
5918 "Unconditionally turn on `orgstruct-mode'."
5919 (orgstruct-mode 1))
5921 ;;;###autoload
5922 (defun turn-on-orgstruct++ ()
5923 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5924 In addition to setting orgstruct-mode, this also exports all indentation and
5925 autofilling variables from org-mode into the buffer. Note that turning
5926 off orgstruct-mode will *not* remove these additional settings."
5927 (orgstruct-mode 1)
5928 (let (var val)
5929 (mapc
5930 (lambda (x)
5931 (when (string-match
5932 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5933 (symbol-name (car x)))
5934 (setq var (car x) val (nth 1 x))
5935 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5936 org-local-vars)))
5938 (defun orgstruct-error ()
5939 "Error when there is no default binding for a structure key."
5940 (interactive)
5941 (error "This key has no function outside structure elements"))
5943 (defun orgstruct-setup ()
5944 "Setup orgstruct keymaps."
5945 (let ((nfunc 0)
5946 (bindings
5947 (list
5948 '([(meta up)] org-metaup)
5949 '([(meta down)] org-metadown)
5950 '([(meta left)] org-metaleft)
5951 '([(meta right)] org-metaright)
5952 '([(meta shift up)] org-shiftmetaup)
5953 '([(meta shift down)] org-shiftmetadown)
5954 '([(meta shift left)] org-shiftmetaleft)
5955 '([(meta shift right)] org-shiftmetaright)
5956 '([(shift up)] org-shiftup)
5957 '([(shift down)] org-shiftdown)
5958 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5959 '("\M-q" fill-paragraph)
5960 '("\C-c^" org-sort)
5961 '("\C-c-" org-cycle-list-bullet)))
5962 elt key fun cmd)
5963 (while (setq elt (pop bindings))
5964 (setq nfunc (1+ nfunc))
5965 (setq key (org-key (car elt))
5966 fun (nth 1 elt)
5967 cmd (orgstruct-make-binding fun nfunc key))
5968 (org-defkey orgstruct-mode-map key cmd))
5970 ;; Special treatment needed for TAB and RET
5971 (org-defkey orgstruct-mode-map [(tab)]
5972 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5973 (org-defkey orgstruct-mode-map "\C-i"
5974 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5976 (org-defkey orgstruct-mode-map "\M-\C-m"
5977 (orgstruct-make-binding 'org-insert-heading 105
5978 "\M-\C-m" [(meta return)]))
5979 (org-defkey orgstruct-mode-map [(meta return)]
5980 (orgstruct-make-binding 'org-insert-heading 106
5981 [(meta return)] "\M-\C-m"))
5983 (org-defkey orgstruct-mode-map [(shift meta return)]
5984 (orgstruct-make-binding 'org-insert-todo-heading 107
5985 [(meta return)] "\M-\C-m"))
5987 (unless org-local-vars
5988 (setq org-local-vars (org-get-local-variables)))
5992 (defun orgstruct-make-binding (fun n &rest keys)
5993 "Create a function for binding in the structure minor mode.
5994 FUN is the command to call inside a table. N is used to create a unique
5995 command name. KEYS are keys that should be checked in for a command
5996 to execute outside of tables."
5997 (eval
5998 (list 'defun
5999 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6000 '(arg)
6001 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6002 "Outside of structure, run the binding of `"
6003 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6004 "'.")
6005 '(interactive "p")
6006 (list 'if
6007 '(org-context-p 'headline 'item)
6008 (list 'org-run-like-in-org-mode (list 'quote fun))
6009 (list 'let '(orgstruct-mode)
6010 (list 'call-interactively
6011 (append '(or)
6012 (mapcar (lambda (k)
6013 (list 'key-binding k))
6014 keys)
6015 '('orgstruct-error))))))))
6017 (defun org-context-p (&rest contexts)
6018 "Check if local context is and of CONTEXTS.
6019 Possible values in the list of contexts are `table', `headline', and `item'."
6020 (let ((pos (point)))
6021 (goto-char (point-at-bol))
6022 (prog1 (or (and (memq 'table contexts)
6023 (looking-at "[ \t]*|"))
6024 (and (memq 'headline contexts)
6025 (looking-at "\\*+"))
6026 (and (memq 'item contexts)
6027 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6028 (goto-char pos))))
6030 (defun org-get-local-variables ()
6031 "Return a list of all local variables in an org-mode buffer."
6032 (let (varlist)
6033 (with-current-buffer (get-buffer-create "*Org tmp*")
6034 (erase-buffer)
6035 (org-mode)
6036 (setq varlist (buffer-local-variables)))
6037 (kill-buffer "*Org tmp*")
6038 (delq nil
6039 (mapcar
6040 (lambda (x)
6041 (setq x
6042 (if (symbolp x)
6043 (list x)
6044 (list (car x) (list 'quote (cdr x)))))
6045 (if (string-match
6046 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6047 (symbol-name (car x)))
6048 x nil))
6049 varlist))))
6051 ;;;###autoload
6052 (defun org-run-like-in-org-mode (cmd)
6053 (org-load-modules-maybe)
6054 (unless org-local-vars
6055 (setq org-local-vars (org-get-local-variables)))
6056 (eval (list 'let org-local-vars
6057 (list 'call-interactively (list 'quote cmd)))))
6059 ;;;; Archiving
6061 (defun org-get-category (&optional pos)
6062 "Get the category applying to position POS."
6063 (get-text-property (or pos (point)) 'org-category))
6065 (defun org-refresh-category-properties ()
6066 "Refresh category text properties in the buffer."
6067 (let ((def-cat (cond
6068 ((null org-category)
6069 (if buffer-file-name
6070 (file-name-sans-extension
6071 (file-name-nondirectory buffer-file-name))
6072 "???"))
6073 ((symbolp org-category) (symbol-name org-category))
6074 (t org-category)))
6075 beg end cat pos optionp)
6076 (org-unmodified
6077 (save-excursion
6078 (save-restriction
6079 (widen)
6080 (goto-char (point-min))
6081 (put-text-property (point) (point-max) 'org-category def-cat)
6082 (while (re-search-forward
6083 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6084 (setq pos (match-end 0)
6085 optionp (equal (char-after (match-beginning 0)) ?#)
6086 cat (org-trim (match-string 2)))
6087 (if optionp
6088 (setq beg (point-at-bol) end (point-max))
6089 (org-back-to-heading t)
6090 (setq beg (point) end (org-end-of-subtree t t)))
6091 (put-text-property beg end 'org-category cat)
6092 (goto-char pos)))))))
6095 ;;;; Link Stuff
6097 ;;; Link abbreviations
6099 (defun org-link-expand-abbrev (link)
6100 "Apply replacements as defined in `org-link-abbrev-alist."
6101 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6102 (let* ((key (match-string 1 link))
6103 (as (or (assoc key org-link-abbrev-alist-local)
6104 (assoc key org-link-abbrev-alist)))
6105 (tag (and (match-end 2) (match-string 3 link)))
6106 rpl)
6107 (if (not as)
6108 link
6109 (setq rpl (cdr as))
6110 (cond
6111 ((symbolp rpl) (funcall rpl tag))
6112 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6113 (t (concat rpl tag)))))
6114 link))
6116 ;;; Storing and inserting links
6118 (defvar org-insert-link-history nil
6119 "Minibuffer history for links inserted with `org-insert-link'.")
6121 (defvar org-stored-links nil
6122 "Contains the links stored with `org-store-link'.")
6124 (defvar org-store-link-plist nil
6125 "Plist with info about the most recently link created with `org-store-link'.")
6127 (defvar org-link-protocols nil
6128 "Link protocols added to Org-mode using `org-add-link-type'.")
6130 (defvar org-store-link-functions nil
6131 "List of functions that are called to create and store a link.
6132 Each function will be called in turn until one returns a non-nil
6133 value. Each function should check if it is responsible for creating
6134 this link (for example by looking at the major mode).
6135 If not, it must exit and return nil.
6136 If yes, it should return a non-nil value after a calling
6137 `org-store-link-props' with a list of properties and values.
6138 Special properties are:
6140 :type The link prefix. like \"http\". This must be given.
6141 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6142 This is obligatory as well.
6143 :description Optional default description for the second pair
6144 of brackets in an Org-mode link. The user can still change
6145 this when inserting this link into an Org-mode buffer.
6147 In addition to these, any additional properties can be specified
6148 and then used in remember templates.")
6150 (defun org-add-link-type (type &optional follow export)
6151 "Add TYPE to the list of `org-link-types'.
6152 Re-compute all regular expressions depending on `org-link-types'
6154 FOLLOW and EXPORT are two functions.
6156 FOLLOW should take the link path as the single argument and do whatever
6157 is necessary to follow the link, for example find a file or display
6158 a mail message.
6160 EXPORT should format the link path for export to one of the export formats.
6161 It should be a function accepting three arguments:
6163 path the path of the link, the text after the prefix (like \"http:\")
6164 desc the description of the link, if any, nil if there was no descripton
6165 format the export format, a symbol like `html' or `latex'.
6167 The function may use the FORMAT information to return different values
6168 depending on the format. The return value will be put literally into
6169 the exported file.
6170 Org-mode has a built-in default for exporting links. If you are happy with
6171 this default, there is no need to define an export function for the link
6172 type. For a simple example of an export function, see `org-bbdb.el'."
6173 (add-to-list 'org-link-types type t)
6174 (org-make-link-regexps)
6175 (if (assoc type org-link-protocols)
6176 (setcdr (assoc type org-link-protocols) (list follow export))
6177 (push (list type follow export) org-link-protocols)))
6180 ;;;###autoload
6181 (defun org-store-link (arg)
6182 "\\<org-mode-map>Store an org-link to the current location.
6183 This link is added to `org-stored-links' and can later be inserted
6184 into an org-buffer with \\[org-insert-link].
6186 For some link types, a prefix arg is interpreted:
6187 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6188 For file links, arg negates `org-context-in-file-links'."
6189 (interactive "P")
6190 (org-load-modules-maybe)
6191 (setq org-store-link-plist nil) ; reset
6192 (let (link cpltxt desc description search txt)
6193 (cond
6195 ((run-hook-with-args-until-success 'org-store-link-functions)
6196 (setq link (plist-get org-store-link-plist :link)
6197 desc (or (plist-get org-store-link-plist :description) link)))
6199 ((eq major-mode 'calendar-mode)
6200 (let ((cd (calendar-cursor-to-date)))
6201 (setq link
6202 (format-time-string
6203 (car org-time-stamp-formats)
6204 (apply 'encode-time
6205 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6206 nil nil nil))))
6207 (org-store-link-props :type "calendar" :date cd)))
6209 ((eq major-mode 'w3-mode)
6210 (setq cpltxt (url-view-url t)
6211 link (org-make-link cpltxt))
6212 (org-store-link-props :type "w3" :url (url-view-url t)))
6214 ((eq major-mode 'w3m-mode)
6215 (setq cpltxt (or w3m-current-title w3m-current-url)
6216 link (org-make-link w3m-current-url))
6217 (org-store-link-props :type "w3m" :url (url-view-url t)))
6219 ((setq search (run-hook-with-args-until-success
6220 'org-create-file-search-functions))
6221 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6222 "::" search))
6223 (setq cpltxt (or description link)))
6225 ((eq major-mode 'image-mode)
6226 (setq cpltxt (concat "file:"
6227 (abbreviate-file-name buffer-file-name))
6228 link (org-make-link cpltxt))
6229 (org-store-link-props :type "image" :file buffer-file-name))
6231 ((eq major-mode 'dired-mode)
6232 ;; link to the file in the current line
6233 (setq cpltxt (concat "file:"
6234 (abbreviate-file-name
6235 (expand-file-name
6236 (dired-get-filename nil t))))
6237 link (org-make-link cpltxt)))
6239 ((and buffer-file-name (org-mode-p))
6240 ;; Just link to current headline
6241 (setq cpltxt (concat "file:"
6242 (abbreviate-file-name buffer-file-name)))
6243 ;; Add a context search string
6244 (when (org-xor org-context-in-file-links arg)
6245 ;; Check if we are on a target
6246 (if (org-in-regexp "<<\\(.*?\\)>>")
6247 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6248 (setq txt (cond
6249 ((org-on-heading-p) nil)
6250 ((org-region-active-p)
6251 (buffer-substring (region-beginning) (region-end)))
6252 (t nil)))
6253 (when (or (null txt) (string-match "\\S-" txt))
6254 (setq cpltxt
6255 (concat cpltxt "::"
6256 (condition-case nil
6257 (org-make-org-heading-search-string txt)
6258 (error "")))
6259 desc "NONE"))))
6260 (if (string-match "::\\'" cpltxt)
6261 (setq cpltxt (substring cpltxt 0 -2)))
6262 (setq link (org-make-link cpltxt)))
6264 ((buffer-file-name (buffer-base-buffer))
6265 ;; Just link to this file here.
6266 (setq cpltxt (concat "file:"
6267 (abbreviate-file-name
6268 (buffer-file-name (buffer-base-buffer)))))
6269 ;; Add a context string
6270 (when (org-xor org-context-in-file-links arg)
6271 (setq txt (if (org-region-active-p)
6272 (buffer-substring (region-beginning) (region-end))
6273 (buffer-substring (point-at-bol) (point-at-eol))))
6274 ;; Only use search option if there is some text.
6275 (when (string-match "\\S-" txt)
6276 (setq cpltxt
6277 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6278 desc "NONE")))
6279 (setq link (org-make-link cpltxt)))
6281 ((interactive-p)
6282 (error "Cannot link to a buffer which is not visiting a file"))
6284 (t (setq link nil)))
6286 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6287 (setq link (or link cpltxt)
6288 desc (or desc cpltxt))
6289 (if (equal desc "NONE") (setq desc nil))
6291 (if (and (interactive-p) link)
6292 (progn
6293 (setq org-stored-links
6294 (cons (list link desc) org-stored-links))
6295 (message "Stored: %s" (or desc link)))
6296 (and link (org-make-link-string link desc)))))
6298 (defun org-store-link-props (&rest plist)
6299 "Store link properties, extract names and addresses."
6300 (let (x adr)
6301 (when (setq x (plist-get plist :from))
6302 (setq adr (mail-extract-address-components x))
6303 (plist-put plist :fromname (car adr))
6304 (plist-put plist :fromaddress (nth 1 adr)))
6305 (when (setq x (plist-get plist :to))
6306 (setq adr (mail-extract-address-components x))
6307 (plist-put plist :toname (car adr))
6308 (plist-put plist :toaddress (nth 1 adr))))
6309 (let ((from (plist-get plist :from))
6310 (to (plist-get plist :to)))
6311 (when (and from to org-from-is-user-regexp)
6312 (plist-put plist :fromto
6313 (if (string-match org-from-is-user-regexp from)
6314 (concat "to %t")
6315 (concat "from %f")))))
6316 (setq org-store-link-plist plist))
6318 (defun org-add-link-props (&rest plist)
6319 "Add these properties to the link property list."
6320 (let (key value)
6321 (while plist
6322 (setq key (pop plist) value (pop plist))
6323 (setq org-store-link-plist
6324 (plist-put org-store-link-plist key value)))))
6326 (defun org-email-link-description (&optional fmt)
6327 "Return the description part of an email link.
6328 This takes information from `org-store-link-plist' and formats it
6329 according to FMT (default from `org-email-link-description-format')."
6330 (setq fmt (or fmt org-email-link-description-format))
6331 (let* ((p org-store-link-plist)
6332 (to (plist-get p :toaddress))
6333 (from (plist-get p :fromaddress))
6334 (table
6335 (list
6336 (cons "%c" (plist-get p :fromto))
6337 (cons "%F" (plist-get p :from))
6338 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6339 (cons "%T" (plist-get p :to))
6340 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6341 (cons "%s" (plist-get p :subject))
6342 (cons "%m" (plist-get p :message-id)))))
6343 (when (string-match "%c" fmt)
6344 ;; Check if the user wrote this message
6345 (if (and org-from-is-user-regexp from to
6346 (save-match-data (string-match org-from-is-user-regexp from)))
6347 (setq fmt (replace-match "to %t" t t fmt))
6348 (setq fmt (replace-match "from %f" t t fmt))))
6349 (org-replace-escapes fmt table)))
6351 (defun org-make-org-heading-search-string (&optional string heading)
6352 "Make search string for STRING or current headline."
6353 (interactive)
6354 (let ((s (or string (org-get-heading))))
6355 (unless (and string (not heading))
6356 ;; We are using a headline, clean up garbage in there.
6357 (if (string-match org-todo-regexp s)
6358 (setq s (replace-match "" t t s)))
6359 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6360 (setq s (replace-match "" t t s)))
6361 (setq s (org-trim s))
6362 (if (string-match (concat "^\\(" org-quote-string "\\|"
6363 org-comment-string "\\)") s)
6364 (setq s (replace-match "" t t s)))
6365 (while (string-match org-ts-regexp s)
6366 (setq s (replace-match "" t t s))))
6367 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6368 (setq s (replace-match " " t t s)))
6369 (or string (setq s (concat "*" s))) ; Add * for headlines
6370 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6372 (defun org-make-link (&rest strings)
6373 "Concatenate STRINGS."
6374 (apply 'concat strings))
6376 (defun org-make-link-string (link &optional description)
6377 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6378 (unless (string-match "\\S-" link)
6379 (error "Empty link"))
6380 (when (stringp description)
6381 ;; Remove brackets from the description, they are fatal.
6382 (while (string-match "\\[" description)
6383 (setq description (replace-match "{" t t description)))
6384 (while (string-match "\\]" description)
6385 (setq description (replace-match "}" t t description))))
6386 (when (equal (org-link-escape link) description)
6387 ;; No description needed, it is identical
6388 (setq description nil))
6389 (when (and (not description)
6390 (not (equal link (org-link-escape link))))
6391 (setq description link))
6392 (concat "[[" (org-link-escape link) "]"
6393 (if description (concat "[" description "]") "")
6394 "]"))
6396 (defconst org-link-escape-chars
6397 '((?\ . "%20")
6398 (?\[ . "%5B")
6399 (?\] . "%5D")
6400 (?\340 . "%E0") ; `a
6401 (?\342 . "%E2") ; ^a
6402 (?\347 . "%E7") ; ,c
6403 (?\350 . "%E8") ; `e
6404 (?\351 . "%E9") ; 'e
6405 (?\352 . "%EA") ; ^e
6406 (?\356 . "%EE") ; ^i
6407 (?\364 . "%F4") ; ^o
6408 (?\371 . "%F9") ; `u
6409 (?\373 . "%FB") ; ^u
6410 (?\; . "%3B")
6411 (?? . "%3F")
6412 (?= . "%3D")
6413 (?+ . "%2B")
6415 "Association list of escapes for some characters problematic in links.
6416 This is the list that is used for internal purposes.")
6418 (defconst org-link-escape-chars-browser
6419 '((?\ . "%20")) ; 32 for the SPC char
6420 "Association list of escapes for some characters problematic in links.
6421 This is the list that is used before handing over to the browser.")
6423 (defun org-link-escape (text &optional table)
6424 "Escape charaters in TEXT that are problematic for links."
6425 (setq table (or table org-link-escape-chars))
6426 (when text
6427 (let ((re (mapconcat (lambda (x) (regexp-quote
6428 (char-to-string (car x))))
6429 table "\\|")))
6430 (while (string-match re text)
6431 (setq text
6432 (replace-match
6433 (cdr (assoc (string-to-char (match-string 0 text))
6434 table))
6435 t t text)))
6436 text)))
6438 (defun org-link-unescape (text &optional table)
6439 "Reverse the action of `org-link-escape'."
6440 (setq table (or table org-link-escape-chars))
6441 (when text
6442 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6443 table "\\|")))
6444 (while (string-match re text)
6445 (setq text
6446 (replace-match
6447 (char-to-string (car (rassoc (match-string 0 text) table)))
6448 t t text)))
6449 text)))
6451 (defun org-xor (a b)
6452 "Exclusive or."
6453 (if a (not b) b))
6455 (defun org-get-header (header)
6456 "Find a header field in the current buffer."
6457 (save-excursion
6458 (goto-char (point-min))
6459 (let ((case-fold-search t) s)
6460 (cond
6461 ((eq header 'from)
6462 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6463 (setq s (match-string 1)))
6464 (while (string-match "\"" s)
6465 (setq s (replace-match "" t t s)))
6466 (if (string-match "[<(].*" s)
6467 (setq s (replace-match "" t t s))))
6468 ((eq header 'message-id)
6469 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6470 (setq s (match-string 1))))
6471 ((eq header 'subject)
6472 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6473 (setq s (match-string 1)))))
6474 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6475 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6476 s)))
6479 (defun org-fixup-message-id-for-http (s)
6480 "Replace special characters in a message id, so it can be used in an http query."
6481 (while (string-match "<" s)
6482 (setq s (replace-match "%3C" t t s)))
6483 (while (string-match ">" s)
6484 (setq s (replace-match "%3E" t t s)))
6485 (while (string-match "@" s)
6486 (setq s (replace-match "%40" t t s)))
6489 ;;;###autoload
6490 (defun org-insert-link-global ()
6491 "Insert a link like Org-mode does.
6492 This command can be called in any mode to insert a link in Org-mode syntax."
6493 (interactive)
6494 (org-load-modules-maybe)
6495 (org-run-like-in-org-mode 'org-insert-link))
6497 (defun org-insert-link (&optional complete-file link-location)
6498 "Insert a link. At the prompt, enter the link.
6500 Completion can be used to select a link previously stored with
6501 `org-store-link'. When the empty string is entered (i.e. if you just
6502 press RET at the prompt), the link defaults to the most recently
6503 stored link. As SPC triggers completion in the minibuffer, you need to
6504 use M-SPC or C-q SPC to force the insertion of a space character.
6506 You will also be prompted for a description, and if one is given, it will
6507 be displayed in the buffer instead of the link.
6509 If there is already a link at point, this command will allow you to edit link
6510 and description parts.
6512 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6513 be selected using completion. The path to the file will be relative to the
6514 current directory if the file is in the current directory or a subdirectory.
6515 Otherwise, the link will be the absolute path as completed in the minibuffer
6516 \(i.e. normally ~/path/to/file).
6518 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6519 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6520 of `org-keep-stored-link-after-insertion'.
6522 If `org-make-link-description-function' is non-nil, this function will be
6523 called with the link target, and the result will be the default
6524 link description.
6526 If the LINK-LOCATION parameter is non-nil, this value will be
6527 used as the link location instead of reading one interactively."
6528 (interactive "P")
6529 (let* ((wcf (current-window-configuration))
6530 (region (if (org-region-active-p)
6531 (buffer-substring (region-beginning) (region-end))))
6532 (remove (and region (list (region-beginning) (region-end))))
6533 (desc region)
6534 tmphist ; byte-compile incorrectly complains about this
6535 (link link-location)
6536 entry file)
6537 (cond
6538 (link-location) ; specified by arg, just use it.
6539 ((org-in-regexp org-bracket-link-regexp 1)
6540 ;; We do have a link at point, and we are going to edit it.
6541 (setq remove (list (match-beginning 0) (match-end 0)))
6542 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6543 (setq link (read-string "Link: "
6544 (org-link-unescape
6545 (org-match-string-no-properties 1)))))
6546 ((or (org-in-regexp org-angle-link-re)
6547 (org-in-regexp org-plain-link-re))
6548 ;; Convert to bracket link
6549 (setq remove (list (match-beginning 0) (match-end 0))
6550 link (read-string "Link: "
6551 (org-remove-angle-brackets (match-string 0)))))
6552 ((equal complete-file '(4))
6553 ;; Completing read for file names.
6554 (setq file (read-file-name "File: "))
6555 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6556 (pwd1 (file-name-as-directory (abbreviate-file-name
6557 (expand-file-name ".")))))
6558 (cond
6559 ((equal complete-file '(16))
6560 (setq link (org-make-link
6561 "file:"
6562 (abbreviate-file-name (expand-file-name file)))))
6563 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6564 (setq link (org-make-link "file:" (match-string 1 file))))
6565 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6566 (expand-file-name file))
6567 (setq link (org-make-link
6568 "file:" (match-string 1 (expand-file-name file)))))
6569 (t (setq link (org-make-link "file:" file))))))
6571 ;; Read link, with completion for stored links.
6572 (with-output-to-temp-buffer "*Org Links*"
6573 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6574 (when org-stored-links
6575 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6576 (princ (mapconcat
6577 (lambda (x)
6578 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6579 (reverse org-stored-links) "\n"))))
6580 (let ((cw (selected-window)))
6581 (select-window (get-buffer-window "*Org Links*"))
6582 (shrink-window-if-larger-than-buffer)
6583 (setq truncate-lines t)
6584 (select-window cw))
6585 ;; Fake a link history, containing the stored links.
6586 (setq tmphist (append (mapcar 'car org-stored-links)
6587 org-insert-link-history))
6588 (unwind-protect
6589 (setq link (org-completing-read
6590 "Link: "
6591 (append
6592 (mapcar (lambda (x) (list (concat (car x) ":")))
6593 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6594 (mapcar (lambda (x) (list (concat x ":")))
6595 org-link-types))
6596 nil nil nil
6597 'tmphist
6598 (or (car (car org-stored-links)))))
6599 (set-window-configuration wcf)
6600 (kill-buffer "*Org Links*"))
6601 (setq entry (assoc link org-stored-links))
6602 (or entry (push link org-insert-link-history))
6603 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6604 (not org-keep-stored-link-after-insertion))
6605 (setq org-stored-links (delq (assoc link org-stored-links)
6606 org-stored-links)))
6607 (setq desc (or desc (nth 1 entry)))))
6609 (if (string-match org-plain-link-re link)
6610 ;; URL-like link, normalize the use of angular brackets.
6611 (setq link (org-make-link (org-remove-angle-brackets link))))
6613 ;; Check if we are linking to the current file with a search option
6614 ;; If yes, simplify the link by using only the search option.
6615 (when (and buffer-file-name
6616 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6617 (let* ((path (match-string 1 link))
6618 (case-fold-search nil)
6619 (search (match-string 2 link)))
6620 (save-match-data
6621 (if (equal (file-truename buffer-file-name) (file-truename path))
6622 ;; We are linking to this same file, with a search option
6623 (setq link search)))))
6625 ;; Check if we can/should use a relative path. If yes, simplify the link
6626 (when (string-match "\\<file:\\(.*\\)" link)
6627 (let* ((path (match-string 1 link))
6628 (origpath path)
6629 (case-fold-search nil))
6630 (cond
6631 ((eq org-link-file-path-type 'absolute)
6632 (setq path (abbreviate-file-name (expand-file-name path))))
6633 ((eq org-link-file-path-type 'noabbrev)
6634 (setq path (expand-file-name path)))
6635 ((eq org-link-file-path-type 'relative)
6636 (setq path (file-relative-name path)))
6638 (save-match-data
6639 (if (string-match (concat "^" (regexp-quote
6640 (file-name-as-directory
6641 (expand-file-name "."))))
6642 (expand-file-name path))
6643 ;; We are linking a file with relative path name.
6644 (setq path (substring (expand-file-name path)
6645 (match-end 0)))))))
6646 (setq link (concat "file:" path))
6647 (if (equal desc origpath)
6648 (setq desc path))))
6650 (if org-make-link-description-function
6651 (setq desc (funcall org-make-link-description-function link desc)))
6653 (setq desc (read-string "Description: " desc))
6654 (unless (string-match "\\S-" desc) (setq desc nil))
6655 (if remove (apply 'delete-region remove))
6656 (insert (org-make-link-string link desc))))
6658 (defun org-completing-read (&rest args)
6659 (let ((minibuffer-local-completion-map
6660 (copy-keymap minibuffer-local-completion-map)))
6661 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6662 (apply 'completing-read args)))
6664 ;;; Opening/following a link
6666 (defvar org-link-search-failed nil)
6668 (defun org-next-link ()
6669 "Move forward to the next link.
6670 If the link is in hidden text, expose it."
6671 (interactive)
6672 (when (and org-link-search-failed (eq this-command last-command))
6673 (goto-char (point-min))
6674 (message "Link search wrapped back to beginning of buffer"))
6675 (setq org-link-search-failed nil)
6676 (let* ((pos (point))
6677 (ct (org-context))
6678 (a (assoc :link ct)))
6679 (if a (goto-char (nth 2 a)))
6680 (if (re-search-forward org-any-link-re nil t)
6681 (progn
6682 (goto-char (match-beginning 0))
6683 (if (org-invisible-p) (org-show-context)))
6684 (goto-char pos)
6685 (setq org-link-search-failed t)
6686 (error "No further link found"))))
6688 (defun org-previous-link ()
6689 "Move backward to the previous link.
6690 If the link is in hidden text, expose it."
6691 (interactive)
6692 (when (and org-link-search-failed (eq this-command last-command))
6693 (goto-char (point-max))
6694 (message "Link search wrapped back to end of buffer"))
6695 (setq org-link-search-failed nil)
6696 (let* ((pos (point))
6697 (ct (org-context))
6698 (a (assoc :link ct)))
6699 (if a (goto-char (nth 1 a)))
6700 (if (re-search-backward org-any-link-re nil t)
6701 (progn
6702 (goto-char (match-beginning 0))
6703 (if (org-invisible-p) (org-show-context)))
6704 (goto-char pos)
6705 (setq org-link-search-failed t)
6706 (error "No further link found"))))
6708 (defun org-find-file-at-mouse (ev)
6709 "Open file link or URL at mouse."
6710 (interactive "e")
6711 (mouse-set-point ev)
6712 (org-open-at-point 'in-emacs))
6714 (defun org-open-at-mouse (ev)
6715 "Open file link or URL at mouse."
6716 (interactive "e")
6717 (mouse-set-point ev)
6718 (org-open-at-point))
6720 (defvar org-window-config-before-follow-link nil
6721 "The window configuration before following a link.
6722 This is saved in case the need arises to restore it.")
6724 (defvar org-open-link-marker (make-marker)
6725 "Marker pointing to the location where `org-open-at-point; was called.")
6727 ;;;###autoload
6728 (defun org-open-at-point-global ()
6729 "Follow a link like Org-mode does.
6730 This command can be called in any mode to follow a link that has
6731 Org-mode syntax."
6732 (interactive)
6733 (org-run-like-in-org-mode 'org-open-at-point))
6735 ;;;###autoload
6736 (defun org-open-link-from-string (s &optional arg)
6737 "Open a link in the string S, as if it was in Org-mode."
6738 (interactive "sLink: \nP")
6739 (with-temp-buffer
6740 (let ((org-inhibit-startup t))
6741 (org-mode)
6742 (insert s)
6743 (goto-char (point-min))
6744 (org-open-at-point arg))))
6746 (defun org-open-at-point (&optional in-emacs)
6747 "Open link at or after point.
6748 If there is no link at point, this function will search forward up to
6749 the end of the current subtree.
6750 Normally, files will be opened by an appropriate application. If the
6751 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6752 (interactive "P")
6753 (org-load-modules-maybe)
6754 (move-marker org-open-link-marker (point))
6755 (setq org-window-config-before-follow-link (current-window-configuration))
6756 (org-remove-occur-highlights nil nil t)
6757 (if (org-at-timestamp-p t)
6758 (org-follow-timestamp-link)
6759 (let (type path link line search (pos (point)))
6760 (catch 'match
6761 (save-excursion
6762 (skip-chars-forward "^]\n\r")
6763 (when (org-in-regexp org-bracket-link-regexp)
6764 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6765 (while (string-match " *\n *" link)
6766 (setq link (replace-match " " t t link)))
6767 (setq link (org-link-expand-abbrev link))
6768 (if (string-match org-link-re-with-space2 link)
6769 (setq type (match-string 1 link) path (match-string 2 link))
6770 (setq type "thisfile" path link))
6771 (throw 'match t)))
6773 (when (get-text-property (point) 'org-linked-text)
6774 (setq type "thisfile"
6775 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6776 (1+ (point)) (point))
6777 path (buffer-substring
6778 (previous-single-property-change pos 'org-linked-text)
6779 (next-single-property-change pos 'org-linked-text)))
6780 (throw 'match t))
6782 (save-excursion
6783 (when (or (org-in-regexp org-angle-link-re)
6784 (org-in-regexp org-plain-link-re))
6785 (setq type (match-string 1) path (match-string 2))
6786 (throw 'match t)))
6787 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6788 (setq type "tree-match"
6789 path (match-string 1))
6790 (throw 'match t))
6791 (save-excursion
6792 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6793 (setq type "tags"
6794 path (match-string 1))
6795 (while (string-match ":" path)
6796 (setq path (replace-match "+" t t path)))
6797 (throw 'match t))))
6798 (unless path
6799 (error "No link found"))
6800 ;; Remove any trailing spaces in path
6801 (if (string-match " +\\'" path)
6802 (setq path (replace-match "" t t path)))
6804 (cond
6806 ((assoc type org-link-protocols)
6807 (funcall (nth 1 (assoc type org-link-protocols)) path))
6809 ((equal type "mailto")
6810 (let ((cmd (car org-link-mailto-program))
6811 (args (cdr org-link-mailto-program)) args1
6812 (address path) (subject "") a)
6813 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6814 (setq address (match-string 1 path)
6815 subject (org-link-escape (match-string 2 path))))
6816 (while args
6817 (cond
6818 ((not (stringp (car args))) (push (pop args) args1))
6819 (t (setq a (pop args))
6820 (if (string-match "%a" a)
6821 (setq a (replace-match address t t a)))
6822 (if (string-match "%s" a)
6823 (setq a (replace-match subject t t a)))
6824 (push a args1))))
6825 (apply cmd (nreverse args1))))
6827 ((member type '("http" "https" "ftp" "news"))
6828 (browse-url (concat type ":" (org-link-escape
6829 path org-link-escape-chars-browser))))
6831 ((member type '("message"))
6832 (browse-url (concat type ":" path)))
6834 ((string= type "tags")
6835 (org-tags-view in-emacs path))
6836 ((string= type "thisfile")
6837 (if in-emacs
6838 (switch-to-buffer-other-window
6839 (org-get-buffer-for-internal-link (current-buffer)))
6840 (org-mark-ring-push))
6841 (let ((cmd `(org-link-search
6842 ,path
6843 ,(cond ((equal in-emacs '(4)) 'occur)
6844 ((equal in-emacs '(16)) 'org-occur)
6845 (t nil))
6846 ,pos)))
6847 (condition-case nil (eval cmd)
6848 (error (progn (widen) (eval cmd))))))
6850 ((string= type "tree-match")
6851 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6853 ((string= type "file")
6854 (if (string-match "::\\([0-9]+\\)\\'" path)
6855 (setq line (string-to-number (match-string 1 path))
6856 path (substring path 0 (match-beginning 0)))
6857 (if (string-match "::\\(.+\\)\\'" path)
6858 (setq search (match-string 1 path)
6859 path (substring path 0 (match-beginning 0)))))
6860 (if (string-match "[*?{]" (file-name-nondirectory path))
6861 (dired path)
6862 (org-open-file path in-emacs line search)))
6864 ((string= type "news")
6865 (require 'org-gnus)
6866 (org-gnus-follow-link path))
6868 ((string= type "shell")
6869 (let ((cmd path))
6870 (if (or (not org-confirm-shell-link-function)
6871 (funcall org-confirm-shell-link-function
6872 (format "Execute \"%s\" in shell? "
6873 (org-add-props cmd nil
6874 'face 'org-warning))))
6875 (progn
6876 (message "Executing %s" cmd)
6877 (shell-command cmd))
6878 (error "Abort"))))
6880 ((string= type "elisp")
6881 (let ((cmd path))
6882 (if (or (not org-confirm-elisp-link-function)
6883 (funcall org-confirm-elisp-link-function
6884 (format "Execute \"%s\" as elisp? "
6885 (org-add-props cmd nil
6886 'face 'org-warning))))
6887 (message "%s => %s" cmd (eval (read cmd)))
6888 (error "Abort"))))
6891 (browse-url-at-point)))))
6892 (move-marker org-open-link-marker nil)
6893 (run-hook-with-args 'org-follow-link-hook))
6895 ;;;; Time estimates
6897 (defun org-get-effort (&optional pom)
6898 "Get the effort estimate for the current entry."
6899 (org-entry-get pom org-effort-property))
6901 ;;; File search
6903 (defvar org-create-file-search-functions nil
6904 "List of functions to construct the right search string for a file link.
6905 These functions are called in turn with point at the location to
6906 which the link should point.
6908 A function in the hook should first test if it would like to
6909 handle this file type, for example by checking the major-mode or
6910 the file extension. If it decides not to handle this file, it
6911 should just return nil to give other functions a chance. If it
6912 does handle the file, it must return the search string to be used
6913 when following the link. The search string will be part of the
6914 file link, given after a double colon, and `org-open-at-point'
6915 will automatically search for it. If special measures must be
6916 taken to make the search successful, another function should be
6917 added to the companion hook `org-execute-file-search-functions',
6918 which see.
6920 A function in this hook may also use `setq' to set the variable
6921 `description' to provide a suggestion for the descriptive text to
6922 be used for this link when it gets inserted into an Org-mode
6923 buffer with \\[org-insert-link].")
6925 (defvar org-execute-file-search-functions nil
6926 "List of functions to execute a file search triggered by a link.
6928 Functions added to this hook must accept a single argument, the
6929 search string that was part of the file link, the part after the
6930 double colon. The function must first check if it would like to
6931 handle this search, for example by checking the major-mode or the
6932 file extension. If it decides not to handle this search, it
6933 should just return nil to give other functions a chance. If it
6934 does handle the search, it must return a non-nil value to keep
6935 other functions from trying.
6937 Each function can access the current prefix argument through the
6938 variable `current-prefix-argument'. Note that a single prefix is
6939 used to force opening a link in Emacs, so it may be good to only
6940 use a numeric or double prefix to guide the search function.
6942 In case this is needed, a function in this hook can also restore
6943 the window configuration before `org-open-at-point' was called using:
6945 (set-window-configuration org-window-config-before-follow-link)")
6947 (defun org-link-search (s &optional type avoid-pos)
6948 "Search for a link search option.
6949 If S is surrounded by forward slashes, it is interpreted as a
6950 regular expression. In org-mode files, this will create an `org-occur'
6951 sparse tree. In ordinary files, `occur' will be used to list matches.
6952 If the current buffer is in `dired-mode', grep will be used to search
6953 in all files. If AVOID-POS is given, ignore matches near that position."
6954 (let ((case-fold-search t)
6955 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6956 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6957 (append '(("") (" ") ("\t") ("\n"))
6958 org-emphasis-alist)
6959 "\\|") "\\)"))
6960 (pos (point))
6961 (pre nil) (post nil)
6962 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6963 (cond
6964 ;; First check if there are any special
6965 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6966 ;; Now try the builtin stuff
6967 ((save-excursion
6968 (goto-char (point-min))
6969 (and
6970 (re-search-forward
6971 (concat "<<" (regexp-quote s0) ">>") nil t)
6972 (setq type 'dedicated
6973 pos (match-beginning 0))))
6974 ;; There is an exact target for this
6975 (goto-char pos))
6976 ((string-match "^/\\(.*\\)/$" s)
6977 ;; A regular expression
6978 (cond
6979 ((org-mode-p)
6980 (org-occur (match-string 1 s)))
6981 ;;((eq major-mode 'dired-mode)
6982 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6983 (t (org-do-occur (match-string 1 s)))))
6985 ;; A normal search strings
6986 (when (equal (string-to-char s) ?*)
6987 ;; Anchor on headlines, post may include tags.
6988 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6989 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6990 s (substring s 1)))
6991 (remove-text-properties
6992 0 (length s)
6993 '(face nil mouse-face nil keymap nil fontified nil) s)
6994 ;; Make a series of regular expressions to find a match
6995 (setq words (org-split-string s "[ \n\r\t]+")
6997 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6998 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6999 "\\)" markers)
7000 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7001 re2a (concat "[ \t\r\n]" re2a_)
7002 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7003 re4 (concat "[^a-zA-Z_]" re4_)
7005 re1 (concat pre re2 post)
7006 re3 (concat pre (if pre re4_ re4) post)
7007 re5 (concat pre ".*" re4)
7008 re2 (concat pre re2)
7009 re2a (concat pre (if pre re2a_ re2a))
7010 re4 (concat pre (if pre re4_ re4))
7011 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7012 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7013 re5 "\\)"
7015 (cond
7016 ((eq type 'org-occur) (org-occur reall))
7017 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7018 (t (goto-char (point-min))
7019 (setq type 'fuzzy)
7020 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7021 (org-search-not-self 1 re1 nil t)
7022 (org-search-not-self 1 re2 nil t)
7023 (org-search-not-self 1 re2a nil t)
7024 (org-search-not-self 1 re3 nil t)
7025 (org-search-not-self 1 re4 nil t)
7026 (org-search-not-self 1 re5 nil t)
7028 (goto-char (match-beginning 1))
7029 (goto-char pos)
7030 (error "No match")))))
7032 ;; Normal string-search
7033 (goto-char (point-min))
7034 (if (search-forward s nil t)
7035 (goto-char (match-beginning 0))
7036 (error "No match"))))
7037 (and (org-mode-p) (org-show-context 'link-search))
7038 type))
7040 (defun org-search-not-self (group &rest args)
7041 "Execute `re-search-forward', but only accept matches that do not
7042 enclose the position of `org-open-link-marker'."
7043 (let ((m org-open-link-marker))
7044 (catch 'exit
7045 (while (apply 're-search-forward args)
7046 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7047 (goto-char (match-end group))
7048 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7049 (> (match-beginning 0) (marker-position m))
7050 (< (match-end 0) (marker-position m)))
7051 (save-match-data
7052 (or (not (org-in-regexp
7053 org-bracket-link-analytic-regexp 1))
7054 (not (match-end 4)) ; no description
7055 (and (<= (match-beginning 4) (point))
7056 (>= (match-end 4) (point))))))
7057 (throw 'exit (point))))))))
7059 (defun org-get-buffer-for-internal-link (buffer)
7060 "Return a buffer to be used for displaying the link target of internal links."
7061 (cond
7062 ((not org-display-internal-link-with-indirect-buffer)
7063 buffer)
7064 ((string-match "(Clone)$" (buffer-name buffer))
7065 (message "Buffer is already a clone, not making another one")
7066 ;; we also do not modify visibility in this case
7067 buffer)
7068 (t ; make a new indirect buffer for displaying the link
7069 (let* ((bn (buffer-name buffer))
7070 (ibn (concat bn "(Clone)"))
7071 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7072 (with-current-buffer ib (org-overview))
7073 ib))))
7075 (defun org-do-occur (regexp &optional cleanup)
7076 "Call the Emacs command `occur'.
7077 If CLEANUP is non-nil, remove the printout of the regular expression
7078 in the *Occur* buffer. This is useful if the regex is long and not useful
7079 to read."
7080 (occur regexp)
7081 (when cleanup
7082 (let ((cwin (selected-window)) win beg end)
7083 (when (setq win (get-buffer-window "*Occur*"))
7084 (select-window win))
7085 (goto-char (point-min))
7086 (when (re-search-forward "match[a-z]+" nil t)
7087 (setq beg (match-end 0))
7088 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7089 (setq end (1- (match-beginning 0)))))
7090 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7091 (goto-char (point-min))
7092 (select-window cwin))))
7094 ;;; The mark ring for links jumps
7096 (defvar org-mark-ring nil
7097 "Mark ring for positions before jumps in Org-mode.")
7098 (defvar org-mark-ring-last-goto nil
7099 "Last position in the mark ring used to go back.")
7100 ;; Fill and close the ring
7101 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7102 (loop for i from 1 to org-mark-ring-length do
7103 (push (make-marker) org-mark-ring))
7104 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7105 org-mark-ring)
7107 (defun org-mark-ring-push (&optional pos buffer)
7108 "Put the current position or POS into the mark ring and rotate it."
7109 (interactive)
7110 (setq pos (or pos (point)))
7111 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7112 (move-marker (car org-mark-ring)
7113 (or pos (point))
7114 (or buffer (current-buffer)))
7115 (message "%s"
7116 (substitute-command-keys
7117 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7119 (defun org-mark-ring-goto (&optional n)
7120 "Jump to the previous position in the mark ring.
7121 With prefix arg N, jump back that many stored positions. When
7122 called several times in succession, walk through the entire ring.
7123 Org-mode commands jumping to a different position in the current file,
7124 or to another Org-mode file, automatically push the old position
7125 onto the ring."
7126 (interactive "p")
7127 (let (p m)
7128 (if (eq last-command this-command)
7129 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7130 (setq p org-mark-ring))
7131 (setq org-mark-ring-last-goto p)
7132 (setq m (car p))
7133 (switch-to-buffer (marker-buffer m))
7134 (goto-char m)
7135 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7137 (defun org-remove-angle-brackets (s)
7138 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7139 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7141 (defun org-add-angle-brackets (s)
7142 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7143 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7146 ;;; Following specific links
7148 (defun org-follow-timestamp-link ()
7149 (cond
7150 ((org-at-date-range-p t)
7151 (let ((org-agenda-start-on-weekday)
7152 (t1 (match-string 1))
7153 (t2 (match-string 2)))
7154 (setq t1 (time-to-days (org-time-string-to-time t1))
7155 t2 (time-to-days (org-time-string-to-time t2)))
7156 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7157 ((org-at-timestamp-p t)
7158 (org-agenda-list nil (time-to-days (org-time-string-to-time
7159 (substring (match-string 1) 0 10)))
7161 (t (error "This should not happen"))))
7164 ;;; Following file links
7165 (defvar org-wait nil)
7166 (defun org-open-file (path &optional in-emacs line search)
7167 "Open the file at PATH.
7168 First, this expands any special file name abbreviations. Then the
7169 configuration variable `org-file-apps' is checked if it contains an
7170 entry for this file type, and if yes, the corresponding command is launched.
7171 If no application is found, Emacs simply visits the file.
7172 With optional argument IN-EMACS, Emacs will visit the file.
7173 Optional LINE specifies a line to go to, optional SEARCH a string to
7174 search for. If LINE or SEARCH is given, the file will always be
7175 opened in Emacs.
7176 If the file does not exist, an error is thrown."
7177 (setq in-emacs (or in-emacs line search))
7178 (let* ((file (if (equal path "")
7179 buffer-file-name
7180 (substitute-in-file-name (expand-file-name path))))
7181 (apps (append org-file-apps (org-default-apps)))
7182 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7183 (dirp (if remp nil (file-directory-p file)))
7184 (dfile (downcase file))
7185 (old-buffer (current-buffer))
7186 (old-pos (point))
7187 (old-mode major-mode)
7188 ext cmd)
7189 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7190 (setq ext (match-string 1 dfile))
7191 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7192 (setq ext (match-string 1 dfile))))
7193 (if in-emacs
7194 (setq cmd 'emacs)
7195 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7196 (and dirp (cdr (assoc 'directory apps)))
7197 (cdr (assoc ext apps))
7198 (cdr (assoc t apps)))))
7199 (when (eq cmd 'mailcap)
7200 (require 'mailcap)
7201 (mailcap-parse-mailcaps)
7202 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7203 (command (mailcap-mime-info mime-type)))
7204 (if (stringp command)
7205 (setq cmd command)
7206 (setq cmd 'emacs))))
7207 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7208 (not (file-exists-p file))
7209 (not org-open-non-existing-files))
7210 (error "No such file: %s" file))
7211 (cond
7212 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7213 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7214 (while (string-match "['\"]%s['\"]" cmd)
7215 (setq cmd (replace-match "%s" t t cmd)))
7216 (while (string-match "%s" cmd)
7217 (setq cmd (replace-match
7218 (save-match-data (shell-quote-argument file))
7219 t t cmd)))
7220 (save-window-excursion
7221 (start-process-shell-command cmd nil cmd)
7222 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7224 ((or (stringp cmd)
7225 (eq cmd 'emacs))
7226 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7227 (widen)
7228 (if line (goto-line line)
7229 (if search (org-link-search search))))
7230 ((consp cmd)
7231 (eval cmd))
7232 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7233 (and (org-mode-p) (eq old-mode 'org-mode)
7234 (or (not (equal old-buffer (current-buffer)))
7235 (not (equal old-pos (point))))
7236 (org-mark-ring-push old-pos old-buffer))))
7238 (defun org-default-apps ()
7239 "Return the default applications for this operating system."
7240 (cond
7241 ((eq system-type 'darwin)
7242 org-file-apps-defaults-macosx)
7243 ((eq system-type 'windows-nt)
7244 org-file-apps-defaults-windowsnt)
7245 (t org-file-apps-defaults-gnu)))
7247 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7248 (defun org-file-remote-p (file)
7249 "Test whether FILE specifies a location on a remote system.
7250 Return non-nil if the location is indeed remote.
7252 For example, the filename \"/user@host:/foo\" specifies a location
7253 on the system \"/user@host:\"."
7254 (cond ((fboundp 'file-remote-p)
7255 (file-remote-p file))
7256 ((fboundp 'tramp-handle-file-remote-p)
7257 (tramp-handle-file-remote-p file))
7258 ((and (boundp 'ange-ftp-name-format)
7259 (string-match (car ange-ftp-name-format) file))
7261 (t nil)))
7264 ;;;; Refiling
7266 (defun org-get-org-file ()
7267 "Read a filename, with default directory `org-directory'."
7268 (let ((default (or org-default-notes-file remember-data-file)))
7269 (read-file-name (format "File name [%s]: " default)
7270 (file-name-as-directory org-directory)
7271 default)))
7273 (defun org-notes-order-reversed-p ()
7274 "Check if the current file should receive notes in reversed order."
7275 (cond
7276 ((not org-reverse-note-order) nil)
7277 ((eq t org-reverse-note-order) t)
7278 ((not (listp org-reverse-note-order)) nil)
7279 (t (catch 'exit
7280 (let ((all org-reverse-note-order)
7281 entry)
7282 (while (setq entry (pop all))
7283 (if (string-match (car entry) buffer-file-name)
7284 (throw 'exit (cdr entry))))
7285 nil)))))
7287 (defvar org-refile-target-table nil
7288 "The list of refile targets, created by `org-refile'.")
7290 (defvar org-agenda-new-buffers nil
7291 "Buffers created to visit agenda files.")
7293 (defun org-get-refile-targets (&optional default-buffer)
7294 "Produce a table with refile targets."
7295 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7296 targets txt re files f desc descre)
7297 (with-current-buffer (or default-buffer (current-buffer))
7298 (while (setq entry (pop entries))
7299 (setq files (car entry) desc (cdr entry))
7300 (cond
7301 ((null files) (setq files (list (current-buffer))))
7302 ((eq files 'org-agenda-files)
7303 (setq files (org-agenda-files 'unrestricted)))
7304 ((and (symbolp files) (fboundp files))
7305 (setq files (funcall files)))
7306 ((and (symbolp files) (boundp files))
7307 (setq files (symbol-value files))))
7308 (if (stringp files) (setq files (list files)))
7309 (cond
7310 ((eq (car desc) :tag)
7311 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7312 ((eq (car desc) :todo)
7313 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7314 ((eq (car desc) :regexp)
7315 (setq descre (cdr desc)))
7316 ((eq (car desc) :level)
7317 (setq descre (concat "^\\*\\{" (number-to-string
7318 (if org-odd-levels-only
7319 (1- (* 2 (cdr desc)))
7320 (cdr desc)))
7321 "\\}[ \t]")))
7322 ((eq (car desc) :maxlevel)
7323 (setq descre (concat "^\\*\\{1," (number-to-string
7324 (if org-odd-levels-only
7325 (1- (* 2 (cdr desc)))
7326 (cdr desc)))
7327 "\\}[ \t]")))
7328 (t (error "Bad refiling target description %s" desc)))
7329 (while (setq f (pop files))
7330 (save-excursion
7331 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7332 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7333 (save-excursion
7334 (save-restriction
7335 (widen)
7336 (goto-char (point-min))
7337 (while (re-search-forward descre nil t)
7338 (goto-char (point-at-bol))
7339 (when (looking-at org-complex-heading-regexp)
7340 (setq txt (match-string 4)
7341 re (concat "^" (regexp-quote
7342 (buffer-substring (match-beginning 1)
7343 (match-end 4)))))
7344 (if (match-end 5) (setq re (concat re "[ \t]+"
7345 (regexp-quote
7346 (match-string 5)))))
7347 (setq re (concat re "[ \t]*$"))
7348 (when org-refile-use-outline-path
7349 (setq txt (mapconcat 'identity
7350 (append
7351 (if (eq org-refile-use-outline-path 'file)
7352 (list (file-name-nondirectory
7353 (buffer-file-name (buffer-base-buffer))))
7354 (if (eq org-refile-use-outline-path 'full-file-path)
7355 (list (buffer-file-name (buffer-base-buffer)))))
7356 (org-get-outline-path)
7357 (list txt))
7358 "/")))
7359 (push (list txt f re (point)) targets))
7360 (goto-char (point-at-eol))))))))
7361 (nreverse targets))))
7363 (defun org-get-outline-path ()
7364 "Return the outline path to the current entry, as a list."
7365 (let (rtn)
7366 (save-excursion
7367 (while (org-up-heading-safe)
7368 (when (looking-at org-complex-heading-regexp)
7369 (push (org-match-string-no-properties 4) rtn)))
7370 rtn)))
7372 (defvar org-refile-history nil
7373 "History for refiling operations.")
7375 (defun org-refile (&optional goto default-buffer)
7376 "Move the entry at point to another heading.
7377 The list of target headings is compiled using the information in
7378 `org-refile-targets', which see. This list is created before each use
7379 and will therefore always be up-to-date.
7381 At the target location, the entry is filed as a subitem of the target heading.
7382 Depending on `org-reverse-note-order', the new subitem will either be the
7383 first of the last subitem.
7385 With prefix arg GOTO, the command will only visit the target location,
7386 not actually move anything.
7387 With a double prefix `C-c C-c', go to the location where the last refiling
7388 operation has put the subtree."
7389 (interactive "P")
7390 (let* ((cbuf (current-buffer))
7391 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7392 pos it nbuf file re level reversed)
7393 (if (equal goto '(16))
7394 (org-refile-goto-last-stored)
7395 (when (setq it (org-refile-get-location
7396 (if goto "Goto: " "Refile to: ") default-buffer))
7397 (setq file (nth 1 it)
7398 re (nth 2 it)
7399 pos (nth 3 it))
7400 (setq nbuf (or (find-buffer-visiting file)
7401 (find-file-noselect file)))
7402 (if goto
7403 (progn
7404 (switch-to-buffer nbuf)
7405 (goto-char pos)
7406 (org-show-context 'org-goto))
7407 (org-copy-subtree 1 nil t)
7408 (save-excursion
7409 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7410 (find-file-noselect file))))
7411 (setq reversed (org-notes-order-reversed-p))
7412 (save-excursion
7413 (save-restriction
7414 (widen)
7415 (goto-char pos)
7416 (looking-at outline-regexp)
7417 (setq level (org-get-valid-level (funcall outline-level) 1))
7418 (goto-char
7419 (if reversed
7420 (outline-next-heading)
7421 (or (save-excursion (outline-get-next-sibling))
7422 (org-end-of-subtree t t)
7423 (point-max))))
7424 (bookmark-set "org-refile-last-stored")
7425 (org-paste-subtree level))))
7426 (org-cut-subtree)
7427 (setq org-markers-to-move nil)
7428 (message "Entry refiled to \"%s\"" (car it)))))))
7430 (defun org-refile-goto-last-stored ()
7431 "Go to the location where the last refile was stored."
7432 (interactive)
7433 (bookmark-jump "org-refile-last-stored")
7434 (message "This is the location of the last refile"))
7436 (defun org-refile-get-location (&optional prompt default-buffer)
7437 "Prompt the user for a refile location, using PROMPT."
7438 (let ((org-refile-targets org-refile-targets)
7439 (org-refile-use-outline-path org-refile-use-outline-path))
7440 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7441 (unless org-refile-target-table
7442 (error "No refile targets"))
7443 (let* ((cbuf (current-buffer))
7444 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7445 (fname (and filename (file-truename filename)))
7446 (tbl (mapcar
7447 (lambda (x)
7448 (if (not (equal fname (file-truename (nth 1 x))))
7449 (cons (concat (car x) " (" (file-name-nondirectory
7450 (nth 1 x)) ")")
7451 (cdr x))
7453 org-refile-target-table))
7454 (completion-ignore-case t))
7455 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7456 tbl)))
7458 ;;;; Dynamic blocks
7460 (defun org-find-dblock (name)
7461 "Find the first dynamic block with name NAME in the buffer.
7462 If not found, stay at current position and return nil."
7463 (let (pos)
7464 (save-excursion
7465 (goto-char (point-min))
7466 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7467 nil t)
7468 (match-beginning 0))))
7469 (if pos (goto-char pos))
7470 pos))
7472 (defconst org-dblock-start-re
7473 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7474 "Matches the startline of a dynamic block, with parameters.")
7476 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7477 "Matches the end of a dyhamic block.")
7479 (defun org-create-dblock (plist)
7480 "Create a dynamic block section, with parameters taken from PLIST.
7481 PLIST must containe a :name entry which is used as name of the block."
7482 (unless (bolp) (newline))
7483 (let ((name (plist-get plist :name)))
7484 (insert "#+BEGIN: " name)
7485 (while plist
7486 (if (eq (car plist) :name)
7487 (setq plist (cddr plist))
7488 (insert " " (prin1-to-string (pop plist)))))
7489 (insert "\n\n#+END:\n")
7490 (beginning-of-line -2)))
7492 (defun org-prepare-dblock ()
7493 "Prepare dynamic block for refresh.
7494 This empties the block, puts the cursor at the insert position and returns
7495 the property list including an extra property :name with the block name."
7496 (unless (looking-at org-dblock-start-re)
7497 (error "Not at a dynamic block"))
7498 (let* ((begdel (1+ (match-end 0)))
7499 (name (org-no-properties (match-string 1)))
7500 (params (append (list :name name)
7501 (read (concat "(" (match-string 3) ")")))))
7502 (unless (re-search-forward org-dblock-end-re nil t)
7503 (error "Dynamic block not terminated"))
7504 (setq params
7505 (append params
7506 (list :content (buffer-substring
7507 begdel (match-beginning 0)))))
7508 (delete-region begdel (match-beginning 0))
7509 (goto-char begdel)
7510 (open-line 1)
7511 params))
7513 (defun org-map-dblocks (&optional command)
7514 "Apply COMMAND to all dynamic blocks in the current buffer.
7515 If COMMAND is not given, use `org-update-dblock'."
7516 (let ((cmd (or command 'org-update-dblock))
7517 pos)
7518 (save-excursion
7519 (goto-char (point-min))
7520 (while (re-search-forward org-dblock-start-re nil t)
7521 (goto-char (setq pos (match-beginning 0)))
7522 (condition-case nil
7523 (funcall cmd)
7524 (error (message "Error during update of dynamic block")))
7525 (goto-char pos)
7526 (unless (re-search-forward org-dblock-end-re nil t)
7527 (error "Dynamic block not terminated"))))))
7529 (defun org-dblock-update (&optional arg)
7530 "User command for updating dynamic blocks.
7531 Update the dynamic block at point. With prefix ARG, update all dynamic
7532 blocks in the buffer."
7533 (interactive "P")
7534 (if arg
7535 (org-update-all-dblocks)
7536 (or (looking-at org-dblock-start-re)
7537 (org-beginning-of-dblock))
7538 (org-update-dblock)))
7540 (defun org-update-dblock ()
7541 "Update the dynamic block at point
7542 This means to empty the block, parse for parameters and then call
7543 the correct writing function."
7544 (save-window-excursion
7545 (let* ((pos (point))
7546 (line (org-current-line))
7547 (params (org-prepare-dblock))
7548 (name (plist-get params :name))
7549 (cmd (intern (concat "org-dblock-write:" name))))
7550 (message "Updating dynamic block `%s' at line %d..." name line)
7551 (funcall cmd params)
7552 (message "Updating dynamic block `%s' at line %d...done" name line)
7553 (goto-char pos))))
7555 (defun org-beginning-of-dblock ()
7556 "Find the beginning of the dynamic block at point.
7557 Error if there is no scuh block at point."
7558 (let ((pos (point))
7559 beg)
7560 (end-of-line 1)
7561 (if (and (re-search-backward org-dblock-start-re nil t)
7562 (setq beg (match-beginning 0))
7563 (re-search-forward org-dblock-end-re nil t)
7564 (> (match-end 0) pos))
7565 (goto-char beg)
7566 (goto-char pos)
7567 (error "Not in a dynamic block"))))
7569 (defun org-update-all-dblocks ()
7570 "Update all dynamic blocks in the buffer.
7571 This function can be used in a hook."
7572 (when (org-mode-p)
7573 (org-map-dblocks 'org-update-dblock)))
7576 ;;;; Completion
7578 (defconst org-additional-option-like-keywords
7579 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7580 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7581 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7583 (defun org-complete (&optional arg)
7584 "Perform completion on word at point.
7585 At the beginning of a headline, this completes TODO keywords as given in
7586 `org-todo-keywords'.
7587 If the current word is preceded by a backslash, completes the TeX symbols
7588 that are supported for HTML support.
7589 If the current word is preceded by \"#+\", completes special words for
7590 setting file options.
7591 In the line after \"#+STARTUP:, complete valid keywords.\"
7592 At all other locations, this simply calls the value of
7593 `org-completion-fallback-command'."
7594 (interactive "P")
7595 (org-without-partial-completion
7596 (catch 'exit
7597 (let* ((end (point))
7598 (beg1 (save-excursion
7599 (skip-chars-backward (org-re "[:alnum:]_@"))
7600 (point)))
7601 (beg (save-excursion
7602 (skip-chars-backward "a-zA-Z0-9_:$")
7603 (point)))
7604 (confirm (lambda (x) (stringp (car x))))
7605 (searchhead (equal (char-before beg) ?*))
7606 (tag (and (equal (char-before beg1) ?:)
7607 (equal (char-after (point-at-bol)) ?*)))
7608 (prop (and (equal (char-before beg1) ?:)
7609 (not (equal (char-after (point-at-bol)) ?*))))
7610 (texp (equal (char-before beg) ?\\))
7611 (link (equal (char-before beg) ?\[))
7612 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7613 beg)
7614 "#+"))
7615 (startup (string-match "^#\\+STARTUP:.*"
7616 (buffer-substring (point-at-bol) (point))))
7617 (completion-ignore-case opt)
7618 (type nil)
7619 (tbl nil)
7620 (table (cond
7621 (opt
7622 (setq type :opt)
7623 (require 'org-exp)
7624 (append
7625 (mapcar
7626 (lambda (x)
7627 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7628 (cons (match-string 2 x) (match-string 1 x)))
7629 (org-split-string (org-get-current-options) "\n"))
7630 (mapcar 'list org-additional-option-like-keywords)))
7631 (startup
7632 (setq type :startup)
7633 org-startup-options)
7634 (link (append org-link-abbrev-alist-local
7635 org-link-abbrev-alist))
7636 (texp
7637 (setq type :tex)
7638 org-html-entities)
7639 ((string-match "\\`\\*+[ \t]+\\'"
7640 (buffer-substring (point-at-bol) beg))
7641 (setq type :todo)
7642 (mapcar 'list org-todo-keywords-1))
7643 (searchhead
7644 (setq type :searchhead)
7645 (save-excursion
7646 (goto-char (point-min))
7647 (while (re-search-forward org-todo-line-regexp nil t)
7648 (push (list
7649 (org-make-org-heading-search-string
7650 (match-string 3) t))
7651 tbl)))
7652 tbl)
7653 (tag (setq type :tag beg beg1)
7654 (or org-tag-alist (org-get-buffer-tags)))
7655 (prop (setq type :prop beg beg1)
7656 (mapcar 'list (org-buffer-property-keys nil t t)))
7657 (t (progn
7658 (call-interactively org-completion-fallback-command)
7659 (throw 'exit nil)))))
7660 (pattern (buffer-substring-no-properties beg end))
7661 (completion (try-completion pattern table confirm)))
7662 (cond ((eq completion t)
7663 (if (not (assoc (upcase pattern) table))
7664 (message "Already complete")
7665 (if (and (equal type :opt)
7666 (not (member (car (assoc (upcase pattern) table))
7667 org-additional-option-like-keywords)))
7668 (insert (substring (cdr (assoc (upcase pattern) table))
7669 (length pattern)))
7670 (if (memq type '(:tag :prop)) (insert ":")))))
7671 ((null completion)
7672 (message "Can't find completion for \"%s\"" pattern)
7673 (ding))
7674 ((not (string= pattern completion))
7675 (delete-region beg end)
7676 (if (string-match " +$" completion)
7677 (setq completion (replace-match "" t t completion)))
7678 (insert completion)
7679 (if (get-buffer-window "*Completions*")
7680 (delete-window (get-buffer-window "*Completions*")))
7681 (if (assoc completion table)
7682 (if (eq type :todo) (insert " ")
7683 (if (memq type '(:tag :prop)) (insert ":"))))
7684 (if (and (equal type :opt) (assoc completion table))
7685 (message "%s" (substitute-command-keys
7686 "Press \\[org-complete] again to insert example settings"))))
7688 (message "Making completion list...")
7689 (let ((list (sort (all-completions pattern table confirm)
7690 'string<)))
7691 (with-output-to-temp-buffer "*Completions*"
7692 (condition-case nil
7693 ;; Protection needed for XEmacs and emacs 21
7694 (display-completion-list list pattern)
7695 (error (display-completion-list list)))))
7696 (message "Making completion list...%s" "done")))))))
7698 ;;;; TODO, DEADLINE, Comments
7700 (defun org-toggle-comment ()
7701 "Change the COMMENT state of an entry."
7702 (interactive)
7703 (save-excursion
7704 (org-back-to-heading)
7705 (let (case-fold-search)
7706 (if (looking-at (concat outline-regexp
7707 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7708 (replace-match "" t t nil 1)
7709 (if (looking-at outline-regexp)
7710 (progn
7711 (goto-char (match-end 0))
7712 (insert org-comment-string " ")))))))
7714 (defvar org-last-todo-state-is-todo nil
7715 "This is non-nil when the last TODO state change led to a TODO state.
7716 If the last change removed the TODO tag or switched to DONE, then
7717 this is nil.")
7719 (defvar org-setting-tags nil) ; dynamically skiped
7721 (defun org-parse-local-options (string var)
7722 "Parse STRING for startup setting relevant for variable VAR."
7723 (let ((rtn (symbol-value var))
7724 e opts)
7725 (save-match-data
7726 (if (or (not string) (not (string-match "\\S-" string)))
7728 (setq opts (delq nil (mapcar (lambda (x)
7729 (setq e (assoc x org-startup-options))
7730 (if (eq (nth 1 e) var) e nil))
7731 (org-split-string string "[ \t]+"))))
7732 (if (not opts)
7734 (setq rtn nil)
7735 (while (setq e (pop opts))
7736 (if (not (nth 3 e))
7737 (setq rtn (nth 2 e))
7738 (if (not (listp rtn)) (setq rtn nil))
7739 (push (nth 2 e) rtn)))
7740 rtn)))))
7742 (defvar org-blocker-hook nil
7743 "Hook for functions that are allowed to block a state change.
7745 Each function gets as its single argument a property list, see
7746 `org-trigger-hook' for more information about this list.
7748 If any of the functions in this hook returns nil, the state change
7749 is blocked.")
7751 (defvar org-trigger-hook nil
7752 "Hook for functions that are triggered by a state change.
7754 Each function gets as its single argument a property list with at least
7755 the following elements:
7757 (:type type-of-change :position pos-at-entry-start
7758 :from old-state :to new-state)
7760 Depending on the type, more properties may be present.
7762 This mechanism is currently implemented for:
7764 TODO state changes
7765 ------------------
7766 :type todo-state-change
7767 :from previous state (keyword as a string), or nil
7768 :to new state (keyword as a string), or nil")
7771 (defun org-todo (&optional arg)
7772 "Change the TODO state of an item.
7773 The state of an item is given by a keyword at the start of the heading,
7774 like
7775 *** TODO Write paper
7776 *** DONE Call mom
7778 The different keywords are specified in the variable `org-todo-keywords'.
7779 By default the available states are \"TODO\" and \"DONE\".
7780 So for this example: when the item starts with TODO, it is changed to DONE.
7781 When it starts with DONE, the DONE is removed. And when neither TODO nor
7782 DONE are present, add TODO at the beginning of the heading.
7784 With C-u prefix arg, use completion to determine the new state.
7785 With numeric prefix arg, switch to that state.
7787 For calling through lisp, arg is also interpreted in the following way:
7788 'none -> empty state
7789 \"\"(empty string) -> switch to empty state
7790 'done -> switch to DONE
7791 'nextset -> switch to the next set of keywords
7792 'previousset -> switch to the previous set of keywords
7793 \"WAITING\" -> switch to the specified keyword, but only if it
7794 really is a member of `org-todo-keywords'."
7795 (interactive "P")
7796 (save-excursion
7797 (catch 'exit
7798 (org-back-to-heading)
7799 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7800 (or (looking-at (concat " +" org-todo-regexp " *"))
7801 (looking-at " *"))
7802 (let* ((match-data (match-data))
7803 (startpos (point-at-bol))
7804 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7805 (org-log-done org-log-done)
7806 (org-log-repeat org-log-repeat)
7807 (org-todo-log-states org-todo-log-states)
7808 (this (match-string 1))
7809 (hl-pos (match-beginning 0))
7810 (head (org-get-todo-sequence-head this))
7811 (ass (assoc head org-todo-kwd-alist))
7812 (interpret (nth 1 ass))
7813 (done-word (nth 3 ass))
7814 (final-done-word (nth 4 ass))
7815 (last-state (or this ""))
7816 (completion-ignore-case t)
7817 (member (member this org-todo-keywords-1))
7818 (tail (cdr member))
7819 (state (cond
7820 ((and org-todo-key-trigger
7821 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7822 (and (not arg) org-use-fast-todo-selection
7823 (not (eq org-use-fast-todo-selection 'prefix)))))
7824 ;; Use fast selection
7825 (org-fast-todo-selection))
7826 ((and (equal arg '(4))
7827 (or (not org-use-fast-todo-selection)
7828 (not org-todo-key-trigger)))
7829 ;; Read a state with completion
7830 (completing-read "State: " (mapcar (lambda(x) (list x))
7831 org-todo-keywords-1)
7832 nil t))
7833 ((eq arg 'right)
7834 (if this
7835 (if tail (car tail) nil)
7836 (car org-todo-keywords-1)))
7837 ((eq arg 'left)
7838 (if (equal member org-todo-keywords-1)
7840 (if this
7841 (nth (- (length org-todo-keywords-1) (length tail) 2)
7842 org-todo-keywords-1)
7843 (org-last org-todo-keywords-1))))
7844 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7845 (setq arg nil))) ; hack to fall back to cycling
7846 (arg
7847 ;; user or caller requests a specific state
7848 (cond
7849 ((equal arg "") nil)
7850 ((eq arg 'none) nil)
7851 ((eq arg 'done) (or done-word (car org-done-keywords)))
7852 ((eq arg 'nextset)
7853 (or (car (cdr (member head org-todo-heads)))
7854 (car org-todo-heads)))
7855 ((eq arg 'previousset)
7856 (let ((org-todo-heads (reverse org-todo-heads)))
7857 (or (car (cdr (member head org-todo-heads)))
7858 (car org-todo-heads))))
7859 ((car (member arg org-todo-keywords-1)))
7860 ((nth (1- (prefix-numeric-value arg))
7861 org-todo-keywords-1))))
7862 ((null member) (or head (car org-todo-keywords-1)))
7863 ((equal this final-done-word) nil) ;; -> make empty
7864 ((null tail) nil) ;; -> first entry
7865 ((eq interpret 'sequence)
7866 (car tail))
7867 ((memq interpret '(type priority))
7868 (if (eq this-command last-command)
7869 (car tail)
7870 (if (> (length tail) 0)
7871 (or done-word (car org-done-keywords))
7872 nil)))
7873 (t nil)))
7874 (next (if state (concat " " state " ") " "))
7875 (change-plist (list :type 'todo-state-change :from this :to state
7876 :position startpos))
7877 dolog now-done-p)
7878 (when org-blocker-hook
7879 (unless (save-excursion
7880 (save-match-data
7881 (run-hook-with-args-until-failure
7882 'org-blocker-hook change-plist)))
7883 (if (interactive-p)
7884 (error "TODO state change from %s to %s blocked" this state)
7885 ;; fail silently
7886 (message "TODO state change from %s to %s blocked" this state)
7887 (throw 'exit nil))))
7888 (store-match-data match-data)
7889 (replace-match next t t)
7890 (unless (pos-visible-in-window-p hl-pos)
7891 (message "TODO state changed to %s" (org-trim next)))
7892 (unless head
7893 (setq head (org-get-todo-sequence-head state)
7894 ass (assoc head org-todo-kwd-alist)
7895 interpret (nth 1 ass)
7896 done-word (nth 3 ass)
7897 final-done-word (nth 4 ass)))
7898 (when (memq arg '(nextset previousset))
7899 (message "Keyword-Set %d/%d: %s"
7900 (- (length org-todo-sets) -1
7901 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7902 (length org-todo-sets)
7903 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7904 (setq org-last-todo-state-is-todo
7905 (not (member state org-done-keywords)))
7906 (setq now-done-p (and (member state org-done-keywords)
7907 (not (member this org-done-keywords))))
7908 (and logging (org-local-logging logging))
7909 (when (and (or org-todo-log-states org-log-done)
7910 (not (memq arg '(nextset previousset))))
7911 ;; we need to look at recording a time and note
7912 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7913 (nth 2 (assoc this org-todo-log-states))))
7914 (when (and state
7915 (member state org-not-done-keywords)
7916 (not (member this org-not-done-keywords)))
7917 ;; This is now a todo state and was not one before
7918 ;; If there was a CLOSED time stamp, get rid of it.
7919 (org-add-planning-info nil nil 'closed))
7920 (when (and now-done-p org-log-done)
7921 ;; It is now done, and it was not done before
7922 (org-add-planning-info 'closed (org-current-time))
7923 (if (and (not dolog) (eq 'note org-log-done))
7924 (org-add-log-setup 'done state 'findpos 'note)))
7925 (when (and state dolog)
7926 ;; This is a non-nil state, and we need to log it
7927 (org-add-log-setup 'state state 'findpos dolog)))
7928 ;; Fixup tag positioning
7929 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7930 (run-hooks 'org-after-todo-state-change-hook)
7931 (if (and arg (not (member state org-done-keywords)))
7932 (setq head (org-get-todo-sequence-head state)))
7933 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7934 ;; Do we need to trigger a repeat?
7935 (when now-done-p (org-auto-repeat-maybe state))
7936 ;; Fixup cursor location if close to the keyword
7937 (if (and (outline-on-heading-p)
7938 (not (bolp))
7939 (save-excursion (beginning-of-line 1)
7940 (looking-at org-todo-line-regexp))
7941 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7942 (progn
7943 (goto-char (or (match-end 2) (match-end 1)))
7944 (just-one-space)))
7945 (when org-trigger-hook
7946 (save-excursion
7947 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7949 (defun org-local-logging (value)
7950 "Get logging settings from a property VALUE."
7951 (let* (words w a)
7952 ;; directly set the variables, they are already local.
7953 (setq org-log-done nil
7954 org-log-repeat nil
7955 org-todo-log-states nil)
7956 (setq words (org-split-string value))
7957 (while (setq w (pop words))
7958 (cond
7959 ((setq a (assoc w org-startup-options))
7960 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7961 (set (nth 1 a) (nth 2 a))))
7962 ((setq a (org-extract-log-state-settings w))
7963 (and (member (car a) org-todo-keywords-1)
7964 (push a org-todo-log-states)))))))
7966 (defun org-get-todo-sequence-head (kwd)
7967 "Return the head of the TODO sequence to which KWD belongs.
7968 If KWD is not set, check if there is a text property remembering the
7969 right sequence."
7970 (let (p)
7971 (cond
7972 ((not kwd)
7973 (or (get-text-property (point-at-bol) 'org-todo-head)
7974 (progn
7975 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7976 nil (point-at-eol)))
7977 (get-text-property p 'org-todo-head))))
7978 ((not (member kwd org-todo-keywords-1))
7979 (car org-todo-keywords-1))
7980 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7982 (defun org-fast-todo-selection ()
7983 "Fast TODO keyword selection with single keys.
7984 Returns the new TODO keyword, or nil if no state change should occur."
7985 (let* ((fulltable org-todo-key-alist)
7986 (done-keywords org-done-keywords) ;; needed for the faces.
7987 (maxlen (apply 'max (mapcar
7988 (lambda (x)
7989 (if (stringp (car x)) (string-width (car x)) 0))
7990 fulltable)))
7991 (expert nil)
7992 (fwidth (+ maxlen 3 1 3))
7993 (ncol (/ (- (window-width) 4) fwidth))
7994 tg cnt e c tbl
7995 groups ingroup)
7996 (save-window-excursion
7997 (if expert
7998 (set-buffer (get-buffer-create " *Org todo*"))
7999 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8000 (erase-buffer)
8001 (org-set-local 'org-done-keywords done-keywords)
8002 (setq tbl fulltable cnt 0)
8003 (while (setq e (pop tbl))
8004 (cond
8005 ((equal e '(:startgroup))
8006 (push '() groups) (setq ingroup t)
8007 (when (not (= cnt 0))
8008 (setq cnt 0)
8009 (insert "\n"))
8010 (insert "{ "))
8011 ((equal e '(:endgroup))
8012 (setq ingroup nil cnt 0)
8013 (insert "}\n"))
8015 (setq tg (car e) c (cdr e))
8016 (if ingroup (push tg (car groups)))
8017 (setq tg (org-add-props tg nil 'face
8018 (org-get-todo-face tg)))
8019 (if (and (= cnt 0) (not ingroup)) (insert " "))
8020 (insert "[" c "] " tg (make-string
8021 (- fwidth 4 (length tg)) ?\ ))
8022 (when (= (setq cnt (1+ cnt)) ncol)
8023 (insert "\n")
8024 (if ingroup (insert " "))
8025 (setq cnt 0)))))
8026 (insert "\n")
8027 (goto-char (point-min))
8028 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8029 (fit-window-to-buffer))
8030 (message "[a-z..]:Set [SPC]:clear")
8031 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8032 (cond
8033 ((or (= c ?\C-g)
8034 (and (= c ?q) (not (rassoc c fulltable))))
8035 (setq quit-flag t))
8036 ((= c ?\ ) nil)
8037 ((setq e (rassoc c fulltable) tg (car e))
8039 (t (setq quit-flag t))))))
8041 (defun org-entry-is-todo-p ()
8042 (member (org-get-todo-state) org-not-done-keywords))
8044 (defun org-entry-is-done-p ()
8045 (member (org-get-todo-state) org-done-keywords))
8047 (defun org-get-todo-state ()
8048 (save-excursion
8049 (org-back-to-heading t)
8050 (and (looking-at org-todo-line-regexp)
8051 (match-end 2)
8052 (match-string 2))))
8054 (defun org-at-date-range-p (&optional inactive-ok)
8055 "Is the cursor inside a date range?"
8056 (interactive)
8057 (save-excursion
8058 (catch 'exit
8059 (let ((pos (point)))
8060 (skip-chars-backward "^[<\r\n")
8061 (skip-chars-backward "<[")
8062 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8063 (>= (match-end 0) pos)
8064 (throw 'exit t))
8065 (skip-chars-backward "^<[\r\n")
8066 (skip-chars-backward "<[")
8067 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8068 (>= (match-end 0) pos)
8069 (throw 'exit t)))
8070 nil)))
8072 (defun org-get-repeat ()
8073 "Check if tere is a deadline/schedule with repeater in this entry."
8074 (save-match-data
8075 (save-excursion
8076 (org-back-to-heading t)
8077 (if (re-search-forward
8078 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8079 (match-string 1)))))
8081 (defvar org-last-changed-timestamp)
8082 (defvar org-log-post-message)
8083 (defvar org-log-note-purpose)
8084 (defvar org-log-note-how)
8085 (defun org-auto-repeat-maybe (done-word)
8086 "Check if the current headline contains a repeated deadline/schedule.
8087 If yes, set TODO state back to what it was and change the base date
8088 of repeating deadline/scheduled time stamps to new date.
8089 This function is run automatically after each state change to a DONE state."
8090 ;; last-state is dynamically scoped into this function
8091 (let* ((repeat (org-get-repeat))
8092 (aa (assoc last-state org-todo-kwd-alist))
8093 (interpret (nth 1 aa))
8094 (head (nth 2 aa))
8095 (whata '(("d" . day) ("m" . month) ("y" . year)))
8096 (msg "Entry repeats: ")
8097 (org-log-done nil)
8098 (org-todo-log-states nil)
8099 (nshiftmax 10) (nshift 0)
8100 re type n what ts mb0 time)
8101 (when repeat
8102 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8103 (org-todo (if (eq interpret 'type) last-state head))
8104 (when org-log-repeat
8105 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8106 (memq 'org-add-log-note post-command-hook))
8107 ;; OK, we are already setup for some record
8108 (if (eq org-log-repeat 'note)
8109 ;; make sure we take a note, not only a time stamp
8110 (setq org-log-note-how 'note))
8111 ;; Set up for taking a record
8112 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8113 'findpos org-log-repeat)))
8114 (org-back-to-heading t)
8115 (org-add-planning-info nil nil 'closed)
8116 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8117 org-deadline-time-regexp "\\)\\|\\("
8118 org-ts-regexp "\\)"))
8119 (while (re-search-forward
8120 re (save-excursion (outline-next-heading) (point)) t)
8121 (setq type (if (match-end 1) org-scheduled-string
8122 (if (match-end 3) org-deadline-string "Plain:"))
8123 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8124 mb0 (match-beginning 0))
8125 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8126 (setq n (string-to-number (match-string 2 ts))
8127 what (match-string 3 ts))
8128 (if (equal what "w") (setq n (* n 7) what "d"))
8129 ;; Preparation, see if we need to modify the start date for the change
8130 (when (match-end 1)
8131 (setq time (save-match-data (org-time-string-to-time ts)))
8132 (cond
8133 ((equal (match-string 1 ts) ".")
8134 ;; Shift starting date to today
8135 (org-timestamp-change
8136 (- (time-to-days (current-time)) (time-to-days time))
8137 'day))
8138 ((equal (match-string 1 ts) "+")
8139 (while (or (= nshift 0)
8140 (<= (time-to-days time) (time-to-days (current-time))))
8141 (when (= (incf nshift) nshiftmax)
8142 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8143 (error "Abort")))
8144 (org-timestamp-change n (cdr (assoc what whata)))
8145 (org-at-timestamp-p t)
8146 (setq ts (match-string 1))
8147 (setq time (save-match-data (org-time-string-to-time ts))))
8148 (org-timestamp-change (- n) (cdr (assoc what whata)))
8149 ;; rematch, so that we have everything in place for the real shift
8150 (org-at-timestamp-p t)
8151 (setq ts (match-string 1))
8152 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8153 (org-timestamp-change n (cdr (assoc what whata)))
8154 (setq msg (concat msg type org-last-changed-timestamp " "))))
8155 (setq org-log-post-message msg)
8156 (message "%s" msg))))
8158 (defun org-show-todo-tree (arg)
8159 "Make a compact tree which shows all headlines marked with TODO.
8160 The tree will show the lines where the regexp matches, and all higher
8161 headlines above the match.
8162 With a \\[universal-argument] prefix, also show the DONE entries.
8163 With a numeric prefix N, construct a sparse tree for the Nth element
8164 of `org-todo-keywords-1'."
8165 (interactive "P")
8166 (let ((case-fold-search nil)
8167 (kwd-re
8168 (cond ((null arg) org-not-done-regexp)
8169 ((equal arg '(4))
8170 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8171 (mapcar 'list org-todo-keywords-1))))
8172 (concat "\\("
8173 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8174 "\\)\\>")))
8175 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8176 (regexp-quote (nth (1- (prefix-numeric-value arg))
8177 org-todo-keywords-1)))
8178 (t (error "Invalid prefix argument: %s" arg)))))
8179 (message "%d TODO entries found"
8180 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8182 (defun org-deadline (&optional remove)
8183 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8184 With argument REMOVE, remove any deadline from the item."
8185 (interactive "P")
8186 (if remove
8187 (progn
8188 (org-remove-timestamp-with-keyword org-deadline-string)
8189 (message "Item no longer has a deadline."))
8190 (org-add-planning-info 'deadline nil 'closed)))
8192 (defun org-schedule (&optional remove)
8193 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8194 With argument REMOVE, remove any scheduling date from the item."
8195 (interactive "P")
8196 (if remove
8197 (progn
8198 (org-remove-timestamp-with-keyword org-scheduled-string)
8199 (message "Item is no longer scheduled."))
8200 (org-add-planning-info 'scheduled nil 'closed)))
8202 (defun org-remove-timestamp-with-keyword (keyword)
8203 "Remove all time stamps with KEYWORD in the current entry."
8204 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8205 beg)
8206 (save-excursion
8207 (org-back-to-heading t)
8208 (setq beg (point))
8209 (org-end-of-subtree t t)
8210 (while (re-search-backward re beg t)
8211 (replace-match "")
8212 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8213 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8215 (defun org-add-planning-info (what &optional time &rest remove)
8216 "Insert new timestamp with keyword in the line directly after the headline.
8217 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8218 If non is given, the user is prompted for a date.
8219 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8220 be removed."
8221 (interactive)
8222 (let (org-time-was-given org-end-time-was-given ts
8223 end default-time default-input)
8225 (when (and (not time) (memq what '(scheduled deadline)))
8226 ;; Try to get a default date/time from existing timestamp
8227 (save-excursion
8228 (org-back-to-heading t)
8229 (setq end (save-excursion (outline-next-heading) (point)))
8230 (when (re-search-forward (if (eq what 'scheduled)
8231 org-scheduled-time-regexp
8232 org-deadline-time-regexp)
8233 end t)
8234 (setq ts (match-string 1)
8235 default-time
8236 (apply 'encode-time (org-parse-time-string ts))
8237 default-input (and ts (org-get-compact-tod ts))))))
8238 (when what
8239 ;; If necessary, get the time from the user
8240 (setq time (or time (org-read-date nil 'to-time nil nil
8241 default-time default-input))))
8243 (when (and org-insert-labeled-timestamps-at-point
8244 (member what '(scheduled deadline)))
8245 (insert
8246 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8247 (org-insert-time-stamp time org-time-was-given
8248 nil nil nil (list org-end-time-was-given))
8249 (setq what nil))
8250 (save-excursion
8251 (save-restriction
8252 (let (col list elt ts buffer-invisibility-spec)
8253 (org-back-to-heading t)
8254 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8255 (goto-char (match-end 1))
8256 (setq col (current-column))
8257 (goto-char (match-end 0))
8258 (if (eobp) (insert "\n") (forward-char 1))
8259 (if (and (not (looking-at outline-regexp))
8260 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8261 "[^\r\n]*"))
8262 (not (equal (match-string 1) org-clock-string)))
8263 (narrow-to-region (match-beginning 0) (match-end 0))
8264 (insert-before-markers "\n")
8265 (backward-char 1)
8266 (narrow-to-region (point) (point))
8267 (org-indent-to-column col))
8268 ;; Check if we have to remove something.
8269 (setq list (cons what remove))
8270 (while list
8271 (setq elt (pop list))
8272 (goto-char (point-min))
8273 (when (or (and (eq elt 'scheduled)
8274 (re-search-forward org-scheduled-time-regexp nil t))
8275 (and (eq elt 'deadline)
8276 (re-search-forward org-deadline-time-regexp nil t))
8277 (and (eq elt 'closed)
8278 (re-search-forward org-closed-time-regexp nil t)))
8279 (replace-match "")
8280 (if (looking-at "--+<[^>]+>") (replace-match ""))
8281 (if (looking-at " +") (replace-match ""))))
8282 (goto-char (point-max))
8283 (when what
8284 (insert
8285 (if (not (equal (char-before) ?\ )) " " "")
8286 (cond ((eq what 'scheduled) org-scheduled-string)
8287 ((eq what 'deadline) org-deadline-string)
8288 ((eq what 'closed) org-closed-string))
8289 " ")
8290 (setq ts (org-insert-time-stamp
8291 time
8292 (or org-time-was-given
8293 (and (eq what 'closed) org-log-done-with-time))
8294 (eq what 'closed)
8295 nil nil (list org-end-time-was-given)))
8296 (end-of-line 1))
8297 (goto-char (point-min))
8298 (widen)
8299 (if (and (looking-at "[ \t]+\n")
8300 (equal (char-before) ?\n))
8301 (backward-delete-char 1))
8302 ts)))))
8304 (defvar org-log-note-marker (make-marker))
8305 (defvar org-log-note-purpose nil)
8306 (defvar org-log-note-state nil)
8307 (defvar org-log-note-how nil)
8308 (defvar org-log-note-window-configuration nil)
8309 (defvar org-log-note-return-to (make-marker))
8310 (defvar org-log-post-message nil
8311 "Message to be displayed after a log note has been stored.
8312 The auto-repeater uses this.")
8314 (defun org-add-note ()
8315 "Add a note to the current entry.
8316 This is done in the same way as adding a state change note."
8317 (interactive)
8318 (org-add-log-setup 'note nil t nil))
8320 (defun org-add-log-setup (&optional purpose state findpos how)
8321 "Set up the post command hook to take a note.
8322 If this is about to TODO state change, the new state is expected in STATE.
8323 When FINDPOS is non-nil, find the correct position for the note in
8324 the current entry. If not, assume that it can be inserted at point."
8325 (save-excursion
8326 (when findpos
8327 (org-back-to-heading t)
8328 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8329 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8330 "[^\r\n]*\\)?"))
8331 (goto-char (match-end 0))
8332 (unless org-log-states-order-reversed
8333 (and (= (char-after) ?\n) (forward-char 1))
8334 (org-skip-over-state-notes)
8335 (skip-chars-backward " \t\n\r")))
8336 (move-marker org-log-note-marker (point))
8337 (setq org-log-note-purpose purpose
8338 org-log-note-state state
8339 org-log-note-how how)
8340 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8342 (defun org-skip-over-state-notes ()
8343 "Skip past the list of State notes in an entry."
8344 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8345 (while (looking-at "[ \t]*- State")
8346 (condition-case nil
8347 (org-next-item)
8348 (error (org-end-of-item)))))
8350 (defun org-add-log-note (&optional purpose)
8351 "Pop up a window for taking a note, and add this note later at point."
8352 (remove-hook 'post-command-hook 'org-add-log-note)
8353 (setq org-log-note-window-configuration (current-window-configuration))
8354 (delete-other-windows)
8355 (move-marker org-log-note-return-to (point))
8356 (switch-to-buffer (marker-buffer org-log-note-marker))
8357 (goto-char org-log-note-marker)
8358 (org-switch-to-buffer-other-window "*Org Note*")
8359 (erase-buffer)
8360 (if (memq org-log-note-how '(time state))
8361 (org-store-log-note)
8362 (let ((org-inhibit-startup t)) (org-mode))
8363 (insert (format "# Insert note for %s.
8364 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8365 (cond
8366 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8367 ((eq org-log-note-purpose 'done) "closed todo item")
8368 ((eq org-log-note-purpose 'state)
8369 (format "state change to \"%s\"" org-log-note-state))
8370 ((eq org-log-note-purpose 'note)
8371 "this entry")
8372 (t (error "This should not happen")))))
8373 (org-set-local 'org-finish-function 'org-store-log-note)))
8375 (defvar org-note-abort nil) ; dynamically scoped
8376 (defun org-store-log-note ()
8377 "Finish taking a log note, and insert it to where it belongs."
8378 (let ((txt (buffer-string))
8379 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8380 lines ind)
8381 (kill-buffer (current-buffer))
8382 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8383 (setq txt (replace-match "" t t txt)))
8384 (if (string-match "\\s-+\\'" txt)
8385 (setq txt (replace-match "" t t txt)))
8386 (setq lines (org-split-string txt "\n"))
8387 (when (and note (string-match "\\S-" note))
8388 (setq note
8389 (org-replace-escapes
8390 note
8391 (list (cons "%u" (user-login-name))
8392 (cons "%U" user-full-name)
8393 (cons "%t" (format-time-string
8394 (org-time-stamp-format 'long 'inactive)
8395 (current-time)))
8396 (cons "%s" (if org-log-note-state
8397 (concat "\"" org-log-note-state "\"")
8398 "")))))
8399 (if lines (setq note (concat note " \\\\")))
8400 (push note lines))
8401 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8402 (when lines
8403 (save-excursion
8404 (set-buffer (marker-buffer org-log-note-marker))
8405 (save-excursion
8406 (goto-char org-log-note-marker)
8407 (move-marker org-log-note-marker nil)
8408 (end-of-line 1)
8409 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8410 (indent-relative nil)
8411 (insert "- " (pop lines))
8412 (org-indent-line-function)
8413 (beginning-of-line 1)
8414 (looking-at "[ \t]*")
8415 (setq ind (concat (match-string 0) " "))
8416 (end-of-line 1)
8417 (while lines (insert "\n" ind (pop lines)))))))
8418 (set-window-configuration org-log-note-window-configuration)
8419 (with-current-buffer (marker-buffer org-log-note-return-to)
8420 (goto-char org-log-note-return-to))
8421 (move-marker org-log-note-return-to nil)
8422 (and org-log-post-message (message "%s" org-log-post-message)))
8424 (defun org-sparse-tree (&optional arg)
8425 "Create a sparse tree, prompt for the details.
8426 This command can create sparse trees. You first need to select the type
8427 of match used to create the tree:
8429 t Show entries with a specific TODO keyword.
8430 T Show entries selected by a tags match.
8431 p Enter a property name and its value (both with completion on existing
8432 names/values) and show entries with that property.
8433 r Show entries matching a regular expression
8434 d Show deadlines due within `org-deadline-warning-days'."
8435 (interactive "P")
8436 (let (ans kwd value)
8437 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8438 (setq ans (read-char-exclusive))
8439 (cond
8440 ((equal ans ?d)
8441 (call-interactively 'org-check-deadlines))
8442 ((equal ans ?b)
8443 (call-interactively 'org-check-before-date))
8444 ((equal ans ?t)
8445 (org-show-todo-tree '(4)))
8446 ((equal ans ?T)
8447 (call-interactively 'org-tags-sparse-tree))
8448 ((member ans '(?p ?P))
8449 (setq kwd (completing-read "Property: "
8450 (mapcar 'list (org-buffer-property-keys))))
8451 (setq value (completing-read "Value: "
8452 (mapcar 'list (org-property-values kwd))))
8453 (unless (string-match "\\`{.*}\\'" value)
8454 (setq value (concat "\"" value "\"")))
8455 (org-tags-sparse-tree arg (concat kwd "=" value)))
8456 ((member ans '(?r ?R ?/))
8457 (call-interactively 'org-occur))
8458 (t (error "No such sparse tree command \"%c\"" ans)))))
8460 (defvar org-occur-highlights nil
8461 "List of overlays used for occur matches.")
8462 (make-variable-buffer-local 'org-occur-highlights)
8463 (defvar org-occur-parameters nil
8464 "Parameters of the active org-occur calls.
8465 This is a list, each call to org-occur pushes as cons cell,
8466 containing the regular expression and the callback, onto the list.
8467 The list can contain several entries if `org-occur' has been called
8468 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8469 will only contain one set of parameters. When the highlights are
8470 removed (for example with `C-c C-c', or with the next edit (depending
8471 on `org-remove-highlights-with-change'), this variable is emptied
8472 as well.")
8473 (make-variable-buffer-local 'org-occur-parameters)
8475 (defun org-occur (regexp &optional keep-previous callback)
8476 "Make a compact tree which shows all matches of REGEXP.
8477 The tree will show the lines where the regexp matches, and all higher
8478 headlines above the match. It will also show the heading after the match,
8479 to make sure editing the matching entry is easy.
8480 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8481 call to `org-occur' will be kept, to allow stacking of calls to this
8482 command.
8483 If CALLBACK is non-nil, it is a function which is called to confirm
8484 that the match should indeed be shown."
8485 (interactive "sRegexp: \nP")
8486 (unless keep-previous
8487 (org-remove-occur-highlights nil nil t))
8488 (push (cons regexp callback) org-occur-parameters)
8489 (let ((cnt 0))
8490 (save-excursion
8491 (goto-char (point-min))
8492 (if (or (not keep-previous) ; do not want to keep
8493 (not org-occur-highlights)) ; no previous matches
8494 ;; hide everything
8495 (org-overview))
8496 (while (re-search-forward regexp nil t)
8497 (when (or (not callback)
8498 (save-match-data (funcall callback)))
8499 (setq cnt (1+ cnt))
8500 (when org-highlight-sparse-tree-matches
8501 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8502 (org-show-context 'occur-tree))))
8503 (when org-remove-highlights-with-change
8504 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8505 nil 'local))
8506 (unless org-sparse-tree-open-archived-trees
8507 (org-hide-archived-subtrees (point-min) (point-max)))
8508 (run-hooks 'org-occur-hook)
8509 (if (interactive-p)
8510 (message "%d match(es) for regexp %s" cnt regexp))
8511 cnt))
8513 (defun org-show-context (&optional key)
8514 "Make sure point and context and visible.
8515 How much context is shown depends upon the variables
8516 `org-show-hierarchy-above', `org-show-following-heading'. and
8517 `org-show-siblings'."
8518 (let ((heading-p (org-on-heading-p t))
8519 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8520 (following-p (org-get-alist-option org-show-following-heading key))
8521 (entry-p (org-get-alist-option org-show-entry-below key))
8522 (siblings-p (org-get-alist-option org-show-siblings key)))
8523 (catch 'exit
8524 ;; Show heading or entry text
8525 (if (and heading-p (not entry-p))
8526 (org-flag-heading nil) ; only show the heading
8527 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8528 (org-show-hidden-entry))) ; show entire entry
8529 (when following-p
8530 ;; Show next sibling, or heading below text
8531 (save-excursion
8532 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8533 (org-flag-heading nil))))
8534 (when siblings-p (org-show-siblings))
8535 (when hierarchy-p
8536 ;; show all higher headings, possibly with siblings
8537 (save-excursion
8538 (while (and (condition-case nil
8539 (progn (org-up-heading-all 1) t)
8540 (error nil))
8541 (not (bobp)))
8542 (org-flag-heading nil)
8543 (when siblings-p (org-show-siblings))))))))
8545 (defun org-reveal (&optional siblings)
8546 "Show current entry, hierarchy above it, and the following headline.
8547 This can be used to show a consistent set of context around locations
8548 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8549 not t for the search context.
8551 With optional argument SIBLINGS, on each level of the hierarchy all
8552 siblings are shown. This repairs the tree structure to what it would
8553 look like when opened with hierarchical calls to `org-cycle'."
8554 (interactive "P")
8555 (let ((org-show-hierarchy-above t)
8556 (org-show-following-heading t)
8557 (org-show-siblings (if siblings t org-show-siblings)))
8558 (org-show-context nil)))
8560 (defun org-highlight-new-match (beg end)
8561 "Highlight from BEG to END and mark the highlight is an occur headline."
8562 (let ((ov (org-make-overlay beg end)))
8563 (org-overlay-put ov 'face 'secondary-selection)
8564 (push ov org-occur-highlights)))
8566 (defun org-remove-occur-highlights (&optional beg end noremove)
8567 "Remove the occur highlights from the buffer.
8568 BEG and END are ignored. If NOREMOVE is nil, remove this function
8569 from the `before-change-functions' in the current buffer."
8570 (interactive)
8571 (unless org-inhibit-highlight-removal
8572 (mapc 'org-delete-overlay org-occur-highlights)
8573 (setq org-occur-highlights nil)
8574 (setq org-occur-parameters nil)
8575 (unless noremove
8576 (remove-hook 'before-change-functions
8577 'org-remove-occur-highlights 'local))))
8579 ;;;; Priorities
8581 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8582 "Regular expression matching the priority indicator.")
8584 (defvar org-remove-priority-next-time nil)
8586 (defun org-priority-up ()
8587 "Increase the priority of the current item."
8588 (interactive)
8589 (org-priority 'up))
8591 (defun org-priority-down ()
8592 "Decrease the priority of the current item."
8593 (interactive)
8594 (org-priority 'down))
8596 (defun org-priority (&optional action)
8597 "Change the priority of an item by ARG.
8598 ACTION can be `set', `up', `down', or a character."
8599 (interactive)
8600 (setq action (or action 'set))
8601 (let (current new news have remove)
8602 (save-excursion
8603 (org-back-to-heading)
8604 (if (looking-at org-priority-regexp)
8605 (setq current (string-to-char (match-string 2))
8606 have t)
8607 (setq current org-default-priority))
8608 (cond
8609 ((or (eq action 'set)
8610 (if (featurep 'xemacs) (characterp action) (integerp action)))
8611 (if (not (eq action 'set))
8612 (setq new action)
8613 (message "Priority %c-%c, SPC to remove: "
8614 org-highest-priority org-lowest-priority)
8615 (setq new (read-char-exclusive)))
8616 (if (and (= (upcase org-highest-priority) org-highest-priority)
8617 (= (upcase org-lowest-priority) org-lowest-priority))
8618 (setq new (upcase new)))
8619 (cond ((equal new ?\ ) (setq remove t))
8620 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8621 (error "Priority must be between `%c' and `%c'"
8622 org-highest-priority org-lowest-priority))))
8623 ((eq action 'up)
8624 (if (and (not have) (eq last-command this-command))
8625 (setq new org-lowest-priority)
8626 (setq new (if (and org-priority-start-cycle-with-default (not have))
8627 org-default-priority (1- current)))))
8628 ((eq action 'down)
8629 (if (and (not have) (eq last-command this-command))
8630 (setq new org-highest-priority)
8631 (setq new (if (and org-priority-start-cycle-with-default (not have))
8632 org-default-priority (1+ current)))))
8633 (t (error "Invalid action")))
8634 (if (or (< (upcase new) org-highest-priority)
8635 (> (upcase new) org-lowest-priority))
8636 (setq remove t))
8637 (setq news (format "%c" new))
8638 (if have
8639 (if remove
8640 (replace-match "" t t nil 1)
8641 (replace-match news t t nil 2))
8642 (if remove
8643 (error "No priority cookie found in line")
8644 (looking-at org-todo-line-regexp)
8645 (if (match-end 2)
8646 (progn
8647 (goto-char (match-end 2))
8648 (insert " [#" news "]"))
8649 (goto-char (match-beginning 3))
8650 (insert "[#" news "] ")))))
8651 (org-preserve-lc (org-set-tags nil 'align))
8652 (if remove
8653 (message "Priority removed")
8654 (message "Priority of current item set to %s" news))))
8657 (defun org-get-priority (s)
8658 "Find priority cookie and return priority."
8659 (save-match-data
8660 (if (not (string-match org-priority-regexp s))
8661 (* 1000 (- org-lowest-priority org-default-priority))
8662 (* 1000 (- org-lowest-priority
8663 (string-to-char (match-string 2 s)))))))
8665 ;;;; Tags
8667 (defun org-scan-tags (action matcher &optional todo-only)
8668 "Scan headline tags with inheritance and produce output ACTION.
8669 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8670 evaluated, testing if a given set of tags qualifies a headline for
8671 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8672 are included in the output."
8673 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8674 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8675 (org-re
8676 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8677 (props (list 'face nil
8678 'done-face 'org-done
8679 'undone-face nil
8680 'mouse-face 'highlight
8681 'org-not-done-regexp org-not-done-regexp
8682 'org-todo-regexp org-todo-regexp
8683 'keymap org-agenda-keymap
8684 'help-echo
8685 (format "mouse-2 or RET jump to org file %s"
8686 (abbreviate-file-name
8687 (or (buffer-file-name (buffer-base-buffer))
8688 (buffer-name (buffer-base-buffer)))))))
8689 (case-fold-search nil)
8690 lspos
8691 tags tags-list tags-alist (llast 0) rtn level category i txt
8692 todo marker entry priority)
8693 (save-excursion
8694 (goto-char (point-min))
8695 (when (eq action 'sparse-tree)
8696 (org-overview)
8697 (org-remove-occur-highlights))
8698 (while (re-search-forward re nil t)
8699 (catch :skip
8700 (setq todo (if (match-end 1) (match-string 2))
8701 tags (if (match-end 4) (match-string 4)))
8702 (goto-char (setq lspos (1+ (match-beginning 0))))
8703 (setq level (org-reduced-level (funcall outline-level))
8704 category (org-get-category))
8705 (setq i llast llast level)
8706 ;; remove tag lists from same and sublevels
8707 (while (>= i level)
8708 (when (setq entry (assoc i tags-alist))
8709 (setq tags-alist (delete entry tags-alist)))
8710 (setq i (1- i)))
8711 ;; add the next tags
8712 (when tags
8713 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8714 tags-alist
8715 (cons (cons level tags) tags-alist)))
8716 ;; compile tags for current headline
8717 (setq tags-list
8718 (if org-use-tag-inheritance
8719 (apply 'append (mapcar 'cdr tags-alist))
8720 tags))
8721 (when (and tags org-use-tag-inheritance
8722 (not (eq t org-use-tag-inheritance)))
8723 ;; selective inheritance, remove uninherited ones
8724 (setcdr (car tags-alist)
8725 (org-remove-uniherited-tags (cdar tags-alist))))
8726 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8727 (eval matcher)
8728 (or (not org-agenda-skip-archived-trees)
8729 (not (member org-archive-tag tags-list))))
8730 (and (eq action 'agenda) (org-agenda-skip))
8731 ;; list this headline
8733 (if (eq action 'sparse-tree)
8734 (progn
8735 (and org-highlight-sparse-tree-matches
8736 (org-get-heading) (match-end 0)
8737 (org-highlight-new-match
8738 (match-beginning 0) (match-beginning 1)))
8739 (org-show-context 'tags-tree))
8740 (setq txt (org-format-agenda-item
8742 (concat
8743 (if org-tags-match-list-sublevels
8744 (make-string (1- level) ?.) "")
8745 (org-get-heading))
8746 category tags-list)
8747 priority (org-get-priority txt))
8748 (goto-char lspos)
8749 (setq marker (org-agenda-new-marker))
8750 (org-add-props txt props
8751 'org-marker marker 'org-hd-marker marker 'org-category category
8752 'priority priority 'type "tagsmatch")
8753 (push txt rtn))
8754 ;; if we are to skip sublevels, jump to end of subtree
8755 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8756 (when (and (eq action 'sparse-tree)
8757 (not org-sparse-tree-open-archived-trees))
8758 (org-hide-archived-subtrees (point-min) (point-max)))
8759 (nreverse rtn)))
8761 (defun org-remove-uniherited-tags (tags)
8762 "Remove all tags that are not inherited from the list TAGS."
8763 (cond
8764 ((eq org-use-tag-inheritance t) tags)
8765 ((not org-use-tag-inheritance) nil)
8766 ((stringp org-use-tag-inheritance)
8767 (delq nil (mapcar
8768 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8769 tags)))
8770 ((listp org-use-tag-inheritance)
8771 (org-delete-all org-use-tag-inheritance tags))))
8773 (defvar todo-only) ;; dynamically scoped
8775 (defun org-tags-sparse-tree (&optional todo-only match)
8776 "Create a sparse tree according to tags string MATCH.
8777 MATCH can contain positive and negative selection of tags, like
8778 \"+WORK+URGENT-WITHBOSS\".
8779 If optional argument TODO_ONLY is non-nil, only select lines that are
8780 also TODO lines."
8781 (interactive "P")
8782 (org-prepare-agenda-buffers (list (current-buffer)))
8783 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8785 (defvar org-cached-props nil)
8786 (defun org-cached-entry-get (pom property)
8787 (if (or (eq t org-use-property-inheritance)
8788 (and (stringp org-use-property-inheritance)
8789 (string-match org-use-property-inheritance property))
8790 (and (listp org-use-property-inheritance)
8791 (member property org-use-property-inheritance)))
8792 ;; Caching is not possible, check it directly
8793 (org-entry-get pom property 'inherit)
8794 ;; Get all properties, so that we can do complicated checks easily
8795 (cdr (assoc property (or org-cached-props
8796 (setq org-cached-props
8797 (org-entry-properties pom)))))))
8799 (defun org-global-tags-completion-table (&optional files)
8800 "Return the list of all tags in all agenda buffer/files."
8801 (save-excursion
8802 (org-uniquify
8803 (delq nil
8804 (apply 'append
8805 (mapcar
8806 (lambda (file)
8807 (set-buffer (find-file-noselect file))
8808 (append (org-get-buffer-tags)
8809 (mapcar (lambda (x) (if (stringp (car-safe x))
8810 (list (car-safe x)) nil))
8811 org-tag-alist)))
8812 (if (and files (car files))
8813 files
8814 (org-agenda-files))))))))
8816 (defun org-make-tags-matcher (match)
8817 "Create the TAGS//TODO matcher form for the selection string MATCH."
8818 ;; todo-only is scoped dynamically into this function, and the function
8819 ;; may change it it the matcher asksk for it.
8820 (unless match
8821 ;; Get a new match request, with completion
8822 (let ((org-last-tags-completion-table
8823 (org-global-tags-completion-table)))
8824 (setq match (completing-read
8825 "Match: " 'org-tags-completion-function nil nil nil
8826 'org-tags-history))))
8828 ;; Parse the string and create a lisp form
8829 (let ((match0 match)
8830 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8831 minus tag mm
8832 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8833 orterms term orlist re-p str-p level-p level-op
8834 prop-p pn pv po cat-p gv)
8835 (if (string-match "/+" match)
8836 ;; match contains also a todo-matching request
8837 (progn
8838 (setq tagsmatch (substring match 0 (match-beginning 0))
8839 todomatch (substring match (match-end 0)))
8840 (if (string-match "^!" todomatch)
8841 (setq todo-only t todomatch (substring todomatch 1)))
8842 (if (string-match "^\\s-*$" todomatch)
8843 (setq todomatch nil)))
8844 ;; only matching tags
8845 (setq tagsmatch match todomatch nil))
8847 ;; Make the tags matcher
8848 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8849 (setq tagsmatcher t)
8850 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8851 (while (setq term (pop orterms))
8852 (while (and (equal (substring term -1) "\\") orterms)
8853 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8854 (while (string-match re term)
8855 (setq minus (and (match-end 1)
8856 (equal (match-string 1 term) "-"))
8857 tag (match-string 2 term)
8858 re-p (equal (string-to-char tag) ?{)
8859 level-p (match-end 4)
8860 prop-p (match-end 5)
8861 mm (cond
8862 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8863 (level-p
8864 (setq level-op (org-op-to-function (match-string 3 term)))
8865 `(,level-op level ,(string-to-number
8866 (match-string 4 term))))
8867 (prop-p
8868 (setq pn (match-string 5 term)
8869 po (match-string 6 term)
8870 pv (match-string 7 term)
8871 cat-p (equal pn "CATEGORY")
8872 re-p (equal (string-to-char pv) ?{)
8873 str-p (equal (string-to-char pv) ?\")
8874 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8875 (setq po (org-op-to-function po str-p))
8876 (if (equal pn "CATEGORY")
8877 (setq gv '(get-text-property (point) 'org-category))
8878 (setq gv `(org-cached-entry-get nil ,pn)))
8879 (if re-p
8880 (if (eq po 'org<>)
8881 `(not (string-match ,pv (or ,gv "")))
8882 `(string-match ,pv (or ,gv "")))
8883 (if str-p
8884 `(,po (or ,gv "") ,pv)
8885 `(,po (string-to-number (or ,gv ""))
8886 ,(string-to-number pv) ))))
8887 (t `(member ,(downcase tag) tags-list)))
8888 mm (if minus (list 'not mm) mm)
8889 term (substring term (match-end 0)))
8890 (push mm tagsmatcher))
8891 (push (if (> (length tagsmatcher) 1)
8892 (cons 'and tagsmatcher)
8893 (car tagsmatcher))
8894 orlist)
8895 (setq tagsmatcher nil))
8896 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8897 (setq tagsmatcher
8898 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8899 ;; Make the todo matcher
8900 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8901 (setq todomatcher t)
8902 (setq orterms (org-split-string todomatch "|") orlist nil)
8903 (while (setq term (pop orterms))
8904 (while (string-match re term)
8905 (setq minus (and (match-end 1)
8906 (equal (match-string 1 term) "-"))
8907 kwd (match-string 2 term)
8908 re-p (equal (string-to-char kwd) ?{)
8909 term (substring term (match-end 0))
8910 mm (if re-p
8911 `(string-match ,(substring kwd 1 -1) todo)
8912 (list 'equal 'todo kwd))
8913 mm (if minus (list 'not mm) mm))
8914 (push mm todomatcher))
8915 (push (if (> (length todomatcher) 1)
8916 (cons 'and todomatcher)
8917 (car todomatcher))
8918 orlist)
8919 (setq todomatcher nil))
8920 (setq todomatcher (if (> (length orlist) 1)
8921 (cons 'or orlist) (car orlist))))
8923 ;; Return the string and lisp forms of the matcher
8924 (setq matcher (if todomatcher
8925 (list 'and tagsmatcher todomatcher)
8926 tagsmatcher))
8927 (cons match0 matcher)))
8929 (defun org-op-to-function (op &optional stringp)
8930 (setq op
8931 (cond
8932 ((equal op "<" ) '(< string< ))
8933 ((equal op ">" ) '(> org-string> ))
8934 ((member op '("<=" "=<")) '(<= org-string<= ))
8935 ((member op '(">=" "=>")) '(>= org-string>= ))
8936 ((member op '("=" "==")) '(= string= ))
8937 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8938 (nth (if stringp 1 0) op))
8940 (defun org<> (a b) (not (= a b)))
8941 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8942 (defun org-string>= (a b) (not (string< a b)))
8943 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8944 (defun org-string<> (a b) (not (string= a b)))
8946 (defun org-match-any-p (re list)
8947 "Does re match any element of list?"
8948 (setq list (mapcar (lambda (x) (string-match re x)) list))
8949 (delq nil list))
8951 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8952 (defvar org-tags-overlay (org-make-overlay 1 1))
8953 (org-detach-overlay org-tags-overlay)
8955 (defun org-get-tags-at (&optional pos)
8956 "Get a list of all headline tags applicable at POS.
8957 POS defaults to point. If tags are inherited, the list contains
8958 the targets in the same sequence as the headlines appear, i.e.
8959 sthe tags of the current headline come last."
8960 (interactive)
8961 (let (tags ltags lastpos parent)
8962 (save-excursion
8963 (save-restriction
8964 (widen)
8965 (goto-char (or pos (point)))
8966 (save-match-data
8967 (condition-case nil
8968 (progn
8969 (org-back-to-heading t)
8970 (while (not (equal lastpos (point)))
8971 (setq lastpos (point))
8972 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8973 (setq ltags (org-split-string
8974 (org-match-string-no-properties 1) ":"))
8975 (setq tags (append (org-remove-uniherited-tags ltags)
8976 tags)))
8977 (or org-use-tag-inheritance (error ""))
8978 (org-up-heading-all 1)
8979 (setq parent t)))
8980 (error nil))))
8981 tags)))
8983 (defun org-toggle-tag (tag &optional onoff)
8984 "Toggle the tag TAG for the current line.
8985 If ONOFF is `on' or `off', don't toggle but set to this state."
8986 (unless (org-on-heading-p t) (error "Not on headling"))
8987 (let (res current)
8988 (save-excursion
8989 (beginning-of-line)
8990 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8991 (point-at-eol) t)
8992 (progn
8993 (setq current (match-string 1))
8994 (replace-match ""))
8995 (setq current ""))
8996 (setq current (nreverse (org-split-string current ":")))
8997 (cond
8998 ((eq onoff 'on)
8999 (setq res t)
9000 (or (member tag current) (push tag current)))
9001 ((eq onoff 'off)
9002 (or (not (member tag current)) (setq current (delete tag current))))
9003 (t (if (member tag current)
9004 (setq current (delete tag current))
9005 (setq res t)
9006 (push tag current))))
9007 (end-of-line 1)
9008 (if current
9009 (progn
9010 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9011 (org-set-tags nil t))
9012 (delete-horizontal-space))
9013 (run-hooks 'org-after-tags-change-hook))
9014 res))
9016 (defun org-align-tags-here (to-col)
9017 ;; Assumes that this is a headline
9018 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9019 (beginning-of-line 1)
9020 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9021 (< pos (match-beginning 2)))
9022 (progn
9023 (setq tags-l (- (match-end 2) (match-beginning 2)))
9024 (goto-char (match-beginning 1))
9025 (insert " ")
9026 (delete-region (point) (1+ (match-beginning 2)))
9027 (setq ncol (max (1+ (current-column))
9028 (1+ col)
9029 (if (> to-col 0)
9030 to-col
9031 (- (abs to-col) tags-l))))
9032 (setq p (point))
9033 (insert (make-string (- ncol (current-column)) ?\ ))
9034 (setq ncol (current-column))
9035 (tabify p (point-at-eol))
9036 (org-move-to-column (min ncol col) t))
9037 (goto-char pos))))
9039 (defun org-set-tags (&optional arg just-align)
9040 "Set the tags for the current headline.
9041 With prefix ARG, realign all tags in headings in the current buffer."
9042 (interactive "P")
9043 (let* ((re (concat "^" outline-regexp))
9044 (current (org-get-tags-string))
9045 (col (current-column))
9046 (org-setting-tags t)
9047 table current-tags inherited-tags ; computed below when needed
9048 tags p0 c0 c1 rpl)
9049 (if arg
9050 (save-excursion
9051 (goto-char (point-min))
9052 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9053 (while (re-search-forward re nil t)
9054 (org-set-tags nil t)
9055 (end-of-line 1)))
9056 (message "All tags realigned to column %d" org-tags-column))
9057 (if just-align
9058 (setq tags current)
9059 ;; Get a new set of tags from the user
9060 (save-excursion
9061 (setq table (or org-tag-alist (org-get-buffer-tags))
9062 org-last-tags-completion-table table
9063 current-tags (org-split-string current ":")
9064 inherited-tags (nreverse
9065 (nthcdr (length current-tags)
9066 (nreverse (org-get-tags-at))))
9067 tags
9068 (if (or (eq t org-use-fast-tag-selection)
9069 (and org-use-fast-tag-selection
9070 (delq nil (mapcar 'cdr table))))
9071 (org-fast-tag-selection
9072 current-tags inherited-tags table
9073 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9074 (let ((org-add-colon-after-tag-completion t))
9075 (org-trim
9076 (org-without-partial-completion
9077 (completing-read "Tags: " 'org-tags-completion-function
9078 nil nil current 'org-tags-history)))))))
9079 (while (string-match "[-+&]+" tags)
9080 ;; No boolean logic, just a list
9081 (setq tags (replace-match ":" t t tags))))
9083 (if (string-match "\\`[\t ]*\\'" tags)
9084 (setq tags "")
9085 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9086 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9088 ;; Insert new tags at the correct column
9089 (beginning-of-line 1)
9090 (cond
9091 ((and (equal current "") (equal tags "")))
9092 ((re-search-forward
9093 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9094 (point-at-eol) t)
9095 (if (equal tags "")
9096 (setq rpl "")
9097 (goto-char (match-beginning 0))
9098 (setq c0 (current-column) p0 (point)
9099 c1 (max (1+ c0) (if (> org-tags-column 0)
9100 org-tags-column
9101 (- (- org-tags-column) (length tags))))
9102 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9103 (replace-match rpl t t)
9104 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9105 tags)
9106 (t (error "Tags alignment failed")))
9107 (org-move-to-column col)
9108 (unless just-align
9109 (run-hooks 'org-after-tags-change-hook)))))
9111 (defun org-change-tag-in-region (beg end tag off)
9112 "Add or remove TAG for each entry in the region.
9113 This works in the agenda, and also in an org-mode buffer."
9114 (interactive
9115 (list (region-beginning) (region-end)
9116 (let ((org-last-tags-completion-table
9117 (if (org-mode-p)
9118 (org-get-buffer-tags)
9119 (org-global-tags-completion-table))))
9120 (completing-read
9121 "Tag: " 'org-tags-completion-function nil nil nil
9122 'org-tags-history))
9123 (progn
9124 (message "[s]et or [r]emove? ")
9125 (equal (read-char-exclusive) ?r))))
9126 (if (fboundp 'deactivate-mark) (deactivate-mark))
9127 (let ((agendap (equal major-mode 'org-agenda-mode))
9128 l1 l2 m buf pos newhead (cnt 0))
9129 (goto-char end)
9130 (setq l2 (1- (org-current-line)))
9131 (goto-char beg)
9132 (setq l1 (org-current-line))
9133 (loop for l from l1 to l2 do
9134 (goto-line l)
9135 (setq m (get-text-property (point) 'org-hd-marker))
9136 (when (or (and (org-mode-p) (org-on-heading-p))
9137 (and agendap m))
9138 (setq buf (if agendap (marker-buffer m) (current-buffer))
9139 pos (if agendap m (point)))
9140 (with-current-buffer buf
9141 (save-excursion
9142 (save-restriction
9143 (goto-char pos)
9144 (setq cnt (1+ cnt))
9145 (org-toggle-tag tag (if off 'off 'on))
9146 (setq newhead (org-get-heading)))))
9147 (and agendap (org-agenda-change-all-lines newhead m))))
9148 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9150 (defun org-tags-completion-function (string predicate &optional flag)
9151 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9152 (confirm (lambda (x) (stringp (car x)))))
9153 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9154 (setq s1 (match-string 1 string)
9155 s2 (match-string 2 string))
9156 (setq s1 "" s2 string))
9157 (cond
9158 ((eq flag nil)
9159 ;; try completion
9160 (setq rtn (try-completion s2 ctable confirm))
9161 (if (stringp rtn)
9162 (setq rtn
9163 (concat s1 s2 (substring rtn (length s2))
9164 (if (and org-add-colon-after-tag-completion
9165 (assoc rtn ctable))
9166 ":" ""))))
9167 rtn)
9168 ((eq flag t)
9169 ;; all-completions
9170 (all-completions s2 ctable confirm)
9172 ((eq flag 'lambda)
9173 ;; exact match?
9174 (assoc s2 ctable)))
9177 (defun org-fast-tag-insert (kwd tags face &optional end)
9178 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9179 (insert (format "%-12s" (concat kwd ":"))
9180 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9181 (or end "")))
9183 (defun org-fast-tag-show-exit (flag)
9184 (save-excursion
9185 (goto-line 3)
9186 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9187 (replace-match ""))
9188 (when flag
9189 (end-of-line 1)
9190 (org-move-to-column (- (window-width) 19) t)
9191 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9193 (defun org-set-current-tags-overlay (current prefix)
9194 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9195 (if (featurep 'xemacs)
9196 (org-overlay-display org-tags-overlay (concat prefix s)
9197 'secondary-selection)
9198 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9199 (org-overlay-display org-tags-overlay (concat prefix s)))))
9201 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9202 "Fast tag selection with single keys.
9203 CURRENT is the current list of tags in the headline, INHERITED is the
9204 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9205 possibly with grouping information. TODO-TABLE is a similar table with
9206 TODO keywords, should these have keys assigned to them.
9207 If the keys are nil, a-z are automatically assigned.
9208 Returns the new tags string, or nil to not change the current settings."
9209 (let* ((fulltable (append table todo-table))
9210 (maxlen (apply 'max (mapcar
9211 (lambda (x)
9212 (if (stringp (car x)) (string-width (car x)) 0))
9213 fulltable)))
9214 (buf (current-buffer))
9215 (expert (eq org-fast-tag-selection-single-key 'expert))
9216 (buffer-tags nil)
9217 (fwidth (+ maxlen 3 1 3))
9218 (ncol (/ (- (window-width) 4) fwidth))
9219 (i-face 'org-done)
9220 (c-face 'org-todo)
9221 tg cnt e c char c1 c2 ntable tbl rtn
9222 ov-start ov-end ov-prefix
9223 (exit-after-next org-fast-tag-selection-single-key)
9224 (done-keywords org-done-keywords)
9225 groups ingroup)
9226 (save-excursion
9227 (beginning-of-line 1)
9228 (if (looking-at
9229 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9230 (setq ov-start (match-beginning 1)
9231 ov-end (match-end 1)
9232 ov-prefix "")
9233 (setq ov-start (1- (point-at-eol))
9234 ov-end (1+ ov-start))
9235 (skip-chars-forward "^\n\r")
9236 (setq ov-prefix
9237 (concat
9238 (buffer-substring (1- (point)) (point))
9239 (if (> (current-column) org-tags-column)
9241 (make-string (- org-tags-column (current-column)) ?\ ))))))
9242 (org-move-overlay org-tags-overlay ov-start ov-end)
9243 (save-window-excursion
9244 (if expert
9245 (set-buffer (get-buffer-create " *Org tags*"))
9246 (delete-other-windows)
9247 (split-window-vertically)
9248 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9249 (erase-buffer)
9250 (org-set-local 'org-done-keywords done-keywords)
9251 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9252 (org-fast-tag-insert "Current" current c-face "\n\n")
9253 (org-fast-tag-show-exit exit-after-next)
9254 (org-set-current-tags-overlay current ov-prefix)
9255 (setq tbl fulltable char ?a cnt 0)
9256 (while (setq e (pop tbl))
9257 (cond
9258 ((equal e '(:startgroup))
9259 (push '() groups) (setq ingroup t)
9260 (when (not (= cnt 0))
9261 (setq cnt 0)
9262 (insert "\n"))
9263 (insert "{ "))
9264 ((equal e '(:endgroup))
9265 (setq ingroup nil cnt 0)
9266 (insert "}\n"))
9268 (setq tg (car e) c2 nil)
9269 (if (cdr e)
9270 (setq c (cdr e))
9271 ;; automatically assign a character.
9272 (setq c1 (string-to-char
9273 (downcase (substring
9274 tg (if (= (string-to-char tg) ?@) 1 0)))))
9275 (if (or (rassoc c1 ntable) (rassoc c1 table))
9276 (while (or (rassoc char ntable) (rassoc char table))
9277 (setq char (1+ char)))
9278 (setq c2 c1))
9279 (setq c (or c2 char)))
9280 (if ingroup (push tg (car groups)))
9281 (setq tg (org-add-props tg nil 'face
9282 (cond
9283 ((not (assoc tg table))
9284 (org-get-todo-face tg))
9285 ((member tg current) c-face)
9286 ((member tg inherited) i-face)
9287 (t nil))))
9288 (if (and (= cnt 0) (not ingroup)) (insert " "))
9289 (insert "[" c "] " tg (make-string
9290 (- fwidth 4 (length tg)) ?\ ))
9291 (push (cons tg c) ntable)
9292 (when (= (setq cnt (1+ cnt)) ncol)
9293 (insert "\n")
9294 (if ingroup (insert " "))
9295 (setq cnt 0)))))
9296 (setq ntable (nreverse ntable))
9297 (insert "\n")
9298 (goto-char (point-min))
9299 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9300 (fit-window-to-buffer))
9301 (setq rtn
9302 (catch 'exit
9303 (while t
9304 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9305 (if groups " [!] no groups" " [!]groups")
9306 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9307 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9308 (cond
9309 ((= c ?\r) (throw 'exit t))
9310 ((= c ?!)
9311 (setq groups (not groups))
9312 (goto-char (point-min))
9313 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9314 ((= c ?\C-c)
9315 (if (not expert)
9316 (org-fast-tag-show-exit
9317 (setq exit-after-next (not exit-after-next)))
9318 (setq expert nil)
9319 (delete-other-windows)
9320 (split-window-vertically)
9321 (org-switch-to-buffer-other-window " *Org tags*")
9322 (and (fboundp 'fit-window-to-buffer)
9323 (fit-window-to-buffer))))
9324 ((or (= c ?\C-g)
9325 (and (= c ?q) (not (rassoc c ntable))))
9326 (org-detach-overlay org-tags-overlay)
9327 (setq quit-flag t))
9328 ((= c ?\ )
9329 (setq current nil)
9330 (if exit-after-next (setq exit-after-next 'now)))
9331 ((= c ?\t)
9332 (condition-case nil
9333 (setq tg (completing-read
9334 "Tag: "
9335 (or buffer-tags
9336 (with-current-buffer buf
9337 (org-get-buffer-tags)))))
9338 (quit (setq tg "")))
9339 (when (string-match "\\S-" tg)
9340 (add-to-list 'buffer-tags (list tg))
9341 (if (member tg current)
9342 (setq current (delete tg current))
9343 (push tg current)))
9344 (if exit-after-next (setq exit-after-next 'now)))
9345 ((setq e (rassoc c todo-table) tg (car e))
9346 (with-current-buffer buf
9347 (save-excursion (org-todo tg)))
9348 (if exit-after-next (setq exit-after-next 'now)))
9349 ((setq e (rassoc c ntable) tg (car e))
9350 (if (member tg current)
9351 (setq current (delete tg current))
9352 (loop for g in groups do
9353 (if (member tg g)
9354 (mapc (lambda (x)
9355 (setq current (delete x current)))
9356 g)))
9357 (push tg current))
9358 (if exit-after-next (setq exit-after-next 'now))))
9360 ;; Create a sorted list
9361 (setq current
9362 (sort current
9363 (lambda (a b)
9364 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9365 (if (eq exit-after-next 'now) (throw 'exit t))
9366 (goto-char (point-min))
9367 (beginning-of-line 2)
9368 (delete-region (point) (point-at-eol))
9369 (org-fast-tag-insert "Current" current c-face)
9370 (org-set-current-tags-overlay current ov-prefix)
9371 (while (re-search-forward
9372 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9373 (setq tg (match-string 1))
9374 (add-text-properties
9375 (match-beginning 1) (match-end 1)
9376 (list 'face
9377 (cond
9378 ((member tg current) c-face)
9379 ((member tg inherited) i-face)
9380 (t (get-text-property (match-beginning 1) 'face))))))
9381 (goto-char (point-min)))))
9382 (org-detach-overlay org-tags-overlay)
9383 (if rtn
9384 (mapconcat 'identity current ":")
9385 nil))))
9387 (defun org-get-tags-string ()
9388 "Get the TAGS string in the current headline."
9389 (unless (org-on-heading-p t)
9390 (error "Not on a heading"))
9391 (save-excursion
9392 (beginning-of-line 1)
9393 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9394 (org-match-string-no-properties 1)
9395 "")))
9397 (defun org-get-tags ()
9398 "Get the list of tags specified in the current headline."
9399 (org-split-string (org-get-tags-string) ":"))
9401 (defun org-get-buffer-tags ()
9402 "Get a table of all tags used in the buffer, for completion."
9403 (let (tags)
9404 (save-excursion
9405 (goto-char (point-min))
9406 (while (re-search-forward
9407 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9408 (when (equal (char-after (point-at-bol 0)) ?*)
9409 (mapc (lambda (x) (add-to-list 'tags x))
9410 (org-split-string (org-match-string-no-properties 1) ":")))))
9411 (mapcar 'list tags)))
9414 ;;;; Properties
9416 ;;; Setting and retrieving properties
9418 (defconst org-special-properties
9419 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9420 "TIMESTAMP" "TIMESTAMP_IA")
9421 "The special properties valid in Org-mode.
9423 These are properties that are not defined in the property drawer,
9424 but in some other way.")
9426 (defconst org-default-properties
9427 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9428 "LOCATION" "LOGGING" "COLUMNS")
9429 "Some properties that are used by Org-mode for various purposes.
9430 Being in this list makes sure that they are offered for completion.")
9432 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9433 "Regular expression matching the first line of a property drawer.")
9435 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9436 "Regular expression matching the first line of a property drawer.")
9438 (defun org-property-action ()
9439 "Do an action on properties."
9440 (interactive)
9441 (let (c)
9442 (org-at-property-p)
9443 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9444 (setq c (read-char-exclusive))
9445 (cond
9446 ((equal c ?s)
9447 (call-interactively 'org-set-property))
9448 ((equal c ?d)
9449 (call-interactively 'org-delete-property))
9450 ((equal c ?D)
9451 (call-interactively 'org-delete-property-globally))
9452 ((equal c ?c)
9453 (call-interactively 'org-compute-property-at-point))
9454 (t (error "No such property action %c" c)))))
9456 (defun org-at-property-p ()
9457 "Is the cursor in a property line?"
9458 ;; FIXME: Does not check if we are actually in the drawer.
9459 ;; FIXME: also returns true on any drawers.....
9460 ;; This is used by C-c C-c for property action.
9461 (save-excursion
9462 (beginning-of-line 1)
9463 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9465 (defun org-get-property-block (&optional beg end force)
9466 "Return the (beg . end) range of the body of the property drawer.
9467 BEG and END can be beginning and end of subtree, if not given
9468 they will be found.
9469 If the drawer does not exist and FORCE is non-nil, create the drawer."
9470 (catch 'exit
9471 (save-excursion
9472 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9473 (end (or end (progn (outline-next-heading) (point)))))
9474 (goto-char beg)
9475 (if (re-search-forward org-property-start-re end t)
9476 (setq beg (1+ (match-end 0)))
9477 (if force
9478 (save-excursion
9479 (org-insert-property-drawer)
9480 (setq end (progn (outline-next-heading) (point))))
9481 (throw 'exit nil))
9482 (goto-char beg)
9483 (if (re-search-forward org-property-start-re end t)
9484 (setq beg (1+ (match-end 0)))))
9485 (if (re-search-forward org-property-end-re end t)
9486 (setq end (match-beginning 0))
9487 (or force (throw 'exit nil))
9488 (goto-char beg)
9489 (setq end beg)
9490 (org-indent-line-function)
9491 (insert ":END:\n"))
9492 (cons beg end)))))
9494 (defun org-entry-properties (&optional pom which)
9495 "Get all properties of the entry at point-or-marker POM.
9496 This includes the TODO keyword, the tags, time strings for deadline,
9497 scheduled, and clocking, and any additional properties defined in the
9498 entry. The return value is an alist, keys may occur multiple times
9499 if the property key was used several times.
9500 POM may also be nil, in which case the current entry is used.
9501 If WHICH is nil or `all', get all properties. If WHICH is
9502 `special' or `standard', only get that subclass."
9503 (setq which (or which 'all))
9504 (org-with-point-at pom
9505 (let ((clockstr (substring org-clock-string 0 -1))
9506 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9507 beg end range props sum-props key value string clocksum)
9508 (save-excursion
9509 (when (condition-case nil (org-back-to-heading t) (error nil))
9510 (setq beg (point))
9511 (setq sum-props (get-text-property (point) 'org-summaries))
9512 (setq clocksum (get-text-property (point) :org-clock-minutes))
9513 (outline-next-heading)
9514 (setq end (point))
9515 (when (memq which '(all special))
9516 ;; Get the special properties, like TODO and tags
9517 (goto-char beg)
9518 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9519 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9520 (when (looking-at org-priority-regexp)
9521 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9522 (when (and (setq value (org-get-tags-string))
9523 (string-match "\\S-" value))
9524 (push (cons "TAGS" value) props))
9525 (when (setq value (org-get-tags-at))
9526 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9527 props))
9528 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9529 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9530 string (if (equal key clockstr)
9531 (org-no-properties
9532 (org-trim
9533 (buffer-substring
9534 (match-beginning 3) (goto-char (point-at-eol)))))
9535 (substring (org-match-string-no-properties 3) 1 -1)))
9536 (unless key
9537 (if (= (char-after (match-beginning 3)) ?\[)
9538 (setq key "TIMESTAMP_IA")
9539 (setq key "TIMESTAMP")))
9540 (when (or (equal key clockstr) (not (assoc key props)))
9541 (push (cons key string) props)))
9545 (when (memq which '(all standard))
9546 ;; Get the standard properties, like :PORP: ...
9547 (setq range (org-get-property-block beg end))
9548 (when range
9549 (goto-char (car range))
9550 (while (re-search-forward
9551 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9552 (cdr range) t)
9553 (setq key (org-match-string-no-properties 1)
9554 value (org-trim (or (org-match-string-no-properties 2) "")))
9555 (unless (member key excluded)
9556 (push (cons key (or value "")) props)))))
9557 (if clocksum
9558 (push (cons "CLOCKSUM"
9559 (org-columns-number-to-string (/ (float clocksum) 60.)
9560 'add_times))
9561 props))
9562 (append sum-props (nreverse props)))))))
9564 (defun org-entry-get (pom property &optional inherit)
9565 "Get value of PROPERTY for entry at point-or-marker POM.
9566 If INHERIT is non-nil and the entry does not have the property,
9567 then also check higher levels of the hierarchy.
9568 If INHERIT is the symbol `selective', use inheritance only if the setting
9569 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9570 If the property is present but empty, the return value is the empty string.
9571 If the property is not present at all, nil is returned."
9572 (org-with-point-at pom
9573 (if (and inherit (if (eq inherit 'selective)
9574 (org-property-inherit-p property)
9576 (org-entry-get-with-inheritance property)
9577 (if (member property org-special-properties)
9578 ;; We need a special property. Use brute force, get all properties.
9579 (cdr (assoc property (org-entry-properties nil 'special)))
9580 (let ((range (org-get-property-block)))
9581 (if (and range
9582 (goto-char (car range))
9583 (re-search-forward
9584 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9585 (cdr range) t))
9586 ;; Found the property, return it.
9587 (if (match-end 1)
9588 (org-match-string-no-properties 1)
9589 "")))))))
9591 (defun org-property-or-variable-value (var &optional inherit)
9592 "Check if there is a property fixing the value of VAR.
9593 If yes, return this value. If not, return the current value of the variable."
9594 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9595 (if (and prop (stringp prop) (string-match "\\S-" prop))
9596 (read prop)
9597 (symbol-value var))))
9599 (defun org-entry-delete (pom property)
9600 "Delete the property PROPERTY from entry at point-or-marker POM."
9601 (org-with-point-at pom
9602 (if (member property org-special-properties)
9603 nil ; cannot delete these properties.
9604 (let ((range (org-get-property-block)))
9605 (if (and range
9606 (goto-char (car range))
9607 (re-search-forward
9608 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9609 (cdr range) t))
9610 (progn
9611 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9613 nil)))))
9615 ;; Multi-values properties are properties that contain multiple values
9616 ;; These values are assumed to be single words, separated by whitespace.
9617 (defun org-entry-add-to-multivalued-property (pom property value)
9618 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9619 (let* ((old (org-entry-get pom property))
9620 (values (and old (org-split-string old "[ \t]"))))
9621 (unless (member value values)
9622 (setq values (cons value values))
9623 (org-entry-put pom property
9624 (mapconcat 'identity values " ")))))
9626 (defun org-entry-remove-from-multivalued-property (pom property value)
9627 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9628 (let* ((old (org-entry-get pom property))
9629 (values (and old (org-split-string old "[ \t]"))))
9630 (when (member value values)
9631 (setq values (delete value values))
9632 (org-entry-put pom property
9633 (mapconcat 'identity values " ")))))
9635 (defun org-entry-member-in-multivalued-property (pom property value)
9636 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9637 (let* ((old (org-entry-get pom property))
9638 (values (and old (org-split-string old "[ \t]"))))
9639 (member value values)))
9641 (defvar org-entry-property-inherited-from (make-marker))
9643 (defun org-entry-get-with-inheritance (property)
9644 "Get entry property, and search higher levels if not present."
9645 (let (tmp)
9646 (save-excursion
9647 (save-restriction
9648 (widen)
9649 (catch 'ex
9650 (while t
9651 (when (setq tmp (org-entry-get nil property))
9652 (org-back-to-heading t)
9653 (move-marker org-entry-property-inherited-from (point))
9654 (throw 'ex tmp))
9655 (or (org-up-heading-safe) (throw 'ex nil)))))
9656 (or tmp (cdr (assoc property org-local-properties))
9657 (cdr (assoc property org-global-properties))))))
9659 (defun org-entry-put (pom property value)
9660 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9661 (org-with-point-at pom
9662 (org-back-to-heading t)
9663 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9664 range)
9665 (cond
9666 ((equal property "TODO")
9667 (when (and (stringp value) (string-match "\\S-" value)
9668 (not (member value org-todo-keywords-1)))
9669 (error "\"%s\" is not a valid TODO state" value))
9670 (if (or (not value)
9671 (not (string-match "\\S-" value)))
9672 (setq value 'none))
9673 (org-todo value)
9674 (org-set-tags nil 'align))
9675 ((equal property "PRIORITY")
9676 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9677 (string-to-char value) ?\ ))
9678 (org-set-tags nil 'align))
9679 ((equal property "SCHEDULED")
9680 (if (re-search-forward org-scheduled-time-regexp end t)
9681 (cond
9682 ((eq value 'earlier) (org-timestamp-change -1 'day))
9683 ((eq value 'later) (org-timestamp-change 1 'day))
9684 (t (call-interactively 'org-schedule)))
9685 (call-interactively 'org-schedule)))
9686 ((equal property "DEADLINE")
9687 (if (re-search-forward org-deadline-time-regexp end t)
9688 (cond
9689 ((eq value 'earlier) (org-timestamp-change -1 'day))
9690 ((eq value 'later) (org-timestamp-change 1 'day))
9691 (t (call-interactively 'org-deadline)))
9692 (call-interactively 'org-deadline)))
9693 ((member property org-special-properties)
9694 (error "The %s property can not yet be set with `org-entry-put'"
9695 property))
9696 (t ; a non-special property
9697 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9698 (setq range (org-get-property-block beg end 'force))
9699 (goto-char (car range))
9700 (if (re-search-forward
9701 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9702 (progn
9703 (delete-region (match-beginning 1) (match-end 1))
9704 (goto-char (match-beginning 1)))
9705 (goto-char (cdr range))
9706 (insert "\n")
9707 (backward-char 1)
9708 (org-indent-line-function)
9709 (insert ":" property ":"))
9710 (and value (insert " " value))
9711 (org-indent-line-function)))))))
9713 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9714 "Get all property keys in the current buffer.
9715 With INCLUDE-SPECIALS, also list the special properties that relect things
9716 like tags and TODO state.
9717 With INCLUDE-DEFAULTS, also include properties that has special meaning
9718 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9719 With INCLUDE-COLUMNS, also include property names given in COLUMN
9720 formats in the current buffer."
9721 (let (rtn range cfmt cols s p)
9722 (save-excursion
9723 (save-restriction
9724 (widen)
9725 (goto-char (point-min))
9726 (while (re-search-forward org-property-start-re nil t)
9727 (setq range (org-get-property-block))
9728 (goto-char (car range))
9729 (while (re-search-forward
9730 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9731 (cdr range) t)
9732 (add-to-list 'rtn (org-match-string-no-properties 1)))
9733 (outline-next-heading))))
9735 (when include-specials
9736 (setq rtn (append org-special-properties rtn)))
9738 (when include-defaults
9739 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9741 (when include-columns
9742 (save-excursion
9743 (save-restriction
9744 (widen)
9745 (goto-char (point-min))
9746 (while (re-search-forward
9747 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9748 nil t)
9749 (setq cfmt (match-string 2) s 0)
9750 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9751 cfmt s)
9752 (setq s (match-end 0)
9753 p (match-string 1 cfmt))
9754 (unless (or (equal p "ITEM")
9755 (member p org-special-properties))
9756 (add-to-list 'rtn (match-string 1 cfmt))))))))
9758 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9760 (defun org-property-values (key)
9761 "Return a list of all values of property KEY."
9762 (save-excursion
9763 (save-restriction
9764 (widen)
9765 (goto-char (point-min))
9766 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9767 values)
9768 (while (re-search-forward re nil t)
9769 (add-to-list 'values (org-trim (match-string 1))))
9770 (delete "" values)))))
9772 (defun org-insert-property-drawer ()
9773 "Insert a property drawer into the current entry."
9774 (interactive)
9775 (org-back-to-heading t)
9776 (looking-at outline-regexp)
9777 (let ((indent (- (match-end 0)(match-beginning 0)))
9778 (beg (point))
9779 (re (concat "^[ \t]*" org-keyword-time-regexp))
9780 end hiddenp)
9781 (outline-next-heading)
9782 (setq end (point))
9783 (goto-char beg)
9784 (while (re-search-forward re end t))
9785 (setq hiddenp (org-invisible-p))
9786 (end-of-line 1)
9787 (and (equal (char-after) ?\n) (forward-char 1))
9788 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9789 (beginning-of-line 2))
9790 (org-skip-over-state-notes)
9791 (skip-chars-backward " \t\n\r")
9792 (if (eq (char-before) ?*) (forward-char 1))
9793 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9794 (beginning-of-line 0)
9795 (org-indent-to-column indent)
9796 (beginning-of-line 2)
9797 (org-indent-to-column indent)
9798 (beginning-of-line 0)
9799 (if hiddenp
9800 (save-excursion
9801 (org-back-to-heading t)
9802 (hide-entry))
9803 (org-flag-drawer t))))
9805 (defun org-set-property (property value)
9806 "In the current entry, set PROPERTY to VALUE.
9807 When called interactively, this will prompt for a property name, offering
9808 completion on existing and default properties. And then it will prompt
9809 for a value, offering competion either on allowed values (via an inherited
9810 xxx_ALL property) or on existing values in other instances of this property
9811 in the current file."
9812 (interactive
9813 (let* ((completion-ignore-case t)
9814 (keys (org-buffer-property-keys nil t t))
9815 (prop0 (completing-read "Property: " (mapcar 'list keys)))
9816 (prop (if (member prop0 keys)
9817 prop0
9818 (or (cdr (assoc (downcase prop0)
9819 (mapcar (lambda (x) (cons (downcase x) x))
9820 keys)))
9821 prop0)))
9822 (cur (org-entry-get nil prop))
9823 (allowed (org-property-get-allowed-values nil prop 'table))
9824 (existing (mapcar 'list (org-property-values prop)))
9825 (val (if allowed
9826 (org-completing-read "Value: " allowed nil 'req-match)
9827 (org-completing-read
9828 (concat "Value" (if (and cur (string-match "\\S-" cur))
9829 (concat "[" cur "]") "")
9830 ": ")
9831 existing nil nil "" nil cur))))
9832 (list prop (if (equal val "") cur val))))
9833 (unless (equal (org-entry-get nil property) value)
9834 (org-entry-put nil property value)))
9836 (defun org-delete-property (property)
9837 "In the current entry, delete PROPERTY."
9838 (interactive
9839 (let* ((completion-ignore-case t)
9840 (prop (completing-read
9841 "Property: " (org-entry-properties nil 'standard))))
9842 (list prop)))
9843 (message "Property %s %s" property
9844 (if (org-entry-delete nil property)
9845 "deleted"
9846 "was not present in the entry")))
9848 (defun org-delete-property-globally (property)
9849 "Remove PROPERTY globally, from all entries."
9850 (interactive
9851 (let* ((completion-ignore-case t)
9852 (prop (completing-read
9853 "Globally remove property: "
9854 (mapcar 'list (org-buffer-property-keys)))))
9855 (list prop)))
9856 (save-excursion
9857 (save-restriction
9858 (widen)
9859 (goto-char (point-min))
9860 (let ((cnt 0))
9861 (while (re-search-forward
9862 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9863 nil t)
9864 (setq cnt (1+ cnt))
9865 (replace-match ""))
9866 (message "Property \"%s\" removed from %d entries" property cnt)))))
9868 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9870 (defun org-compute-property-at-point ()
9871 "Compute the property at point.
9872 This looks for an enclosing column format, extracts the operator and
9873 then applies it to the proerty in the column format's scope."
9874 (interactive)
9875 (unless (org-at-property-p)
9876 (error "Not at a property"))
9877 (let ((prop (org-match-string-no-properties 2)))
9878 (org-columns-get-format-and-top-level)
9879 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9880 (error "No operator defined for property %s" prop))
9881 (org-columns-compute prop)))
9883 (defun org-property-get-allowed-values (pom property &optional table)
9884 "Get allowed values for the property PROPERTY.
9885 When TABLE is non-nil, return an alist that can directly be used for
9886 completion."
9887 (let (vals)
9888 (cond
9889 ((equal property "TODO")
9890 (setq vals (org-with-point-at pom
9891 (append org-todo-keywords-1 '("")))))
9892 ((equal property "PRIORITY")
9893 (let ((n org-lowest-priority))
9894 (while (>= n org-highest-priority)
9895 (push (char-to-string n) vals)
9896 (setq n (1- n)))))
9897 ((member property org-special-properties))
9899 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9901 (when (and vals (string-match "\\S-" vals))
9902 (setq vals (car (read-from-string (concat "(" vals ")"))))
9903 (setq vals (mapcar (lambda (x)
9904 (cond ((stringp x) x)
9905 ((numberp x) (number-to-string x))
9906 ((symbolp x) (symbol-name x))
9907 (t "???")))
9908 vals)))))
9909 (if table (mapcar 'list vals) vals)))
9911 (defun org-property-previous-allowed-value (&optional previous)
9912 "Switch to the next allowed value for this property."
9913 (interactive)
9914 (org-property-next-allowed-value t))
9916 (defun org-property-next-allowed-value (&optional previous)
9917 "Switch to the next allowed value for this property."
9918 (interactive)
9919 (unless (org-at-property-p)
9920 (error "Not at a property"))
9921 (let* ((key (match-string 2))
9922 (value (match-string 3))
9923 (allowed (or (org-property-get-allowed-values (point) key)
9924 (and (member value '("[ ]" "[-]" "[X]"))
9925 '("[ ]" "[X]"))))
9926 nval)
9927 (unless allowed
9928 (error "Allowed values for this property have not been defined"))
9929 (if previous (setq allowed (reverse allowed)))
9930 (if (member value allowed)
9931 (setq nval (car (cdr (member value allowed)))))
9932 (setq nval (or nval (car allowed)))
9933 (if (equal nval value)
9934 (error "Only one allowed value for this property"))
9935 (org-at-property-p)
9936 (replace-match (concat " :" key ": " nval) t t)
9937 (org-indent-line-function)
9938 (beginning-of-line 1)
9939 (skip-chars-forward " \t")))
9941 (defun org-find-entry-with-id (ident)
9942 "Locate the entry that contains the ID property with exact value IDENT.
9943 IDENT can be a string, a symbol or a number, this function will search for
9944 the string representation of it.
9945 Return the position where this entry starts, or nil if there is no such entry."
9946 (let ((id (cond
9947 ((stringp ident) ident)
9948 ((symbol-name ident) (symbol-name ident))
9949 ((numberp ident) (number-to-string ident))
9950 (t (error "IDENT %s must be a string, symbol or number" ident))))
9951 (case-fold-search nil))
9952 (save-excursion
9953 (save-restriction
9954 (widen)
9955 (goto-char (point-min))
9956 (when (re-search-forward
9957 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9958 nil t)
9959 (org-back-to-heading)
9960 (point))))))
9962 ;;;; Timestamps
9964 (defvar org-last-changed-timestamp nil)
9965 (defvar org-time-was-given) ; dynamically scoped parameter
9966 (defvar org-end-time-was-given) ; dynamically scoped parameter
9967 (defvar org-ts-what) ; dynamically scoped parameter
9969 (defun org-time-stamp (arg)
9970 "Prompt for a date/time and insert a time stamp.
9971 If the user specifies a time like HH:MM, or if this command is called
9972 with a prefix argument, the time stamp will contain date and time.
9973 Otherwise, only the date will be included. All parts of a date not
9974 specified by the user will be filled in from the current date/time.
9975 So if you press just return without typing anything, the time stamp
9976 will represent the current date/time. If there is already a timestamp
9977 at the cursor, it will be modified."
9978 (interactive "P")
9979 (let* ((ts nil)
9980 (default-time
9981 ;; Default time is either today, or, when entering a range,
9982 ;; the range start.
9983 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9984 (save-excursion
9985 (re-search-backward
9986 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9987 (- (point) 20) t)))
9988 (apply 'encode-time (org-parse-time-string (match-string 1)))
9989 (current-time)))
9990 (default-input (and ts (org-get-compact-tod ts)))
9991 org-time-was-given org-end-time-was-given time)
9992 (cond
9993 ((and (org-at-timestamp-p)
9994 (eq last-command 'org-time-stamp)
9995 (eq this-command 'org-time-stamp))
9996 (insert "--")
9997 (setq time (let ((this-command this-command))
9998 (org-read-date arg 'totime nil nil default-time default-input)))
9999 (org-insert-time-stamp time (or org-time-was-given arg)))
10000 ((org-at-timestamp-p)
10001 (setq time (let ((this-command this-command))
10002 (org-read-date arg 'totime nil nil default-time default-input)))
10003 (when (org-at-timestamp-p) ; just to get the match data
10004 (replace-match "")
10005 (setq org-last-changed-timestamp
10006 (org-insert-time-stamp
10007 time (or org-time-was-given arg)
10008 nil nil nil (list org-end-time-was-given))))
10009 (message "Timestamp updated"))
10011 (setq time (let ((this-command this-command))
10012 (org-read-date arg 'totime nil nil default-time default-input)))
10013 (org-insert-time-stamp time (or org-time-was-given arg)
10014 nil nil nil (list org-end-time-was-given))))))
10016 ;; FIXME: can we use this for something else, like computing time differences?
10017 (defun org-get-compact-tod (s)
10018 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10019 (let* ((t1 (match-string 1 s))
10020 (h1 (string-to-number (match-string 2 s)))
10021 (m1 (string-to-number (match-string 3 s)))
10022 (t2 (and (match-end 4) (match-string 5 s)))
10023 (h2 (and t2 (string-to-number (match-string 6 s))))
10024 (m2 (and t2 (string-to-number (match-string 7 s))))
10025 dh dm)
10026 (if (not t2)
10028 (setq dh (- h2 h1) dm (- m2 m1))
10029 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10030 (concat t1 "+" (number-to-string dh)
10031 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10033 (defun org-time-stamp-inactive (&optional arg)
10034 "Insert an inactive time stamp.
10035 An inactive time stamp is enclosed in square brackets instead of angle
10036 brackets. It is inactive in the sense that it does not trigger agenda entries,
10037 does not link to the calendar and cannot be changed with the S-cursor keys.
10038 So these are more for recording a certain time/date."
10039 (interactive "P")
10040 (let (org-time-was-given org-end-time-was-given time)
10041 (setq time (org-read-date arg 'totime))
10042 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10043 nil nil (list org-end-time-was-given))))
10045 (defvar org-date-ovl (org-make-overlay 1 1))
10046 (org-overlay-put org-date-ovl 'face 'org-warning)
10047 (org-detach-overlay org-date-ovl)
10049 (defvar org-ans1) ; dynamically scoped parameter
10050 (defvar org-ans2) ; dynamically scoped parameter
10052 (defvar org-plain-time-of-day-regexp) ; defined below
10054 (defvar org-read-date-overlay nil)
10055 (defvar org-dcst nil) ; dynamically scoped
10057 (defun org-read-date (&optional with-time to-time from-string prompt
10058 default-time default-input)
10059 "Read a date, possibly a time, and make things smooth for the user.
10060 The prompt will suggest to enter an ISO date, but you can also enter anything
10061 which will at least partially be understood by `parse-time-string'.
10062 Unrecognized parts of the date will default to the current day, month, year,
10063 hour and minute. If this command is called to replace a timestamp at point,
10064 of to enter the second timestamp of a range, the default time is taken from the
10065 existing stamp. For example,
10066 3-2-5 --> 2003-02-05
10067 feb 15 --> currentyear-02-15
10068 sep 12 9 --> 2009-09-12
10069 12:45 --> today 12:45
10070 22 sept 0:34 --> currentyear-09-22 0:34
10071 12 --> currentyear-currentmonth-12
10072 Fri --> nearest Friday (today or later)
10073 etc.
10075 Furthermore you can specify a relative date by giving, as the *first* thing
10076 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10077 change in days weeks, months, years.
10078 With a single plus or minus, the date is relative to today. With a double
10079 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10080 +4d --> four days from today
10081 +4 --> same as above
10082 +2w --> two weeks from today
10083 ++5 --> five days from default date
10085 The function understands only English month and weekday abbreviations,
10086 but this can be configured with the variables `parse-time-months' and
10087 `parse-time-weekdays'.
10089 While prompting, a calendar is popped up - you can also select the
10090 date with the mouse (button 1). The calendar shows a period of three
10091 months. To scroll it to other months, use the keys `>' and `<'.
10092 If you don't like the calendar, turn it off with
10093 \(setq org-read-date-popup-calendar nil)
10095 With optional argument TO-TIME, the date will immediately be converted
10096 to an internal time.
10097 With an optional argument WITH-TIME, the prompt will suggest to also
10098 insert a time. Note that when WITH-TIME is not set, you can still
10099 enter a time, and this function will inform the calling routine about
10100 this change. The calling routine may then choose to change the format
10101 used to insert the time stamp into the buffer to include the time.
10102 With optional argument FROM-STRING, read from this string instead from
10103 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10104 the time/date that is used for everything that is not specified by the
10105 user."
10106 (require 'parse-time)
10107 (let* ((org-time-stamp-rounding-minutes
10108 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10109 (org-dcst org-display-custom-times)
10110 (ct (org-current-time))
10111 (def (or default-time ct))
10112 (defdecode (decode-time def))
10113 (dummy (progn
10114 (when (< (nth 2 defdecode) org-extend-today-until)
10115 (setcar (nthcdr 2 defdecode) -1)
10116 (setcar (nthcdr 1 defdecode) 59)
10117 (setq def (apply 'encode-time defdecode)
10118 defdecode (decode-time def)))))
10119 (calendar-move-hook nil)
10120 (calendar-view-diary-initially-flag nil)
10121 (view-diary-entries-initially nil)
10122 (calendar-view-holidays-initially-flag nil)
10123 (view-calendar-holidays-initially nil)
10124 (timestr (format-time-string
10125 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10126 (prompt (concat (if prompt (concat prompt " ") "")
10127 (format "Date+time [%s]: " timestr)))
10128 ans (org-ans0 "") org-ans1 org-ans2 final)
10130 (cond
10131 (from-string (setq ans from-string))
10132 (org-read-date-popup-calendar
10133 (save-excursion
10134 (save-window-excursion
10135 (calendar)
10136 (calendar-forward-day (- (time-to-days def)
10137 (calendar-absolute-from-gregorian
10138 (calendar-current-date))))
10139 (org-eval-in-calendar nil t)
10140 (let* ((old-map (current-local-map))
10141 (map (copy-keymap calendar-mode-map))
10142 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10143 (org-defkey map (kbd "RET") 'org-calendar-select)
10144 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10145 'org-calendar-select-mouse)
10146 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10147 'org-calendar-select-mouse)
10148 (org-defkey minibuffer-local-map [(meta shift left)]
10149 (lambda () (interactive)
10150 (org-eval-in-calendar '(calendar-backward-month 1))))
10151 (org-defkey minibuffer-local-map [(meta shift right)]
10152 (lambda () (interactive)
10153 (org-eval-in-calendar '(calendar-forward-month 1))))
10154 (org-defkey minibuffer-local-map [(meta shift up)]
10155 (lambda () (interactive)
10156 (org-eval-in-calendar '(calendar-backward-year 1))))
10157 (org-defkey minibuffer-local-map [(meta shift down)]
10158 (lambda () (interactive)
10159 (org-eval-in-calendar '(calendar-forward-year 1))))
10160 (org-defkey minibuffer-local-map [(shift up)]
10161 (lambda () (interactive)
10162 (org-eval-in-calendar '(calendar-backward-week 1))))
10163 (org-defkey minibuffer-local-map [(shift down)]
10164 (lambda () (interactive)
10165 (org-eval-in-calendar '(calendar-forward-week 1))))
10166 (org-defkey minibuffer-local-map [(shift left)]
10167 (lambda () (interactive)
10168 (org-eval-in-calendar '(calendar-backward-day 1))))
10169 (org-defkey minibuffer-local-map [(shift right)]
10170 (lambda () (interactive)
10171 (org-eval-in-calendar '(calendar-forward-day 1))))
10172 (org-defkey minibuffer-local-map ">"
10173 (lambda () (interactive)
10174 (org-eval-in-calendar '(scroll-calendar-left 1))))
10175 (org-defkey minibuffer-local-map "<"
10176 (lambda () (interactive)
10177 (org-eval-in-calendar '(scroll-calendar-right 1))))
10178 (unwind-protect
10179 (progn
10180 (use-local-map map)
10181 (add-hook 'post-command-hook 'org-read-date-display)
10182 (setq org-ans0 (read-string prompt default-input nil nil))
10183 ;; org-ans0: from prompt
10184 ;; org-ans1: from mouse click
10185 ;; org-ans2: from calendar motion
10186 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10187 (remove-hook 'post-command-hook 'org-read-date-display)
10188 (use-local-map old-map)
10189 (when org-read-date-overlay
10190 (org-delete-overlay org-read-date-overlay)
10191 (setq org-read-date-overlay nil)))))))
10193 (t ; Naked prompt only
10194 (unwind-protect
10195 (setq ans (read-string prompt default-input nil timestr))
10196 (when org-read-date-overlay
10197 (org-delete-overlay org-read-date-overlay)
10198 (setq org-read-date-overlay nil)))))
10200 (setq final (org-read-date-analyze ans def defdecode))
10202 (if to-time
10203 (apply 'encode-time final)
10204 (if (and (boundp 'org-time-was-given) org-time-was-given)
10205 (format "%04d-%02d-%02d %02d:%02d"
10206 (nth 5 final) (nth 4 final) (nth 3 final)
10207 (nth 2 final) (nth 1 final))
10208 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10209 (defvar def)
10210 (defvar defdecode)
10211 (defvar with-time)
10212 (defun org-read-date-display ()
10213 "Display the currrent date prompt interpretation in the minibuffer."
10214 (when org-read-date-display-live
10215 (when org-read-date-overlay
10216 (org-delete-overlay org-read-date-overlay))
10217 (let ((p (point)))
10218 (end-of-line 1)
10219 (while (not (equal (buffer-substring
10220 (max (point-min) (- (point) 4)) (point))
10221 " "))
10222 (insert " "))
10223 (goto-char p))
10224 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10225 " " (or org-ans1 org-ans2)))
10226 (org-end-time-was-given nil)
10227 (f (org-read-date-analyze ans def defdecode))
10228 (fmts (if org-dcst
10229 org-time-stamp-custom-formats
10230 org-time-stamp-formats))
10231 (fmt (if (or with-time
10232 (and (boundp 'org-time-was-given) org-time-was-given))
10233 (cdr fmts)
10234 (car fmts)))
10235 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10236 (when (and org-end-time-was-given
10237 (string-match org-plain-time-of-day-regexp txt))
10238 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10239 org-end-time-was-given
10240 (substring txt (match-end 0)))))
10241 (setq org-read-date-overlay
10242 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10243 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10245 (defun org-read-date-analyze (ans def defdecode)
10246 "Analyze the combined answer of the date prompt."
10247 ;; FIXME: cleanup and comment
10248 (let (delta deltan deltaw deltadef year month day
10249 hour minute second wday pm h2 m2 tl wday1
10250 iso-year iso-weekday iso-week iso-year iso-date)
10252 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10253 (setq ans "+0"))
10255 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10256 (setq ans (replace-match "" t t ans)
10257 deltan (car delta)
10258 deltaw (nth 1 delta)
10259 deltadef (nth 2 delta)))
10261 ;; Check if there is an iso week date in there
10262 ;; If yes, sore the info and ostpone interpreting it until the rest
10263 ;; of the parsing is done
10264 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10265 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10266 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10267 iso-week (string-to-number (match-string 2 ans)))
10268 (setq ans (replace-match "" t t ans)))
10270 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10271 (when (string-match
10272 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10273 (setq year (if (match-end 2)
10274 (string-to-number (match-string 2 ans))
10275 (string-to-number (format-time-string "%Y")))
10276 month (string-to-number (match-string 3 ans))
10277 day (string-to-number (match-string 4 ans)))
10278 (if (< year 100) (setq year (+ 2000 year)))
10279 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10280 t nil ans)))
10281 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10282 ;; If there is a time with am/pm, and *no* time without it, we convert
10283 ;; so that matching will be successful.
10284 (loop for i from 1 to 2 do ; twice, for end time as well
10285 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10286 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10287 (setq hour (string-to-number (match-string 1 ans))
10288 minute (if (match-end 3)
10289 (string-to-number (match-string 3 ans))
10291 pm (equal ?p
10292 (string-to-char (downcase (match-string 4 ans)))))
10293 (if (and (= hour 12) (not pm))
10294 (setq hour 0)
10295 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10296 (setq ans (replace-match (format "%02d:%02d" hour minute)
10297 t t ans))))
10299 ;; Check if a time range is given as a duration
10300 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10301 (setq hour (string-to-number (match-string 1 ans))
10302 h2 (+ hour (string-to-number (match-string 3 ans)))
10303 minute (string-to-number (match-string 2 ans))
10304 m2 (+ minute (if (match-end 5) (string-to-number
10305 (match-string 5 ans))0)))
10306 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10307 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10308 t t ans)))
10310 ;; Check if there is a time range
10311 (when (boundp 'org-end-time-was-given)
10312 (setq org-time-was-given nil)
10313 (when (and (string-match org-plain-time-of-day-regexp ans)
10314 (match-end 8))
10315 (setq org-end-time-was-given (match-string 8 ans))
10316 (setq ans (concat (substring ans 0 (match-beginning 7))
10317 (substring ans (match-end 7))))))
10319 (setq tl (parse-time-string ans)
10320 day (or (nth 3 tl) (nth 3 defdecode))
10321 month (or (nth 4 tl)
10322 (if (and org-read-date-prefer-future
10323 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10324 (1+ (nth 4 defdecode))
10325 (nth 4 defdecode)))
10326 year (or (nth 5 tl)
10327 (if (and org-read-date-prefer-future
10328 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10329 (1+ (nth 5 defdecode))
10330 (nth 5 defdecode)))
10331 hour (or (nth 2 tl) (nth 2 defdecode))
10332 minute (or (nth 1 tl) (nth 1 defdecode))
10333 second (or (nth 0 tl) 0)
10334 wday (nth 6 tl))
10336 ;; Special date definitions below
10337 (cond
10338 (iso-week
10339 ;; There was an iso week
10340 (setq year (or iso-year year)
10341 day (or iso-weekday wday 1)
10342 wday nil ; to make sure that the trigger below does not match
10343 iso-date (calendar-gregorian-from-absolute
10344 (calendar-absolute-from-iso
10345 (list iso-week day year))))
10346 ; FIXME: Should we also push ISO weeks into the future?
10347 ; (when (and org-read-date-prefer-future
10348 ; (not iso-year)
10349 ; (< (calendar-absolute-from-gregorian iso-date)
10350 ; (time-to-days (current-time))))
10351 ; (setq year (1+ year)
10352 ; iso-date (calendar-gregorian-from-absolute
10353 ; (calendar-absolute-from-iso
10354 ; (list iso-week day year)))))
10355 (setq month (car iso-date)
10356 year (nth 2 iso-date)
10357 day (nth 1 iso-date)))
10358 (deltan
10359 (unless deltadef
10360 (let ((now (decode-time (current-time))))
10361 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10362 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10363 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10364 ((equal deltaw "m") (setq month (+ month deltan)))
10365 ((equal deltaw "y") (setq year (+ year deltan)))))
10366 ((and wday (not (nth 3 tl)))
10367 ;; Weekday was given, but no day, so pick that day in the week
10368 ;; on or after the derived date.
10369 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10370 (unless (equal wday wday1)
10371 (setq day (+ day (% (- wday wday1 -7) 7))))))
10372 (if (and (boundp 'org-time-was-given)
10373 (nth 2 tl))
10374 (setq org-time-was-given t))
10375 (if (< year 100) (setq year (+ 2000 year)))
10376 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10377 (list second minute hour day month year)))
10379 (defvar parse-time-weekdays)
10381 (defun org-read-date-get-relative (s today default)
10382 "Check string S for special relative date string.
10383 TODAY and DEFAULT are internal times, for today and for a default.
10384 Return shift list (N what def-flag)
10385 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10386 N is the number of WHATs to shift.
10387 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10388 the DEFAULT date rather than TODAY."
10389 (when (and
10390 (string-match
10391 (concat
10392 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10393 "\\([0-9]+\\)?"
10394 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10395 "\\([ \t]\\|$\\)") s)
10396 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10397 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10398 (string-to-char (substring (match-string 1 s) -1))
10399 ?+))
10400 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10401 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10402 (what (if (match-end 3) (match-string 3 s) "d"))
10403 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10404 (date (if rel default today))
10405 (wday (nth 6 (decode-time date)))
10406 delta)
10407 (if wday1
10408 (progn
10409 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10410 (if (= dir ?-) (setq delta (- delta 7)))
10411 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10412 (list delta "d" rel))
10413 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10415 (defun org-eval-in-calendar (form &optional keepdate)
10416 "Eval FORM in the calendar window and return to current window.
10417 Also, store the cursor date in variable org-ans2."
10418 (let ((sw (selected-window)))
10419 (select-window (get-buffer-window "*Calendar*"))
10420 (eval form)
10421 (when (and (not keepdate) (calendar-cursor-to-date))
10422 (let* ((date (calendar-cursor-to-date))
10423 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10424 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10425 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10426 (select-window sw)))
10428 ; ;; Update the prompt to show new default date
10429 ; (save-excursion
10430 ; (goto-char (point-min))
10431 ; (when (and org-ans2
10432 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10433 ; (get-text-property (match-end 0) 'field))
10434 ; (let ((inhibit-read-only t))
10435 ; (replace-match (concat "[" org-ans2 "]") t t)
10436 ; (add-text-properties (point-min) (1+ (match-end 0))
10437 ; (text-properties-at (1+ (point-min)))))))))
10439 (defun org-calendar-select ()
10440 "Return to `org-read-date' with the date currently selected.
10441 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10442 (interactive)
10443 (when (calendar-cursor-to-date)
10444 (let* ((date (calendar-cursor-to-date))
10445 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10446 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10447 (if (active-minibuffer-window) (exit-minibuffer))))
10449 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10450 "Insert a date stamp for the date given by the internal TIME.
10451 WITH-HM means, use the stamp format that includes the time of the day.
10452 INACTIVE means use square brackets instead of angular ones, so that the
10453 stamp will not contribute to the agenda.
10454 PRE and POST are optional strings to be inserted before and after the
10455 stamp.
10456 The command returns the inserted time stamp."
10457 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10458 stamp)
10459 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10460 (insert-before-markers (or pre ""))
10461 (insert-before-markers (setq stamp (format-time-string fmt time)))
10462 (when (listp extra)
10463 (setq extra (car extra))
10464 (if (and (stringp extra)
10465 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10466 (setq extra (format "-%02d:%02d"
10467 (string-to-number (match-string 1 extra))
10468 (string-to-number (match-string 2 extra))))
10469 (setq extra nil)))
10470 (when extra
10471 (backward-char 1)
10472 (insert-before-markers extra)
10473 (forward-char 1))
10474 (insert-before-markers (or post ""))
10475 stamp))
10477 (defun org-toggle-time-stamp-overlays ()
10478 "Toggle the use of custom time stamp formats."
10479 (interactive)
10480 (setq org-display-custom-times (not org-display-custom-times))
10481 (unless org-display-custom-times
10482 (let ((p (point-min)) (bmp (buffer-modified-p)))
10483 (while (setq p (next-single-property-change p 'display))
10484 (if (and (get-text-property p 'display)
10485 (eq (get-text-property p 'face) 'org-date))
10486 (remove-text-properties
10487 p (setq p (next-single-property-change p 'display))
10488 '(display t))))
10489 (set-buffer-modified-p bmp)))
10490 (if (featurep 'xemacs)
10491 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10492 (org-restart-font-lock)
10493 (setq org-table-may-need-update t)
10494 (if org-display-custom-times
10495 (message "Time stamps are overlayed with custom format")
10496 (message "Time stamp overlays removed")))
10498 (defun org-display-custom-time (beg end)
10499 "Overlay modified time stamp format over timestamp between BEG and END."
10500 (let* ((ts (buffer-substring beg end))
10501 t1 w1 with-hm tf time str w2 (off 0))
10502 (save-match-data
10503 (setq t1 (org-parse-time-string ts t))
10504 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10505 (setq off (- (match-end 0) (match-beginning 0)))))
10506 (setq end (- end off))
10507 (setq w1 (- end beg)
10508 with-hm (and (nth 1 t1) (nth 2 t1))
10509 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10510 time (org-fix-decoded-time t1)
10511 str (org-add-props
10512 (format-time-string
10513 (substring tf 1 -1) (apply 'encode-time time))
10514 nil 'mouse-face 'highlight)
10515 w2 (length str))
10516 (if (not (= w2 w1))
10517 (add-text-properties (1+ beg) (+ 2 beg)
10518 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10519 (if (featurep 'xemacs)
10520 (progn
10521 (put-text-property beg end 'invisible t)
10522 (put-text-property beg end 'end-glyph (make-glyph str)))
10523 (put-text-property beg end 'display str))))
10525 (defun org-translate-time (string)
10526 "Translate all timestamps in STRING to custom format.
10527 But do this only if the variable `org-display-custom-times' is set."
10528 (when org-display-custom-times
10529 (save-match-data
10530 (let* ((start 0)
10531 (re org-ts-regexp-both)
10532 t1 with-hm inactive tf time str beg end)
10533 (while (setq start (string-match re string start))
10534 (setq beg (match-beginning 0)
10535 end (match-end 0)
10536 t1 (save-match-data
10537 (org-parse-time-string (substring string beg end) t))
10538 with-hm (and (nth 1 t1) (nth 2 t1))
10539 inactive (equal (substring string beg (1+ beg)) "[")
10540 tf (funcall (if with-hm 'cdr 'car)
10541 org-time-stamp-custom-formats)
10542 time (org-fix-decoded-time t1)
10543 str (format-time-string
10544 (concat
10545 (if inactive "[" "<") (substring tf 1 -1)
10546 (if inactive "]" ">"))
10547 (apply 'encode-time time))
10548 string (replace-match str t t string)
10549 start (+ start (length str)))))))
10550 string)
10552 (defun org-fix-decoded-time (time)
10553 "Set 0 instead of nil for the first 6 elements of time.
10554 Don't touch the rest."
10555 (let ((n 0))
10556 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10558 (defun org-days-to-time (timestamp-string)
10559 "Difference between TIMESTAMP-STRING and now in days."
10560 (- (time-to-days (org-time-string-to-time timestamp-string))
10561 (time-to-days (current-time))))
10563 (defun org-deadline-close (timestamp-string &optional ndays)
10564 "Is the time in TIMESTAMP-STRING close to the current date?"
10565 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10566 (and (< (org-days-to-time timestamp-string) ndays)
10567 (not (org-entry-is-done-p))))
10569 (defun org-get-wdays (ts)
10570 "Get the deadline lead time appropriate for timestring TS."
10571 (cond
10572 ((<= org-deadline-warning-days 0)
10573 ;; 0 or negative, enforce this value no matter what
10574 (- org-deadline-warning-days))
10575 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10576 ;; lead time is specified.
10577 (floor (* (string-to-number (match-string 1 ts))
10578 (cdr (assoc (match-string 2 ts)
10579 '(("d" . 1) ("w" . 7)
10580 ("m" . 30.4) ("y" . 365.25)))))))
10581 ;; go for the default.
10582 (t org-deadline-warning-days)))
10584 (defun org-calendar-select-mouse (ev)
10585 "Return to `org-read-date' with the date currently selected.
10586 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10587 (interactive "e")
10588 (mouse-set-point ev)
10589 (when (calendar-cursor-to-date)
10590 (let* ((date (calendar-cursor-to-date))
10591 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10592 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10593 (if (active-minibuffer-window) (exit-minibuffer))))
10595 (defun org-check-deadlines (ndays)
10596 "Check if there are any deadlines due or past due.
10597 A deadline is considered due if it happens within `org-deadline-warning-days'
10598 days from today's date. If the deadline appears in an entry marked DONE,
10599 it is not shown. The prefix arg NDAYS can be used to test that many
10600 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10601 (interactive "P")
10602 (let* ((org-warn-days
10603 (cond
10604 ((equal ndays '(4)) 100000)
10605 (ndays (prefix-numeric-value ndays))
10606 (t (abs org-deadline-warning-days))))
10607 (case-fold-search nil)
10608 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10609 (callback
10610 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10612 (message "%d deadlines past-due or due within %d days"
10613 (org-occur regexp nil callback)
10614 org-warn-days)))
10616 (defun org-check-before-date (date)
10617 "Check if there are deadlines or scheduled entries before DATE."
10618 (interactive (list (org-read-date)))
10619 (let ((case-fold-search nil)
10620 (regexp (concat "\\<\\(" org-deadline-string
10621 "\\|" org-scheduled-string
10622 "\\) *<\\([^>]+\\)>"))
10623 (callback
10624 (lambda () (time-less-p
10625 (org-time-string-to-time (match-string 2))
10626 (org-time-string-to-time date)))))
10627 (message "%d entries before %s"
10628 (org-occur regexp nil callback) date)))
10630 (defun org-evaluate-time-range (&optional to-buffer)
10631 "Evaluate a time range by computing the difference between start and end.
10632 Normally the result is just printed in the echo area, but with prefix arg
10633 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10634 If the time range is actually in a table, the result is inserted into the
10635 next column.
10636 For time difference computation, a year is assumed to be exactly 365
10637 days in order to avoid rounding problems."
10638 (interactive "P")
10640 (org-clock-update-time-maybe)
10641 (save-excursion
10642 (unless (org-at-date-range-p t)
10643 (goto-char (point-at-bol))
10644 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10645 (if (not (org-at-date-range-p t))
10646 (error "Not at a time-stamp range, and none found in current line")))
10647 (let* ((ts1 (match-string 1))
10648 (ts2 (match-string 2))
10649 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10650 (match-end (match-end 0))
10651 (time1 (org-time-string-to-time ts1))
10652 (time2 (org-time-string-to-time ts2))
10653 (t1 (time-to-seconds time1))
10654 (t2 (time-to-seconds time2))
10655 (diff (abs (- t2 t1)))
10656 (negative (< (- t2 t1) 0))
10657 ;; (ys (floor (* 365 24 60 60)))
10658 (ds (* 24 60 60))
10659 (hs (* 60 60))
10660 (fy "%dy %dd %02d:%02d")
10661 (fy1 "%dy %dd")
10662 (fd "%dd %02d:%02d")
10663 (fd1 "%dd")
10664 (fh "%02d:%02d")
10665 y d h m align)
10666 (if havetime
10667 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10669 d (floor (/ diff ds)) diff (mod diff ds)
10670 h (floor (/ diff hs)) diff (mod diff hs)
10671 m (floor (/ diff 60)))
10672 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10674 d (floor (+ (/ diff ds) 0.5))
10675 h 0 m 0))
10676 (if (not to-buffer)
10677 (message "%s" (org-make-tdiff-string y d h m))
10678 (if (org-at-table-p)
10679 (progn
10680 (goto-char match-end)
10681 (setq align t)
10682 (and (looking-at " *|") (goto-char (match-end 0))))
10683 (goto-char match-end))
10684 (if (looking-at
10685 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10686 (replace-match ""))
10687 (if negative (insert " -"))
10688 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10689 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10690 (insert " " (format fh h m))))
10691 (if align (org-table-align))
10692 (message "Time difference inserted")))))
10694 (defun org-make-tdiff-string (y d h m)
10695 (let ((fmt "")
10696 (l nil))
10697 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10698 l (push y l)))
10699 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10700 l (push d l)))
10701 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10702 l (push h l)))
10703 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10704 l (push m l)))
10705 (apply 'format fmt (nreverse l))))
10707 (defun org-time-string-to-time (s)
10708 (apply 'encode-time (org-parse-time-string s)))
10710 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10711 "Convert a time stamp to an absolute day number.
10712 If there is a specifyer for a cyclic time stamp, get the closest date to
10713 DAYNR.
10714 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10715 (cond
10716 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10717 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10718 daynr
10719 (+ daynr 1000)))
10720 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10721 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10722 (time-to-days (current-time))) (match-string 0 s)
10723 prefer show-all))
10724 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10726 (defun org-days-to-iso-week (days)
10727 "Return the iso week number."
10728 (require 'cal-iso)
10729 (car (calendar-iso-from-absolute days)))
10731 (defun org-small-year-to-year (year)
10732 "Convert 2-digit years into 4-digit years.
10733 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10734 The year 2000 cannot be abbreviated. Any year lager than 99
10735 is retrned unchanged."
10736 (if (< year 38)
10737 (setq year (+ 2000 year))
10738 (if (< year 100)
10739 (setq year (+ 1900 year))))
10740 year)
10742 (defun org-time-from-absolute (d)
10743 "Return the time corresponding to date D.
10744 D may be an absolute day number, or a calendar-type list (month day year)."
10745 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10746 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10748 (defun org-calendar-holiday ()
10749 "List of holidays, for Diary display in Org-mode."
10750 (require 'holidays)
10751 (let ((hl (funcall
10752 (if (fboundp 'calendar-check-holidays)
10753 'calendar-check-holidays 'check-calendar-holidays) date)))
10754 (if hl (mapconcat 'identity hl "; "))))
10756 (defun org-diary-sexp-entry (sexp entry date)
10757 "Process a SEXP diary ENTRY for DATE."
10758 (require 'diary-lib)
10759 (let ((result (if calendar-debug-sexp
10760 (let ((stack-trace-on-error t))
10761 (eval (car (read-from-string sexp))))
10762 (condition-case nil
10763 (eval (car (read-from-string sexp)))
10764 (error
10765 (beep)
10766 (message "Bad sexp at line %d in %s: %s"
10767 (org-current-line)
10768 (buffer-file-name) sexp)
10769 (sleep-for 2))))))
10770 (cond ((stringp result) result)
10771 ((and (consp result)
10772 (stringp (cdr result))) (cdr result))
10773 (result entry)
10774 (t nil))))
10776 (defun org-diary-to-ical-string (frombuf)
10777 "Get iCalendar entries from diary entries in buffer FROMBUF.
10778 This uses the icalendar.el library."
10779 (let* ((tmpdir (if (featurep 'xemacs)
10780 (temp-directory)
10781 temporary-file-directory))
10782 (tmpfile (make-temp-name
10783 (expand-file-name "orgics" tmpdir)))
10784 buf rtn b e)
10785 (save-excursion
10786 (set-buffer frombuf)
10787 (icalendar-export-region (point-min) (point-max) tmpfile)
10788 (setq buf (find-buffer-visiting tmpfile))
10789 (set-buffer buf)
10790 (goto-char (point-min))
10791 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10792 (setq b (match-beginning 0)))
10793 (goto-char (point-max))
10794 (if (re-search-backward "^END:VEVENT" nil t)
10795 (setq e (match-end 0)))
10796 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10797 (kill-buffer buf)
10798 (kill-buffer frombuf)
10799 (delete-file tmpfile)
10800 rtn))
10802 (defun org-closest-date (start current change prefer show-all)
10803 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10804 When PREFER is `past' return a date that is either CURRENT or past.
10805 When PREFER is `future', return a date that is either CURRENT or future.
10806 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10807 ;; Make the proper lists from the dates
10808 (catch 'exit
10809 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10810 dn dw sday cday n1 n2
10811 d m y y1 y2 date1 date2 nmonths nm ny m2)
10813 (setq start (org-date-to-gregorian start)
10814 current (org-date-to-gregorian
10815 (if show-all
10816 current
10817 (time-to-days (current-time))))
10818 sday (calendar-absolute-from-gregorian start)
10819 cday (calendar-absolute-from-gregorian current))
10821 (if (<= cday sday) (throw 'exit sday))
10823 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10824 (setq dn (string-to-number (match-string 1 change))
10825 dw (cdr (assoc (match-string 2 change) a1)))
10826 (error "Invalid change specifyer: %s" change))
10827 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10828 (cond
10829 ((eq dw 'day)
10830 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10831 n2 (+ n1 dn)))
10832 ((eq dw 'year)
10833 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10834 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10835 (setq date1 (list m d y1)
10836 n1 (calendar-absolute-from-gregorian date1)
10837 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10838 n2 (calendar-absolute-from-gregorian date2)))
10839 ((eq dw 'month)
10840 ;; approx number of month between the tow dates
10841 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10842 ;; How often does dn fit in there?
10843 (setq d (nth 1 start) m (car start) y (nth 2 start)
10844 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10845 m (+ m nm)
10846 ny (floor (/ m 12))
10847 y (+ y ny)
10848 m (- m (* ny 12)))
10849 (while (> m 12) (setq m (- m 12) y (1+ y)))
10850 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10851 (setq m2 (+ m dn) y2 y)
10852 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10853 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10854 (while (< n2 cday)
10855 (setq n1 n2 m m2 y y2)
10856 (setq m2 (+ m dn) y2 y)
10857 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10858 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10860 (if show-all
10861 (cond
10862 ((eq prefer 'past) n1)
10863 ((eq prefer 'future) (if (= cday n1) n1 n2))
10864 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10865 (cond
10866 ((eq prefer 'past) n1)
10867 ((eq prefer 'future) (if (= cday n1) n1 n2))
10868 (t (if (= cday n1) n1 n2)))))))
10870 (defun org-date-to-gregorian (date)
10871 "Turn any specification of DATE into a gregorian date for the calendar."
10872 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10873 ((and (listp date) (= (length date) 3)) date)
10874 ((stringp date)
10875 (setq date (org-parse-time-string date))
10876 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10877 ((listp date)
10878 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10880 (defun org-parse-time-string (s &optional nodefault)
10881 "Parse the standard Org-mode time string.
10882 This should be a lot faster than the normal `parse-time-string'.
10883 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10884 hour and minute fields will be nil if not given."
10885 (if (string-match org-ts-regexp0 s)
10886 (list 0
10887 (if (or (match-beginning 8) (not nodefault))
10888 (string-to-number (or (match-string 8 s) "0")))
10889 (if (or (match-beginning 7) (not nodefault))
10890 (string-to-number (or (match-string 7 s) "0")))
10891 (string-to-number (match-string 4 s))
10892 (string-to-number (match-string 3 s))
10893 (string-to-number (match-string 2 s))
10894 nil nil nil)
10895 (make-list 9 0)))
10897 (defun org-timestamp-up (&optional arg)
10898 "Increase the date item at the cursor by one.
10899 If the cursor is on the year, change the year. If it is on the month or
10900 the day, change that.
10901 With prefix ARG, change by that many units."
10902 (interactive "p")
10903 (org-timestamp-change (prefix-numeric-value arg)))
10905 (defun org-timestamp-down (&optional arg)
10906 "Decrease the date item at the cursor by one.
10907 If the cursor is on the year, change the year. If it is on the month or
10908 the day, change that.
10909 With prefix ARG, change by that many units."
10910 (interactive "p")
10911 (org-timestamp-change (- (prefix-numeric-value arg))))
10913 (defun org-timestamp-up-day (&optional arg)
10914 "Increase the date in the time stamp by one day.
10915 With prefix ARG, change that many days."
10916 (interactive "p")
10917 (if (and (not (org-at-timestamp-p t))
10918 (org-on-heading-p))
10919 (org-todo 'up)
10920 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10922 (defun org-timestamp-down-day (&optional arg)
10923 "Decrease the date in the time stamp by one day.
10924 With prefix ARG, change that many days."
10925 (interactive "p")
10926 (if (and (not (org-at-timestamp-p t))
10927 (org-on-heading-p))
10928 (org-todo 'down)
10929 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10931 (defun org-at-timestamp-p (&optional inactive-ok)
10932 "Determine if the cursor is in or at a timestamp."
10933 (interactive)
10934 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10935 (pos (point))
10936 (ans (or (looking-at tsr)
10937 (save-excursion
10938 (skip-chars-backward "^[<\n\r\t")
10939 (if (> (point) (point-min)) (backward-char 1))
10940 (and (looking-at tsr)
10941 (> (- (match-end 0) pos) -1))))))
10942 (and ans
10943 (boundp 'org-ts-what)
10944 (setq org-ts-what
10945 (cond
10946 ((= pos (match-beginning 0)) 'bracket)
10947 ((= pos (1- (match-end 0))) 'bracket)
10948 ((org-pos-in-match-range pos 2) 'year)
10949 ((org-pos-in-match-range pos 3) 'month)
10950 ((org-pos-in-match-range pos 7) 'hour)
10951 ((org-pos-in-match-range pos 8) 'minute)
10952 ((or (org-pos-in-match-range pos 4)
10953 (org-pos-in-match-range pos 5)) 'day)
10954 ((and (> pos (or (match-end 8) (match-end 5)))
10955 (< pos (match-end 0)))
10956 (- pos (or (match-end 8) (match-end 5))))
10957 (t 'day))))
10958 ans))
10960 (defun org-toggle-timestamp-type ()
10961 "Toggle the type (<active> or [inactive]) of a time stamp."
10962 (interactive)
10963 (when (org-at-timestamp-p t)
10964 (save-excursion
10965 (goto-char (match-beginning 0))
10966 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10967 (goto-char (1- (match-end 0)))
10968 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10969 (message "Timestamp is now %sactive"
10970 (if (equal (char-before) ?>) "in" ""))))
10972 (defun org-timestamp-change (n &optional what)
10973 "Change the date in the time stamp at point.
10974 The date will be changed by N times WHAT. WHAT can be `day', `month',
10975 `year', `minute', `second'. If WHAT is not given, the cursor position
10976 in the timestamp determines what will be changed."
10977 (let ((pos (point))
10978 with-hm inactive
10979 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10980 org-ts-what
10981 extra rem
10982 ts time time0)
10983 (if (not (org-at-timestamp-p t))
10984 (error "Not at a timestamp"))
10985 (if (and (not what) (eq org-ts-what 'bracket))
10986 (org-toggle-timestamp-type)
10987 (if (and (not what) (not (eq org-ts-what 'day))
10988 org-display-custom-times
10989 (get-text-property (point) 'display)
10990 (not (get-text-property (1- (point)) 'display)))
10991 (setq org-ts-what 'day))
10992 (setq org-ts-what (or what org-ts-what)
10993 inactive (= (char-after (match-beginning 0)) ?\[)
10994 ts (match-string 0))
10995 (replace-match "")
10996 (if (string-match
10997 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10999 (setq extra (match-string 1 ts)))
11000 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11001 (setq with-hm t))
11002 (setq time0 (org-parse-time-string ts))
11003 (when (and (eq org-ts-what 'minute)
11004 (eq current-prefix-arg nil))
11005 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11006 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11007 (setcar (cdr time0) (+ (nth 1 time0)
11008 (if (> n 0) (- rem) (- dm rem))))))
11009 (setq time
11010 (encode-time (or (car time0) 0)
11011 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11012 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11013 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11014 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11015 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11016 (nthcdr 6 time0)))
11017 (when (integerp org-ts-what)
11018 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11019 (if (eq what 'calendar)
11020 (let ((cal-date (org-get-date-from-calendar)))
11021 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11022 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11023 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11024 (setcar time0 (or (car time0) 0))
11025 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11026 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11027 (setq time (apply 'encode-time time0))))
11028 (setq org-last-changed-timestamp
11029 (org-insert-time-stamp time with-hm inactive nil nil extra))
11030 (org-clock-update-time-maybe)
11031 (goto-char pos)
11032 ;; Try to recenter the calendar window, if any
11033 (if (and org-calendar-follow-timestamp-change
11034 (get-buffer-window "*Calendar*" t)
11035 (memq org-ts-what '(day month year)))
11036 (org-recenter-calendar (time-to-days time))))))
11038 (defun org-modify-ts-extra (s pos n dm)
11039 "Change the different parts of the lead-time and repeat fields in timestamp."
11040 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11041 ng h m new rem)
11042 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11043 (cond
11044 ((or (org-pos-in-match-range pos 2)
11045 (org-pos-in-match-range pos 3))
11046 (setq m (string-to-number (match-string 3 s))
11047 h (string-to-number (match-string 2 s)))
11048 (if (org-pos-in-match-range pos 2)
11049 (setq h (+ h n))
11050 (setq n (* dm (org-no-warnings (signum n))))
11051 (when (not (= 0 (setq rem (% m dm))))
11052 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11053 (setq m (+ m n)))
11054 (if (< m 0) (setq m (+ m 60) h (1- h)))
11055 (if (> m 59) (setq m (- m 60) h (1+ h)))
11056 (setq h (min 24 (max 0 h)))
11057 (setq ng 1 new (format "-%02d:%02d" h m)))
11058 ((org-pos-in-match-range pos 6)
11059 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11060 ((org-pos-in-match-range pos 5)
11061 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11063 ((org-pos-in-match-range pos 9)
11064 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11065 ((org-pos-in-match-range pos 8)
11066 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11068 (when ng
11069 (setq s (concat
11070 (substring s 0 (match-beginning ng))
11072 (substring s (match-end ng))))))
11075 (defun org-recenter-calendar (date)
11076 "If the calendar is visible, recenter it to DATE."
11077 (let* ((win (selected-window))
11078 (cwin (get-buffer-window "*Calendar*" t))
11079 (calendar-move-hook nil))
11080 (when cwin
11081 (select-window cwin)
11082 (calendar-goto-date (if (listp date) date
11083 (calendar-gregorian-from-absolute date)))
11084 (select-window win))))
11086 (defun org-goto-calendar (&optional arg)
11087 "Go to the Emacs calendar at the current date.
11088 If there is a time stamp in the current line, go to that date.
11089 A prefix ARG can be used to force the current date."
11090 (interactive "P")
11091 (let ((tsr org-ts-regexp) diff
11092 (calendar-move-hook nil)
11093 (calendar-view-holidays-initially-flag nil)
11094 (view-calendar-holidays-initially nil)
11095 (calendar-view-diary-initially-flag nil)
11096 (view-diary-entries-initially nil))
11097 (if (or (org-at-timestamp-p)
11098 (save-excursion
11099 (beginning-of-line 1)
11100 (looking-at (concat ".*" tsr))))
11101 (let ((d1 (time-to-days (current-time)))
11102 (d2 (time-to-days
11103 (org-time-string-to-time (match-string 1)))))
11104 (setq diff (- d2 d1))))
11105 (calendar)
11106 (calendar-goto-today)
11107 (if (and diff (not arg)) (calendar-forward-day diff))))
11109 (defun org-get-date-from-calendar ()
11110 "Return a list (month day year) of date at point in calendar."
11111 (with-current-buffer "*Calendar*"
11112 (save-match-data
11113 (calendar-cursor-to-date))))
11115 (defun org-date-from-calendar ()
11116 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11117 If there is already a time stamp at the cursor position, update it."
11118 (interactive)
11119 (if (org-at-timestamp-p t)
11120 (org-timestamp-change 0 'calendar)
11121 (let ((cal-date (org-get-date-from-calendar)))
11122 (org-insert-time-stamp
11123 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11125 (defun org-minutes-to-hh:mm-string (m)
11126 "Compute H:MM from a number of minutes."
11127 (let ((h (/ m 60)))
11128 (setq m (- m (* 60 h)))
11129 (format "%d:%02d" h m)))
11131 (defun org-hh:mm-string-to-minutes (s)
11132 "Convert a string H:MM to a number of minutes."
11133 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11134 (+ (* (string-to-number (match-string 1 s)) 60)
11135 (string-to-number (match-string 2 s)))
11138 ;;;; Agenda files
11140 ;;;###autoload
11141 (defun org-iswitchb (&optional arg)
11142 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11143 With a prefix argument, restrict available to files.
11144 With two prefix arguments, restrict available buffers to agenda files.
11146 Due to some yet unresolved reason, global function
11147 `iswitchb-mode' needs to be active for this function to work."
11148 (interactive "P")
11149 (require 'iswitchb)
11150 (let ((enabled iswitchb-mode) blist)
11151 (or enabled (iswitchb-mode 1))
11152 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11153 ((equal arg '(16)) (org-buffer-list 'agenda))
11154 (t (org-buffer-list))))
11155 (unwind-protect
11156 (let ((iswitchb-make-buflist-hook
11157 (lambda ()
11158 (setq iswitchb-temp-buflist
11159 (mapcar 'buffer-name blist)))))
11160 (switch-to-buffer
11161 (iswitchb-read-buffer
11162 "Switch-to: " nil t))
11163 (or enabled (iswitchb-mode -1))))))
11165 (defun org-buffer-list (&optional predicate tmp)
11166 "Return a list of Org buffers.
11167 PREDICATE can be either 'export, 'files or 'agenda.
11169 'export restrict the list to Export buffers.
11170 'files restrict the list to buffers visiting Org files.
11171 'agenda restrict the list to buffers visiting agenda files.
11173 If TMP is non-nil, don't include temporary buffers."
11174 (let (filter blist)
11175 (setq filter
11176 (cond ((eq predicate 'files) "\.org$")
11177 ((eq predicate 'export) "\*Org .*Export")
11178 (t "\*Org \\|\.org$")))
11179 (setq blist
11180 (mapcar
11181 (lambda(b)
11182 (let ((bname (buffer-name b))
11183 (bfile (buffer-file-name b)))
11184 (if (and (string-match filter bname)
11185 (if (eq predicate 'agenda)
11186 (member bfile
11187 (mapcar (lambda(f) (file-truename f))
11188 org-agenda-files)) t)
11189 (if tmp (not (string-match "tmp" bname)) t)) b)))
11190 (buffer-list)))
11191 (delete nil blist)))
11193 (defun org-agenda-files (&optional unrestricted ext)
11194 "Get the list of agenda files.
11195 Optional UNRESTRICTED means return the full list even if a restriction
11196 is currently in place.
11197 When EXT is non-nil, try to add all files that are created by adding EXT
11198 to the file nemes. Basically, this is a way to add the archive files
11199 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11200 a string, \"_archive\" will be used."
11201 (let ((files
11202 (cond
11203 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11204 ((stringp org-agenda-files) (org-read-agenda-file-list))
11205 ((listp org-agenda-files) org-agenda-files)
11206 (t (error "Invalid value of `org-agenda-files'")))))
11207 (setq files (apply 'append
11208 (mapcar (lambda (f)
11209 (if (file-directory-p f)
11210 (directory-files
11211 f t org-agenda-file-regexp)
11212 (list f)))
11213 files)))
11214 (when org-agenda-skip-unavailable-files
11215 (setq files (delq nil
11216 (mapcar (function
11217 (lambda (file)
11218 (and (file-readable-p file) file)))
11219 files))))
11220 (when ext
11221 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11222 ext "_archive"))
11223 (setq files (apply 'append
11224 (mapcar
11225 (lambda (f)
11226 (if (file-exists-p (concat f ext))
11227 (list f (concat f ext))
11228 (list f)))
11229 files))))
11230 files))
11232 (defun org-edit-agenda-file-list ()
11233 "Edit the list of agenda files.
11234 Depending on setup, this either uses customize to edit the variable
11235 `org-agenda-files', or it visits the file that is holding the list. In the
11236 latter case, the buffer is set up in a way that saving it automatically kills
11237 the buffer and restores the previous window configuration."
11238 (interactive)
11239 (if (stringp org-agenda-files)
11240 (let ((cw (current-window-configuration)))
11241 (find-file org-agenda-files)
11242 (org-set-local 'org-window-configuration cw)
11243 (org-add-hook 'after-save-hook
11244 (lambda ()
11245 (set-window-configuration
11246 (prog1 org-window-configuration
11247 (kill-buffer (current-buffer))))
11248 (org-install-agenda-files-menu)
11249 (message "New agenda file list installed"))
11250 nil 'local)
11251 (message "%s" (substitute-command-keys
11252 "Edit list and finish with \\[save-buffer]")))
11253 (customize-variable 'org-agenda-files)))
11255 (defun org-store-new-agenda-file-list (list)
11256 "Set new value for the agenda file list and save it correcly."
11257 (if (stringp org-agenda-files)
11258 (let ((f org-agenda-files) b)
11259 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11260 (with-temp-file f
11261 (insert (mapconcat 'identity list "\n") "\n")))
11262 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11263 (setq org-agenda-files list)
11264 (customize-save-variable 'org-agenda-files org-agenda-files))))
11266 (defun org-read-agenda-file-list ()
11267 "Read the list of agenda files from a file."
11268 (when (file-directory-p org-agenda-files)
11269 (error "`org-agenda-files' cannot be a single directory"))
11270 (when (stringp org-agenda-files)
11271 (with-temp-buffer
11272 (insert-file-contents org-agenda-files)
11273 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11276 ;;;###autoload
11277 (defun org-cycle-agenda-files ()
11278 "Cycle through the files in `org-agenda-files'.
11279 If the current buffer visits an agenda file, find the next one in the list.
11280 If the current buffer does not, find the first agenda file."
11281 (interactive)
11282 (let* ((fs (org-agenda-files t))
11283 (files (append fs (list (car fs))))
11284 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11285 file)
11286 (unless files (error "No agenda files"))
11287 (catch 'exit
11288 (while (setq file (pop files))
11289 (if (equal (file-truename file) tcf)
11290 (when (car files)
11291 (find-file (car files))
11292 (throw 'exit t))))
11293 (find-file (car fs)))
11294 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11296 (defun org-agenda-file-to-front (&optional to-end)
11297 "Move/add the current file to the top of the agenda file list.
11298 If the file is not present in the list, it is added to the front. If it is
11299 present, it is moved there. With optional argument TO-END, add/move to the
11300 end of the list."
11301 (interactive "P")
11302 (let ((org-agenda-skip-unavailable-files nil)
11303 (file-alist (mapcar (lambda (x)
11304 (cons (file-truename x) x))
11305 (org-agenda-files t)))
11306 (ctf (file-truename buffer-file-name))
11307 x had)
11308 (setq x (assoc ctf file-alist) had x)
11310 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11311 (if to-end
11312 (setq file-alist (append (delq x file-alist) (list x)))
11313 (setq file-alist (cons x (delq x file-alist))))
11314 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11315 (org-install-agenda-files-menu)
11316 (message "File %s to %s of agenda file list"
11317 (if had "moved" "added") (if to-end "end" "front"))))
11319 (defun org-remove-file (&optional file)
11320 "Remove current file from the list of files in variable `org-agenda-files'.
11321 These are the files which are being checked for agenda entries.
11322 Optional argument FILE means, use this file instead of the current."
11323 (interactive)
11324 (let* ((org-agenda-skip-unavailable-files nil)
11325 (file (or file buffer-file-name))
11326 (true-file (file-truename file))
11327 (afile (abbreviate-file-name file))
11328 (files (delq nil (mapcar
11329 (lambda (x)
11330 (if (equal true-file
11331 (file-truename x))
11332 nil x))
11333 (org-agenda-files t)))))
11334 (if (not (= (length files) (length (org-agenda-files t))))
11335 (progn
11336 (org-store-new-agenda-file-list files)
11337 (org-install-agenda-files-menu)
11338 (message "Removed file: %s" afile))
11339 (message "File was not in list: %s (not removed)" afile))))
11341 (defun org-file-menu-entry (file)
11342 (vector file (list 'find-file file) t))
11344 (defun org-check-agenda-file (file)
11345 "Make sure FILE exists. If not, ask user what to do."
11346 (when (not (file-exists-p file))
11347 (message "non-existent file %s. [R]emove from list or [A]bort?"
11348 (abbreviate-file-name file))
11349 (let ((r (downcase (read-char-exclusive))))
11350 (cond
11351 ((equal r ?r)
11352 (org-remove-file file)
11353 (throw 'nextfile t))
11354 (t (error "Abort"))))))
11356 (defun org-get-agenda-file-buffer (file)
11357 "Get a buffer visiting FILE. If the buffer needs to be created, add
11358 it to the list of buffers which might be released later."
11359 (let ((buf (org-find-base-buffer-visiting file)))
11360 (if buf
11361 buf ; just return it
11362 ;; Make a new buffer and remember it
11363 (setq buf (find-file-noselect file))
11364 (if buf (push buf org-agenda-new-buffers))
11365 buf)))
11367 (defun org-release-buffers (blist)
11368 "Release all buffers in list, asking the user for confirmation when needed.
11369 When a buffer is unmodified, it is just killed. When modified, it is saved
11370 \(if the user agrees) and then killed."
11371 (let (buf file)
11372 (while (setq buf (pop blist))
11373 (setq file (buffer-file-name buf))
11374 (when (and (buffer-modified-p buf)
11375 file
11376 (y-or-n-p (format "Save file %s? " file)))
11377 (with-current-buffer buf (save-buffer)))
11378 (kill-buffer buf))))
11380 (defun org-prepare-agenda-buffers (files)
11381 "Create buffers for all agenda files, protect archived trees and comments."
11382 (interactive)
11383 (let ((pa '(:org-archived t))
11384 (pc '(:org-comment t))
11385 (pall '(:org-archived t :org-comment t))
11386 (inhibit-read-only t)
11387 (rea (concat ":" org-archive-tag ":"))
11388 bmp file re)
11389 (save-excursion
11390 (save-restriction
11391 (while (setq file (pop files))
11392 (if (bufferp file)
11393 (set-buffer file)
11394 (org-check-agenda-file file)
11395 (set-buffer (org-get-agenda-file-buffer file)))
11396 (widen)
11397 (setq bmp (buffer-modified-p))
11398 (org-refresh-category-properties)
11399 (setq org-todo-keywords-for-agenda
11400 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11401 (setq org-done-keywords-for-agenda
11402 (append org-done-keywords-for-agenda org-done-keywords))
11403 (save-excursion
11404 (remove-text-properties (point-min) (point-max) pall)
11405 (when org-agenda-skip-archived-trees
11406 (goto-char (point-min))
11407 (while (re-search-forward rea nil t)
11408 (if (org-on-heading-p t)
11409 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11410 (goto-char (point-min))
11411 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11412 (while (re-search-forward re nil t)
11413 (add-text-properties
11414 (match-beginning 0) (org-end-of-subtree t) pc)))
11415 (set-buffer-modified-p bmp))))))
11417 ;;;; Embedded LaTeX
11419 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11420 "Keymap for the minor `org-cdlatex-mode'.")
11422 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11423 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11424 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11425 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11426 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11428 (defvar org-cdlatex-texmathp-advice-is-done nil
11429 "Flag remembering if we have applied the advice to texmathp already.")
11431 (define-minor-mode org-cdlatex-mode
11432 "Toggle the minor `org-cdlatex-mode'.
11433 This mode supports entering LaTeX environment and math in LaTeX fragments
11434 in Org-mode.
11435 \\{org-cdlatex-mode-map}"
11436 nil " OCDL" nil
11437 (when org-cdlatex-mode (require 'cdlatex))
11438 (unless org-cdlatex-texmathp-advice-is-done
11439 (setq org-cdlatex-texmathp-advice-is-done t)
11440 (defadvice texmathp (around org-math-always-on activate)
11441 "Always return t in org-mode buffers.
11442 This is because we want to insert math symbols without dollars even outside
11443 the LaTeX math segments. If Orgmode thinks that point is actually inside
11444 en embedded LaTeX fragement, let texmathp do its job.
11445 \\[org-cdlatex-mode-map]"
11446 (interactive)
11447 (let (p)
11448 (cond
11449 ((not (org-mode-p)) ad-do-it)
11450 ((eq this-command 'cdlatex-math-symbol)
11451 (setq ad-return-value t
11452 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11454 (let ((p (org-inside-LaTeX-fragment-p)))
11455 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11456 (setq ad-return-value t
11457 texmathp-why '("Org-mode embedded math" . 0))
11458 (if p ad-do-it)))))))))
11460 (defun turn-on-org-cdlatex ()
11461 "Unconditionally turn on `org-cdlatex-mode'."
11462 (org-cdlatex-mode 1))
11464 (defun org-inside-LaTeX-fragment-p ()
11465 "Test if point is inside a LaTeX fragment.
11466 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11467 sequence appearing also before point.
11468 Even though the matchers for math are configurable, this function assumes
11469 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11470 delimiters are skipped when they have been removed by customization.
11471 The return value is nil, or a cons cell with the delimiter and
11472 and the position of this delimiter.
11474 This function does a reasonably good job, but can locally be fooled by
11475 for example currency specifications. For example it will assume being in
11476 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11477 fragments that are properly closed, but during editing, we have to live
11478 with the uncertainty caused by missing closing delimiters. This function
11479 looks only before point, not after."
11480 (catch 'exit
11481 (let ((pos (point))
11482 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11483 (lim (progn
11484 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11485 (point)))
11486 dd-on str (start 0) m re)
11487 (goto-char pos)
11488 (when dodollar
11489 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11490 re (nth 1 (assoc "$" org-latex-regexps)))
11491 (while (string-match re str start)
11492 (cond
11493 ((= (match-end 0) (length str))
11494 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11495 ((= (match-end 0) (- (length str) 5))
11496 (throw 'exit nil))
11497 (t (setq start (match-end 0))))))
11498 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11499 (goto-char pos)
11500 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11501 (and (match-beginning 2) (throw 'exit nil))
11502 ;; count $$
11503 (while (re-search-backward "\\$\\$" lim t)
11504 (setq dd-on (not dd-on)))
11505 (goto-char pos)
11506 (if dd-on (cons "$$" m))))))
11509 (defun org-try-cdlatex-tab ()
11510 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11511 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11512 - inside a LaTeX fragment, or
11513 - after the first word in a line, where an abbreviation expansion could
11514 insert a LaTeX environment."
11515 (when org-cdlatex-mode
11516 (cond
11517 ((save-excursion
11518 (skip-chars-backward "a-zA-Z0-9*")
11519 (skip-chars-backward " \t")
11520 (bolp))
11521 (cdlatex-tab) t)
11522 ((org-inside-LaTeX-fragment-p)
11523 (cdlatex-tab) t)
11524 (t nil))))
11526 (defun org-cdlatex-underscore-caret (&optional arg)
11527 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11528 Revert to the normal definition outside of these fragments."
11529 (interactive "P")
11530 (if (org-inside-LaTeX-fragment-p)
11531 (call-interactively 'cdlatex-sub-superscript)
11532 (let (org-cdlatex-mode)
11533 (call-interactively (key-binding (vector last-input-event))))))
11535 (defun org-cdlatex-math-modify (&optional arg)
11536 "Execute `cdlatex-math-modify' in LaTeX fragments.
11537 Revert to the normal definition outside of these fragments."
11538 (interactive "P")
11539 (if (org-inside-LaTeX-fragment-p)
11540 (call-interactively 'cdlatex-math-modify)
11541 (let (org-cdlatex-mode)
11542 (call-interactively (key-binding (vector last-input-event))))))
11544 (defvar org-latex-fragment-image-overlays nil
11545 "List of overlays carrying the images of latex fragments.")
11546 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11548 (defun org-remove-latex-fragment-image-overlays ()
11549 "Remove all overlays with LaTeX fragment images in current buffer."
11550 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11551 (setq org-latex-fragment-image-overlays nil))
11553 (defun org-preview-latex-fragment (&optional subtree)
11554 "Preview the LaTeX fragment at point, or all locally or globally.
11555 If the cursor is in a LaTeX fragment, create the image and overlay
11556 it over the source code. If there is no fragment at point, display
11557 all fragments in the current text, from one headline to the next. With
11558 prefix SUBTREE, display all fragments in the current subtree. With a
11559 double prefix `C-u C-u', or when the cursor is before the first headline,
11560 display all fragments in the buffer.
11561 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11562 (interactive "P")
11563 (org-remove-latex-fragment-image-overlays)
11564 (save-excursion
11565 (save-restriction
11566 (let (beg end at msg)
11567 (cond
11568 ((or (equal subtree '(16))
11569 (not (save-excursion
11570 (re-search-backward (concat "^" outline-regexp) nil t))))
11571 (setq beg (point-min) end (point-max)
11572 msg "Creating images for buffer...%s"))
11573 ((equal subtree '(4))
11574 (org-back-to-heading)
11575 (setq beg (point) end (org-end-of-subtree t)
11576 msg "Creating images for subtree...%s"))
11578 (if (setq at (org-inside-LaTeX-fragment-p))
11579 (goto-char (max (point-min) (- (cdr at) 2)))
11580 (org-back-to-heading))
11581 (setq beg (point) end (progn (outline-next-heading) (point))
11582 msg (if at "Creating image...%s"
11583 "Creating images for entry...%s"))))
11584 (message msg "")
11585 (narrow-to-region beg end)
11586 (goto-char beg)
11587 (org-format-latex
11588 (concat "ltxpng/" (file-name-sans-extension
11589 (file-name-nondirectory
11590 buffer-file-name)))
11591 default-directory 'overlays msg at 'forbuffer)
11592 (message msg "done. Use `C-c C-c' to remove images.")))))
11594 (defvar org-latex-regexps
11595 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11596 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11597 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11598 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11599 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11600 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11601 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11602 "Regular expressions for matching embedded LaTeX.")
11604 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11605 "Replace LaTeX fragments with links to an image, and produce images."
11606 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11607 (let* ((prefixnodir (file-name-nondirectory prefix))
11608 (absprefix (expand-file-name prefix dir))
11609 (todir (file-name-directory absprefix))
11610 (opt org-format-latex-options)
11611 (matchers (plist-get opt :matchers))
11612 (re-list org-latex-regexps)
11613 (cnt 0) txt link beg end re e checkdir
11614 m n block linkfile movefile ov)
11615 ;; Check if there are old images files with this prefix, and remove them
11616 (when (file-directory-p todir)
11617 (mapc 'delete-file
11618 (directory-files
11619 todir 'full
11620 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11621 ;; Check the different regular expressions
11622 (while (setq e (pop re-list))
11623 (setq m (car e) re (nth 1 e) n (nth 2 e)
11624 block (if (nth 3 e) "\n\n" ""))
11625 (when (member m matchers)
11626 (goto-char (point-min))
11627 (while (re-search-forward re nil t)
11628 (when (or (not at) (equal (cdr at) (match-beginning n)))
11629 (setq txt (match-string n)
11630 beg (match-beginning n) end (match-end n)
11631 cnt (1+ cnt)
11632 linkfile (format "%s_%04d.png" prefix cnt)
11633 movefile (format "%s_%04d.png" absprefix cnt)
11634 link (concat block "[[file:" linkfile "]]" block))
11635 (if msg (message msg cnt))
11636 (goto-char beg)
11637 (unless checkdir ; make sure the directory exists
11638 (setq checkdir t)
11639 (or (file-directory-p todir) (make-directory todir)))
11640 (org-create-formula-image
11641 txt movefile opt forbuffer)
11642 (if overlays
11643 (progn
11644 (setq ov (org-make-overlay beg end))
11645 (if (featurep 'xemacs)
11646 (progn
11647 (org-overlay-put ov 'invisible t)
11648 (org-overlay-put
11649 ov 'end-glyph
11650 (make-glyph (vector 'png :file movefile))))
11651 (org-overlay-put
11652 ov 'display
11653 (list 'image :type 'png :file movefile :ascent 'center)))
11654 (push ov org-latex-fragment-image-overlays)
11655 (goto-char end))
11656 (delete-region beg end)
11657 (insert link))))))))
11659 ;; This function borrows from Ganesh Swami's latex2png.el
11660 (defun org-create-formula-image (string tofile options buffer)
11661 (let* ((tmpdir (if (featurep 'xemacs)
11662 (temp-directory)
11663 temporary-file-directory))
11664 (texfilebase (make-temp-name
11665 (expand-file-name "orgtex" tmpdir)))
11666 (texfile (concat texfilebase ".tex"))
11667 (dvifile (concat texfilebase ".dvi"))
11668 (pngfile (concat texfilebase ".png"))
11669 (fnh (if (featurep 'xemacs)
11670 (font-height (get-face-font 'default))
11671 (face-attribute 'default :height nil)))
11672 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11673 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11674 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11675 "Black"))
11676 (bg (or (plist-get options (if buffer :background :html-background))
11677 "Transparent")))
11678 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11679 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11680 (with-temp-file texfile
11681 (insert org-format-latex-header
11682 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11683 (let ((dir default-directory))
11684 (condition-case nil
11685 (progn
11686 (cd tmpdir)
11687 (call-process "latex" nil nil nil texfile))
11688 (error nil))
11689 (cd dir))
11690 (if (not (file-exists-p dvifile))
11691 (progn (message "Failed to create dvi file from %s" texfile) nil)
11692 (call-process "dvipng" nil nil nil
11693 "-E" "-fg" fg "-bg" bg
11694 "-D" dpi
11695 ;;"-x" scale "-y" scale
11696 "-T" "tight"
11697 "-o" pngfile
11698 dvifile)
11699 (if (not (file-exists-p pngfile))
11700 (progn (message "Failed to create png file from %s" texfile) nil)
11701 ;; Use the requested file name and clean up
11702 (copy-file pngfile tofile 'replace)
11703 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11704 (delete-file (concat texfilebase e)))
11705 pngfile))))
11707 (defun org-dvipng-color (attr)
11708 "Return an rgb color specification for dvipng."
11709 (apply 'format "rgb %s %s %s"
11710 (mapcar 'org-normalize-color
11711 (color-values (face-attribute 'default attr nil)))))
11713 (defun org-normalize-color (value)
11714 "Return string to be used as color value for an RGB component."
11715 (format "%g" (/ value 65535.0)))
11718 ;;;; Key bindings
11720 ;; Make `C-c C-x' a prefix key
11721 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11723 ;; TAB key with modifiers
11724 (org-defkey org-mode-map "\C-i" 'org-cycle)
11725 (org-defkey org-mode-map [(tab)] 'org-cycle)
11726 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11727 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11728 (org-defkey org-mode-map "\M-\t" 'org-complete)
11729 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11730 ;; The following line is necessary under Suse GNU/Linux
11731 (unless (featurep 'xemacs)
11732 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11733 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11734 (define-key org-mode-map [backtab] 'org-shifttab)
11736 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11737 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11738 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11740 ;; Cursor keys with modifiers
11741 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11742 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11743 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11744 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11746 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11747 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11748 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11749 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11751 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11752 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11753 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11754 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11756 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11757 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11759 ;;; Extra keys for tty access.
11760 ;; We only set them when really needed because otherwise the
11761 ;; menus don't show the simple keys
11763 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11764 (not window-system))
11765 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11766 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11767 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11768 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11769 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11770 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11771 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11772 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11773 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11774 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11775 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11776 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11777 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11778 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11779 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11780 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11781 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11782 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11783 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11784 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11785 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11786 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11788 ;; All the other keys
11790 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11791 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11792 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11793 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11794 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11795 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11796 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11797 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11798 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11799 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11800 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11801 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11802 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11803 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11804 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11805 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11806 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11807 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11808 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11809 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11810 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11811 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11812 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11813 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11814 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11815 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11816 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11817 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11818 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11819 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11820 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11821 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11822 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11823 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11824 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11825 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11826 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11827 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11828 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11829 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11830 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11831 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11832 (org-defkey org-mode-map "\C-c^" 'org-sort)
11833 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11834 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11835 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11836 (org-defkey org-mode-map "\C-m" 'org-return)
11837 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11838 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11839 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11840 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11841 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11842 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11843 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11844 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11845 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11846 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11847 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11848 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11849 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11850 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11851 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11852 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11854 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11855 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11856 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11857 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11859 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11860 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11861 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11862 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11863 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11864 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11865 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11866 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11867 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11868 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11869 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11870 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11872 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11874 (when (featurep 'xemacs)
11875 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11877 (defvar org-table-auto-blank-field) ; defined in org-table.el
11878 (defun org-self-insert-command (N)
11879 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11880 If the cursor is in a table looking at whitespace, the whitespace is
11881 overwritten, and the table is not marked as requiring realignment."
11882 (interactive "p")
11883 (if (and (org-table-p)
11884 (progn
11885 ;; check if we blank the field, and if that triggers align
11886 (and (featurep 'org-table) org-table-auto-blank-field
11887 (member last-command
11888 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11889 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11890 ;; got extra space, this field does not determine column width
11891 (let (org-table-may-need-update) (org-table-blank-field))
11892 ;; no extra space, this field may determine column width
11893 (org-table-blank-field)))
11895 (eq N 1)
11896 (looking-at "[^|\n]* |"))
11897 (let (org-table-may-need-update)
11898 (goto-char (1- (match-end 0)))
11899 (delete-backward-char 1)
11900 (goto-char (match-beginning 0))
11901 (self-insert-command N))
11902 (setq org-table-may-need-update t)
11903 (self-insert-command N)
11904 (org-fix-tags-on-the-fly)))
11906 (defun org-fix-tags-on-the-fly ()
11907 (when (and (equal (char-after (point-at-bol)) ?*)
11908 (org-on-heading-p))
11909 (org-align-tags-here org-tags-column)))
11911 (defun org-delete-backward-char (N)
11912 "Like `delete-backward-char', insert whitespace at field end in tables.
11913 When deleting backwards, in tables this function will insert whitespace in
11914 front of the next \"|\" separator, to keep the table aligned. The table will
11915 still be marked for re-alignment if the field did fill the entire column,
11916 because, in this case the deletion might narrow the column."
11917 (interactive "p")
11918 (if (and (org-table-p)
11919 (eq N 1)
11920 (string-match "|" (buffer-substring (point-at-bol) (point)))
11921 (looking-at ".*?|"))
11922 (let ((pos (point))
11923 (noalign (looking-at "[^|\n\r]* |"))
11924 (c org-table-may-need-update))
11925 (backward-delete-char N)
11926 (skip-chars-forward "^|")
11927 (insert " ")
11928 (goto-char (1- pos))
11929 ;; noalign: if there were two spaces at the end, this field
11930 ;; does not determine the width of the column.
11931 (if noalign (setq org-table-may-need-update c)))
11932 (backward-delete-char N)
11933 (org-fix-tags-on-the-fly)))
11935 (defun org-delete-char (N)
11936 "Like `delete-char', but insert whitespace at field end in tables.
11937 When deleting characters, in tables this function will insert whitespace in
11938 front of the next \"|\" separator, to keep the table aligned. The table will
11939 still be marked for re-alignment if the field did fill the entire column,
11940 because, in this case the deletion might narrow the column."
11941 (interactive "p")
11942 (if (and (org-table-p)
11943 (not (bolp))
11944 (not (= (char-after) ?|))
11945 (eq N 1))
11946 (if (looking-at ".*?|")
11947 (let ((pos (point))
11948 (noalign (looking-at "[^|\n\r]* |"))
11949 (c org-table-may-need-update))
11950 (replace-match (concat
11951 (substring (match-string 0) 1 -1)
11952 " |"))
11953 (goto-char pos)
11954 ;; noalign: if there were two spaces at the end, this field
11955 ;; does not determine the width of the column.
11956 (if noalign (setq org-table-may-need-update c)))
11957 (delete-char N))
11958 (delete-char N)
11959 (org-fix-tags-on-the-fly)))
11961 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11962 (put 'org-self-insert-command 'delete-selection t)
11963 (put 'orgtbl-self-insert-command 'delete-selection t)
11964 (put 'org-delete-char 'delete-selection 'supersede)
11965 (put 'org-delete-backward-char 'delete-selection 'supersede)
11967 ;; Make `flyspell-mode' delay after some commands
11968 (put 'org-self-insert-command 'flyspell-delayed t)
11969 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11970 (put 'org-delete-char 'flyspell-delayed t)
11971 (put 'org-delete-backward-char 'flyspell-delayed t)
11973 ;; Make pabbrev-mode expand after org-mode commands
11974 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11975 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11977 ;; How to do this: Measure non-white length of current string
11978 ;; If equal to column width, we should realign.
11980 (defun org-remap (map &rest commands)
11981 "In MAP, remap the functions given in COMMANDS.
11982 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11983 (let (new old)
11984 (while commands
11985 (setq old (pop commands) new (pop commands))
11986 (if (fboundp 'command-remapping)
11987 (org-defkey map (vector 'remap old) new)
11988 (substitute-key-definition old new map global-map)))))
11990 (when (eq org-enable-table-editor 'optimized)
11991 ;; If the user wants maximum table support, we need to hijack
11992 ;; some standard editing functions
11993 (org-remap org-mode-map
11994 'self-insert-command 'org-self-insert-command
11995 'delete-char 'org-delete-char
11996 'delete-backward-char 'org-delete-backward-char)
11997 (org-defkey org-mode-map "|" 'org-force-self-insert))
11999 (defun org-shiftcursor-error ()
12000 "Throw an error because Shift-Cursor command was applied in wrong context."
12001 (error "This command is active in special context like tables, headlines or timestamps"))
12003 (defun org-shifttab (&optional arg)
12004 "Global visibility cycling or move to previous table field.
12005 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12006 on context.
12007 See the individual commands for more information."
12008 (interactive "P")
12009 (cond
12010 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12011 (arg (message "Content view to level: ")
12012 (org-content (prefix-numeric-value arg))
12013 (setq org-cycle-global-status 'overview))
12014 (t (call-interactively 'org-global-cycle))))
12016 (defun org-shiftmetaleft ()
12017 "Promote subtree or delete table column.
12018 Calls `org-promote-subtree', `org-outdent-item',
12019 or `org-table-delete-column', depending on context.
12020 See the individual commands for more information."
12021 (interactive)
12022 (cond
12023 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12024 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12025 ((org-at-item-p) (call-interactively 'org-outdent-item))
12026 (t (org-shiftcursor-error))))
12028 (defun org-shiftmetaright ()
12029 "Demote subtree or insert table column.
12030 Calls `org-demote-subtree', `org-indent-item',
12031 or `org-table-insert-column', depending on context.
12032 See the individual commands for more information."
12033 (interactive)
12034 (cond
12035 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12036 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12037 ((org-at-item-p) (call-interactively 'org-indent-item))
12038 (t (org-shiftcursor-error))))
12040 (defun org-shiftmetaup (&optional arg)
12041 "Move subtree up or kill table row.
12042 Calls `org-move-subtree-up' or `org-table-kill-row' or
12043 `org-move-item-up' depending on context. See the individual commands
12044 for more information."
12045 (interactive "P")
12046 (cond
12047 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12048 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12049 ((org-at-item-p) (call-interactively 'org-move-item-up))
12050 (t (org-shiftcursor-error))))
12051 (defun org-shiftmetadown (&optional arg)
12052 "Move subtree down or insert table row.
12053 Calls `org-move-subtree-down' or `org-table-insert-row' or
12054 `org-move-item-down', depending on context. See the individual
12055 commands for more information."
12056 (interactive "P")
12057 (cond
12058 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12059 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12060 ((org-at-item-p) (call-interactively 'org-move-item-down))
12061 (t (org-shiftcursor-error))))
12063 (defun org-metaleft (&optional arg)
12064 "Promote heading or move table column to left.
12065 Calls `org-do-promote' or `org-table-move-column', depending on context.
12066 With no specific context, calls the Emacs default `backward-word'.
12067 See the individual commands for more information."
12068 (interactive "P")
12069 (cond
12070 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12071 ((or (org-on-heading-p) (org-region-active-p))
12072 (call-interactively 'org-do-promote))
12073 ((org-at-item-p) (call-interactively 'org-outdent-item))
12074 (t (call-interactively 'backward-word))))
12076 (defun org-metaright (&optional arg)
12077 "Demote subtree or move table column to right.
12078 Calls `org-do-demote' or `org-table-move-column', depending on context.
12079 With no specific context, calls the Emacs default `forward-word'.
12080 See the individual commands for more information."
12081 (interactive "P")
12082 (cond
12083 ((org-at-table-p) (call-interactively 'org-table-move-column))
12084 ((or (org-on-heading-p) (org-region-active-p))
12085 (call-interactively 'org-do-demote))
12086 ((org-at-item-p) (call-interactively 'org-indent-item))
12087 (t (call-interactively 'forward-word))))
12089 (defun org-metaup (&optional arg)
12090 "Move subtree up or move table row up.
12091 Calls `org-move-subtree-up' or `org-table-move-row' or
12092 `org-move-item-up', depending on context. See the individual commands
12093 for more information."
12094 (interactive "P")
12095 (cond
12096 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12097 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12098 ((org-at-item-p) (call-interactively 'org-move-item-up))
12099 (t (transpose-lines 1) (beginning-of-line -1))))
12101 (defun org-metadown (&optional arg)
12102 "Move subtree down or move table row down.
12103 Calls `org-move-subtree-down' or `org-table-move-row' or
12104 `org-move-item-down', depending on context. See the individual
12105 commands for more information."
12106 (interactive "P")
12107 (cond
12108 ((org-at-table-p) (call-interactively 'org-table-move-row))
12109 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12110 ((org-at-item-p) (call-interactively 'org-move-item-down))
12111 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12113 (defun org-shiftup (&optional arg)
12114 "Increase item in timestamp or increase priority of current headline.
12115 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12116 depending on context. See the individual commands for more information."
12117 (interactive "P")
12118 (cond
12119 ((org-at-timestamp-p t)
12120 (call-interactively (if org-edit-timestamp-down-means-later
12121 'org-timestamp-down 'org-timestamp-up)))
12122 ((org-on-heading-p) (call-interactively 'org-priority-up))
12123 ((org-at-item-p) (call-interactively 'org-previous-item))
12124 ((org-clocktable-try-shift 'up arg))
12125 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12127 (defun org-shiftdown (&optional arg)
12128 "Decrease item in timestamp or decrease priority of current headline.
12129 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12130 depending on context. See the individual commands for more information."
12131 (interactive "P")
12132 (cond
12133 ((org-at-timestamp-p t)
12134 (call-interactively (if org-edit-timestamp-down-means-later
12135 'org-timestamp-up 'org-timestamp-down)))
12136 ((org-on-heading-p) (call-interactively 'org-priority-down))
12137 ((org-clocktable-try-shift 'down arg))
12138 (t (call-interactively 'org-next-item))))
12140 (defun org-shiftright (&optional arg)
12141 "Next TODO keyword or timestamp one day later, depending on context."
12142 (interactive "P")
12143 (cond
12144 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12145 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12146 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12147 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12148 ((org-clocktable-try-shift 'right arg))
12149 (t (org-shiftcursor-error))))
12151 (defun org-shiftleft (&optional arg)
12152 "Previous TODO keyword or timestamp one day earlier, depending on context."
12153 (interactive "P")
12154 (cond
12155 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12156 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12157 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12158 ((org-at-property-p)
12159 (call-interactively 'org-property-previous-allowed-value))
12160 ((org-clocktable-try-shift 'left arg))
12161 (t (org-shiftcursor-error))))
12163 (defun org-shiftcontrolright ()
12164 "Switch to next TODO set."
12165 (interactive)
12166 (cond
12167 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12168 (t (org-shiftcursor-error))))
12170 (defun org-shiftcontrolleft ()
12171 "Switch to previous TODO set."
12172 (interactive)
12173 (cond
12174 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12175 (t (org-shiftcursor-error))))
12177 (defun org-ctrl-c-ret ()
12178 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12179 (interactive)
12180 (cond
12181 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12182 (t (call-interactively 'org-insert-heading))))
12184 (defun org-copy-special ()
12185 "Copy region in table or copy current subtree.
12186 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12187 See the individual commands for more information."
12188 (interactive)
12189 (call-interactively
12190 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12192 (defun org-cut-special ()
12193 "Cut region in table or cut current subtree.
12194 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12195 See the individual commands for more information."
12196 (interactive)
12197 (call-interactively
12198 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12200 (defun org-paste-special (arg)
12201 "Paste rectangular region into table, or past subtree relative to level.
12202 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12203 See the individual commands for more information."
12204 (interactive "P")
12205 (if (org-at-table-p)
12206 (org-table-paste-rectangle)
12207 (org-paste-subtree arg)))
12209 (defun org-ctrl-c-ctrl-c (&optional arg)
12210 "Set tags in headline, or update according to changed information at point.
12212 This command does many different things, depending on context:
12214 - If the cursor is in a headline, prompt for tags and insert them
12215 into the current line, aligned to `org-tags-column'. When called
12216 with prefix arg, realign all tags in the current buffer.
12218 - If the cursor is in one of the special #+KEYWORD lines, this
12219 triggers scanning the buffer for these lines and updating the
12220 information.
12222 - If the cursor is inside a table, realign the table. This command
12223 works even if the automatic table editor has been turned off.
12225 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12226 the entire table.
12228 - If the cursor is a the beginning of a dynamic block, update it.
12230 - If the cursor is inside a table created by the table.el package,
12231 activate that table.
12233 - If the current buffer is a remember buffer, close note and file it.
12234 with a prefix argument, file it without further interaction to the default
12235 location.
12237 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12238 links in this buffer.
12240 - If the cursor is on a numbered item in a plain list, renumber the
12241 ordered list.
12243 - If the cursor is on a checkbox, toggle it."
12244 (interactive "P")
12245 (let ((org-enable-table-editor t))
12246 (cond
12247 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12248 org-occur-highlights
12249 org-latex-fragment-image-overlays)
12250 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12251 (org-remove-occur-highlights)
12252 (org-remove-latex-fragment-image-overlays)
12253 (message "Temporary highlights/overlays removed from current buffer"))
12254 ((and (local-variable-p 'org-finish-function (current-buffer))
12255 (fboundp org-finish-function))
12256 (funcall org-finish-function))
12257 ((org-at-property-p)
12258 (call-interactively 'org-property-action))
12259 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12260 ((org-on-heading-p) (call-interactively 'org-set-tags))
12261 ((org-at-table.el-p)
12262 (require 'table)
12263 (beginning-of-line 1)
12264 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12265 (call-interactively 'table-recognize-table))
12266 ((org-at-table-p)
12267 (org-table-maybe-eval-formula)
12268 (if arg
12269 (call-interactively 'org-table-recalculate)
12270 (org-table-maybe-recalculate-line))
12271 (call-interactively 'org-table-align))
12272 ((org-at-item-checkbox-p)
12273 (call-interactively 'org-toggle-checkbox))
12274 ((org-at-item-p)
12275 (call-interactively 'org-maybe-renumber-ordered-list))
12276 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12277 ;; Dynamic block
12278 (beginning-of-line 1)
12279 (org-update-dblock))
12280 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12281 (cond
12282 ((equal (match-string 1) "TBLFM")
12283 ;; Recalculate the table before this line
12284 (save-excursion
12285 (beginning-of-line 1)
12286 (skip-chars-backward " \r\n\t")
12287 (if (org-at-table-p)
12288 (org-call-with-arg 'org-table-recalculate t))))
12290 (call-interactively 'org-mode-restart))))
12291 (t (error "C-c C-c can do nothing useful at this location.")))))
12293 (defun org-mode-restart ()
12294 "Restart Org-mode, to scan again for special lines.
12295 Also updates the keyword regular expressions."
12296 (interactive)
12297 (let ((org-inhibit-startup t)) (org-mode))
12298 (message "Org-mode restarted to refresh keyword and special line setup"))
12300 (defun org-kill-note-or-show-branches ()
12301 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12302 (interactive)
12303 (if (not org-finish-function)
12304 (call-interactively 'show-branches)
12305 (let ((org-note-abort t))
12306 (funcall org-finish-function))))
12308 (defun org-return (&optional indent)
12309 "Goto next table row or insert a newline.
12310 Calls `org-table-next-row' or `newline', depending on context.
12311 See the individual commands for more information."
12312 (interactive)
12313 (cond
12314 ((bobp) (if indent (newline-and-indent) (newline)))
12315 ((and (org-at-heading-p)
12316 (looking-at
12317 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12318 (org-show-entry)
12319 (end-of-line 1)
12320 (newline))
12321 ((org-at-table-p)
12322 (org-table-justify-field-maybe)
12323 (call-interactively 'org-table-next-row))
12324 (t (if indent (newline-and-indent) (newline)))))
12326 (defun org-return-indent ()
12327 "Goto next table row or insert a newline and indent.
12328 Calls `org-table-next-row' or `newline-and-indent', depending on
12329 context. See the individual commands for more information."
12330 (interactive)
12331 (org-return t))
12333 (defun org-ctrl-c-star ()
12334 "Compute table, or change heading status of lines.
12335 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12336 depending on context. This will also turn a plain list item or a normal
12337 line into a subheading."
12338 (interactive)
12339 (cond
12340 ((org-at-table-p)
12341 (call-interactively 'org-table-recalculate))
12342 ((org-region-active-p)
12343 ;; Convert all lines in region to list items
12344 (call-interactively 'org-toggle-region-headings))
12345 ((org-on-heading-p)
12346 (org-toggle-region-headings (point-at-bol)
12347 (min (1+ (point-at-eol)) (point-max))))
12348 ((org-at-item-p)
12349 ;; Convert to heading
12350 (let ((level (save-match-data
12351 (save-excursion
12352 (condition-case nil
12353 (progn
12354 (org-back-to-heading t)
12355 (funcall outline-level))
12356 (error 0))))))
12357 (replace-match
12358 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12359 (t (org-toggle-region-headings (point-at-bol)
12360 (min (1+ (point-at-eol)) (point-max))))))
12362 (defun org-ctrl-c-minus ()
12363 "Insert separator line in table or modify bullet status of line.
12364 Also turns a plain line or a region of lines into list items.
12365 Calls `org-table-insert-hline', `org-toggle-region-items', or
12366 `org-cycle-list-bullet', depending on context."
12367 (interactive)
12368 (cond
12369 ((org-at-table-p)
12370 (call-interactively 'org-table-insert-hline))
12371 ((org-on-heading-p)
12372 ;; Convert to item
12373 (save-excursion
12374 (beginning-of-line 1)
12375 (if (looking-at "\\*+ ")
12376 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12377 ((org-region-active-p)
12378 ;; Convert all lines in region to list items
12379 (call-interactively 'org-toggle-region-items))
12380 ((org-in-item-p)
12381 (call-interactively 'org-cycle-list-bullet))
12382 (t (org-toggle-region-items (point-at-bol)
12383 (min (1+ (point-at-eol)) (point-max))))))
12385 (defun org-toggle-region-items (beg end)
12386 "Convert all lines in region to list items.
12387 If the first line is already an item, convert all list items in the region
12388 to normal lines."
12389 (interactive "r")
12390 (let (l2 l)
12391 (save-excursion
12392 (goto-char end)
12393 (setq l2 (org-current-line))
12394 (goto-char beg)
12395 (beginning-of-line 1)
12396 (setq l (1- (org-current-line)))
12397 (if (org-at-item-p)
12398 ;; We already have items, de-itemize
12399 (while (< (setq l (1+ l)) l2)
12400 (when (org-at-item-p)
12401 (goto-char (match-beginning 2))
12402 (delete-region (match-beginning 2) (match-end 2))
12403 (and (looking-at "[ \t]+") (replace-match "")))
12404 (beginning-of-line 2))
12405 (while (< (setq l (1+ l)) l2)
12406 (unless (org-at-item-p)
12407 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12408 (replace-match "\\1- \\2")))
12409 (beginning-of-line 2))))))
12411 (defun org-toggle-region-headings (beg end)
12412 "Convert all lines in region to list items.
12413 If the first line is already an item, convert all list items in the region
12414 to normal lines."
12415 (interactive "r")
12416 (let (l2 l)
12417 (save-excursion
12418 (goto-char end)
12419 (setq l2 (org-current-line))
12420 (goto-char beg)
12421 (beginning-of-line 1)
12422 (setq l (1- (org-current-line)))
12423 (if (org-on-heading-p)
12424 ;; We already have headlines, de-star them
12425 (while (< (setq l (1+ l)) l2)
12426 (when (org-on-heading-p t)
12427 (and (looking-at outline-regexp) (replace-match "")))
12428 (beginning-of-line 2))
12429 (let* ((stars (save-excursion
12430 (re-search-backward org-complex-heading-regexp nil t)
12431 (or (match-string 1) "*")))
12432 (add-stars (if org-odd-levels-only "**" "*"))
12433 (rpl (concat stars add-stars " \\2")))
12434 (while (< (setq l (1+ l)) l2)
12435 (unless (org-on-heading-p)
12436 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12437 (replace-match rpl)))
12438 (beginning-of-line 2)))))))
12440 (defun org-meta-return (&optional arg)
12441 "Insert a new heading or wrap a region in a table.
12442 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12443 See the individual commands for more information."
12444 (interactive "P")
12445 (cond
12446 ((org-at-table-p)
12447 (call-interactively 'org-table-wrap-region))
12448 (t (call-interactively 'org-insert-heading))))
12450 ;;; Menu entries
12452 ;; Define the Org-mode menus
12453 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12454 '("Tbl"
12455 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12456 ["Next Field" org-cycle (org-at-table-p)]
12457 ["Previous Field" org-shifttab (org-at-table-p)]
12458 ["Next Row" org-return (org-at-table-p)]
12459 "--"
12460 ["Blank Field" org-table-blank-field (org-at-table-p)]
12461 ["Edit Field" org-table-edit-field (org-at-table-p)]
12462 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12463 "--"
12464 ("Column"
12465 ["Move Column Left" org-metaleft (org-at-table-p)]
12466 ["Move Column Right" org-metaright (org-at-table-p)]
12467 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12468 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12469 ("Row"
12470 ["Move Row Up" org-metaup (org-at-table-p)]
12471 ["Move Row Down" org-metadown (org-at-table-p)]
12472 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12473 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12474 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12475 "--"
12476 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12477 ("Rectangle"
12478 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12479 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12480 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12481 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12482 "--"
12483 ("Calculate"
12484 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12485 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12486 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12487 "--"
12488 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12489 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12490 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12491 "--"
12492 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12493 "--"
12494 ["Sum Column/Rectangle" org-table-sum
12495 (or (org-at-table-p) (org-region-active-p))]
12496 ["Which Column?" org-table-current-column (org-at-table-p)])
12497 ["Debug Formulas"
12498 org-table-toggle-formula-debugger
12499 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12500 ["Show Col/Row Numbers"
12501 org-table-toggle-coordinate-overlays
12502 :style toggle
12503 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12504 "--"
12505 ["Create" org-table-create (and (not (org-at-table-p))
12506 org-enable-table-editor)]
12507 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12508 ["Import from File" org-table-import (not (org-at-table-p))]
12509 ["Export to File" org-table-export (org-at-table-p)]
12510 "--"
12511 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12513 (easy-menu-define org-org-menu org-mode-map "Org menu"
12514 '("Org"
12515 ("Show/Hide"
12516 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12517 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12518 ["Sparse Tree..." org-sparse-tree t]
12519 ["Reveal Context" org-reveal t]
12520 ["Show All" show-all t]
12521 "--"
12522 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12523 "--"
12524 ["New Heading" org-insert-heading t]
12525 ("Navigate Headings"
12526 ["Up" outline-up-heading t]
12527 ["Next" outline-next-visible-heading t]
12528 ["Previous" outline-previous-visible-heading t]
12529 ["Next Same Level" outline-forward-same-level t]
12530 ["Previous Same Level" outline-backward-same-level t]
12531 "--"
12532 ["Jump" org-goto t])
12533 ("Edit Structure"
12534 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12535 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12536 "--"
12537 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12538 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12539 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12540 "--"
12541 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12542 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12543 ["Demote Heading" org-metaright (not (org-at-table-p))]
12544 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12545 "--"
12546 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12547 "--"
12548 ["Convert to odd levels" org-convert-to-odd-levels t]
12549 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12550 ("Editing"
12551 ["Emphasis..." org-emphasize t])
12552 ("Archive"
12553 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12554 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12555 ; :active t :keys "C-u C-c C-x C-a"]
12556 ["Sparse trees open ARCHIVE trees"
12557 (setq org-sparse-tree-open-archived-trees
12558 (not org-sparse-tree-open-archived-trees))
12559 :style toggle :selected org-sparse-tree-open-archived-trees]
12560 ["Cycling opens ARCHIVE trees"
12561 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12562 :style toggle :selected org-cycle-open-archived-trees]
12563 ["Agenda includes ARCHIVE trees"
12564 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12565 :style toggle :selected (not org-agenda-skip-archived-trees)]
12566 "--"
12567 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12568 ; ["Check and Move Children" (org-archive-subtree '(4))
12569 ; :active t :keys "C-u C-c C-x C-s"]
12571 "--"
12572 ("TODO Lists"
12573 ["TODO/DONE/-" org-todo t]
12574 ("Select keyword"
12575 ["Next keyword" org-shiftright (org-on-heading-p)]
12576 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12577 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12578 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12579 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12580 ["Show TODO Tree" org-show-todo-tree t]
12581 ["Global TODO list" org-todo-list t]
12582 "--"
12583 ["Set Priority" org-priority t]
12584 ["Priority Up" org-shiftup t]
12585 ["Priority Down" org-shiftdown t])
12586 ("TAGS and Properties"
12587 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12588 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12589 "--"
12590 ["Set property" 'org-set-property t]
12591 ["Column view of properties" org-columns t]
12592 ["Insert Column View DBlock" org-insert-columns-dblock t])
12593 ("Dates and Scheduling"
12594 ["Timestamp" org-time-stamp t]
12595 ["Timestamp (inactive)" org-time-stamp-inactive t]
12596 ("Change Date"
12597 ["1 Day Later" org-shiftright t]
12598 ["1 Day Earlier" org-shiftleft t]
12599 ["1 ... Later" org-shiftup t]
12600 ["1 ... Earlier" org-shiftdown t])
12601 ["Compute Time Range" org-evaluate-time-range t]
12602 ["Schedule Item" org-schedule t]
12603 ["Deadline" org-deadline t]
12604 "--"
12605 ["Custom time format" org-toggle-time-stamp-overlays
12606 :style radio :selected org-display-custom-times]
12607 "--"
12608 ["Goto Calendar" org-goto-calendar t]
12609 ["Date from Calendar" org-date-from-calendar t])
12610 ("Logging work"
12611 ["Clock in" org-clock-in t]
12612 ["Clock out" org-clock-out t]
12613 ["Clock cancel" org-clock-cancel t]
12614 ["Goto running clock" org-clock-goto t]
12615 ["Display times" org-clock-display t]
12616 ["Create clock table" org-clock-report t]
12617 "--"
12618 ["Record DONE time"
12619 (progn (setq org-log-done (not org-log-done))
12620 (message "Switching to %s will %s record a timestamp"
12621 (car org-done-keywords)
12622 (if org-log-done "automatically" "not")))
12623 :style toggle :selected org-log-done])
12624 "--"
12625 ["Agenda Command..." org-agenda t]
12626 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12627 ("File List for Agenda")
12628 ("Special views current file"
12629 ["TODO Tree" org-show-todo-tree t]
12630 ["Check Deadlines" org-check-deadlines t]
12631 ["Timeline" org-timeline t]
12632 ["Tags Tree" org-tags-sparse-tree t])
12633 "--"
12634 ("Hyperlinks"
12635 ["Store Link (Global)" org-store-link t]
12636 ["Insert Link" org-insert-link t]
12637 ["Follow Link" org-open-at-point t]
12638 "--"
12639 ["Next link" org-next-link t]
12640 ["Previous link" org-previous-link t]
12641 "--"
12642 ["Descriptive Links"
12643 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12644 :style radio
12645 :selected (member '(org-link) buffer-invisibility-spec)]
12646 ["Literal Links"
12647 (progn
12648 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12649 :style radio
12650 :selected (not (member '(org-link) buffer-invisibility-spec))])
12651 "--"
12652 ["Export/Publish..." org-export t]
12653 ("LaTeX"
12654 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12655 :selected org-cdlatex-mode]
12656 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12657 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12658 ["Modify math symbol" org-cdlatex-math-modify
12659 (org-inside-LaTeX-fragment-p)]
12660 ["Export LaTeX fragments as images"
12661 (if (featurep 'org-exp)
12662 (setq org-export-with-LaTeX-fragments
12663 (not org-export-with-LaTeX-fragments))
12664 (require 'org-exp))
12665 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12666 org-export-with-LaTeX-fragments)])
12667 "--"
12668 ("Documentation"
12669 ["Show Version" org-version t]
12670 ["Info Documentation" org-info t])
12671 ("Customize"
12672 ["Browse Org Group" org-customize t]
12673 "--"
12674 ["Expand This Menu" org-create-customize-menu
12675 (fboundp 'customize-menu-create)])
12676 "--"
12677 ["Refresh setup" org-mode-restart t]
12680 (defun org-info (&optional node)
12681 "Read documentation for Org-mode in the info system.
12682 With optional NODE, go directly to that node."
12683 (interactive)
12684 (info (format "(org)%s" (or node ""))))
12686 (defun org-install-agenda-files-menu ()
12687 (let ((bl (buffer-list)))
12688 (save-excursion
12689 (while bl
12690 (set-buffer (pop bl))
12691 (if (org-mode-p) (setq bl nil)))
12692 (when (org-mode-p)
12693 (easy-menu-change
12694 '("Org") "File List for Agenda"
12695 (append
12696 (list
12697 ["Edit File List" (org-edit-agenda-file-list) t]
12698 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12699 ["Remove Current File from List" org-remove-file t]
12700 ["Cycle through agenda files" org-cycle-agenda-files t]
12701 ["Occur in all agenda files" org-occur-in-agenda-files t]
12702 "--")
12703 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12705 ;;;; Documentation
12707 (defun org-require-autoloaded-modules ()
12708 (interactive)
12709 (mapc 'require
12710 '(org-agenda org-archive org-clock org-colview
12711 org-exp org-export-latex org-publish
12712 org-remember org-table)))
12714 (defun org-customize ()
12715 "Call the customize function with org as argument."
12716 (interactive)
12717 (org-load-modules-maybe)
12718 (org-require-autoloaded-modules)
12719 (customize-browse 'org))
12721 (defun org-create-customize-menu ()
12722 "Create a full customization menu for Org-mode, insert it into the menu."
12723 (interactive)
12724 (org-load-modules-maybe)
12725 (org-require-autoloaded-modules)
12726 (if (fboundp 'customize-menu-create)
12727 (progn
12728 (easy-menu-change
12729 '("Org") "Customize"
12730 `(["Browse Org group" org-customize t]
12731 "--"
12732 ,(customize-menu-create 'org)
12733 ["Set" Custom-set t]
12734 ["Save" Custom-save t]
12735 ["Reset to Current" Custom-reset-current t]
12736 ["Reset to Saved" Custom-reset-saved t]
12737 ["Reset to Standard Settings" Custom-reset-standard t]))
12738 (message "\"Org\"-menu now contains full customization menu"))
12739 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12741 ;;;; Miscellaneous stuff
12743 ;;; Generally useful functions
12745 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12746 "Display the given MESSAGE as a warning."
12747 (if (fboundp 'display-warning)
12748 (display-warning 'org message
12749 (if (featurep 'xemacs)
12750 'warning
12751 :warning))
12752 (let ((buf (get-buffer-create "*Org warnings*")))
12753 (with-current-buffer buf
12754 (goto-char (point-max))
12755 (insert "Warning (Org): " message)
12756 (unless (bolp)
12757 (newline)))
12758 (display-buffer buf)
12759 (sit-for 0))))
12761 (defun org-plist-delete (plist property)
12762 "Delete PROPERTY from PLIST.
12763 This is in contrast to merely setting it to 0."
12764 (let (p)
12765 (while plist
12766 (if (not (eq property (car plist)))
12767 (setq p (plist-put p (car plist) (nth 1 plist))))
12768 (setq plist (cddr plist)))
12771 (defun org-force-self-insert (N)
12772 "Needed to enforce self-insert under remapping."
12773 (interactive "p")
12774 (self-insert-command N))
12776 (defun org-string-width (s)
12777 "Compute width of string, ignoring invisible characters.
12778 This ignores character with invisibility property `org-link', and also
12779 characters with property `org-cwidth', because these will become invisible
12780 upon the next fontification round."
12781 (let (b l)
12782 (when (or (eq t buffer-invisibility-spec)
12783 (assq 'org-link buffer-invisibility-spec))
12784 (while (setq b (text-property-any 0 (length s)
12785 'invisible 'org-link s))
12786 (setq s (concat (substring s 0 b)
12787 (substring s (or (next-single-property-change
12788 b 'invisible s) (length s)))))))
12789 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12790 (setq s (concat (substring s 0 b)
12791 (substring s (or (next-single-property-change
12792 b 'org-cwidth s) (length s))))))
12793 (setq l (string-width s) b -1)
12794 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12795 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12798 (defun org-base-buffer (buffer)
12799 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12800 (if (not buffer)
12801 buffer
12802 (or (buffer-base-buffer buffer)
12803 buffer)))
12805 (defun org-trim (s)
12806 "Remove whitespace at beginning and end of string."
12807 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12808 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12811 (defun org-wrap (string &optional width lines)
12812 "Wrap string to either a number of lines, or a width in characters.
12813 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12814 that costs. If there is a word longer than WIDTH, the text is actually
12815 wrapped to the length of that word.
12816 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12817 many lines, whatever width that takes.
12818 The return value is a list of lines, without newlines at the end."
12819 (let* ((words (org-split-string string "[ \t\n]+"))
12820 (maxword (apply 'max (mapcar 'org-string-width words)))
12821 w ll)
12822 (cond (width
12823 (org-do-wrap words (max maxword width)))
12824 (lines
12825 (setq w maxword)
12826 (setq ll (org-do-wrap words maxword))
12827 (if (<= (length ll) lines)
12829 (setq ll words)
12830 (while (> (length ll) lines)
12831 (setq w (1+ w))
12832 (setq ll (org-do-wrap words w)))
12833 ll))
12834 (t (error "Cannot wrap this")))))
12836 (defun org-do-wrap (words width)
12837 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12838 (let (lines line)
12839 (while words
12840 (setq line (pop words))
12841 (while (and words (< (+ (length line) (length (car words))) width))
12842 (setq line (concat line " " (pop words))))
12843 (setq lines (push line lines)))
12844 (nreverse lines)))
12846 (defun org-split-string (string &optional separators)
12847 "Splits STRING into substrings at SEPARATORS.
12848 No empty strings are returned if there are matches at the beginning
12849 and end of string."
12850 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12851 (start 0)
12852 notfirst
12853 (list nil))
12854 (while (and (string-match rexp string
12855 (if (and notfirst
12856 (= start (match-beginning 0))
12857 (< start (length string)))
12858 (1+ start) start))
12859 (< (match-beginning 0) (length string)))
12860 (setq notfirst t)
12861 (or (eq (match-beginning 0) 0)
12862 (and (eq (match-beginning 0) (match-end 0))
12863 (eq (match-beginning 0) start))
12864 (setq list
12865 (cons (substring string start (match-beginning 0))
12866 list)))
12867 (setq start (match-end 0)))
12868 (or (eq start (length string))
12869 (setq list
12870 (cons (substring string start)
12871 list)))
12872 (nreverse list)))
12874 (defun org-context ()
12875 "Return a list of contexts of the current cursor position.
12876 If several contexts apply, all are returned.
12877 Each context entry is a list with a symbol naming the context, and
12878 two positions indicating start and end of the context. Possible
12879 contexts are:
12881 :headline anywhere in a headline
12882 :headline-stars on the leading stars in a headline
12883 :todo-keyword on a TODO keyword (including DONE) in a headline
12884 :tags on the TAGS in a headline
12885 :priority on the priority cookie in a headline
12886 :item on the first line of a plain list item
12887 :item-bullet on the bullet/number of a plain list item
12888 :checkbox on the checkbox in a plain list item
12889 :table in an org-mode table
12890 :table-special on a special filed in a table
12891 :table-table in a table.el table
12892 :link on a hyperlink
12893 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12894 :target on a <<target>>
12895 :radio-target on a <<<radio-target>>>
12896 :latex-fragment on a LaTeX fragment
12897 :latex-preview on a LaTeX fragment with overlayed preview image
12899 This function expects the position to be visible because it uses font-lock
12900 faces as a help to recognize the following contexts: :table-special, :link,
12901 and :keyword."
12902 (let* ((f (get-text-property (point) 'face))
12903 (faces (if (listp f) f (list f)))
12904 (p (point)) clist o)
12905 ;; First the large context
12906 (cond
12907 ((org-on-heading-p t)
12908 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12909 (when (progn
12910 (beginning-of-line 1)
12911 (looking-at org-todo-line-tags-regexp))
12912 (push (org-point-in-group p 1 :headline-stars) clist)
12913 (push (org-point-in-group p 2 :todo-keyword) clist)
12914 (push (org-point-in-group p 4 :tags) clist))
12915 (goto-char p)
12916 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12917 (if (looking-at "\\[#[A-Z0-9]\\]")
12918 (push (org-point-in-group p 0 :priority) clist)))
12920 ((org-at-item-p)
12921 (push (org-point-in-group p 2 :item-bullet) clist)
12922 (push (list :item (point-at-bol)
12923 (save-excursion (org-end-of-item) (point)))
12924 clist)
12925 (and (org-at-item-checkbox-p)
12926 (push (org-point-in-group p 0 :checkbox) clist)))
12928 ((org-at-table-p)
12929 (push (list :table (org-table-begin) (org-table-end)) clist)
12930 (if (memq 'org-formula faces)
12931 (push (list :table-special
12932 (previous-single-property-change p 'face)
12933 (next-single-property-change p 'face)) clist)))
12934 ((org-at-table-p 'any)
12935 (push (list :table-table) clist)))
12936 (goto-char p)
12938 ;; Now the small context
12939 (cond
12940 ((org-at-timestamp-p)
12941 (push (org-point-in-group p 0 :timestamp) clist))
12942 ((memq 'org-link faces)
12943 (push (list :link
12944 (previous-single-property-change p 'face)
12945 (next-single-property-change p 'face)) clist))
12946 ((memq 'org-special-keyword faces)
12947 (push (list :keyword
12948 (previous-single-property-change p 'face)
12949 (next-single-property-change p 'face)) clist))
12950 ((org-on-target-p)
12951 (push (org-point-in-group p 0 :target) clist)
12952 (goto-char (1- (match-beginning 0)))
12953 (if (looking-at org-radio-target-regexp)
12954 (push (org-point-in-group p 0 :radio-target) clist))
12955 (goto-char p))
12956 ((setq o (car (delq nil
12957 (mapcar
12958 (lambda (x)
12959 (if (memq x org-latex-fragment-image-overlays) x))
12960 (org-overlays-at (point))))))
12961 (push (list :latex-fragment
12962 (org-overlay-start o) (org-overlay-end o)) clist)
12963 (push (list :latex-preview
12964 (org-overlay-start o) (org-overlay-end o)) clist))
12965 ((org-inside-LaTeX-fragment-p)
12966 ;; FIXME: positions wrong.
12967 (push (list :latex-fragment (point) (point)) clist)))
12969 (setq clist (nreverse (delq nil clist)))
12970 clist))
12972 ;; FIXME: Compare with at-regexp-p Do we need both?
12973 (defun org-in-regexp (re &optional nlines visually)
12974 "Check if point is inside a match of regexp.
12975 Normally only the current line is checked, but you can include NLINES extra
12976 lines both before and after point into the search.
12977 If VISUALLY is set, require that the cursor is not after the match but
12978 really on, so that the block visually is on the match."
12979 (catch 'exit
12980 (let ((pos (point))
12981 (eol (point-at-eol (+ 1 (or nlines 0))))
12982 (inc (if visually 1 0)))
12983 (save-excursion
12984 (beginning-of-line (- 1 (or nlines 0)))
12985 (while (re-search-forward re eol t)
12986 (if (and (<= (match-beginning 0) pos)
12987 (>= (+ inc (match-end 0)) pos))
12988 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12990 (defun org-at-regexp-p (regexp)
12991 "Is point inside a match of REGEXP in the current line?"
12992 (catch 'exit
12993 (save-excursion
12994 (let ((pos (point)) (end (point-at-eol)))
12995 (beginning-of-line 1)
12996 (while (re-search-forward regexp end t)
12997 (if (and (<= (match-beginning 0) pos)
12998 (>= (match-end 0) pos))
12999 (throw 'exit t)))
13000 nil))))
13002 (defun org-occur-in-agenda-files (regexp &optional nlines)
13003 "Call `multi-occur' with buffers for all agenda files."
13004 (interactive "sOrg-files matching: \np")
13005 (let* ((files (org-agenda-files))
13006 (tnames (mapcar 'file-truename files))
13007 (extra org-agenda-text-search-extra-files)
13009 (when (eq (car extra) 'agenda-archives)
13010 (setq extra (cdr extra))
13011 (setq files (org-add-archive-files files)))
13012 (while (setq f (pop extra))
13013 (unless (member (file-truename f) tnames)
13014 (add-to-list 'files f 'append)
13015 (add-to-list 'tnames (file-truename f) 'append)))
13016 (multi-occur
13017 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13018 regexp)))
13020 (if (boundp 'occur-mode-find-occurrence-hook)
13021 ;; Emacs 23
13022 (add-hook 'occur-mode-find-occurrence-hook
13023 (lambda ()
13024 (when (org-mode-p)
13025 (org-reveal))))
13026 ;; Emacs 22
13027 (defadvice occur-mode-goto-occurrence
13028 (after org-occur-reveal activate)
13029 (and (org-mode-p) (org-reveal)))
13030 (defadvice occur-mode-goto-occurrence-other-window
13031 (after org-occur-reveal activate)
13032 (and (org-mode-p) (org-reveal)))
13033 (defadvice occur-mode-display-occurrence
13034 (after org-occur-reveal activate)
13035 (when (org-mode-p)
13036 (let ((pos (occur-mode-find-occurrence)))
13037 (with-current-buffer (marker-buffer pos)
13038 (save-excursion
13039 (goto-char pos)
13040 (org-reveal)))))))
13042 (defun org-uniquify (list)
13043 "Remove duplicate elements from LIST."
13044 (let (res)
13045 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13046 res))
13048 (defun org-delete-all (elts list)
13049 "Remove all elements in ELTS from LIST."
13050 (while elts
13051 (setq list (delete (pop elts) list)))
13052 list)
13054 (defun org-back-over-empty-lines ()
13055 "Move backwards over witespace, to the beginning of the first empty line.
13056 Returns the number of empty lines passed."
13057 (let ((pos (point)))
13058 (skip-chars-backward " \t\n\r")
13059 (beginning-of-line 2)
13060 (goto-char (min (point) pos))
13061 (count-lines (point) pos)))
13063 (defun org-skip-whitespace ()
13064 (skip-chars-forward " \t\n\r"))
13066 (defun org-point-in-group (point group &optional context)
13067 "Check if POINT is in match-group GROUP.
13068 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13069 match. If the match group does ot exist or point is not inside it,
13070 return nil."
13071 (and (match-beginning group)
13072 (>= point (match-beginning group))
13073 (<= point (match-end group))
13074 (if context
13075 (list context (match-beginning group) (match-end group))
13076 t)))
13078 (defun org-switch-to-buffer-other-window (&rest args)
13079 "Switch to buffer in a second window on the current frame.
13080 In particular, do not allow pop-up frames."
13081 (let (pop-up-frames special-display-buffer-names special-display-regexps
13082 special-display-function)
13083 (apply 'switch-to-buffer-other-window args)))
13085 (defun org-combine-plists (&rest plists)
13086 "Create a single property list from all plists in PLISTS.
13087 The process starts by copying the first list, and then setting properties
13088 from the other lists. Settings in the last list are the most significant
13089 ones and overrule settings in the other lists."
13090 (let ((rtn (copy-sequence (pop plists)))
13091 p v ls)
13092 (while plists
13093 (setq ls (pop plists))
13094 (while ls
13095 (setq p (pop ls) v (pop ls))
13096 (setq rtn (plist-put rtn p v))))
13097 rtn))
13099 (defun org-move-line-down (arg)
13100 "Move the current line down. With prefix argument, move it past ARG lines."
13101 (interactive "p")
13102 (let ((col (current-column))
13103 beg end pos)
13104 (beginning-of-line 1) (setq beg (point))
13105 (beginning-of-line 2) (setq end (point))
13106 (beginning-of-line (+ 1 arg))
13107 (setq pos (move-marker (make-marker) (point)))
13108 (insert (delete-and-extract-region beg end))
13109 (goto-char pos)
13110 (org-move-to-column col)))
13112 (defun org-move-line-up (arg)
13113 "Move the current line up. With prefix argument, move it past ARG lines."
13114 (interactive "p")
13115 (let ((col (current-column))
13116 beg end pos)
13117 (beginning-of-line 1) (setq beg (point))
13118 (beginning-of-line 2) (setq end (point))
13119 (beginning-of-line (- arg))
13120 (setq pos (move-marker (make-marker) (point)))
13121 (insert (delete-and-extract-region beg end))
13122 (goto-char pos)
13123 (org-move-to-column col)))
13125 (defun org-replace-escapes (string table)
13126 "Replace %-escapes in STRING with values in TABLE.
13127 TABLE is an association list with keys like \"%a\" and string values.
13128 The sequences in STRING may contain normal field width and padding information,
13129 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13130 so values can contain further %-escapes if they are define later in TABLE."
13131 (let ((case-fold-search nil)
13132 e re rpl)
13133 (while (setq e (pop table))
13134 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13135 (while (string-match re string)
13136 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13137 (cdr e)))
13138 (setq string (replace-match rpl t t string))))
13139 string))
13142 (defun org-sublist (list start end)
13143 "Return a section of LIST, from START to END.
13144 Counting starts at 1."
13145 (let (rtn (c start))
13146 (setq list (nthcdr (1- start) list))
13147 (while (and list (<= c end))
13148 (push (pop list) rtn)
13149 (setq c (1+ c)))
13150 (nreverse rtn)))
13152 (defun org-find-base-buffer-visiting (file)
13153 "Like `find-buffer-visiting' but alway return the base buffer and
13154 not an indirect buffer."
13155 (let ((buf (find-buffer-visiting file)))
13156 (if buf
13157 (or (buffer-base-buffer buf) buf)
13158 nil)))
13160 (defun org-image-file-name-regexp ()
13161 "Return regexp matching the file names of images."
13162 (if (fboundp 'image-file-name-regexp)
13163 (image-file-name-regexp)
13164 (let ((image-file-name-extensions
13165 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13166 "xbm" "xpm" "pbm" "pgm" "ppm")))
13167 (concat "\\."
13168 (regexp-opt (nconc (mapcar 'upcase
13169 image-file-name-extensions)
13170 image-file-name-extensions)
13172 "\\'"))))
13174 (defun org-file-image-p (file)
13175 "Return non-nil if FILE is an image."
13176 (save-match-data
13177 (string-match (org-image-file-name-regexp) file)))
13179 ;;; Paragraph filling stuff.
13180 ;; We want this to be just right, so use the full arsenal.
13182 (defun org-indent-line-function ()
13183 "Indent line like previous, but further if previous was headline or item."
13184 (interactive)
13185 (let* ((pos (point))
13186 (itemp (org-at-item-p))
13187 column bpos bcol tpos tcol bullet btype bullet-type)
13188 ;; Find the previous relevant line
13189 (beginning-of-line 1)
13190 (cond
13191 ((looking-at "#") (setq column 0))
13192 ((looking-at "\\*+ ") (setq column 0))
13194 (beginning-of-line 0)
13195 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13196 (beginning-of-line 0))
13197 (cond
13198 ((looking-at "\\*+[ \t]+")
13199 (goto-char (match-end 0))
13200 (setq column (current-column)))
13201 ((org-in-item-p)
13202 (org-beginning-of-item)
13203 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13204 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13205 (setq bpos (match-beginning 1) tpos (match-end 0)
13206 bcol (progn (goto-char bpos) (current-column))
13207 tcol (progn (goto-char tpos) (current-column))
13208 bullet (match-string 1)
13209 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13210 (if (not itemp)
13211 (setq column tcol)
13212 (goto-char pos)
13213 (beginning-of-line 1)
13214 (if (looking-at "\\S-")
13215 (progn
13216 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13217 (setq bullet (match-string 1)
13218 btype (if (string-match "[0-9]" bullet) "n" bullet))
13219 (setq column (if (equal btype bullet-type) bcol tcol)))
13220 (setq column (org-get-indentation)))))
13221 (t (setq column (org-get-indentation))))))
13222 (goto-char pos)
13223 (if (<= (current-column) (current-indentation))
13224 (org-indent-line-to column)
13225 (save-excursion (org-indent-line-to column)))
13226 (setq column (current-column))
13227 (beginning-of-line 1)
13228 (if (looking-at
13229 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13230 (replace-match (concat "\\1" (format org-property-format
13231 (match-string 2) (match-string 3)))
13232 t nil))
13233 (org-move-to-column column)))
13235 (defun org-set-autofill-regexps ()
13236 (interactive)
13237 ;; In the paragraph separator we include headlines, because filling
13238 ;; text in a line directly attached to a headline would otherwise
13239 ;; fill the headline as well.
13240 (org-set-local 'comment-start-skip "^#+[ \t]*")
13241 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13242 ;; The paragraph starter includes hand-formatted lists.
13243 (org-set-local 'paragraph-start
13244 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13245 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13246 ;; But only if the user has not turned off tables or fixed-width regions
13247 (org-set-local
13248 'auto-fill-inhibit-regexp
13249 (concat "\\*+ \\|#\\+"
13250 "\\|[ \t]*" org-keyword-time-regexp
13251 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13252 (concat
13253 "\\|[ \t]*["
13254 (if org-enable-table-editor "|" "")
13255 (if org-enable-fixed-width-editor ":" "")
13256 "]"))))
13257 ;; We use our own fill-paragraph function, to make sure that tables
13258 ;; and fixed-width regions are not wrapped. That function will pass
13259 ;; through to `fill-paragraph' when appropriate.
13260 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13261 ; Adaptive filling: To get full control, first make sure that
13262 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13263 (org-set-local 'adaptive-fill-regexp "\000")
13264 (org-set-local 'adaptive-fill-function
13265 'org-adaptive-fill-function)
13266 (org-set-local
13267 'align-mode-rules-list
13268 '((org-in-buffer-settings
13269 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13270 (modes . '(org-mode))))))
13272 (defun org-fill-paragraph (&optional justify)
13273 "Re-align a table, pass through to fill-paragraph if no table."
13274 (let ((table-p (org-at-table-p))
13275 (table.el-p (org-at-table.el-p)))
13276 (cond ((and (equal (char-after (point-at-bol)) ?*)
13277 (save-excursion (goto-char (point-at-bol))
13278 (looking-at outline-regexp)))
13279 t) ; skip headlines
13280 (table.el-p t) ; skip table.el tables
13281 (table-p (org-table-align) t) ; align org-mode tables
13282 (t nil)))) ; call paragraph-fill
13284 ;; For reference, this is the default value of adaptive-fill-regexp
13285 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13287 (defun org-adaptive-fill-function ()
13288 "Return a fill prefix for org-mode files.
13289 In particular, this makes sure hanging paragraphs for hand-formatted lists
13290 work correctly."
13291 (cond ((looking-at "#[ \t]+")
13292 (match-string 0))
13293 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13294 (save-excursion
13295 (goto-char (match-end 0))
13296 (make-string (current-column) ?\ )))
13297 (t nil)))
13299 ;;; Other stuff.
13301 (defun org-toggle-fixed-width-section (arg)
13302 "Toggle the fixed-width export.
13303 If there is no active region, the QUOTE keyword at the current headline is
13304 inserted or removed. When present, it causes the text between this headline
13305 and the next to be exported as fixed-width text, and unmodified.
13306 If there is an active region, this command adds or removes a colon as the
13307 first character of this line. If the first character of a line is a colon,
13308 this line is also exported in fixed-width font."
13309 (interactive "P")
13310 (let* ((cc 0)
13311 (regionp (org-region-active-p))
13312 (beg (if regionp (region-beginning) (point)))
13313 (end (if regionp (region-end)))
13314 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13315 (case-fold-search nil)
13316 (re "[ \t]*\\(:\\)")
13317 off)
13318 (if regionp
13319 (save-excursion
13320 (goto-char beg)
13321 (setq cc (current-column))
13322 (beginning-of-line 1)
13323 (setq off (looking-at re))
13324 (while (> nlines 0)
13325 (setq nlines (1- nlines))
13326 (beginning-of-line 1)
13327 (cond
13328 (arg
13329 (org-move-to-column cc t)
13330 (insert ":\n")
13331 (forward-line -1))
13332 ((and off (looking-at re))
13333 (replace-match "" t t nil 1))
13334 ((not off) (org-move-to-column cc t) (insert ":")))
13335 (forward-line 1)))
13336 (save-excursion
13337 (org-back-to-heading)
13338 (if (looking-at (concat outline-regexp
13339 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13340 (replace-match "" t t nil 1)
13341 (if (looking-at outline-regexp)
13342 (progn
13343 (goto-char (match-end 0))
13344 (insert org-quote-string " "))))))))
13346 ;;;; Functions extending outline functionality
13348 (defun org-beginning-of-line (&optional arg)
13349 "Go to the beginning of the current line. If that is invisible, continue
13350 to a visible line beginning. This makes the function of C-a more intuitive.
13351 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13352 first attempt, and only move to after the tags when the cursor is already
13353 beyond the end of the headline."
13354 (interactive "P")
13355 (let ((pos (point)))
13356 (beginning-of-line 1)
13357 (if (bobp)
13359 (backward-char 1)
13360 (if (org-invisible-p)
13361 (while (and (not (bobp)) (org-invisible-p))
13362 (backward-char 1)
13363 (beginning-of-line 1))
13364 (forward-char 1)))
13365 (when org-special-ctrl-a/e
13366 (cond
13367 ((and (looking-at org-todo-line-regexp)
13368 (= (char-after (match-end 1)) ?\ ))
13369 (goto-char
13370 (if (eq org-special-ctrl-a/e t)
13371 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13372 ((= pos (point)) (match-beginning 3))
13373 (t (point)))
13374 (cond ((> pos (point)) (point))
13375 ((not (eq last-command this-command)) (point))
13376 (t (match-beginning 3))))))
13377 ((org-at-item-p)
13378 (goto-char
13379 (if (eq org-special-ctrl-a/e t)
13380 (cond ((> pos (match-end 4)) (match-end 4))
13381 ((= pos (point)) (match-end 4))
13382 (t (point)))
13383 (cond ((> pos (point)) (point))
13384 ((not (eq last-command this-command)) (point))
13385 (t (match-end 4))))))))))
13387 (defun org-end-of-line (&optional arg)
13388 "Go to the end of the line.
13389 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13390 first attempt, and only move to after the tags when the cursor is already
13391 beyond the end of the headline."
13392 (interactive "P")
13393 (if (or (not org-special-ctrl-a/e)
13394 (not (org-on-heading-p)))
13395 (end-of-line arg)
13396 (let ((pos (point)))
13397 (beginning-of-line 1)
13398 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13399 (if (eq org-special-ctrl-a/e t)
13400 (if (or (< pos (match-beginning 1))
13401 (= pos (match-end 0)))
13402 (goto-char (match-beginning 1))
13403 (goto-char (match-end 0)))
13404 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13405 (goto-char (match-end 0))
13406 (goto-char (match-beginning 1))))
13407 (end-of-line arg)))))
13409 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13410 (define-key org-mode-map "\C-e" 'org-end-of-line)
13412 (defun org-kill-line (&optional arg)
13413 "Kill line, to tags or end of line."
13414 (interactive "P")
13415 (cond
13416 ((or (not org-special-ctrl-k)
13417 (bolp)
13418 (not (org-on-heading-p)))
13419 (call-interactively 'kill-line))
13420 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13421 (kill-region (point) (match-beginning 1))
13422 (org-set-tags nil t))
13423 (t (kill-region (point) (point-at-eol)))))
13425 (define-key org-mode-map "\C-k" 'org-kill-line)
13427 (defun org-invisible-p ()
13428 "Check if point is at a character currently not visible."
13429 ;; Early versions of noutline don't have `outline-invisible-p'.
13430 (if (fboundp 'outline-invisible-p)
13431 (outline-invisible-p)
13432 (get-char-property (point) 'invisible)))
13434 (defun org-invisible-p2 ()
13435 "Check if point is at a character currently not visible."
13436 (save-excursion
13437 (if (and (eolp) (not (bobp))) (backward-char 1))
13438 ;; Early versions of noutline don't have `outline-invisible-p'.
13439 (if (fboundp 'outline-invisible-p)
13440 (outline-invisible-p)
13441 (get-char-property (point) 'invisible))))
13443 (defalias 'org-back-to-heading 'outline-back-to-heading)
13444 (defalias 'org-on-heading-p 'outline-on-heading-p)
13445 (defalias 'org-at-heading-p 'outline-on-heading-p)
13446 (defun org-at-heading-or-item-p ()
13447 (or (org-on-heading-p) (org-at-item-p)))
13449 (defun org-on-target-p ()
13450 (or (org-in-regexp org-radio-target-regexp)
13451 (org-in-regexp org-target-regexp)))
13453 (defun org-up-heading-all (arg)
13454 "Move to the heading line of which the present line is a subheading.
13455 This function considers both visible and invisible heading lines.
13456 With argument, move up ARG levels."
13457 (if (fboundp 'outline-up-heading-all)
13458 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13459 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13461 (defun org-up-heading-safe ()
13462 "Move to the heading line of which the present line is a subheading.
13463 This version will not throw an error. It will return the level of the
13464 headline found, or nil if no higher level is found."
13465 (let ((pos (point)) start-level level
13466 (re (concat "^" outline-regexp)))
13467 (catch 'exit
13468 (outline-back-to-heading t)
13469 (setq start-level (funcall outline-level))
13470 (if (equal start-level 1) (throw 'exit nil))
13471 (while (re-search-backward re nil t)
13472 (setq level (funcall outline-level))
13473 (if (< level start-level) (throw 'exit level)))
13474 nil)))
13476 (defun org-first-sibling-p ()
13477 "Is this heading the first child of its parents?"
13478 (interactive)
13479 (let ((re (concat "^" outline-regexp))
13480 level l)
13481 (unless (org-at-heading-p t)
13482 (error "Not at a heading"))
13483 (setq level (funcall outline-level))
13484 (save-excursion
13485 (if (not (re-search-backward re nil t))
13487 (setq l (funcall outline-level))
13488 (< l level)))))
13490 (defun org-goto-sibling (&optional previous)
13491 "Goto the next sibling, even if it is invisible.
13492 When PREVIOUS is set, go to the previous sibling instead. Returns t
13493 when a sibling was found. When none is found, return nil and don't
13494 move point."
13495 (let ((fun (if previous 're-search-backward 're-search-forward))
13496 (pos (point))
13497 (re (concat "^" outline-regexp))
13498 level l)
13499 (when (condition-case nil (org-back-to-heading t) (error nil))
13500 (setq level (funcall outline-level))
13501 (catch 'exit
13502 (or previous (forward-char 1))
13503 (while (funcall fun re nil t)
13504 (setq l (funcall outline-level))
13505 (when (< l level) (goto-char pos) (throw 'exit nil))
13506 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13507 (goto-char pos)
13508 nil))))
13510 (defun org-show-siblings ()
13511 "Show all siblings of the current headline."
13512 (save-excursion
13513 (while (org-goto-sibling) (org-flag-heading nil)))
13514 (save-excursion
13515 (while (org-goto-sibling 'previous)
13516 (org-flag-heading nil))))
13518 (defun org-show-hidden-entry ()
13519 "Show an entry where even the heading is hidden."
13520 (save-excursion
13521 (org-show-entry)))
13523 (defun org-flag-heading (flag &optional entry)
13524 "Flag the current heading. FLAG non-nil means make invisible.
13525 When ENTRY is non-nil, show the entire entry."
13526 (save-excursion
13527 (org-back-to-heading t)
13528 ;; Check if we should show the entire entry
13529 (if entry
13530 (progn
13531 (org-show-entry)
13532 (save-excursion
13533 (and (outline-next-heading)
13534 (org-flag-heading nil))))
13535 (outline-flag-region (max (point-min) (1- (point)))
13536 (save-excursion (outline-end-of-heading) (point))
13537 flag))))
13539 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13540 ;; This is an exact copy of the original function, but it uses
13541 ;; `org-back-to-heading', to make it work also in invisible
13542 ;; trees. And is uses an invisible-OK argument.
13543 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13544 (org-back-to-heading invisible-OK)
13545 (let ((first t)
13546 (level (funcall outline-level)))
13547 (while (and (not (eobp))
13548 (or first (> (funcall outline-level) level)))
13549 (setq first nil)
13550 (outline-next-heading))
13551 (unless to-heading
13552 (if (memq (preceding-char) '(?\n ?\^M))
13553 (progn
13554 ;; Go to end of line before heading
13555 (forward-char -1)
13556 (if (memq (preceding-char) '(?\n ?\^M))
13557 ;; leave blank line before heading
13558 (forward-char -1))))))
13559 (point))
13561 (defun org-show-subtree ()
13562 "Show everything after this heading at deeper levels."
13563 (outline-flag-region
13564 (point)
13565 (save-excursion
13566 (outline-end-of-subtree) (outline-next-heading) (point))
13567 nil))
13569 (defun org-show-entry ()
13570 "Show the body directly following this heading.
13571 Show the heading too, if it is currently invisible."
13572 (interactive)
13573 (save-excursion
13574 (condition-case nil
13575 (progn
13576 (org-back-to-heading t)
13577 (outline-flag-region
13578 (max (point-min) (1- (point)))
13579 (save-excursion
13580 (re-search-forward
13581 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13582 (or (match-beginning 1) (point-max)))
13583 nil))
13584 (error nil))))
13586 (defun org-make-options-regexp (kwds)
13587 "Make a regular expression for keyword lines."
13588 (concat
13590 "#?[ \t]*\\+\\("
13591 (mapconcat 'regexp-quote kwds "\\|")
13592 "\\):[ \t]*"
13593 "\\(.+\\)"))
13595 ;; Make isearch reveal the necessary context
13596 (defun org-isearch-end ()
13597 "Reveal context after isearch exits."
13598 (when isearch-success ; only if search was successful
13599 (if (featurep 'xemacs)
13600 ;; Under XEmacs, the hook is run in the correct place,
13601 ;; we directly show the context.
13602 (org-show-context 'isearch)
13603 ;; In Emacs the hook runs *before* restoring the overlays.
13604 ;; So we have to use a one-time post-command-hook to do this.
13605 ;; (Emacs 22 has a special variable, see function `org-mode')
13606 (unless (and (boundp 'isearch-mode-end-hook-quit)
13607 isearch-mode-end-hook-quit)
13608 ;; Only when the isearch was not quitted.
13609 (org-add-hook 'post-command-hook 'org-isearch-post-command
13610 'append 'local)))))
13612 (defun org-isearch-post-command ()
13613 "Remove self from hook, and show context."
13614 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13615 (org-show-context 'isearch))
13618 ;;;; Integration with and fixes for other packages
13620 ;;; Imenu support
13622 (defvar org-imenu-markers nil
13623 "All markers currently used by Imenu.")
13624 (make-variable-buffer-local 'org-imenu-markers)
13626 (defun org-imenu-new-marker (&optional pos)
13627 "Return a new marker for use by Imenu, and remember the marker."
13628 (let ((m (make-marker)))
13629 (move-marker m (or pos (point)))
13630 (push m org-imenu-markers)
13633 (defun org-imenu-get-tree ()
13634 "Produce the index for Imenu."
13635 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13636 (setq org-imenu-markers nil)
13637 (let* ((n org-imenu-depth)
13638 (re (concat "^" outline-regexp))
13639 (subs (make-vector (1+ n) nil))
13640 (last-level 0)
13641 m tree level head)
13642 (save-excursion
13643 (save-restriction
13644 (widen)
13645 (goto-char (point-max))
13646 (while (re-search-backward re nil t)
13647 (setq level (org-reduced-level (funcall outline-level)))
13648 (when (<= level n)
13649 (looking-at org-complex-heading-regexp)
13650 (setq head (org-match-string-no-properties 4)
13651 m (org-imenu-new-marker))
13652 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13653 (if (>= level last-level)
13654 (push (cons head m) (aref subs level))
13655 (push (cons head (aref subs (1+ level))) (aref subs level))
13656 (loop for i from (1+ level) to n do (aset subs i nil)))
13657 (setq last-level level)))))
13658 (aref subs 1)))
13660 (eval-after-load "imenu"
13661 '(progn
13662 (add-hook 'imenu-after-jump-hook
13663 (lambda () (org-show-context 'org-goto)))))
13665 ;; Speedbar support
13667 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13668 "Overlay marking the agenda restriction line in speedbar.")
13669 (org-overlay-put org-speedbar-restriction-lock-overlay
13670 'face 'org-agenda-restriction-lock)
13671 (org-overlay-put org-speedbar-restriction-lock-overlay
13672 'help-echo "Agendas are currently limited to this item.")
13673 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13675 (defun org-speedbar-set-agenda-restriction ()
13676 "Restrict future agenda commands to the location at point in speedbar.
13677 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13678 (interactive)
13679 (require 'org-agenda)
13680 (let (p m tp np dir txt w)
13681 (cond
13682 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13683 'org-imenu t))
13684 (setq m (get-text-property p 'org-imenu-marker))
13685 (save-excursion
13686 (save-restriction
13687 (set-buffer (marker-buffer m))
13688 (goto-char m)
13689 (org-agenda-set-restriction-lock 'subtree))))
13690 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13691 'speedbar-function 'speedbar-find-file))
13692 (setq tp (previous-single-property-change
13693 (1+ p) 'speedbar-function)
13694 np (next-single-property-change
13695 tp 'speedbar-function)
13696 dir (speedbar-line-directory)
13697 txt (buffer-substring-no-properties (or tp (point-min))
13698 (or np (point-max))))
13699 (save-excursion
13700 (save-restriction
13701 (set-buffer (find-file-noselect
13702 (let ((default-directory dir))
13703 (expand-file-name txt))))
13704 (unless (org-mode-p)
13705 (error "Cannot restrict to non-Org-mode file"))
13706 (org-agenda-set-restriction-lock 'file))))
13707 (t (error "Don't know how to restrict Org-mode's agenda")))
13708 (org-move-overlay org-speedbar-restriction-lock-overlay
13709 (point-at-bol) (point-at-eol))
13710 (setq current-prefix-arg nil)
13711 (org-agenda-maybe-redo)))
13713 (eval-after-load "speedbar"
13714 '(progn
13715 (speedbar-add-supported-extension ".org")
13716 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13717 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13718 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13719 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13720 (add-hook 'speedbar-visiting-tag-hook
13721 (lambda () (org-show-context 'org-goto)))))
13724 ;;; Fixes and Hacks for problems with other packages
13726 ;; Make flyspell not check words in links, to not mess up our keymap
13727 (defun org-mode-flyspell-verify ()
13728 "Don't let flyspell put overlays at active buttons."
13729 (not (get-text-property (point) 'keymap)))
13731 ;; Make `bookmark-jump' show the jump location if it was hidden.
13732 (eval-after-load "bookmark"
13733 '(if (boundp 'bookmark-after-jump-hook)
13734 ;; We can use the hook
13735 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13736 ;; Hook not available, use advice
13737 (defadvice bookmark-jump (after org-make-visible activate)
13738 "Make the position visible."
13739 (org-bookmark-jump-unhide))))
13741 (defun org-bookmark-jump-unhide ()
13742 "Unhide the current position, to show the bookmark location."
13743 (and (org-mode-p)
13744 (or (org-invisible-p)
13745 (save-excursion (goto-char (max (point-min) (1- (point))))
13746 (org-invisible-p)))
13747 (org-show-context 'bookmark-jump)))
13749 ;; Make session.el ignore our circular variable
13750 (eval-after-load "session"
13751 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13753 ;;;; Experimental code
13755 (defun org-closed-in-range ()
13756 "Sparse tree of items closed in a certain time range.
13757 Still experimental, may disappear in the future."
13758 (interactive)
13759 ;; Get the time interval from the user.
13760 (let* ((time1 (time-to-seconds
13761 (org-read-date nil 'to-time nil "Starting date: ")))
13762 (time2 (time-to-seconds
13763 (org-read-date nil 'to-time nil "End date:")))
13764 ;; callback function
13765 (callback (lambda ()
13766 (let ((time
13767 (time-to-seconds
13768 (apply 'encode-time
13769 (org-parse-time-string
13770 (match-string 1))))))
13771 ;; check if time in interval
13772 (and (>= time time1) (<= time time2))))))
13773 ;; make tree, check each match with the callback
13774 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13777 ;;;; Finish up
13779 (provide 'org)
13781 (run-hooks 'org-load-hook)
13783 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13785 ;;; org.el ends here