Install a better error message for the "Before first heading" error.
[org-mode/org-tableheadings.git] / lisp / org.el
blobe41cbeebbebe875a3f803603f8379bf656e834dc
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.12b
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)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.12b"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees. However, do this only if no
641 text after the yank would be swallowed into a folded tree by this action."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-yank-adjusted-subtrees t
646 "Non-nil means, when yanking subtrees, adjust the level.
647 With this setting, `org-paste-subtree' is used to insert the subtree, see
648 this function for details."
649 :group 'org-edit-structure
650 :type 'boolean)
652 (defcustom org-M-RET-may-split-line '((default . t))
653 "Non-nil means, M-RET will split the line at the cursor position.
654 When nil, it will go to the end of the line before making a
655 new line.
656 You may also set this option in a different way for different
657 contexts. Valid contexts are:
659 headline when creating a new headline
660 item when creating a new item
661 table in a table field
662 default the value to be used for all contexts not explicitly
663 customized"
664 :group 'org-structure
665 :group 'org-table
666 :type '(choice
667 (const :tag "Always" t)
668 (const :tag "Never" nil)
669 (repeat :greedy t :tag "Individual contexts"
670 (cons
671 (choice :tag "Context"
672 (const headline)
673 (const item)
674 (const table)
675 (const default))
676 (boolean)))))
679 (defcustom org-insert-heading-respect-content nil
680 "Non-nil means, insert new headings after the current subtree.
681 When nil, the new heading is created directly after the current line.
682 The commands \\[org-insert-heading-respect-content] and
683 \\[org-insert-todo-heading-respect-content] turn this variable on
684 for the duration of the command."
685 :group 'org-structure
686 :type 'boolean)
688 (defcustom org-blank-before-new-entry '((heading . nil)
689 (plain-list-item . nil))
690 "Should `org-insert-heading' leave a blank line before new heading/item?
691 The value is an alist, with `heading' and `plain-list-item' as car,
692 and a boolean flag as cdr."
693 :group 'org-edit-structure
694 :type '(list
695 (cons (const heading) (boolean))
696 (cons (const plain-list-item) (boolean))))
698 (defcustom org-insert-heading-hook nil
699 "Hook being run after inserting a new heading."
700 :group 'org-edit-structure
701 :type 'hook)
703 (defcustom org-enable-fixed-width-editor t
704 "Non-nil means, lines starting with \":\" are treated as fixed-width.
705 This currently only means, they are never auto-wrapped.
706 When nil, such lines will be treated like ordinary lines.
707 See also the QUOTE keyword."
708 :group 'org-edit-structure
709 :type 'boolean)
711 (defcustom org-edit-src-region-extra nil
712 "Additional regexps to identify regions for editing with `org-edit-src-code'.
713 For examples see the function `org-edit-src-find-region-and-lang'.
714 The regular expression identifying the begin marker should end with a newline,
715 and the regexp marking the end line should start with a newline, to make sure
716 there are kept outside the narrowed region."
717 :group 'org-edit-structure
718 :type '(repeat
719 (list
720 (regexp :tag "begin regexp")
721 (regexp :tag "end regexp")
722 (choice :tag "language"
723 (string :tag "specify")
724 (integer :tag "from match group")
725 (const :tag "from `lang' element")
726 (const :tag "from `style' element")))))
728 (defcustom org-edit-fixed-width-region-mode 'artist-mode
729 "The mode that should be used to edit fixed-width regions.
730 These are the regions where each line starts with a colon."
731 :group 'org-edit-structure
732 :type '(choice
733 (const artist-mode)
734 (const picture-mode)
735 (const fundamental-mode)
736 (function :tag "Other (specify)")))
738 (defcustom org-goto-auto-isearch t
739 "Non-nil means, typing characters in org-goto starts incremental search."
740 :group 'org-edit-structure
741 :type 'boolean)
743 (defgroup org-sparse-trees nil
744 "Options concerning sparse trees in Org-mode."
745 :tag "Org Sparse Trees"
746 :group 'org-structure)
748 (defcustom org-highlight-sparse-tree-matches t
749 "Non-nil means, highlight all matches that define a sparse tree.
750 The highlights will automatically disappear the next time the buffer is
751 changed by an edit command."
752 :group 'org-sparse-trees
753 :type 'boolean)
755 (defcustom org-remove-highlights-with-change t
756 "Non-nil means, any change to the buffer will remove temporary highlights.
757 Such highlights are created by `org-occur' and `org-clock-display'.
758 When nil, `C-c C-c needs to be used to get rid of the highlights.
759 The highlights created by `org-preview-latex-fragment' always need
760 `C-c C-c' to be removed."
761 :group 'org-sparse-trees
762 :group 'org-time
763 :type 'boolean)
766 (defcustom org-occur-hook '(org-first-headline-recenter)
767 "Hook that is run after `org-occur' has constructed a sparse tree.
768 This can be used to recenter the window to show as much of the structure
769 as possible."
770 :group 'org-sparse-trees
771 :type 'hook)
773 (defgroup org-imenu-and-speedbar nil
774 "Options concerning imenu and speedbar in Org-mode."
775 :tag "Org Imenu and Speedbar"
776 :group 'org-structure)
778 (defcustom org-imenu-depth 2
779 "The maximum level for Imenu access to Org-mode headlines.
780 This also applied for speedbar access."
781 :group 'org-imenu-and-speedbar
782 :type 'number)
784 (defgroup org-table nil
785 "Options concerning tables in Org-mode."
786 :tag "Org Table"
787 :group 'org)
789 (defcustom org-enable-table-editor 'optimized
790 "Non-nil means, lines starting with \"|\" are handled by the table editor.
791 When nil, such lines will be treated like ordinary lines.
793 When equal to the symbol `optimized', the table editor will be optimized to
794 do the following:
795 - Automatic overwrite mode in front of whitespace in table fields.
796 This makes the structure of the table stay in tact as long as the edited
797 field does not exceed the column width.
798 - Minimize the number of realigns. Normally, the table is aligned each time
799 TAB or RET are pressed to move to another field. With optimization this
800 happens only if changes to a field might have changed the column width.
801 Optimization requires replacing the functions `self-insert-command',
802 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
803 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
804 very good at guessing when a re-align will be necessary, but you can always
805 force one with \\[org-ctrl-c-ctrl-c].
807 If you would like to use the optimized version in Org-mode, but the
808 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
810 This variable can be used to turn on and off the table editor during a session,
811 but in order to toggle optimization, a restart is required.
813 See also the variable `org-table-auto-blank-field'."
814 :group 'org-table
815 :type '(choice
816 (const :tag "off" nil)
817 (const :tag "on" t)
818 (const :tag "on, optimized" optimized)))
820 (defcustom org-table-tab-recognizes-table.el t
821 "Non-nil means, TAB will automatically notice a table.el table.
822 When it sees such a table, it moves point into it and - if necessary -
823 calls `table-recognize-table'."
824 :group 'org-table-editing
825 :type 'boolean)
827 (defgroup org-link nil
828 "Options concerning links in Org-mode."
829 :tag "Org Link"
830 :group 'org)
832 (defvar org-link-abbrev-alist-local nil
833 "Buffer-local version of `org-link-abbrev-alist', which see.
834 The value of this is taken from the #+LINK lines.")
835 (make-variable-buffer-local 'org-link-abbrev-alist-local)
837 (defcustom org-link-abbrev-alist nil
838 "Alist of link abbreviations.
839 The car of each element is a string, to be replaced at the start of a link.
840 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
841 links in Org-mode buffers can have an optional tag after a double colon, e.g.
843 [[linkkey:tag][description]]
845 If REPLACE is a string, the tag will simply be appended to create the link.
846 If the string contains \"%s\", the tag will be inserted there.
848 REPLACE may also be a function that will be called with the tag as the
849 only argument to create the link, which should be returned as a string.
851 See the manual for examples."
852 :group 'org-link
853 :type '(repeat
854 (cons
855 (string :tag "Protocol")
856 (choice
857 (string :tag "Format")
858 (function)))))
860 (defcustom org-descriptive-links t
861 "Non-nil means, hide link part and only show description of bracket links.
862 Bracket links are like [[link][descritpion]]. This variable sets the initial
863 state in new org-mode buffers. The setting can then be toggled on a
864 per-buffer basis from the Org->Hyperlinks menu."
865 :group 'org-link
866 :type 'boolean)
868 (defcustom org-link-file-path-type 'adaptive
869 "How the path name in file links should be stored.
870 Valid values are:
872 relative Relative to the current directory, i.e. the directory of the file
873 into which the link is being inserted.
874 absolute Absolute path, if possible with ~ for home directory.
875 noabbrev Absolute path, no abbreviation of home directory.
876 adaptive Use relative path for files in the current directory and sub-
877 directories of it. For other files, use an absolute path."
878 :group 'org-link
879 :type '(choice
880 (const relative)
881 (const absolute)
882 (const noabbrev)
883 (const adaptive)))
885 (defcustom org-activate-links '(bracket angle plain radio tag date)
886 "Types of links that should be activated in Org-mode files.
887 This is a list of symbols, each leading to the activation of a certain link
888 type. In principle, it does not hurt to turn on most link types - there may
889 be a small gain when turning off unused link types. The types are:
891 bracket The recommended [[link][description]] or [[link]] links with hiding.
892 angular Links in angular brackes that may contain whitespace like
893 <bbdb:Carsten Dominik>.
894 plain Plain links in normal text, no whitespace, like http://google.com.
895 radio Text that is matched by a radio target, see manual for details.
896 tag Tag settings in a headline (link to tag search).
897 date Time stamps (link to calendar).
899 Changing this variable requires a restart of Emacs to become effective."
900 :group 'org-link
901 :type '(set (const :tag "Double bracket links (new style)" bracket)
902 (const :tag "Angular bracket links (old style)" angular)
903 (const :tag "Plain text links" plain)
904 (const :tag "Radio target matches" radio)
905 (const :tag "Tags" tag)
906 (const :tag "Timestamps" date)))
908 (defcustom org-make-link-description-function nil
909 "Function to use to generate link descriptions from links. If
910 nil the link location will be used. This function must take two
911 parameters; the first is the link and the second the description
912 org-insert-link has generated, and should return the description
913 to use."
914 :group 'org-link
915 :type 'function)
917 (defgroup org-link-store nil
918 "Options concerning storing links in Org-mode."
919 :tag "Org Store Link"
920 :group 'org-link)
922 (defcustom org-email-link-description-format "Email %c: %.30s"
923 "Format of the description part of a link to an email or usenet message.
924 The following %-excapes will be replaced by corresponding information:
926 %F full \"From\" field
927 %f name, taken from \"From\" field, address if no name
928 %T full \"To\" field
929 %t first name in \"To\" field, address if no name
930 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
931 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
932 %s subject
933 %m message-id.
935 You may use normal field width specification between the % and the letter.
936 This is for example useful to limit the length of the subject.
938 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
939 :group 'org-link-store
940 :type 'string)
942 (defcustom org-from-is-user-regexp
943 (let (r1 r2)
944 (when (and user-mail-address (not (string= user-mail-address "")))
945 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
946 (when (and user-full-name (not (string= user-full-name "")))
947 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
948 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
949 "Regexp mached against the \"From:\" header of an email or usenet message.
950 It should match if the message is from the user him/herself."
951 :group 'org-link-store
952 :type 'regexp)
954 (defcustom org-context-in-file-links t
955 "Non-nil means, file links from `org-store-link' contain context.
956 A search string will be added to the file name with :: as separator and
957 used to find the context when the link is activated by the command
958 `org-open-at-point'.
959 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
960 negates this setting for the duration of the command."
961 :group 'org-link-store
962 :type 'boolean)
964 (defcustom org-keep-stored-link-after-insertion nil
965 "Non-nil means, keep link in list for entire session.
967 The command `org-store-link' adds a link pointing to the current
968 location to an internal list. These links accumulate during a session.
969 The command `org-insert-link' can be used to insert links into any
970 Org-mode file (offering completion for all stored links). When this
971 option is nil, every link which has been inserted once using \\[org-insert-link]
972 will be removed from the list, to make completing the unused links
973 more efficient."
974 :group 'org-link-store
975 :type 'boolean)
977 (defgroup org-link-follow nil
978 "Options concerning following links in Org-mode."
979 :tag "Org Follow Link"
980 :group 'org-link)
982 (defcustom org-follow-link-hook nil
983 "Hook that is run after a link has been followed."
984 :group 'org-link-follow
985 :type 'hook)
987 (defcustom org-tab-follows-link nil
988 "Non-nil means, on links TAB will follow the link.
989 Needs to be set before org.el is loaded."
990 :group 'org-link-follow
991 :type 'boolean)
993 (defcustom org-return-follows-link nil
994 "Non-nil means, on links RET will follow the link.
995 Needs to be set before org.el is loaded."
996 :group 'org-link-follow
997 :type 'boolean)
999 (defcustom org-mouse-1-follows-link
1000 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1001 "Non-nil means, mouse-1 on a link will follow the link.
1002 A longer mouse click will still set point. Does not work on XEmacs.
1003 Needs to be set before org.el is loaded."
1004 :group 'org-link-follow
1005 :type 'boolean)
1007 (defcustom org-mark-ring-length 4
1008 "Number of different positions to be recorded in the ring
1009 Changing this requires a restart of Emacs to work correctly."
1010 :group 'org-link-follow
1011 :type 'interger)
1013 (defcustom org-link-frame-setup
1014 '((vm . vm-visit-folder-other-frame)
1015 (gnus . gnus-other-frame)
1016 (file . find-file-other-window))
1017 "Setup the frame configuration for following links.
1018 When following a link with Emacs, it may often be useful to display
1019 this link in another window or frame. This variable can be used to
1020 set this up for the different types of links.
1021 For VM, use any of
1022 `vm-visit-folder'
1023 `vm-visit-folder-other-frame'
1024 For Gnus, use any of
1025 `gnus'
1026 `gnus-other-frame'
1027 `org-gnus-no-new-news'
1028 For FILE, use any of
1029 `find-file'
1030 `find-file-other-window'
1031 `find-file-other-frame'
1032 For the calendar, use the variable `calendar-setup'.
1033 For BBDB, it is currently only possible to display the matches in
1034 another window."
1035 :group 'org-link-follow
1036 :type '(list
1037 (cons (const vm)
1038 (choice
1039 (const vm-visit-folder)
1040 (const vm-visit-folder-other-window)
1041 (const vm-visit-folder-other-frame)))
1042 (cons (const gnus)
1043 (choice
1044 (const gnus)
1045 (const gnus-other-frame)
1046 (const org-gnus-no-new-news)))
1047 (cons (const file)
1048 (choice
1049 (const find-file)
1050 (const find-file-other-window)
1051 (const find-file-other-frame)))))
1053 (defcustom org-display-internal-link-with-indirect-buffer nil
1054 "Non-nil means, use indirect buffer to display infile links.
1055 Activating internal links (from one location in a file to another location
1056 in the same file) normally just jumps to the location. When the link is
1057 activated with a C-u prefix (or with mouse-3), the link is displayed in
1058 another window. When this option is set, the other window actually displays
1059 an indirect buffer clone of the current buffer, to avoid any visibility
1060 changes to the current buffer."
1061 :group 'org-link-follow
1062 :type 'boolean)
1064 (defcustom org-open-non-existing-files nil
1065 "Non-nil means, `org-open-file' will open non-existing files.
1066 When nil, an error will be generated."
1067 :group 'org-link-follow
1068 :type 'boolean)
1070 (defcustom org-open-directory-means-index-dot-org nil
1071 "Non-nil means, a link to a directory really means to index.org.
1072 When nil, following a directory link will run dired or open a finder/explorer
1073 window on that directory."
1074 :group 'org-link-follow
1075 :type 'boolean)
1077 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1078 "Function and arguments to call for following mailto links.
1079 This is a list with the first element being a lisp function, and the
1080 remaining elements being arguments to the function. In string arguments,
1081 %a will be replaced by the address, and %s will be replaced by the subject
1082 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1083 :group 'org-link-follow
1084 :type '(choice
1085 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1086 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1087 (const :tag "message-mail" (message-mail "%a" "%s"))
1088 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1090 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1091 "Non-nil means, ask for confirmation before executing shell links.
1092 Shell links can be dangerous: just think about a link
1094 [[shell:rm -rf ~/*][Google Search]]
1096 This link would show up in your Org-mode document as \"Google Search\",
1097 but really it would remove your entire home directory.
1098 Therefore we advise against setting this variable to nil.
1099 Just change it to `y-or-n-p' of you want to confirm with a
1100 single keystroke rather than having to type \"yes\"."
1101 :group 'org-link-follow
1102 :type '(choice
1103 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1104 (const :tag "with y-or-n (faster)" y-or-n-p)
1105 (const :tag "no confirmation (dangerous)" nil)))
1107 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1108 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1109 Elisp links can be dangerous: just think about a link
1111 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1113 This link would show up in your Org-mode document as \"Google Search\",
1114 but really it would remove your entire home directory.
1115 Therefore we advise against setting this variable to nil.
1116 Just change it to `y-or-n-p' of you want to confirm with a
1117 single keystroke rather than having to type \"yes\"."
1118 :group 'org-link-follow
1119 :type '(choice
1120 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1121 (const :tag "with y-or-n (faster)" y-or-n-p)
1122 (const :tag "no confirmation (dangerous)" nil)))
1124 (defconst org-file-apps-defaults-gnu
1125 '((remote . emacs)
1126 (system . mailcap)
1127 (t . mailcap))
1128 "Default file applications on a UNIX or GNU/Linux system.
1129 See `org-file-apps'.")
1131 (defconst org-file-apps-defaults-macosx
1132 '((remote . emacs)
1133 (t . "open %s")
1134 (system . "open %s")
1135 ("ps.gz" . "gv %s")
1136 ("eps.gz" . "gv %s")
1137 ("dvi" . "xdvi %s")
1138 ("fig" . "xfig %s"))
1139 "Default file applications on a MacOS X system.
1140 The system \"open\" is known as a default, but we use X11 applications
1141 for some files for which the OS does not have a good default.
1142 See `org-file-apps'.")
1144 (defconst org-file-apps-defaults-windowsnt
1145 (list
1146 '(remote . emacs)
1147 (cons t
1148 (list (if (featurep 'xemacs)
1149 'mswindows-shell-execute
1150 'w32-shell-execute)
1151 "open" 'file))
1152 (cons 'system
1153 (list (if (featurep 'xemacs)
1154 'mswindows-shell-execute
1155 'w32-shell-execute)
1156 "open" 'file)))
1157 "Default file applications on a Windows NT system.
1158 The system \"open\" is used for most files.
1159 See `org-file-apps'.")
1161 (defcustom org-file-apps
1163 (auto-mode . emacs)
1164 ("\\.x?html?\\'" . default)
1165 ("\\.pdf\\'" . default)
1167 "External applications for opening `file:path' items in a document.
1168 Org-mode uses system defaults for different file types, but
1169 you can use this variable to set the application for a given file
1170 extension. The entries in this list are cons cells where the car identifies
1171 files and the cdr the corresponding command. Possible values for the
1172 file identifier are
1173 \"regex\" Regular expression matched against the file name. For backward
1174 compatibility, this can also be a string with only alphanumeric
1175 characters, which is then interpreted as an extension.
1176 `directory' Matches a directory
1177 `remote' Matches a remote file, accessible through tramp or efs.
1178 Remote files most likely should be visited through Emacs
1179 because external applications cannot handle such paths.
1180 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1181 so all files Emacs knows how to handle. Using this with
1182 command `emacs' will open most files in Emacs. Beware that this
1183 will also open html files insite Emacs, unless you add
1184 (\"html\" . default) to the list as well.
1185 t Default for files not matched by any of the other options.
1186 `system' The system command to open files, like `open' on Windows
1187 and Mac OS X, and mailcap under GNU/Linux. This is the command
1188 that will be selected if you call `C-c C-o' with a double
1189 `C-u C-u' prefix.
1191 Possible values for the command are:
1192 `emacs' The file will be visited by the current Emacs process.
1193 `default' Use the default application for this file type, which is the
1194 association for t in the list, most likely in the system-specific
1195 part.
1196 This can be used to overrule an unwanted seting in the
1197 system-specific variable.
1198 `system' Use the system command for opening files, like \"open\".
1199 This command is specified by the entry whose car is `system'.
1200 Most likely, the system-specific version of this variable
1201 does define this command, but you can overrule/replace it
1202 here.
1203 string A command to be executed by a shell; %s will be replaced
1204 by the path to the file.
1205 sexp A Lisp form which will be evaluated. The file path will
1206 be available in the Lisp variable `file'.
1207 For more examples, see the system specific constants
1208 `org-file-apps-defaults-macosx'
1209 `org-file-apps-defaults-windowsnt'
1210 `org-file-apps-defaults-gnu'."
1211 :group 'org-link-follow
1212 :type '(repeat
1213 (cons (choice :value ""
1214 (string :tag "Extension")
1215 (const :tag "System command to open files" system)
1216 (const :tag "Default for unrecognized files" t)
1217 (const :tag "Remote file" remote)
1218 (const :tag "Links to a directory" directory)
1219 (const :tag "Any files that have Emacs modes"
1220 auto-mode))
1221 (choice :value ""
1222 (const :tag "Visit with Emacs" emacs)
1223 (const :tag "Use default" default)
1224 (const :tag "Use the system command" system)
1225 (string :tag "Command")
1226 (sexp :tag "Lisp form")))))
1228 (defgroup org-refile nil
1229 "Options concerning refiling entries in Org-mode."
1230 :tag "Org Remember"
1231 :group 'org)
1233 (defcustom org-directory "~/org"
1234 "Directory with org files.
1235 This directory will be used as default to prompt for org files.
1236 Used by the hooks for remember.el."
1237 :group 'org-refile
1238 :group 'org-remember
1239 :type 'directory)
1241 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1242 "Default target for storing notes.
1243 Used by the hooks for remember.el. This can be a string, or nil to mean
1244 the value of `remember-data-file'.
1245 You can set this on a per-template basis with the variable
1246 `org-remember-templates'."
1247 :group 'org-refile
1248 :group 'org-remember
1249 :type '(choice
1250 (const :tag "Default from remember-data-file" nil)
1251 file))
1253 (defcustom org-goto-interface 'outline
1254 "The default interface to be used for `org-goto'.
1255 Allowed vaues are:
1256 outline The interface shows an outline of the relevant file
1257 and the correct heading is found by moving through
1258 the outline or by searching with incremental search.
1259 outline-path-completion Headlines in the current buffer are offered via
1260 completion."
1261 :group 'org-refile
1262 :type '(choice
1263 (const :tag "Outline" outline)
1264 (const :tag "Outline-path-completion" outline-path-completion)))
1266 (defcustom org-reverse-note-order nil
1267 "Non-nil means, store new notes at the beginning of a file or entry.
1268 When nil, new notes will be filed to the end of a file or entry.
1269 This can also be a list with cons cells of regular expressions that
1270 are matched against file names, and values."
1271 :group 'org-remember
1272 :type '(choice
1273 (const :tag "Reverse always" t)
1274 (const :tag "Reverse never" nil)
1275 (repeat :tag "By file name regexp"
1276 (cons regexp boolean))))
1278 (defcustom org-refile-targets nil
1279 "Targets for refiling entries with \\[org-refile].
1280 This is list of cons cells. Each cell contains:
1281 - a specification of the files to be considered, either a list of files,
1282 or a symbol whose function or variable value will be used to retrieve
1283 a file name or a list of file names. Nil means, refile to a different
1284 heading in the current buffer.
1285 - A specification of how to find candidate refile targets. This may be
1286 any of
1287 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1288 This tag has to be present in all target headlines, inheritance will
1289 not be considered.
1290 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1291 todo keyword.
1292 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1293 headlines that are refiling targets.
1294 - a cons cell (:level . N). Any headline of level N is considered a target.
1295 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1297 When this variable is nil, all top-level headlines in the current buffer
1298 are used, equivalent to the value `((nil . (:level . 1))'."
1299 :group 'org-remember
1300 :type '(repeat
1301 (cons
1302 (choice :value org-agenda-files
1303 (const :tag "All agenda files" org-agenda-files)
1304 (const :tag "Current buffer" nil)
1305 (function) (variable) (file))
1306 (choice :tag "Identify target headline by"
1307 (cons :tag "Specific tag" (const :tag) (string))
1308 (cons :tag "TODO keyword" (const :todo) (string))
1309 (cons :tag "Regular expression" (const :regexp) (regexp))
1310 (cons :tag "Level number" (const :level) (integer))
1311 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1313 (defcustom org-refile-use-outline-path nil
1314 "Non-nil means, provide refile targets as paths.
1315 So a level 3 headline will be available as level1/level2/level3.
1316 When the value is `file', also include the file name (without directory)
1317 into the path. When `full-file-path', include the full file path."
1318 :group 'org-remember
1319 :type '(choice
1320 (const :tag "Not" nil)
1321 (const :tag "Yes" t)
1322 (const :tag "Start with file name" file)
1323 (const :tag "Start with full file path" full-file-path)))
1325 (defgroup org-todo nil
1326 "Options concerning TODO items in Org-mode."
1327 :tag "Org TODO"
1328 :group 'org)
1330 (defgroup org-progress nil
1331 "Options concerning Progress logging in Org-mode."
1332 :tag "Org Progress"
1333 :group 'org-time)
1335 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1336 "List of TODO entry keyword sequences and their interpretation.
1337 \\<org-mode-map>This is a list of sequences.
1339 Each sequence starts with a symbol, either `sequence' or `type',
1340 indicating if the keywords should be interpreted as a sequence of
1341 action steps, or as different types of TODO items. The first
1342 keywords are states requiring action - these states will select a headline
1343 for inclusion into the global TODO list Org-mode produces. If one of
1344 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1345 signify that no further action is necessary. If \"|\" is not found,
1346 the last keyword is treated as the only DONE state of the sequence.
1348 The command \\[org-todo] cycles an entry through these states, and one
1349 additional state where no keyword is present. For details about this
1350 cycling, see the manual.
1352 TODO keywords and interpretation can also be set on a per-file basis with
1353 the special #+SEQ_TODO and #+TYP_TODO lines.
1355 Each keyword can optionally specify a character for fast state selection
1356 \(in combination with the variable `org-use-fast-todo-selection')
1357 and specifiers for state change logging, using the same syntax
1358 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1359 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1360 indicates to record a time stamp each time this state is selected.
1362 Each keyword may also specify if a timestamp or a note should be
1363 recorded when entering or leaving the state, by adding additional
1364 characters in the parenthesis after the keyword. This looks like this:
1365 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1366 record only the time of the state change. With X and Y being either
1367 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1368 Y when leaving the state if and only if the *target* state does not
1369 define X. You may omit any of the fast-selection key or X or /Y,
1370 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1372 For backward compatibility, this variable may also be just a list
1373 of keywords - in this case the interptetation (sequence or type) will be
1374 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1375 :group 'org-todo
1376 :group 'org-keywords
1377 :type '(choice
1378 (repeat :tag "Old syntax, just keywords"
1379 (string :tag "Keyword"))
1380 (repeat :tag "New syntax"
1381 (cons
1382 (choice
1383 :tag "Interpretation"
1384 (const :tag "Sequence (cycling hits every state)" sequence)
1385 (const :tag "Type (cycling directly to DONE)" type))
1386 (repeat
1387 (string :tag "Keyword"))))))
1389 (defvar org-todo-keywords-1 nil
1390 "All TODO and DONE keywords active in a buffer.")
1391 (make-variable-buffer-local 'org-todo-keywords-1)
1392 (defvar org-todo-keywords-for-agenda nil)
1393 (defvar org-done-keywords-for-agenda nil)
1394 (defvar org-todo-keyword-alist-for-agenda nil)
1395 (defvar org-tag-alist-for-agenda nil)
1396 (defvar org-agenda-contributing-files nil)
1397 (defvar org-not-done-keywords nil)
1398 (make-variable-buffer-local 'org-not-done-keywords)
1399 (defvar org-done-keywords nil)
1400 (make-variable-buffer-local 'org-done-keywords)
1401 (defvar org-todo-heads nil)
1402 (make-variable-buffer-local 'org-todo-heads)
1403 (defvar org-todo-sets nil)
1404 (make-variable-buffer-local 'org-todo-sets)
1405 (defvar org-todo-log-states nil)
1406 (make-variable-buffer-local 'org-todo-log-states)
1407 (defvar org-todo-kwd-alist nil)
1408 (make-variable-buffer-local 'org-todo-kwd-alist)
1409 (defvar org-todo-key-alist nil)
1410 (make-variable-buffer-local 'org-todo-key-alist)
1411 (defvar org-todo-key-trigger nil)
1412 (make-variable-buffer-local 'org-todo-key-trigger)
1414 (defcustom org-todo-interpretation 'sequence
1415 "Controls how TODO keywords are interpreted.
1416 This variable is in principle obsolete and is only used for
1417 backward compatibility, if the interpretation of todo keywords is
1418 not given already in `org-todo-keywords'. See that variable for
1419 more information."
1420 :group 'org-todo
1421 :group 'org-keywords
1422 :type '(choice (const sequence)
1423 (const type)))
1425 (defcustom org-use-fast-todo-selection 'prefix
1426 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1427 This variable describes if and under what circumstances the cycling
1428 mechanism for TODO keywords will be replaced by a single-key, direct
1429 selection scheme.
1431 When nil, fast selection is never used.
1433 When the symbol `prefix', it will be used when `org-todo' is called with
1434 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1435 in an agenda buffer.
1437 When t, fast selection is used by default. In this case, the prefix
1438 argument forces cycling instead.
1440 In all cases, the special interface is only used if access keys have actually
1441 been assigned by the user, i.e. if keywords in the configuration are followed
1442 by a letter in parenthesis, like TODO(t)."
1443 :group 'org-todo
1444 :type '(choice
1445 (const :tag "Never" nil)
1446 (const :tag "By default" t)
1447 (const :tag "Only with C-u C-c C-t" prefix)))
1449 (defcustom org-provide-todo-statistics t
1450 "Non-nil means, update todo statistics after insert and toggle.
1451 When this is set, todo statistics is updated in the parent of the current
1452 entry each time a todo state is changed."
1453 :group 'org-todo
1454 :type 'boolean)
1456 (defcustom org-after-todo-state-change-hook nil
1457 "Hook which is run after the state of a TODO item was changed.
1458 The new state (a string with a TODO keyword, or nil) is available in the
1459 Lisp variable `state'."
1460 :group 'org-todo
1461 :type 'hook)
1463 (defcustom org-todo-state-tags-triggers nil
1464 "Tag changes that should be triggered by TODO state changes.
1465 This is a list. Each entry is
1467 (state-change (tag . flag) .......)
1469 State-change can be a string with a state, and empty string to indicate the
1470 state that has no TODO keyword, or it can be one of the symbols `todo'
1471 or `done', meaning any not-done or done state, respectively."
1472 :group 'org-todo
1473 :group 'org-tags
1474 :type '(repeat
1475 (cons (choice :tag "When changing to"
1476 (const :tag "Not-done state" todo)
1477 (const :tag "Done state" done)
1478 (string :tag "State"))
1479 (repeat
1480 (cons :tag "Tag action"
1481 (string :tag "Tag")
1482 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1484 (defcustom org-log-done nil
1485 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1486 When equal to the list (done), also prompt for a closing note.
1487 This can also be configured on a per-file basis by adding one of
1488 the following lines anywhere in the buffer:
1490 #+STARTUP: logdone
1491 #+STARTUP: lognotedone
1492 #+STARTUP: nologdone"
1493 :group 'org-todo
1494 :group 'org-progress
1495 :type '(choice
1496 (const :tag "No logging" nil)
1497 (const :tag "Record CLOSED timestamp" time)
1498 (const :tag "Record CLOSED timestamp with closing note." note)))
1500 ;; Normalize old uses of org-log-done.
1501 (cond
1502 ((eq org-log-done t) (setq org-log-done 'time))
1503 ((and (listp org-log-done) (memq 'done org-log-done))
1504 (setq org-log-done 'note)))
1506 (defcustom org-log-note-clock-out nil
1507 "Non-nil means, record a note when clocking out of an item.
1508 This can also be configured on a per-file basis by adding one of
1509 the following lines anywhere in the buffer:
1511 #+STARTUP: lognoteclock-out
1512 #+STARTUP: nolognoteclock-out"
1513 :group 'org-todo
1514 :group 'org-progress
1515 :type 'boolean)
1517 (defcustom org-log-done-with-time t
1518 "Non-nil means, the CLOSED time stamp will contain date and time.
1519 When nil, only the date will be recorded."
1520 :group 'org-progress
1521 :type 'boolean)
1523 (defcustom org-log-note-headings
1524 '((done . "CLOSING NOTE %t")
1525 (state . "State %-12s %t")
1526 (note . "Note taken on %t")
1527 (clock-out . ""))
1528 "Headings for notes added to entries.
1529 The value is an alist, with the car being a symbol indicating the note
1530 context, and the cdr is the heading to be used. The heading may also be the
1531 empty string.
1532 %t in the heading will be replaced by a time stamp.
1533 %s will be replaced by the new TODO state, in double quotes.
1534 %u will be replaced by the user name.
1535 %U will be replaced by the full user name."
1536 :group 'org-todo
1537 :group 'org-progress
1538 :type '(list :greedy t
1539 (cons (const :tag "Heading when closing an item" done) string)
1540 (cons (const :tag
1541 "Heading when changing todo state (todo sequence only)"
1542 state) string)
1543 (cons (const :tag "Heading when just taking a note" note) string)
1544 (cons (const :tag "Heading when clocking out" clock-out) string)))
1546 (unless (assq 'note org-log-note-headings)
1547 (push '(note . "%t") org-log-note-headings))
1549 (defcustom org-log-state-notes-insert-after-drawers nil
1550 "Non-nil means, insert state change notes after any drawers in entry.
1551 Only the drawers that *immediately* follow the headline and the
1552 deadline/scheduled line are skipped.
1553 When nil, insert notes right after the heading and perhaps the line
1554 with deadline/scheduling if present."
1555 :group 'org-todo
1556 :group 'org-progress
1557 :type 'boolean)
1559 (defcustom org-log-states-order-reversed t
1560 "Non-nil means, the latest state change note will be directly after heading.
1561 When nil, the notes will be orderer according to time."
1562 :group 'org-todo
1563 :group 'org-progress
1564 :type 'boolean)
1566 (defcustom org-log-repeat 'time
1567 "Non-nil means, record moving through the DONE state when triggering repeat.
1568 An auto-repeating tasks is immediately switched back to TODO when marked
1569 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1570 the TODO keyword definition, or recording a closing note by setting
1571 `org-log-done', there will be no record of the task moving through DONE.
1572 This variable forces taking a note anyway. Possible values are:
1574 nil Don't force a record
1575 time Record a time stamp
1576 note Record a note
1578 This option can also be set with on a per-file-basis with
1580 #+STARTUP: logrepeat
1581 #+STARTUP: lognoterepeat
1582 #+STARTUP: nologrepeat
1584 You can have local logging settings for a subtree by setting the LOGGING
1585 property to one or more of these keywords."
1586 :group 'org-todo
1587 :group 'org-progress
1588 :type '(choice
1589 (const :tag "Don't force a record" nil)
1590 (const :tag "Force recording the DONE state" time)
1591 (const :tag "Force recording a note with the DONE state" note)))
1594 (defgroup org-priorities nil
1595 "Priorities in Org-mode."
1596 :tag "Org Priorities"
1597 :group 'org-todo)
1599 (defcustom org-highest-priority ?A
1600 "The highest priority of TODO items. A character like ?A, ?B etc.
1601 Must have a smaller ASCII number than `org-lowest-priority'."
1602 :group 'org-priorities
1603 :type 'character)
1605 (defcustom org-lowest-priority ?C
1606 "The lowest priority of TODO items. A character like ?A, ?B etc.
1607 Must have a larger ASCII number than `org-highest-priority'."
1608 :group 'org-priorities
1609 :type 'character)
1611 (defcustom org-default-priority ?B
1612 "The default priority of TODO items.
1613 This is the priority an item get if no explicit priority is given."
1614 :group 'org-priorities
1615 :type 'character)
1617 (defcustom org-priority-start-cycle-with-default t
1618 "Non-nil means, start with default priority when starting to cycle.
1619 When this is nil, the first step in the cycle will be (depending on the
1620 command used) one higher or lower that the default priority."
1621 :group 'org-priorities
1622 :type 'boolean)
1624 (defgroup org-time nil
1625 "Options concerning time stamps and deadlines in Org-mode."
1626 :tag "Org Time"
1627 :group 'org)
1629 (defcustom org-insert-labeled-timestamps-at-point nil
1630 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1631 When nil, these labeled time stamps are forces into the second line of an
1632 entry, just after the headline. When scheduling from the global TODO list,
1633 the time stamp will always be forced into the second line."
1634 :group 'org-time
1635 :type 'boolean)
1637 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1638 "Formats for `format-time-string' which are used for time stamps.
1639 It is not recommended to change this constant.")
1641 (defcustom org-time-stamp-rounding-minutes '(0 5)
1642 "Number of minutes to round time stamps to.
1643 These are two values, the first applies when first creating a time stamp.
1644 The second applies when changing it with the commands `S-up' and `S-down'.
1645 When changing the time stamp, this means that it will change in steps
1646 of N minutes, as given by the second value.
1648 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1649 numbers should be factors of 60, so for example 5, 10, 15.
1651 When this is larger than 1, you can still force an exact time-stamp by using
1652 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1653 and by using a prefix arg to `S-up/down' to specify the exact number
1654 of minutes to shift."
1655 :group 'org-time
1656 :get '(lambda (var) ; Make sure all entries have 5 elements
1657 (if (integerp (default-value var))
1658 (list (default-value var) 5)
1659 (default-value var)))
1660 :type '(list
1661 (integer :tag "when inserting times")
1662 (integer :tag "when modifying times")))
1664 ;; Normalize old customizations of this variable.
1665 (when (integerp org-time-stamp-rounding-minutes)
1666 (setq org-time-stamp-rounding-minutes
1667 (list org-time-stamp-rounding-minutes
1668 org-time-stamp-rounding-minutes)))
1670 (defcustom org-display-custom-times nil
1671 "Non-nil means, overlay custom formats over all time stamps.
1672 The formats are defined through the variable `org-time-stamp-custom-formats'.
1673 To turn this on on a per-file basis, insert anywhere in the file:
1674 #+STARTUP: customtime"
1675 :group 'org-time
1676 :set 'set-default
1677 :type 'sexp)
1678 (make-variable-buffer-local 'org-display-custom-times)
1680 (defcustom org-time-stamp-custom-formats
1681 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1682 "Custom formats for time stamps. See `format-time-string' for the syntax.
1683 These are overlayed over the default ISO format if the variable
1684 `org-display-custom-times' is set. Time like %H:%M should be at the
1685 end of the second format."
1686 :group 'org-time
1687 :type 'sexp)
1689 (defun org-time-stamp-format (&optional long inactive)
1690 "Get the right format for a time string."
1691 (let ((f (if long (cdr org-time-stamp-formats)
1692 (car org-time-stamp-formats))))
1693 (if inactive
1694 (concat "[" (substring f 1 -1) "]")
1695 f)))
1697 (defcustom org-time-clocksum-format "%d:%02d"
1698 "The format string used when creating CLOCKSUM lines, or when
1699 org-mode generates a time duration."
1700 :group 'org-time
1701 :type 'string)
1703 (defcustom org-deadline-warning-days 14
1704 "No. of days before expiration during which a deadline becomes active.
1705 This variable governs the display in sparse trees and in the agenda.
1706 When 0 or negative, it means use this number (the absolute value of it)
1707 even if a deadline has a different individual lead time specified."
1708 :group 'org-time
1709 :group 'org-agenda-daily/weekly
1710 :type 'number)
1712 (defcustom org-read-date-prefer-future t
1713 "Non-nil means, assume future for incomplete date input from user.
1714 This affects the following situations:
1715 1. The user gives a day, but no month.
1716 For example, if today is the 15th, and you enter \"3\", Org-mode will
1717 read this as the third of *next* month. However, if you enter \"17\",
1718 it will be considered as *this* month.
1719 2. The user gives a month but not a year.
1720 For example, if it is april and you enter \"feb 2\", this will be read
1721 as feb 2, *next* year. \"May 5\", however, will be this year.
1723 Currently this does not work for ISO week specifications.
1725 When this option is nil, the current month and year will always be used
1726 as defaults."
1727 :group 'org-time
1728 :type 'boolean)
1730 (defcustom org-read-date-display-live t
1731 "Non-nil means, display current interpretation of date prompt live.
1732 This display will be in an overlay, in the minibuffer."
1733 :group 'org-time
1734 :type 'boolean)
1736 (defcustom org-read-date-popup-calendar t
1737 "Non-nil means, pop up a calendar when prompting for a date.
1738 In the calendar, the date can be selected with mouse-1. However, the
1739 minibuffer will also be active, and you can simply enter the date as well.
1740 When nil, only the minibuffer will be available."
1741 :group 'org-time
1742 :type 'boolean)
1743 (if (fboundp 'defvaralias)
1744 (defvaralias 'org-popup-calendar-for-date-prompt
1745 'org-read-date-popup-calendar))
1747 (defcustom org-extend-today-until 0
1748 "The hour when your day really ends. Must be an integer.
1749 This has influence for the following applications:
1750 - When switching the agenda to \"today\". It it is still earlier than
1751 the time given here, the day recognized as TODAY is actually yesterday.
1752 - When a date is read from the user and it is still before the time given
1753 here, the current date and time will be assumed to be yesterday, 23:59.
1754 Also, timestamps inserted in remember templates follow this rule.
1756 IMPORTANT: This is a feature whose implementation is and likely will
1757 remain incomplete. Really, it is only here because past midnight seems to
1758 be the favorite working time of John Wiegley :-)"
1759 :group 'org-time
1760 :type 'number)
1762 (defcustom org-edit-timestamp-down-means-later nil
1763 "Non-nil means, S-down will increase the time in a time stamp.
1764 When nil, S-up will increase."
1765 :group 'org-time
1766 :type 'boolean)
1768 (defcustom org-calendar-follow-timestamp-change t
1769 "Non-nil means, make the calendar window follow timestamp changes.
1770 When a timestamp is modified and the calendar window is visible, it will be
1771 moved to the new date."
1772 :group 'org-time
1773 :type 'boolean)
1775 (defgroup org-tags nil
1776 "Options concerning tags in Org-mode."
1777 :tag "Org Tags"
1778 :group 'org)
1780 (defcustom org-tag-alist nil
1781 "List of tags allowed in Org-mode files.
1782 When this list is nil, Org-mode will base TAG input on what is already in the
1783 buffer.
1784 The value of this variable is an alist, the car of each entry must be a
1785 keyword as a string, the cdr may be a character that is used to select
1786 that tag through the fast-tag-selection interface.
1787 See the manual for details."
1788 :group 'org-tags
1789 :type '(repeat
1790 (choice
1791 (cons (string :tag "Tag name")
1792 (character :tag "Access char"))
1793 (const :tag "Start radio group" (:startgroup))
1794 (const :tag "End radio group" (:endgroup)))))
1796 (defvar org-file-tags nil
1797 "List of tags that can be inherited by all entries in the file.
1798 The tags will be inherited if the variable `org-use-tag-inheritance'
1799 says they should be.
1800 This variable is populated from #+TAG lines.")
1802 (defcustom org-use-fast-tag-selection 'auto
1803 "Non-nil means, use fast tag selection scheme.
1804 This is a special interface to select and deselect tags with single keys.
1805 When nil, fast selection is never used.
1806 When the symbol `auto', fast selection is used if and only if selection
1807 characters for tags have been configured, either through the variable
1808 `org-tag-alist' or through a #+TAGS line in the buffer.
1809 When t, fast selection is always used and selection keys are assigned
1810 automatically if necessary."
1811 :group 'org-tags
1812 :type '(choice
1813 (const :tag "Always" t)
1814 (const :tag "Never" nil)
1815 (const :tag "When selection characters are configured" 'auto)))
1817 (defcustom org-fast-tag-selection-single-key nil
1818 "Non-nil means, fast tag selection exits after first change.
1819 When nil, you have to press RET to exit it.
1820 During fast tag selection, you can toggle this flag with `C-c'.
1821 This variable can also have the value `expert'. In this case, the window
1822 displaying the tags menu is not even shown, until you press C-c again."
1823 :group 'org-tags
1824 :type '(choice
1825 (const :tag "No" nil)
1826 (const :tag "Yes" t)
1827 (const :tag "Expert" expert)))
1829 (defvar org-fast-tag-selection-include-todo nil
1830 "Non-nil means, fast tags selection interface will also offer TODO states.
1831 This is an undocumented feature, you should not rely on it.")
1833 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1834 "The column to which tags should be indented in a headline.
1835 If this number is positive, it specifies the column. If it is negative,
1836 it means that the tags should be flushright to that column. For example,
1837 -80 works well for a normal 80 character screen."
1838 :group 'org-tags
1839 :type 'integer)
1841 (defcustom org-auto-align-tags t
1842 "Non-nil means, realign tags after pro/demotion of TODO state change.
1843 These operations change the length of a headline and therefore shift
1844 the tags around. With this options turned on, after each such operation
1845 the tags are again aligned to `org-tags-column'."
1846 :group 'org-tags
1847 :type 'boolean)
1849 (defcustom org-use-tag-inheritance t
1850 "Non-nil means, tags in levels apply also for sublevels.
1851 When nil, only the tags directly given in a specific line apply there.
1852 If this option is t, a match early-on in a tree can lead to a large
1853 number of matches in the subtree. If you only want to see the first
1854 match in a tree during a search, check out the variable
1855 `org-tags-match-list-sublevels'.
1857 This may also be a list of tags that should be inherited, or a regexp that
1858 matches tags that should be inherited."
1859 :group 'org-tags
1860 :type '(choice
1861 (const :tag "Not" nil)
1862 (const :tag "Always" t)
1863 (repeat :tag "Specific tags" (string :tag "Tag"))
1864 (regexp :tag "Tags matched by regexp")))
1866 (defun org-tag-inherit-p (tag)
1867 "Check if TAG is one that should be inherited."
1868 (cond
1869 ((eq org-use-tag-inheritance t) t)
1870 ((not org-use-tag-inheritance) nil)
1871 ((stringp org-use-tag-inheritance)
1872 (string-match org-use-tag-inheritance tag))
1873 ((listp org-use-tag-inheritance)
1874 (member tag org-use-tag-inheritance))
1875 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1877 (defcustom org-tags-match-list-sublevels t
1878 "Non-nil means list also sublevels of headlines matching tag search.
1879 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1880 the sublevels of a headline matching a tag search often also match
1881 the same search. Listing all of them can create very long lists.
1882 Setting this variable to nil causes subtrees of a match to be skipped.
1883 This option is off by default, because inheritance in on. If you turn
1884 inheritance off, you very likely want to turn this option on.
1886 As a special case, if the tag search is restricted to TODO items, the
1887 value of this variable is ignored and sublevels are always checked, to
1888 make sure all corresponding TODO items find their way into the list."
1889 :group 'org-tags
1890 :type 'boolean)
1892 (defvar org-tags-history nil
1893 "History of minibuffer reads for tags.")
1894 (defvar org-last-tags-completion-table nil
1895 "The last used completion table for tags.")
1896 (defvar org-after-tags-change-hook nil
1897 "Hook that is run after the tags in a line have changed.")
1899 (defgroup org-properties nil
1900 "Options concerning properties in Org-mode."
1901 :tag "Org Properties"
1902 :group 'org)
1904 (defcustom org-property-format "%-10s %s"
1905 "How property key/value pairs should be formatted by `indent-line'.
1906 When `indent-line' hits a property definition, it will format the line
1907 according to this format, mainly to make sure that the values are
1908 lined-up with respect to each other."
1909 :group 'org-properties
1910 :type 'string)
1912 (defcustom org-use-property-inheritance nil
1913 "Non-nil means, properties apply also for sublevels.
1915 This setting is chiefly used during property searches. Turning it on can
1916 cause significant overhead when doing a search, which is why it is not
1917 on by default.
1919 When nil, only the properties directly given in the current entry count.
1920 When t, every property is inherited. The value may also be a list of
1921 properties that should have inheritance, or a regular expression matching
1922 properties that should be inherited.
1924 However, note that some special properties use inheritance under special
1925 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1926 and the properties ending in \"_ALL\" when they are used as descriptor
1927 for valid values of a property.
1929 Note for programmers:
1930 When querying an entry with `org-entry-get', you can control if inheritance
1931 should be used. By default, `org-entry-get' looks only at the local
1932 properties. You can request inheritance by setting the inherit argument
1933 to t (to force inheritance) or to `selective' (to respect the setting
1934 in this variable)."
1935 :group 'org-properties
1936 :type '(choice
1937 (const :tag "Not" nil)
1938 (const :tag "Always" t)
1939 (repeat :tag "Specific properties" (string :tag "Property"))
1940 (regexp :tag "Properties matched by regexp")))
1942 (defun org-property-inherit-p (property)
1943 "Check if PROPERTY is one that should be inherited."
1944 (cond
1945 ((eq org-use-property-inheritance t) t)
1946 ((not org-use-property-inheritance) nil)
1947 ((stringp org-use-property-inheritance)
1948 (string-match org-use-property-inheritance property))
1949 ((listp org-use-property-inheritance)
1950 (member property org-use-property-inheritance))
1951 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1953 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1954 "The default column format, if no other format has been defined.
1955 This variable can be set on the per-file basis by inserting a line
1957 #+COLUMNS: %25ITEM ....."
1958 :group 'org-properties
1959 :type 'string)
1961 (defcustom org-columns-ellipses ".."
1962 "The ellipses to be used when a field in column view is truncated.
1963 When this is the empty string, as many characters as possible are shown,
1964 but then there will be no visual indication that the field has been truncated.
1965 When this is a string of length N, the last N characters of a truncated
1966 field are replaced by this string. If the column is narrower than the
1967 ellipses string, only part of the ellipses string will be shown."
1968 :group 'org-properties
1969 :type 'string)
1971 (defcustom org-columns-modify-value-for-display-function nil
1972 "Function that modifies values for display in column view.
1973 For example, it can be used to cut out a certain part from a time stamp.
1974 The function must take 2 arguments:
1976 column-title The tite of the column (*not* the property name)
1977 value The value that should be modified.
1979 The function should return the value that should be displayed,
1980 or nil if the normal value should be used."
1981 :group 'org-properties
1982 :type 'function)
1984 (defcustom org-effort-property "Effort"
1985 "The property that is being used to keep track of effort estimates.
1986 Effort estimates given in this property need to have the format H:MM."
1987 :group 'org-properties
1988 :group 'org-progress
1989 :type '(string :tag "Property"))
1991 (defconst org-global-properties-fixed
1992 '(("VISIBILITY_ALL" . "folded children content all"))
1993 "List of property/value pairs that can be inherited by any entry.
1994 These are fixed values, for the preset properties.")
1997 (defcustom org-global-properties nil
1998 "List of property/value pairs that can be inherited by any entry.
1999 You can set buffer-local values for this by adding lines like
2001 #+PROPERTY: NAME VALUE"
2002 :group 'org-properties
2003 :type '(repeat
2004 (cons (string :tag "Property")
2005 (string :tag "Value"))))
2007 (defvar org-file-properties nil
2008 "List of property/value pairs that can be inherited by any entry.
2009 Valid for the current buffer.
2010 This variable is populated from #+PROPERTY lines.")
2011 (make-variable-buffer-local 'org-file-properties)
2013 (defgroup org-agenda nil
2014 "Options concerning agenda views in Org-mode."
2015 :tag "Org Agenda"
2016 :group 'org)
2018 (defvar org-category nil
2019 "Variable used by org files to set a category for agenda display.
2020 Such files should use a file variable to set it, for example
2022 # -*- mode: org; org-category: \"ELisp\"
2024 or contain a special line
2026 #+CATEGORY: ELisp
2028 If the file does not specify a category, then file's base name
2029 is used instead.")
2030 (make-variable-buffer-local 'org-category)
2031 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2033 (defcustom org-agenda-files nil
2034 "The files to be used for agenda display.
2035 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2036 \\[org-remove-file]. You can also use customize to edit the list.
2038 If an entry is a directory, all files in that directory that are matched by
2039 `org-agenda-file-regexp' will be part of the file list.
2041 If the value of the variable is not a list but a single file name, then
2042 the list of agenda files is actually stored and maintained in that file, one
2043 agenda file per line."
2044 :group 'org-agenda
2045 :type '(choice
2046 (repeat :tag "List of files and directories" file)
2047 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2049 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2050 "Regular expression to match files for `org-agenda-files'.
2051 If any element in the list in that variable contains a directory instead
2052 of a normal file, all files in that directory that are matched by this
2053 regular expression will be included."
2054 :group 'org-agenda
2055 :type 'regexp)
2057 (defcustom org-agenda-text-search-extra-files nil
2058 "List of extra files to be searched by text search commands.
2059 These files will be search in addition to the agenda files by the
2060 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2061 Note that these files will only be searched for text search commands,
2062 not for the other agenda views like todo lists, tag searches or the weekly
2063 agenda. This variable is intended to list notes and possibly archive files
2064 that should also be searched by these two commands.
2065 In fact, if the first element in the list is the symbol `agenda-archives',
2066 than all archive files of all agenda files will be added to the search
2067 scope."
2068 :group 'org-agenda
2069 :type '(set :greedy t
2070 (const :tag "Agenda Archives" agenda-archives)
2071 (repeat :inline t (file))))
2073 (if (fboundp 'defvaralias)
2074 (defvaralias 'org-agenda-multi-occur-extra-files
2075 'org-agenda-text-search-extra-files))
2077 (defcustom org-agenda-skip-unavailable-files nil
2078 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2079 A nil value means to remove them, after a query, from the list."
2080 :group 'org-agenda
2081 :type 'boolean)
2083 (defcustom org-calendar-to-agenda-key [?c]
2084 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2085 The command `org-calendar-goto-agenda' will be bound to this key. The
2086 default is the character `c' because then `c' can be used to switch back and
2087 forth between agenda and calendar."
2088 :group 'org-agenda
2089 :type 'sexp)
2091 (defcustom org-calendar-agenda-action-key [?k]
2092 "The key to be installed in `calendar-mode-map' for agenda-action.
2093 The command `org-agenda-action' will be bound to this key. The
2094 default is the character `k' because we use the same key in the agenda."
2095 :group 'org-agenda
2096 :type 'sexp)
2098 (eval-after-load "calendar"
2099 '(progn
2100 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2101 'org-calendar-goto-agenda)
2102 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2103 'org-agenda-action)))
2105 (defgroup org-latex nil
2106 "Options for embedding LaTeX code into Org-mode."
2107 :tag "Org LaTeX"
2108 :group 'org)
2110 (defcustom org-format-latex-options
2111 '(:foreground default :background default :scale 1.0
2112 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2113 :matchers ("begin" "$" "$$" "\\(" "\\["))
2114 "Options for creating images from LaTeX fragments.
2115 This is a property list with the following properties:
2116 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2117 `default' means use the foreground of the default face.
2118 :background the background color, or \"Transparent\".
2119 `default' means use the background of the default face.
2120 :scale a scaling factor for the size of the images.
2121 :html-foreground, :html-background, :html-scale
2122 the same numbers for HTML export.
2123 :matchers a list indicating which matchers should be used to
2124 find LaTeX fragments. Valid members of this list are:
2125 \"begin\" find environments
2126 \"$\" find math expressions surrounded by $...$
2127 \"$$\" find math expressions surrounded by $$....$$
2128 \"\\(\" find math expressions surrounded by \\(...\\)
2129 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2130 :group 'org-latex
2131 :type 'plist)
2133 (defcustom org-format-latex-header "\\documentclass{article}
2134 \\usepackage{fullpage} % do not remove
2135 \\usepackage{amssymb}
2136 \\usepackage[usenames]{color}
2137 \\usepackage{amsmath}
2138 \\usepackage{latexsym}
2139 \\usepackage[mathscr]{eucal}
2140 \\pagestyle{empty} % do not remove"
2141 "The document header used for processing LaTeX fragments."
2142 :group 'org-latex
2143 :type 'string)
2146 (defgroup org-font-lock nil
2147 "Font-lock settings for highlighting in Org-mode."
2148 :tag "Org Font Lock"
2149 :group 'org)
2151 (defcustom org-level-color-stars-only nil
2152 "Non-nil means fontify only the stars in each headline.
2153 When nil, the entire headline is fontified.
2154 Changing it requires restart of `font-lock-mode' to become effective
2155 also in regions already fontified."
2156 :group 'org-font-lock
2157 :type 'boolean)
2159 (defcustom org-hide-leading-stars nil
2160 "Non-nil means, hide the first N-1 stars in a headline.
2161 This works by using the face `org-hide' for these stars. This
2162 face is white for a light background, and black for a dark
2163 background. You may have to customize the face `org-hide' to
2164 make this work.
2165 Changing it requires restart of `font-lock-mode' to become effective
2166 also in regions already fontified.
2167 You may also set this on a per-file basis by adding one of the following
2168 lines to the buffer:
2170 #+STARTUP: hidestars
2171 #+STARTUP: showstars"
2172 :group 'org-font-lock
2173 :type 'boolean)
2175 (defcustom org-fontify-done-headline nil
2176 "Non-nil means, change the face of a headline if it is marked DONE.
2177 Normally, only the TODO/DONE keyword indicates the state of a headline.
2178 When this is non-nil, the headline after the keyword is set to the
2179 `org-headline-done' as an additional indication."
2180 :group 'org-font-lock
2181 :type 'boolean)
2183 (defcustom org-fontify-emphasized-text t
2184 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2185 Changing this variable requires a restart of Emacs to take effect."
2186 :group 'org-font-lock
2187 :type 'boolean)
2189 (defcustom org-highlight-latex-fragments-and-specials nil
2190 "Non-nil means, fontify what is treated specially by the exporters."
2191 :group 'org-font-lock
2192 :type 'boolean)
2194 (defcustom org-hide-emphasis-markers nil
2195 "Non-nil mean font-lock should hide the emphasis marker characters."
2196 :group 'org-font-lock
2197 :type 'boolean)
2199 (defvar org-emph-re nil
2200 "Regular expression for matching emphasis.")
2201 (defvar org-verbatim-re nil
2202 "Regular expression for matching verbatim text.")
2203 (defvar org-emphasis-regexp-components) ; defined just below
2204 (defvar org-emphasis-alist) ; defined just below
2205 (defun org-set-emph-re (var val)
2206 "Set variable and compute the emphasis regular expression."
2207 (set var val)
2208 (when (and (boundp 'org-emphasis-alist)
2209 (boundp 'org-emphasis-regexp-components)
2210 org-emphasis-alist org-emphasis-regexp-components)
2211 (let* ((e org-emphasis-regexp-components)
2212 (pre (car e))
2213 (post (nth 1 e))
2214 (border (nth 2 e))
2215 (body (nth 3 e))
2216 (nl (nth 4 e))
2217 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2218 (body1 (concat body "*?"))
2219 (markers (mapconcat 'car org-emphasis-alist ""))
2220 (vmarkers (mapconcat
2221 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2222 org-emphasis-alist "")))
2223 ;; make sure special characters appear at the right position in the class
2224 (if (string-match "\\^" markers)
2225 (setq markers (concat (replace-match "" t t markers) "^")))
2226 (if (string-match "-" markers)
2227 (setq markers (concat (replace-match "" t t markers) "-")))
2228 (if (string-match "\\^" vmarkers)
2229 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2230 (if (string-match "-" vmarkers)
2231 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2232 (if (> nl 0)
2233 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2234 (int-to-string nl) "\\}")))
2235 ;; Make the regexp
2236 (setq org-emph-re
2237 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2238 "\\("
2239 "\\([" markers "]\\)"
2240 "\\("
2241 "[^" border "]\\|"
2242 "[^" border (if (and nil stacked) markers) "]"
2243 body1
2244 "[^" border (if (and nil stacked) markers) "]"
2245 "\\)"
2246 "\\3\\)"
2247 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2248 (setq org-verbatim-re
2249 (concat "\\([" pre "]\\|^\\)"
2250 "\\("
2251 "\\([" vmarkers "]\\)"
2252 "\\("
2253 "[^" border "]\\|"
2254 "[^" border "]"
2255 body1
2256 "[^" border "]"
2257 "\\)"
2258 "\\3\\)"
2259 "\\([" post "]\\|$\\)")))))
2261 (defcustom org-emphasis-regexp-components
2262 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2263 "Components used to build the regular expression for emphasis.
2264 This is a list with 6 entries. Terminology: In an emphasis string
2265 like \" *strong word* \", we call the initial space PREMATCH, the final
2266 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2267 and \"trong wor\" is the body. The different components in this variable
2268 specify what is allowed/forbidden in each part:
2270 pre Chars allowed as prematch. Beginning of line will be allowed too.
2271 post Chars allowed as postmatch. End of line will be allowed too.
2272 border The chars *forbidden* as border characters.
2273 body-regexp A regexp like \".\" to match a body character. Don't use
2274 non-shy groups here, and don't allow newline here.
2275 newline The maximum number of newlines allowed in an emphasis exp.
2277 Use customize to modify this, or restart Emacs after changing it."
2278 :group 'org-font-lock
2279 :set 'org-set-emph-re
2280 :type '(list
2281 (sexp :tag "Allowed chars in pre ")
2282 (sexp :tag "Allowed chars in post ")
2283 (sexp :tag "Forbidden chars in border ")
2284 (sexp :tag "Regexp for body ")
2285 (integer :tag "number of newlines allowed")
2286 (option (boolean :tag "Please ignore this button"))))
2288 (defcustom org-emphasis-alist
2289 `(("*" bold "<b>" "</b>")
2290 ("/" italic "<i>" "</i>")
2291 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2292 ("=" org-code "<code>" "</code>" verbatim)
2293 ("~" org-verbatim "<code>" "</code>" verbatim)
2294 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2295 "<del>" "</del>")
2297 "Special syntax for emphasized text.
2298 Text starting and ending with a special character will be emphasized, for
2299 example *bold*, _underlined_ and /italic/. This variable sets the marker
2300 characters, the face to be used by font-lock for highlighting in Org-mode
2301 Emacs buffers, and the HTML tags to be used for this.
2302 Use customize to modify this, or restart Emacs after changing it."
2303 :group 'org-font-lock
2304 :set 'org-set-emph-re
2305 :type '(repeat
2306 (list
2307 (string :tag "Marker character")
2308 (choice
2309 (face :tag "Font-lock-face")
2310 (plist :tag "Face property list"))
2311 (string :tag "HTML start tag")
2312 (string :tag "HTML end tag")
2313 (option (const verbatim)))))
2315 ;;; Miscellaneous options
2317 (defgroup org-completion nil
2318 "Completion in Org-mode."
2319 :tag "Org Completion"
2320 :group 'org)
2322 (defcustom org-completion-fallback-command 'hippie-expand
2323 "The expansion command called by \\[org-complete] in normal context.
2324 Normal means, no org-mode-specific context."
2325 :group 'org-completion
2326 :type 'function)
2328 ;;; Functions and variables from ther packages
2329 ;; Declared here to avoid compiler warnings
2331 ;; XEmacs only
2332 (defvar outline-mode-menu-heading)
2333 (defvar outline-mode-menu-show)
2334 (defvar outline-mode-menu-hide)
2335 (defvar zmacs-regions) ; XEmacs regions
2337 ;; Emacs only
2338 (defvar mark-active)
2340 ;; Various packages
2341 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2342 (declare-function calendar-forward-day "cal-move" (arg))
2343 (declare-function calendar-goto-date "cal-move" (date))
2344 (declare-function calendar-goto-today "cal-move" ())
2345 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2346 (defvar calc-embedded-close-formula)
2347 (defvar calc-embedded-open-formula)
2348 (declare-function cdlatex-tab "ext:cdlatex" ())
2349 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2350 (defvar font-lock-unfontify-region-function)
2351 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2352 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2353 (defvar iswitchb-temp-buflist)
2354 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2355 (declare-function org-agenda-skip "org-agenda" ())
2356 (declare-function org-format-agenda-item "org-agenda"
2357 (extra txt &optional category tags dotime noprefix remove-re))
2358 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2359 (declare-function org-agenda-change-all-lines "org-agenda"
2360 (newhead hdmarker &optional fixface))
2361 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2362 (declare-function org-agenda-maybe-redo "org-agenda" ())
2363 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2364 (beg end))
2365 (declare-function parse-time-string "parse-time" (string))
2366 (declare-function remember "remember" (&optional initial))
2367 (declare-function remember-buffer-desc "remember" ())
2368 (declare-function remember-finalize "remember" ())
2369 (defvar remember-save-after-remembering)
2370 (defvar remember-data-file)
2371 (defvar remember-register)
2372 (defvar remember-buffer)
2373 (defvar remember-handler-functions)
2374 (defvar remember-annotation-functions)
2375 (defvar texmathp-why)
2376 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2377 (declare-function table--at-cell-p "table" (position &optional object at-column))
2379 (defvar w3m-current-url)
2380 (defvar w3m-current-title)
2382 (defvar org-latex-regexps)
2384 ;;; Autoload and prepare some org modules
2386 ;; Some table stuff that needs to be defined here, because it is used
2387 ;; by the functions setting up org-mode or checking for table context.
2389 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2390 "Detects an org-type or table-type table.")
2391 (defconst org-table-line-regexp "^[ \t]*|"
2392 "Detects an org-type table line.")
2393 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2394 "Detects an org-type table line.")
2395 (defconst org-table-hline-regexp "^[ \t]*|-"
2396 "Detects an org-type table hline.")
2397 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2398 "Detects a table-type table hline.")
2399 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2400 "Searching from within a table (any type) this finds the first line
2401 outside the table.")
2403 ;; Autoload the functions in org-table.el that are needed by functions here.
2405 (eval-and-compile
2406 (org-autoload "org-table"
2407 '(org-table-align org-table-begin org-table-blank-field
2408 org-table-convert org-table-convert-region org-table-copy-down
2409 org-table-copy-region org-table-create
2410 org-table-create-or-convert-from-region
2411 org-table-create-with-table.el org-table-current-dline
2412 org-table-cut-region org-table-delete-column org-table-edit-field
2413 org-table-edit-formulas org-table-end org-table-eval-formula
2414 org-table-export org-table-field-info
2415 org-table-get-stored-formulas org-table-goto-column
2416 org-table-hline-and-move org-table-import org-table-insert-column
2417 org-table-insert-hline org-table-insert-row org-table-iterate
2418 org-table-justify-field-maybe org-table-kill-row
2419 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2420 org-table-move-column org-table-move-column-left
2421 org-table-move-column-right org-table-move-row
2422 org-table-move-row-down org-table-move-row-up
2423 org-table-next-field org-table-next-row org-table-paste-rectangle
2424 org-table-previous-field org-table-recalculate
2425 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2426 org-table-toggle-coordinate-overlays
2427 org-table-toggle-formula-debugger org-table-wrap-region
2428 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2430 (defun org-at-table-p (&optional table-type)
2431 "Return t if the cursor is inside an org-type table.
2432 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2433 (if org-enable-table-editor
2434 (save-excursion
2435 (beginning-of-line 1)
2436 (looking-at (if table-type org-table-any-line-regexp
2437 org-table-line-regexp)))
2438 nil))
2439 (defsubst org-table-p () (org-at-table-p))
2441 (defun org-at-table.el-p ()
2442 "Return t if and only if we are at a table.el table."
2443 (and (org-at-table-p 'any)
2444 (save-excursion
2445 (goto-char (org-table-begin 'any))
2446 (looking-at org-table1-hline-regexp))))
2447 (defun org-table-recognize-table.el ()
2448 "If there is a table.el table nearby, recognize it and move into it."
2449 (if org-table-tab-recognizes-table.el
2450 (if (org-at-table.el-p)
2451 (progn
2452 (beginning-of-line 1)
2453 (if (looking-at org-table-dataline-regexp)
2455 (if (looking-at org-table1-hline-regexp)
2456 (progn
2457 (beginning-of-line 2)
2458 (if (looking-at org-table-any-border-regexp)
2459 (beginning-of-line -1)))))
2460 (if (re-search-forward "|" (org-table-end t) t)
2461 (progn
2462 (require 'table)
2463 (if (table--at-cell-p (point))
2465 (message "recognizing table.el table...")
2466 (table-recognize-table)
2467 (message "recognizing table.el table...done")))
2468 (error "This should not happen..."))
2470 nil)
2471 nil))
2473 (defun org-at-table-hline-p ()
2474 "Return t if the cursor is inside a hline in a table."
2475 (if org-enable-table-editor
2476 (save-excursion
2477 (beginning-of-line 1)
2478 (looking-at org-table-hline-regexp))
2479 nil))
2481 (defvar org-table-clean-did-remove-column nil)
2483 (defun org-table-map-tables (function)
2484 "Apply FUNCTION to the start of all tables in the buffer."
2485 (save-excursion
2486 (save-restriction
2487 (widen)
2488 (goto-char (point-min))
2489 (while (re-search-forward org-table-any-line-regexp nil t)
2490 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2491 (beginning-of-line 1)
2492 (if (looking-at org-table-line-regexp)
2493 (save-excursion (funcall function)))
2494 (re-search-forward org-table-any-border-regexp nil 1))))
2495 (message "Mapping tables: done"))
2497 ;; Declare and autoload functions from org-exp.el
2499 (declare-function org-default-export-plist "org-exp")
2500 (declare-function org-infile-export-plist "org-exp")
2501 (declare-function org-get-current-options "org-exp")
2502 (eval-and-compile
2503 (org-autoload "org-exp"
2504 '(org-export org-export-as-ascii org-export-visible
2505 org-insert-export-options-template org-export-as-html-and-open
2506 org-export-as-html-batch org-export-as-html-to-buffer
2507 org-replace-region-by-html org-export-region-as-html
2508 org-export-as-html org-export-icalendar-this-file
2509 org-export-icalendar-all-agenda-files
2510 org-table-clean-before-export
2511 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2513 ;; Declare and autoload functions from org-agenda.el
2515 (eval-and-compile
2516 (org-autoload "org-agenda"
2517 '(org-agenda org-agenda-list org-search-view
2518 org-todo-list org-tags-view org-agenda-list-stuck-projects
2519 org-diary org-agenda-to-appt)))
2521 ;; Autoload org-remember
2523 (eval-and-compile
2524 (org-autoload "org-remember"
2525 '(org-remember-insinuate org-remember-annotation
2526 org-remember-apply-template org-remember org-remember-handler)))
2528 ;; Autoload org-clock.el
2531 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2532 (beg end))
2533 (declare-function org-update-mode-line "org-clock" ())
2534 (defvar org-clock-start-time)
2535 (defvar org-clock-marker (make-marker)
2536 "Marker recording the last clock-in.")
2538 (eval-and-compile
2539 (org-autoload
2540 "org-clock"
2541 '(org-clock-in org-clock-out org-clock-cancel
2542 org-clock-goto org-clock-sum org-clock-display
2543 org-remove-clock-overlays org-clock-report
2544 org-clocktable-shift org-dblock-write:clocktable
2545 org-get-clocktable)))
2547 (defun org-clock-update-time-maybe ()
2548 "If this is a CLOCK line, update it and return t.
2549 Otherwise, return nil."
2550 (interactive)
2551 (save-excursion
2552 (beginning-of-line 1)
2553 (skip-chars-forward " \t")
2554 (when (looking-at org-clock-string)
2555 (let ((re (concat "[ \t]*" org-clock-string
2556 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2557 "\\([ \t]*=>.*\\)?\\)?"))
2558 ts te h m s neg)
2559 (cond
2560 ((not (looking-at re))
2561 nil)
2562 ((not (match-end 2))
2563 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2564 (> org-clock-marker (point))
2565 (<= org-clock-marker (point-at-eol)))
2566 ;; The clock is running here
2567 (setq org-clock-start-time
2568 (apply 'encode-time
2569 (org-parse-time-string (match-string 1))))
2570 (org-update-mode-line)))
2572 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2573 (end-of-line 1)
2574 (setq ts (match-string 1)
2575 te (match-string 3))
2576 (setq s (- (time-to-seconds
2577 (apply 'encode-time (org-parse-time-string te)))
2578 (time-to-seconds
2579 (apply 'encode-time (org-parse-time-string ts))))
2580 neg (< s 0)
2581 s (abs s)
2582 h (floor (/ s 3600))
2583 s (- s (* 3600 h))
2584 m (floor (/ s 60))
2585 s (- s (* 60 s)))
2586 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2587 t))))))
2589 (defun org-check-running-clock ()
2590 "Check if the current buffer contains the running clock.
2591 If yes, offer to stop it and to save the buffer with the changes."
2592 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2593 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2594 (buffer-name))))
2595 (org-clock-out)
2596 (when (y-or-n-p "Save changed buffer?")
2597 (save-buffer))))
2599 (defun org-clocktable-try-shift (dir n)
2600 "Check if this line starts a clock table, if yes, shift the time block."
2601 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2602 (org-clocktable-shift dir n)))
2604 ;; Autoload archiving code
2605 ;; The stuff that is needed for cycling and tags has to be defined here.
2607 (defgroup org-archive nil
2608 "Options concerning archiving in Org-mode."
2609 :tag "Org Archive"
2610 :group 'org-structure)
2612 (defcustom org-archive-location "%s_archive::"
2613 "The location where subtrees should be archived.
2615 Otherwise, the value of this variable is a string, consisting of two
2616 parts, separated by a double-colon.
2618 The first part is a file name - when omitted, archiving happens in the same
2619 file. %s will be replaced by the current file name (without directory part).
2620 Archiving to a different file is useful to keep archived entries from
2621 contributing to the Org-mode Agenda.
2623 The part after the double colon is a headline. The archived entries will be
2624 filed under that headline. When omitted, the subtrees are simply filed away
2625 at the end of the file, as top-level entries.
2627 Here are a few examples:
2628 \"%s_archive::\"
2629 If the current file is Projects.org, archive in file
2630 Projects.org_archive, as top-level trees. This is the default.
2632 \"::* Archived Tasks\"
2633 Archive in the current file, under the top-level headline
2634 \"* Archived Tasks\".
2636 \"~/org/archive.org::\"
2637 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2639 \"basement::** Finished Tasks\"
2640 Archive in file ./basement (relative path), as level 3 trees
2641 below the level 2 heading \"** Finished Tasks\".
2643 You may set this option on a per-file basis by adding to the buffer a
2644 line like
2646 #+ARCHIVE: basement::** Finished Tasks
2648 You may also define it locally for a subtree by setting an ARCHIVE property
2649 in the entry. If such a property is found in an entry, or anywhere up
2650 the hierarchy, it will be used."
2651 :group 'org-archive
2652 :type 'string)
2654 (defcustom org-archive-tag "ARCHIVE"
2655 "The tag that marks a subtree as archived.
2656 An archived subtree does not open during visibility cycling, and does
2657 not contribute to the agenda listings.
2658 After changing this, font-lock must be restarted in the relevant buffers to
2659 get the proper fontification."
2660 :group 'org-archive
2661 :group 'org-keywords
2662 :type 'string)
2664 (defcustom org-agenda-skip-archived-trees t
2665 "Non-nil means, the agenda will skip any items located in archived trees.
2666 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2667 variable is no longer recommended, you should leave it at the value t.
2668 Instead, use the key `v' to cycle the archives-mode in the agenda."
2669 :group 'org-archive
2670 :group 'org-agenda-skip
2671 :type 'boolean)
2673 (defcustom org-cycle-open-archived-trees nil
2674 "Non-nil means, `org-cycle' will open archived trees.
2675 An archived tree is a tree marked with the tag ARCHIVE.
2676 When nil, archived trees will stay folded. You can still open them with
2677 normal outline commands like `show-all', but not with the cycling commands."
2678 :group 'org-archive
2679 :group 'org-cycle
2680 :type 'boolean)
2682 (defcustom org-sparse-tree-open-archived-trees nil
2683 "Non-nil means sparse tree construction shows matches in archived trees.
2684 When nil, matches in these trees are highlighted, but the trees are kept in
2685 collapsed state."
2686 :group 'org-archive
2687 :group 'org-sparse-trees
2688 :type 'boolean)
2690 (defun org-cycle-hide-archived-subtrees (state)
2691 "Re-hide all archived subtrees after a visibility state change."
2692 (when (and (not org-cycle-open-archived-trees)
2693 (not (memq state '(overview folded))))
2694 (save-excursion
2695 (let* ((globalp (memq state '(contents all)))
2696 (beg (if globalp (point-min) (point)))
2697 (end (if globalp (point-max) (org-end-of-subtree t))))
2698 (org-hide-archived-subtrees beg end)
2699 (goto-char beg)
2700 (if (looking-at (concat ".*:" org-archive-tag ":"))
2701 (message "%s" (substitute-command-keys
2702 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2704 (defun org-force-cycle-archived ()
2705 "Cycle subtree even if it is archived."
2706 (interactive)
2707 (setq this-command 'org-cycle)
2708 (let ((org-cycle-open-archived-trees t))
2709 (call-interactively 'org-cycle)))
2711 (defun org-hide-archived-subtrees (beg end)
2712 "Re-hide all archived subtrees after a visibility state change."
2713 (save-excursion
2714 (let* ((re (concat ":" org-archive-tag ":")))
2715 (goto-char beg)
2716 (while (re-search-forward re end t)
2717 (and (org-on-heading-p) (hide-subtree))
2718 (org-end-of-subtree t)))))
2720 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2722 (eval-and-compile
2723 (org-autoload "org-archive"
2724 '(org-add-archive-files org-archive-subtree
2725 org-archive-to-archive-sibling org-toggle-archive-tag)))
2727 ;; Autoload Column View Code
2729 (declare-function org-columns-number-to-string "org-colview")
2730 (declare-function org-columns-get-format-and-top-level "org-colview")
2731 (declare-function org-columns-compute "org-colview")
2733 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2734 '(org-columns-number-to-string org-columns-get-format-and-top-level
2735 org-columns-compute org-agenda-columns org-columns-remove-overlays
2736 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2738 ;; Autoload ID code
2740 (org-autoload "org-id"
2741 '(org-id-get-create org-id-new org-id-copy org-id-get
2742 org-id-get-with-outline-path-completion
2743 org-id-get-with-outline-drilling
2744 org-id-goto org-id-find))
2746 ;;; Variables for pre-computed regular expressions, all buffer local
2748 (defvar org-drawer-regexp nil
2749 "Matches first line of a hidden block.")
2750 (make-variable-buffer-local 'org-drawer-regexp)
2751 (defvar org-todo-regexp nil
2752 "Matches any of the TODO state keywords.")
2753 (make-variable-buffer-local 'org-todo-regexp)
2754 (defvar org-not-done-regexp nil
2755 "Matches any of the TODO state keywords except the last one.")
2756 (make-variable-buffer-local 'org-not-done-regexp)
2757 (defvar org-todo-line-regexp nil
2758 "Matches a headline and puts TODO state into group 2 if present.")
2759 (make-variable-buffer-local 'org-todo-line-regexp)
2760 (defvar org-complex-heading-regexp nil
2761 "Matches a headline and puts everything into groups:
2762 group 1: the stars
2763 group 2: The todo keyword, maybe
2764 group 3: Priority cookie
2765 group 4: True headline
2766 group 5: Tags")
2767 (make-variable-buffer-local 'org-complex-heading-regexp)
2768 (defvar org-todo-line-tags-regexp nil
2769 "Matches a headline and puts TODO state into group 2 if present.
2770 Also put tags into group 4 if tags are present.")
2771 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2772 (defvar org-nl-done-regexp nil
2773 "Matches newline followed by a headline with the DONE keyword.")
2774 (make-variable-buffer-local 'org-nl-done-regexp)
2775 (defvar org-looking-at-done-regexp nil
2776 "Matches the DONE keyword a point.")
2777 (make-variable-buffer-local 'org-looking-at-done-regexp)
2778 (defvar org-ds-keyword-length 12
2779 "Maximum length of the Deadline and SCHEDULED keywords.")
2780 (make-variable-buffer-local 'org-ds-keyword-length)
2781 (defvar org-deadline-regexp nil
2782 "Matches the DEADLINE keyword.")
2783 (make-variable-buffer-local 'org-deadline-regexp)
2784 (defvar org-deadline-time-regexp nil
2785 "Matches the DEADLINE keyword together with a time stamp.")
2786 (make-variable-buffer-local 'org-deadline-time-regexp)
2787 (defvar org-deadline-line-regexp nil
2788 "Matches the DEADLINE keyword and the rest of the line.")
2789 (make-variable-buffer-local 'org-deadline-line-regexp)
2790 (defvar org-scheduled-regexp nil
2791 "Matches the SCHEDULED keyword.")
2792 (make-variable-buffer-local 'org-scheduled-regexp)
2793 (defvar org-scheduled-time-regexp nil
2794 "Matches the SCHEDULED keyword together with a time stamp.")
2795 (make-variable-buffer-local 'org-scheduled-time-regexp)
2796 (defvar org-closed-time-regexp nil
2797 "Matches the CLOSED keyword together with a time stamp.")
2798 (make-variable-buffer-local 'org-closed-time-regexp)
2800 (defvar org-keyword-time-regexp nil
2801 "Matches any of the 4 keywords, together with the time stamp.")
2802 (make-variable-buffer-local 'org-keyword-time-regexp)
2803 (defvar org-keyword-time-not-clock-regexp nil
2804 "Matches any of the 3 keywords, together with the time stamp.")
2805 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2806 (defvar org-maybe-keyword-time-regexp nil
2807 "Matches a timestamp, possibly preceeded by a keyword.")
2808 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2809 (defvar org-planning-or-clock-line-re nil
2810 "Matches a line with planning or clock info.")
2811 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2813 (defconst org-plain-time-of-day-regexp
2814 (concat
2815 "\\(\\<[012]?[0-9]"
2816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2817 "\\(--?"
2818 "\\(\\<[012]?[0-9]"
2819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2820 "\\)?")
2821 "Regular expression to match a plain time or time range.
2822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2823 groups carry important information:
2824 0 the full match
2825 1 the first time, range or not
2826 8 the second time, if it is a range.")
2828 (defconst org-plain-time-extension-regexp
2829 (concat
2830 "\\(\\<[012]?[0-9]"
2831 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2832 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2833 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2834 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2835 groups carry important information:
2836 0 the full match
2837 7 hours of duration
2838 9 minutes of duration")
2840 (defconst org-stamp-time-of-day-regexp
2841 (concat
2842 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2843 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2844 "\\(--?"
2845 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2846 "Regular expression to match a timestamp time or time range.
2847 After a match, the following groups carry important information:
2848 0 the full match
2849 1 date plus weekday, for backreferencing to make sure both times on same day
2850 2 the first time, range or not
2851 4 the second time, if it is a range.")
2853 (defconst org-startup-options
2854 '(("fold" org-startup-folded t)
2855 ("overview" org-startup-folded t)
2856 ("nofold" org-startup-folded nil)
2857 ("showall" org-startup-folded nil)
2858 ("content" org-startup-folded content)
2859 ("hidestars" org-hide-leading-stars t)
2860 ("showstars" org-hide-leading-stars nil)
2861 ("odd" org-odd-levels-only t)
2862 ("oddeven" org-odd-levels-only nil)
2863 ("align" org-startup-align-all-tables t)
2864 ("noalign" org-startup-align-all-tables nil)
2865 ("customtime" org-display-custom-times t)
2866 ("logdone" org-log-done time)
2867 ("lognotedone" org-log-done note)
2868 ("nologdone" org-log-done nil)
2869 ("lognoteclock-out" org-log-note-clock-out t)
2870 ("nolognoteclock-out" org-log-note-clock-out nil)
2871 ("logrepeat" org-log-repeat state)
2872 ("lognoterepeat" org-log-repeat note)
2873 ("nologrepeat" org-log-repeat nil)
2874 ("constcgs" constants-unit-system cgs)
2875 ("constSI" constants-unit-system SI))
2876 "Variable associated with STARTUP options for org-mode.
2877 Each element is a list of three items: The startup options as written
2878 in the #+STARTUP line, the corresponding variable, and the value to
2879 set this variable to if the option is found. An optional forth element PUSH
2880 means to push this value onto the list in the variable.")
2882 (defun org-set-regexps-and-options ()
2883 "Precompute regular expressions for current buffer."
2884 (when (org-mode-p)
2885 (org-set-local 'org-todo-kwd-alist nil)
2886 (org-set-local 'org-todo-key-alist nil)
2887 (org-set-local 'org-todo-key-trigger nil)
2888 (org-set-local 'org-todo-keywords-1 nil)
2889 (org-set-local 'org-done-keywords nil)
2890 (org-set-local 'org-todo-heads nil)
2891 (org-set-local 'org-todo-sets nil)
2892 (org-set-local 'org-todo-log-states nil)
2893 (org-set-local 'org-file-properties nil)
2894 (org-set-local 'org-file-tags nil)
2895 (let ((re (org-make-options-regexp
2896 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2897 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2898 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2899 (splitre "[ \t]+")
2900 kwds kws0 kwsa key log value cat arch tags const links hw dws
2901 tail sep kws1 prio props ftags drawers
2902 ext-setup-or-nil setup-contents (start 0))
2903 (save-excursion
2904 (save-restriction
2905 (widen)
2906 (goto-char (point-min))
2907 (while (or (and ext-setup-or-nil
2908 (string-match re ext-setup-or-nil start)
2909 (setq start (match-end 0)))
2910 (and (setq ext-setup-or-nil nil start 0)
2911 (re-search-forward re nil t)))
2912 (setq key (upcase (match-string 1 ext-setup-or-nil))
2913 value (org-match-string-no-properties 2 ext-setup-or-nil))
2914 (cond
2915 ((equal key "CATEGORY")
2916 (if (string-match "[ \t]+$" value)
2917 (setq value (replace-match "" t t value)))
2918 (setq cat value))
2919 ((member key '("SEQ_TODO" "TODO"))
2920 (push (cons 'sequence (org-split-string value splitre)) kwds))
2921 ((equal key "TYP_TODO")
2922 (push (cons 'type (org-split-string value splitre)) kwds))
2923 ((equal key "TAGS")
2924 (setq tags (append tags (org-split-string value splitre))))
2925 ((equal key "COLUMNS")
2926 (org-set-local 'org-columns-default-format value))
2927 ((equal key "LINK")
2928 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2929 (push (cons (match-string 1 value)
2930 (org-trim (match-string 2 value)))
2931 links)))
2932 ((equal key "PRIORITIES")
2933 (setq prio (org-split-string value " +")))
2934 ((equal key "PROPERTY")
2935 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2936 (push (cons (match-string 1 value) (match-string 2 value))
2937 props)))
2938 ((equal key "FILETAGS")
2939 (when (string-match "\\S-" value)
2940 (setq ftags
2941 (append
2942 ftags
2943 (apply 'append
2944 (mapcar (lambda (x) (org-split-string x ":"))
2945 (org-split-string value)))))))
2946 ((equal key "DRAWERS")
2947 (setq drawers (org-split-string value splitre)))
2948 ((equal key "CONSTANTS")
2949 (setq const (append const (org-split-string value splitre))))
2950 ((equal key "STARTUP")
2951 (let ((opts (org-split-string value splitre))
2952 l var val)
2953 (while (setq l (pop opts))
2954 (when (setq l (assoc l org-startup-options))
2955 (setq var (nth 1 l) val (nth 2 l))
2956 (if (not (nth 3 l))
2957 (set (make-local-variable var) val)
2958 (if (not (listp (symbol-value var)))
2959 (set (make-local-variable var) nil))
2960 (set (make-local-variable var) (symbol-value var))
2961 (add-to-list var val))))))
2962 ((equal key "ARCHIVE")
2963 (string-match " *$" value)
2964 (setq arch (replace-match "" t t value))
2965 (remove-text-properties 0 (length arch)
2966 '(face t fontified t) arch))
2967 ((equal key "SETUPFILE")
2968 (setq setup-contents (org-file-contents
2969 (expand-file-name
2970 (org-remove-double-quotes value))
2971 'noerror))
2972 (if (not ext-setup-or-nil)
2973 (setq ext-setup-or-nil setup-contents start 0)
2974 (setq ext-setup-or-nil
2975 (concat (substring ext-setup-or-nil 0 start)
2976 "\n" setup-contents "\n"
2977 (substring ext-setup-or-nil start)))))
2978 ))))
2979 (when cat
2980 (org-set-local 'org-category (intern cat))
2981 (push (cons "CATEGORY" cat) props))
2982 (when prio
2983 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2984 (setq prio (mapcar 'string-to-char prio))
2985 (org-set-local 'org-highest-priority (nth 0 prio))
2986 (org-set-local 'org-lowest-priority (nth 1 prio))
2987 (org-set-local 'org-default-priority (nth 2 prio)))
2988 (and props (org-set-local 'org-file-properties (nreverse props)))
2989 (and ftags (org-set-local 'org-file-tags ftags))
2990 (and drawers (org-set-local 'org-drawers drawers))
2991 (and arch (org-set-local 'org-archive-location arch))
2992 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2993 ;; Process the TODO keywords
2994 (unless kwds
2995 ;; Use the global values as if they had been given locally.
2996 (setq kwds (default-value 'org-todo-keywords))
2997 (if (stringp (car kwds))
2998 (setq kwds (list (cons org-todo-interpretation
2999 (default-value 'org-todo-keywords)))))
3000 (setq kwds (reverse kwds)))
3001 (setq kwds (nreverse kwds))
3002 (let (inter kws kw)
3003 (while (setq kws (pop kwds))
3004 (setq inter (pop kws) sep (member "|" kws)
3005 kws0 (delete "|" (copy-sequence kws))
3006 kwsa nil
3007 kws1 (mapcar
3008 (lambda (x)
3009 ;; 1 2
3010 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3011 (progn
3012 (setq kw (match-string 1 x)
3013 key (and (match-end 2) (match-string 2 x))
3014 log (org-extract-log-state-settings x))
3015 (push (cons kw (and key (string-to-char key))) kwsa)
3016 (and log (push log org-todo-log-states))
3018 (error "Invalid TODO keyword %s" x)))
3019 kws0)
3020 kwsa (if kwsa (append '((:startgroup))
3021 (nreverse kwsa)
3022 '((:endgroup))))
3023 hw (car kws1)
3024 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3025 tail (list inter hw (car dws) (org-last dws)))
3026 (add-to-list 'org-todo-heads hw 'append)
3027 (push kws1 org-todo-sets)
3028 (setq org-done-keywords (append org-done-keywords dws nil))
3029 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3030 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3031 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3032 (setq org-todo-sets (nreverse org-todo-sets)
3033 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3034 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3035 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3036 ;; Process the constants
3037 (when const
3038 (let (e cst)
3039 (while (setq e (pop const))
3040 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3041 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3042 (setq org-table-formula-constants-local cst)))
3044 ;; Process the tags.
3045 (when tags
3046 (let (e tgs)
3047 (while (setq e (pop tags))
3048 (cond
3049 ((equal e "{") (push '(:startgroup) tgs))
3050 ((equal e "}") (push '(:endgroup) tgs))
3051 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3052 (push (cons (match-string 1 e)
3053 (string-to-char (match-string 2 e)))
3054 tgs))
3055 (t (push (list e) tgs))))
3056 (org-set-local 'org-tag-alist nil)
3057 (while (setq e (pop tgs))
3058 (or (and (stringp (car e))
3059 (assoc (car e) org-tag-alist))
3060 (push e org-tag-alist)))))
3062 ;; Compute the regular expressions and other local variables
3063 (if (not org-done-keywords)
3064 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3066 (length org-scheduled-string)
3067 (length org-clock-string)
3068 (length org-closed-string)))
3069 org-drawer-regexp
3070 (concat "^[ \t]*:\\("
3071 (mapconcat 'regexp-quote org-drawers "\\|")
3072 "\\):[ \t]*$")
3073 org-not-done-keywords
3074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3075 org-todo-regexp
3076 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3077 "\\|") "\\)\\>")
3078 org-not-done-regexp
3079 (concat "\\<\\("
3080 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3081 "\\)\\>")
3082 org-todo-line-regexp
3083 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3085 "\\)\\>\\)?[ \t]*\\(.*\\)")
3086 org-complex-heading-regexp
3087 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3088 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3089 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3090 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3091 org-nl-done-regexp
3092 (concat "\n\\*+[ \t]+"
3093 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3094 "\\)" "\\>")
3095 org-todo-line-tags-regexp
3096 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3097 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3098 (org-re
3099 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3100 org-looking-at-done-regexp
3101 (concat "^" "\\(?:"
3102 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3103 "\\>")
3104 org-deadline-regexp (concat "\\<" org-deadline-string)
3105 org-deadline-time-regexp
3106 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3107 org-deadline-line-regexp
3108 (concat "\\<\\(" org-deadline-string "\\).*")
3109 org-scheduled-regexp
3110 (concat "\\<" org-scheduled-string)
3111 org-scheduled-time-regexp
3112 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3113 org-closed-time-regexp
3114 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3115 org-keyword-time-regexp
3116 (concat "\\<\\(" org-scheduled-string
3117 "\\|" org-deadline-string
3118 "\\|" org-closed-string
3119 "\\|" org-clock-string "\\)"
3120 " *[[<]\\([^]>]+\\)[]>]")
3121 org-keyword-time-not-clock-regexp
3122 (concat "\\<\\(" org-scheduled-string
3123 "\\|" org-deadline-string
3124 "\\|" org-closed-string
3125 "\\)"
3126 " *[[<]\\([^]>]+\\)[]>]")
3127 org-maybe-keyword-time-regexp
3128 (concat "\\(\\<\\(" org-scheduled-string
3129 "\\|" org-deadline-string
3130 "\\|" org-closed-string
3131 "\\|" org-clock-string "\\)\\)?"
3132 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3133 org-planning-or-clock-line-re
3134 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3135 "\\|" org-deadline-string
3136 "\\|" org-closed-string "\\|" org-clock-string
3137 "\\)\\>\\)")
3139 (org-compute-latex-and-specials-regexp)
3140 (org-set-font-lock-defaults))))
3142 (defun org-file-contents (file &optional noerror)
3143 "Return the contents of FILE, as a string."
3144 (if (or (not file)
3145 (not (file-readable-p file)))
3146 (if noerror
3147 (progn
3148 (message "Cannot read file %s" file)
3149 (ding) (sit-for 2)
3151 (error "Cannot read file %s" file))
3152 (with-temp-buffer
3153 (insert-file-contents file)
3154 (buffer-string))))
3156 (defun org-extract-log-state-settings (x)
3157 "Extract the log state setting from a TODO keyword string.
3158 This will extract info from a string like \"WAIT(w@/!)\"."
3159 (let (kw key log1 log2)
3160 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3161 (setq kw (match-string 1 x)
3162 key (and (match-end 2) (match-string 2 x))
3163 log1 (and (match-end 3) (match-string 3 x))
3164 log2 (and (match-end 4) (match-string 4 x)))
3165 (and (or log1 log2)
3166 (list kw
3167 (and log1 (if (equal log1 "!") 'time 'note))
3168 (and log2 (if (equal log2 "!") 'time 'note)))))))
3170 (defun org-remove-keyword-keys (list)
3171 "Remove a pair of parenthesis at the end of each string in LIST."
3172 (mapcar (lambda (x)
3173 (if (string-match "(.*)$" x)
3174 (substring x 0 (match-beginning 0))
3176 list))
3178 ;; FIXME: this could be done much better, using second characters etc.
3179 (defun org-assign-fast-keys (alist)
3180 "Assign fast keys to a keyword-key alist.
3181 Respect keys that are already there."
3182 (let (new e k c c1 c2 (char ?a))
3183 (while (setq e (pop alist))
3184 (cond
3185 ((equal e '(:startgroup)) (push e new))
3186 ((equal e '(:endgroup)) (push e new))
3188 (setq k (car e) c2 nil)
3189 (if (cdr e)
3190 (setq c (cdr e))
3191 ;; automatically assign a character.
3192 (setq c1 (string-to-char
3193 (downcase (substring
3194 k (if (= (string-to-char k) ?@) 1 0)))))
3195 (if (or (rassoc c1 new) (rassoc c1 alist))
3196 (while (or (rassoc char new) (rassoc char alist))
3197 (setq char (1+ char)))
3198 (setq c2 c1))
3199 (setq c (or c2 char)))
3200 (push (cons k c) new))))
3201 (nreverse new)))
3203 ;;; Some variables used in various places
3205 (defvar org-window-configuration nil
3206 "Used in various places to store a window configuration.")
3207 (defvar org-finish-function nil
3208 "Function to be called when `C-c C-c' is used.
3209 This is for getting out of special buffers like remember.")
3212 ;; FIXME: Occasionally check by commenting these, to make sure
3213 ;; no other functions uses these, forgetting to let-bind them.
3214 (defvar entry)
3215 (defvar state)
3216 (defvar last-state)
3217 (defvar date)
3218 (defvar description)
3220 ;; Defined somewhere in this file, but used before definition.
3221 (defvar org-html-entities)
3222 (defvar org-struct-menu)
3223 (defvar org-org-menu)
3224 (defvar org-tbl-menu)
3225 (defvar org-agenda-keymap)
3227 ;;;; Define the Org-mode
3229 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3230 (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."))
3233 ;; We use a before-change function to check if a table might need
3234 ;; an update.
3235 (defvar org-table-may-need-update t
3236 "Indicates that a table might need an update.
3237 This variable is set by `org-before-change-function'.
3238 `org-table-align' sets it back to nil.")
3239 (defun org-before-change-function (beg end)
3240 "Every change indicates that a table might need an update."
3241 (setq org-table-may-need-update t))
3242 (defvar org-mode-map)
3243 (defvar org-mode-hook nil)
3244 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3245 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3246 (defvar org-table-buffer-is-an nil)
3247 (defconst org-outline-regexp "\\*+ ")
3249 ;;;###autoload
3250 (define-derived-mode org-mode outline-mode "Org"
3251 "Outline-based notes management and organizer, alias
3252 \"Carsten's outline-mode for keeping track of everything.\"
3254 Org-mode develops organizational tasks around a NOTES file which
3255 contains information about projects as plain text. Org-mode is
3256 implemented on top of outline-mode, which is ideal to keep the content
3257 of large files well structured. It supports ToDo items, deadlines and
3258 time stamps, which magically appear in the diary listing of the Emacs
3259 calendar. Tables are easily created with a built-in table editor.
3260 Plain text URL-like links connect to websites, emails (VM), Usenet
3261 messages (Gnus), BBDB entries, and any files related to the project.
3262 For printing and sharing of notes, an Org-mode file (or a part of it)
3263 can be exported as a structured ASCII or HTML file.
3265 The following commands are available:
3267 \\{org-mode-map}"
3269 ;; Get rid of Outline menus, they are not needed
3270 ;; Need to do this here because define-derived-mode sets up
3271 ;; the keymap so late. Still, it is a waste to call this each time
3272 ;; we switch another buffer into org-mode.
3273 (if (featurep 'xemacs)
3274 (when (boundp 'outline-mode-menu-heading)
3275 ;; Assume this is Greg's port, it used easymenu
3276 (easy-menu-remove outline-mode-menu-heading)
3277 (easy-menu-remove outline-mode-menu-show)
3278 (easy-menu-remove outline-mode-menu-hide))
3279 (define-key org-mode-map [menu-bar headings] 'undefined)
3280 (define-key org-mode-map [menu-bar hide] 'undefined)
3281 (define-key org-mode-map [menu-bar show] 'undefined))
3283 (org-load-modules-maybe)
3284 (easy-menu-add org-org-menu)
3285 (easy-menu-add org-tbl-menu)
3286 (org-install-agenda-files-menu)
3287 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3288 (org-add-to-invisibility-spec '(org-cwidth))
3289 (when (featurep 'xemacs)
3290 (org-set-local 'line-move-ignore-invisible t))
3291 (org-set-local 'outline-regexp org-outline-regexp)
3292 (org-set-local 'outline-level 'org-outline-level)
3293 (when (and org-ellipsis
3294 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3295 (fboundp 'make-glyph-code))
3296 (unless org-display-table
3297 (setq org-display-table (make-display-table)))
3298 (set-display-table-slot
3299 org-display-table 4
3300 (vconcat (mapcar
3301 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3302 org-ellipsis)))
3303 (if (stringp org-ellipsis) org-ellipsis "..."))))
3304 (setq buffer-display-table org-display-table))
3305 (org-set-regexps-and-options)
3306 ;; Calc embedded
3307 (org-set-local 'calc-embedded-open-mode "# ")
3308 (modify-syntax-entry ?# "<")
3309 (modify-syntax-entry ?@ "w")
3310 (if org-startup-truncated (setq truncate-lines t))
3311 (org-set-local 'font-lock-unfontify-region-function
3312 'org-unfontify-region)
3313 ;; Activate before-change-function
3314 (org-set-local 'org-table-may-need-update t)
3315 (org-add-hook 'before-change-functions 'org-before-change-function nil
3316 'local)
3317 ;; Check for running clock before killing a buffer
3318 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3319 ;; Paragraphs and auto-filling
3320 (org-set-autofill-regexps)
3321 (setq indent-line-function 'org-indent-line-function)
3322 (org-update-radio-target-regexp)
3324 ;; Comment characters
3325 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3326 (org-set-local 'comment-padding " ")
3328 ;; Align options lines
3329 (org-set-local
3330 'align-mode-rules-list
3331 '((org-in-buffer-settings
3332 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3333 (modes . '(org-mode)))))
3335 ;; Imenu
3336 (org-set-local 'imenu-create-index-function
3337 'org-imenu-get-tree)
3339 ;; Make isearch reveal context
3340 (if (or (featurep 'xemacs)
3341 (not (boundp 'outline-isearch-open-invisible-function)))
3342 ;; Emacs 21 and XEmacs make use of the hook
3343 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3344 ;; Emacs 22 deals with this through a special variable
3345 (org-set-local 'outline-isearch-open-invisible-function
3346 (lambda (&rest ignore) (org-show-context 'isearch))))
3348 ;; If empty file that did not turn on org-mode automatically, make it to.
3349 (if (and org-insert-mode-line-in-empty-file
3350 (interactive-p)
3351 (= (point-min) (point-max)))
3352 (insert "# -*- mode: org -*-\n\n"))
3354 (unless org-inhibit-startup
3355 (when org-startup-align-all-tables
3356 (let ((bmp (buffer-modified-p)))
3357 (org-table-map-tables 'org-table-align)
3358 (set-buffer-modified-p bmp)))
3359 (org-set-startup-visibility)))
3361 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3363 (defun org-current-time ()
3364 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3365 (if (> (car org-time-stamp-rounding-minutes) 1)
3366 (let ((r (car org-time-stamp-rounding-minutes))
3367 (time (decode-time)))
3368 (apply 'encode-time
3369 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3370 (nthcdr 2 time))))
3371 (current-time)))
3373 ;;;; Font-Lock stuff, including the activators
3375 (defvar org-mouse-map (make-sparse-keymap))
3376 (org-defkey org-mouse-map
3377 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3378 (org-defkey org-mouse-map
3379 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3380 (when org-mouse-1-follows-link
3381 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3382 (when org-tab-follows-link
3383 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3384 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3385 (when org-return-follows-link
3386 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3387 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3389 (require 'font-lock)
3391 (defconst org-non-link-chars "]\t\n\r<>")
3392 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3393 "shell" "elisp"))
3394 (defvar org-link-types-re nil
3395 "Matches a link that has a url-like prefix like \"http:\"")
3396 (defvar org-link-re-with-space nil
3397 "Matches a link with spaces, optional angular brackets around it.")
3398 (defvar org-link-re-with-space2 nil
3399 "Matches a link with spaces, optional angular brackets around it.")
3400 (defvar org-angle-link-re nil
3401 "Matches link with angular brackets, spaces are allowed.")
3402 (defvar org-plain-link-re nil
3403 "Matches plain link, without spaces.")
3404 (defvar org-bracket-link-regexp nil
3405 "Matches a link in double brackets.")
3406 (defvar org-bracket-link-analytic-regexp nil
3407 "Regular expression used to analyze links.
3408 Here is what the match groups contain after a match:
3409 1: http:
3410 2: http
3411 3: path
3412 4: [desc]
3413 5: desc")
3414 (defvar org-any-link-re nil
3415 "Regular expression matching any link.")
3417 (defun org-make-link-regexps ()
3418 "Update the link regular expressions.
3419 This should be called after the variable `org-link-types' has changed."
3420 (setq org-link-types-re
3421 (concat
3422 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3423 org-link-re-with-space
3424 (concat
3425 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3426 "\\([^" org-non-link-chars " ]"
3427 "[^" org-non-link-chars "]*"
3428 "[^" org-non-link-chars " ]\\)>?")
3429 org-link-re-with-space2
3430 (concat
3431 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3432 "\\([^" org-non-link-chars " ]"
3433 "[^\t\n\r]*"
3434 "[^" org-non-link-chars " ]\\)>?")
3435 org-angle-link-re
3436 (concat
3437 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3438 "\\([^" org-non-link-chars " ]"
3439 "[^" org-non-link-chars "]*"
3440 "\\)>")
3441 org-plain-link-re
3442 (concat
3443 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3444 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3445 org-bracket-link-regexp
3446 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3447 org-bracket-link-analytic-regexp
3448 (concat
3449 "\\[\\["
3450 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3451 "\\([^]]+\\)"
3452 "\\]"
3453 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3454 "\\]")
3455 org-any-link-re
3456 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3457 org-angle-link-re "\\)\\|\\("
3458 org-plain-link-re "\\)")))
3460 (org-make-link-regexps)
3462 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3463 "Regular expression for fast time stamp matching.")
3464 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3465 "Regular expression for fast time stamp matching.")
3466 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3467 "Regular expression matching time strings for analysis.
3468 This one does not require the space after the date, so it can be used
3469 on a string that terminates immediately after the date.")
3470 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3471 "Regular expression matching time strings for analysis.")
3472 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3473 "Regular expression matching time stamps, with groups.")
3474 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3475 "Regular expression matching time stamps (also [..]), with groups.")
3476 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3477 "Regular expression matching a time stamp range.")
3478 (defconst org-tr-regexp-both
3479 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3480 "Regular expression matching a time stamp range.")
3481 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3482 org-ts-regexp "\\)?")
3483 "Regular expression matching a time stamp or time stamp range.")
3484 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3485 org-ts-regexp-both "\\)?")
3486 "Regular expression matching a time stamp or time stamp range.
3487 The time stamps may be either active or inactive.")
3489 (defvar org-emph-face nil)
3491 (defun org-do-emphasis-faces (limit)
3492 "Run through the buffer and add overlays to links."
3493 (let (rtn)
3494 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3495 (if (not (= (char-after (match-beginning 3))
3496 (char-after (match-beginning 4))))
3497 (progn
3498 (setq rtn t)
3499 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3500 'face
3501 (nth 1 (assoc (match-string 3)
3502 org-emphasis-alist)))
3503 (add-text-properties (match-beginning 2) (match-end 2)
3504 '(font-lock-multiline t))
3505 (when org-hide-emphasis-markers
3506 (add-text-properties (match-end 4) (match-beginning 5)
3507 '(invisible org-link))
3508 (add-text-properties (match-beginning 3) (match-end 3)
3509 '(invisible org-link)))))
3510 (backward-char 1))
3511 rtn))
3513 (defun org-emphasize (&optional char)
3514 "Insert or change an emphasis, i.e. a font like bold or italic.
3515 If there is an active region, change that region to a new emphasis.
3516 If there is no region, just insert the marker characters and position
3517 the cursor between them.
3518 CHAR should be either the marker character, or the first character of the
3519 HTML tag associated with that emphasis. If CHAR is a space, the means
3520 to remove the emphasis of the selected region.
3521 If char is not given (for example in an interactive call) it
3522 will be prompted for."
3523 (interactive)
3524 (let ((eal org-emphasis-alist) e det
3525 (erc org-emphasis-regexp-components)
3526 (prompt "")
3527 (string "") beg end move tag c s)
3528 (if (org-region-active-p)
3529 (setq beg (region-beginning) end (region-end)
3530 string (buffer-substring beg end))
3531 (setq move t))
3533 (while (setq e (pop eal))
3534 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3535 c (aref tag 0))
3536 (push (cons c (string-to-char (car e))) det)
3537 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3538 (substring tag 1)))))
3539 (setq det (nreverse det))
3540 (unless char
3541 (message "%s" (concat "Emphasis marker or tag:" prompt))
3542 (setq char (read-char-exclusive)))
3543 (setq char (or (cdr (assoc char det)) char))
3544 (if (equal char ?\ )
3545 (setq s "" move nil)
3546 (unless (assoc (char-to-string char) org-emphasis-alist)
3547 (error "No such emphasis marker: \"%c\"" char))
3548 (setq s (char-to-string char)))
3549 (while (and (> (length string) 1)
3550 (equal (substring string 0 1) (substring string -1))
3551 (assoc (substring string 0 1) org-emphasis-alist))
3552 (setq string (substring string 1 -1)))
3553 (setq string (concat s string s))
3554 (if beg (delete-region beg end))
3555 (unless (or (bolp)
3556 (string-match (concat "[" (nth 0 erc) "\n]")
3557 (char-to-string (char-before (point)))))
3558 (insert " "))
3559 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3560 (char-to-string (char-after (point))))
3561 (insert " ") (backward-char 1))
3562 (insert string)
3563 (and move (backward-char 1))))
3565 (defconst org-nonsticky-props
3566 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3569 (defun org-activate-plain-links (limit)
3570 "Run through the buffer and add overlays to links."
3571 (catch 'exit
3572 (let (f)
3573 (while (re-search-forward org-plain-link-re limit t)
3574 (setq f (get-text-property (match-beginning 0) 'face))
3575 (if (or (eq f 'org-tag)
3576 (and (listp f) (memq 'org-tag f)))
3578 (add-text-properties (match-beginning 0) (match-end 0)
3579 (list 'mouse-face 'highlight
3580 'rear-nonsticky org-nonsticky-props
3581 'keymap org-mouse-map
3583 (throw 'exit t))))))
3585 (defun org-activate-code (limit)
3586 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3587 (progn
3588 (remove-text-properties (match-beginning 0) (match-end 0)
3589 '(display t invisible t intangible t))
3590 t)))
3592 (defun org-activate-angle-links (limit)
3593 "Run through the buffer and add overlays to links."
3594 (if (re-search-forward org-angle-link-re limit t)
3595 (progn
3596 (add-text-properties (match-beginning 0) (match-end 0)
3597 (list 'mouse-face 'highlight
3598 'rear-nonsticky org-nonsticky-props
3599 'keymap org-mouse-map
3601 t)))
3603 (defun org-activate-bracket-links (limit)
3604 "Run through the buffer and add overlays to bracketed links."
3605 (if (re-search-forward org-bracket-link-regexp limit t)
3606 (let* ((help (concat "LINK: "
3607 (org-match-string-no-properties 1)))
3608 ;; FIXME: above we should remove the escapes.
3609 ;; but that requires another match, protecting match data,
3610 ;; a lot of overhead for font-lock.
3611 (ip (org-maybe-intangible
3612 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3613 'keymap org-mouse-map 'mouse-face 'highlight
3614 'font-lock-multiline t 'help-echo help)))
3615 (vp (list 'rear-nonsticky org-nonsticky-props
3616 'keymap org-mouse-map 'mouse-face 'highlight
3617 ' font-lock-multiline t 'help-echo help)))
3618 ;; We need to remove the invisible property here. Table narrowing
3619 ;; may have made some of this invisible.
3620 (remove-text-properties (match-beginning 0) (match-end 0)
3621 '(invisible nil))
3622 (if (match-end 3)
3623 (progn
3624 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3625 (add-text-properties (match-beginning 3) (match-end 3) vp)
3626 (add-text-properties (match-end 3) (match-end 0) ip))
3627 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3628 (add-text-properties (match-beginning 1) (match-end 1) vp)
3629 (add-text-properties (match-end 1) (match-end 0) ip))
3630 t)))
3632 (defun org-activate-dates (limit)
3633 "Run through the buffer and add overlays to dates."
3634 (if (re-search-forward org-tsr-regexp-both limit t)
3635 (progn
3636 (add-text-properties (match-beginning 0) (match-end 0)
3637 (list 'mouse-face 'highlight
3638 'rear-nonsticky org-nonsticky-props
3639 'keymap org-mouse-map))
3640 (when org-display-custom-times
3641 (if (match-end 3)
3642 (org-display-custom-time (match-beginning 3) (match-end 3)))
3643 (org-display-custom-time (match-beginning 1) (match-end 1)))
3644 t)))
3646 (defvar org-target-link-regexp nil
3647 "Regular expression matching radio targets in plain text.")
3648 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3649 "Regular expression matching a link target.")
3650 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3651 "Regular expression matching a radio target.")
3652 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3653 "Regular expression matching any target.")
3655 (defun org-activate-target-links (limit)
3656 "Run through the buffer and add overlays to target matches."
3657 (when org-target-link-regexp
3658 (let ((case-fold-search t))
3659 (if (re-search-forward org-target-link-regexp limit t)
3660 (progn
3661 (add-text-properties (match-beginning 0) (match-end 0)
3662 (list 'mouse-face 'highlight
3663 'rear-nonsticky org-nonsticky-props
3664 'keymap org-mouse-map
3665 'help-echo "Radio target link"
3666 'org-linked-text t))
3667 t)))))
3669 (defun org-update-radio-target-regexp ()
3670 "Find all radio targets in this file and update the regular expression."
3671 (interactive)
3672 (when (memq 'radio org-activate-links)
3673 (setq org-target-link-regexp
3674 (org-make-target-link-regexp (org-all-targets 'radio)))
3675 (org-restart-font-lock)))
3677 (defun org-hide-wide-columns (limit)
3678 (let (s e)
3679 (setq s (text-property-any (point) (or limit (point-max))
3680 'org-cwidth t))
3681 (when s
3682 (setq e (next-single-property-change s 'org-cwidth))
3683 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3684 (goto-char e)
3685 t)))
3687 (defvar org-latex-and-specials-regexp nil
3688 "Regular expression for highlighting export special stuff.")
3689 (defvar org-match-substring-regexp)
3690 (defvar org-match-substring-with-braces-regexp)
3691 (defvar org-export-html-special-string-regexps)
3693 (defun org-compute-latex-and-specials-regexp ()
3694 "Compute regular expression for stuff treated specially by exporters."
3695 (if (not org-highlight-latex-fragments-and-specials)
3696 (org-set-local 'org-latex-and-specials-regexp nil)
3697 (require 'org-exp)
3698 (let*
3699 ((matchers (plist-get org-format-latex-options :matchers))
3700 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3701 org-latex-regexps)))
3702 (options (org-combine-plists (org-default-export-plist)
3703 (org-infile-export-plist)))
3704 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3705 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3706 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3707 (org-export-html-expand (plist-get options :expand-quoted-html))
3708 (org-export-with-special-strings (plist-get options :special-strings))
3709 (re-sub
3710 (cond
3711 ((equal org-export-with-sub-superscripts '{})
3712 (list org-match-substring-with-braces-regexp))
3713 (org-export-with-sub-superscripts
3714 (list org-match-substring-regexp))
3715 (t nil)))
3716 (re-latex
3717 (if org-export-with-LaTeX-fragments
3718 (mapcar (lambda (x) (nth 1 x)) latexs)))
3719 (re-macros
3720 (if org-export-with-TeX-macros
3721 (list (concat "\\\\"
3722 (regexp-opt
3723 (append (mapcar 'car org-html-entities)
3724 (if (boundp 'org-latex-entities)
3725 org-latex-entities nil))
3726 'words))) ; FIXME
3728 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3729 (re-special (if org-export-with-special-strings
3730 (mapcar (lambda (x) (car x))
3731 org-export-html-special-string-regexps)))
3732 (re-rest
3733 (delq nil
3734 (list
3735 (if org-export-html-expand "@<[^>\n]+>")
3736 ))))
3737 (org-set-local
3738 'org-latex-and-specials-regexp
3739 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3740 re-rest) "\\|")))))
3742 (defun org-do-latex-and-special-faces (limit)
3743 "Run through the buffer and add overlays to links."
3744 (when org-latex-and-specials-regexp
3745 (let (rtn d)
3746 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3747 limit t))
3748 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3749 'face))
3750 '(org-code org-verbatim underline)))
3751 (progn
3752 (setq rtn t
3753 d (cond ((member (char-after (1+ (match-beginning 0)))
3754 '(?_ ?^)) 1)
3755 (t 0)))
3756 (font-lock-prepend-text-property
3757 (+ d (match-beginning 0)) (match-end 0)
3758 'face 'org-latex-and-export-specials)
3759 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3760 '(font-lock-multiline t)))))
3761 rtn)))
3763 (defun org-restart-font-lock ()
3764 "Restart font-lock-mode, to force refontification."
3765 (when (and (boundp 'font-lock-mode) font-lock-mode)
3766 (font-lock-mode -1)
3767 (font-lock-mode 1)))
3769 (defun org-all-targets (&optional radio)
3770 "Return a list of all targets in this file.
3771 With optional argument RADIO, only find radio targets."
3772 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3773 rtn)
3774 (save-excursion
3775 (goto-char (point-min))
3776 (while (re-search-forward re nil t)
3777 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3778 rtn)))
3780 (defun org-make-target-link-regexp (targets)
3781 "Make regular expression matching all strings in TARGETS.
3782 The regular expression finds the targets also if there is a line break
3783 between words."
3784 (and targets
3785 (concat
3786 "\\<\\("
3787 (mapconcat
3788 (lambda (x)
3789 (while (string-match " +" x)
3790 (setq x (replace-match "\\s-+" t t x)))
3792 targets
3793 "\\|")
3794 "\\)\\>")))
3796 (defun org-activate-tags (limit)
3797 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3798 (progn
3799 (add-text-properties (match-beginning 1) (match-end 1)
3800 (list 'mouse-face 'highlight
3801 'rear-nonsticky org-nonsticky-props
3802 'keymap org-mouse-map))
3803 t)))
3805 (defun org-outline-level ()
3806 (save-excursion
3807 (looking-at outline-regexp)
3808 (if (match-beginning 1)
3809 (+ (org-get-string-indentation (match-string 1)) 1000)
3810 (1- (- (match-end 0) (match-beginning 0))))))
3812 (defvar org-font-lock-keywords nil)
3814 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3815 "Regular expression matching a property line.")
3817 (defvar org-font-lock-hook nil
3818 "Functions to be called for special font lock stuff.")
3820 (defun org-font-lock-hook (limit)
3821 (run-hook-with-args 'org-font-lock-hook limit))
3823 (defun org-set-font-lock-defaults ()
3824 (let* ((em org-fontify-emphasized-text)
3825 (lk org-activate-links)
3826 (org-font-lock-extra-keywords
3827 (list
3828 ;; Call the hook
3829 '(org-font-lock-hook)
3830 ;; Headlines
3831 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3832 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3833 ;; Table lines
3834 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3835 (1 'org-table t))
3836 ;; Table internals
3837 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3838 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3839 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3840 ;; Drawers
3841 (list org-drawer-regexp '(0 'org-special-keyword t))
3842 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3843 ;; Properties
3844 (list org-property-re
3845 '(1 'org-special-keyword t)
3846 '(3 'org-property-value t))
3847 (if org-format-transports-properties-p
3848 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3849 ;; Links
3850 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3851 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3852 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3853 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3854 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3855 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3856 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3857 '(org-hide-wide-columns (0 nil append))
3858 ;; TODO lines
3859 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3860 '(1 (org-get-todo-face 1) t))
3861 ;; DONE
3862 (if org-fontify-done-headline
3863 (list (concat "^[*]+ +\\<\\("
3864 (mapconcat 'regexp-quote org-done-keywords "\\|")
3865 "\\)\\(.*\\)")
3866 '(2 'org-headline-done t))
3867 nil)
3868 ;; Priorities
3869 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3870 ;; Special keywords
3871 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3872 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3873 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3874 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3875 ;; Emphasis
3876 (if em
3877 (if (featurep 'xemacs)
3878 '(org-do-emphasis-faces (0 nil append))
3879 '(org-do-emphasis-faces)))
3880 ;; Checkboxes
3881 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3882 2 'bold prepend)
3883 (if org-provide-checkbox-statistics
3884 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3885 (0 (org-get-checkbox-statistics-face) t)))
3886 ;; Description list items
3887 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3888 2 'bold prepend)
3889 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3890 '(1 'org-archived prepend))
3891 ;; Specials
3892 '(org-do-latex-and-special-faces)
3893 ;; Code
3894 '(org-activate-code (1 'org-code t))
3895 ;; COMMENT
3896 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3897 "\\|" org-quote-string "\\)\\>")
3898 '(1 'org-special-keyword t))
3899 '("^#.*" (0 'font-lock-comment-face t))
3901 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3902 ;; Now set the full font-lock-keywords
3903 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3904 (org-set-local 'font-lock-defaults
3905 '(org-font-lock-keywords t nil nil backward-paragraph))
3906 (kill-local-variable 'font-lock-keywords) nil))
3908 (defvar org-m nil)
3909 (defvar org-l nil)
3910 (defvar org-f nil)
3911 (defun org-get-level-face (n)
3912 "Get the right face for match N in font-lock matching of healdines."
3913 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3914 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3915 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3916 (cond
3917 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3918 ((eq n 2) org-f)
3919 (t (if org-level-color-stars-only nil org-f))))
3921 (defun org-get-todo-face (kwd)
3922 "Get the right face for a TODO keyword KWD.
3923 If KWD is a number, get the corresponding match group."
3924 (if (numberp kwd) (setq kwd (match-string kwd)))
3925 (or (cdr (assoc kwd org-todo-keyword-faces))
3926 (and (member kwd org-done-keywords) 'org-done)
3927 'org-todo))
3929 (defun org-unfontify-region (beg end &optional maybe_loudly)
3930 "Remove fontification and activation overlays from links."
3931 (font-lock-default-unfontify-region beg end)
3932 (let* ((buffer-undo-list t)
3933 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3934 (inhibit-modification-hooks t)
3935 deactivate-mark buffer-file-name buffer-file-truename)
3936 (remove-text-properties beg end
3937 '(mouse-face t keymap t org-linked-text t
3938 invisible t intangible t))))
3940 ;;;; Visibility cycling, including org-goto and indirect buffer
3942 ;;; Cycling
3944 (defvar org-cycle-global-status nil)
3945 (make-variable-buffer-local 'org-cycle-global-status)
3946 (defvar org-cycle-subtree-status nil)
3947 (make-variable-buffer-local 'org-cycle-subtree-status)
3949 ;;;###autoload
3950 (defun org-cycle (&optional arg)
3951 "Visibility cycling for Org-mode.
3953 - When this function is called with a prefix argument, rotate the entire
3954 buffer through 3 states (global cycling)
3955 1. OVERVIEW: Show only top-level headlines.
3956 2. CONTENTS: Show all headlines of all levels, but no body text.
3957 3. SHOW ALL: Show everything.
3958 When called with two C-u C-u prefixes, switch to the startup visibility,
3959 determined by the variable `org-startup-folded', and by any VISIBILITY
3960 properties in the buffer.
3961 When called with three C-u C-u C-u prefixed, show the entire buffer,
3962 including drawers.
3964 - When point is at the beginning of a headline, rotate the subtree started
3965 by this line through 3 different states (local cycling)
3966 1. FOLDED: Only the main headline is shown.
3967 2. CHILDREN: The main headline and the direct children are shown.
3968 From this state, you can move to one of the children
3969 and zoom in further.
3970 3. SUBTREE: Show the entire subtree, including body text.
3972 - When there is a numeric prefix, go up to a heading with level ARG, do
3973 a `show-subtree' and return to the previous cursor position. If ARG
3974 is negative, go up that many levels.
3976 - When point is not at the beginning of a headline, execute the global
3977 binding for TAB, which is re-indenting the line. See the option
3978 `org-cycle-emulate-tab' for details.
3980 - Special case: if point is at the beginning of the buffer and there is
3981 no headline in line 1, this function will act as if called with prefix arg.
3982 But only if also the variable `org-cycle-global-at-bob' is t."
3983 (interactive "P")
3984 (org-load-modules-maybe)
3985 (let* ((outline-regexp
3986 (if (and (org-mode-p) org-cycle-include-plain-lists)
3987 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3988 outline-regexp))
3989 (bob-special (and org-cycle-global-at-bob (bobp)
3990 (not (looking-at outline-regexp))))
3991 (org-cycle-hook
3992 (if bob-special
3993 (delq 'org-optimize-window-after-visibility-change
3994 (copy-sequence org-cycle-hook))
3995 org-cycle-hook))
3996 (pos (point)))
3998 (if (or bob-special (equal arg '(4)))
3999 ;; special case: use global cycling
4000 (setq arg t))
4002 (cond
4004 ((equal arg '(16))
4005 (org-set-startup-visibility)
4006 (message "Startup visibility, plus VISIBILITY properties"))
4008 ((equal arg '(64))
4009 (show-all)
4010 (message "Entire buffer visible, including drawers"))
4012 ((org-at-table-p 'any)
4013 ;; Enter the table or move to the next field in the table
4014 (or (org-table-recognize-table.el)
4015 (progn
4016 (if arg (org-table-edit-field t)
4017 (org-table-justify-field-maybe)
4018 (call-interactively 'org-table-next-field)))))
4020 ((eq arg t) ;; Global cycling
4022 (cond
4023 ((and (eq last-command this-command)
4024 (eq org-cycle-global-status 'overview))
4025 ;; We just created the overview - now do table of contents
4026 ;; This can be slow in very large buffers, so indicate action
4027 (message "CONTENTS...")
4028 (org-content)
4029 (message "CONTENTS...done")
4030 (setq org-cycle-global-status 'contents)
4031 (run-hook-with-args 'org-cycle-hook 'contents))
4033 ((and (eq last-command this-command)
4034 (eq org-cycle-global-status 'contents))
4035 ;; We just showed the table of contents - now show everything
4036 (show-all)
4037 (message "SHOW ALL")
4038 (setq org-cycle-global-status 'all)
4039 (run-hook-with-args 'org-cycle-hook 'all))
4042 ;; Default action: go to overview
4043 (org-overview)
4044 (message "OVERVIEW")
4045 (setq org-cycle-global-status 'overview)
4046 (run-hook-with-args 'org-cycle-hook 'overview))))
4048 ((and org-drawers org-drawer-regexp
4049 (save-excursion
4050 (beginning-of-line 1)
4051 (looking-at org-drawer-regexp)))
4052 ;; Toggle block visibility
4053 (org-flag-drawer
4054 (not (get-char-property (match-end 0) 'invisible))))
4056 ((integerp arg)
4057 ;; Show-subtree, ARG levels up from here.
4058 (save-excursion
4059 (org-back-to-heading)
4060 (outline-up-heading (if (< arg 0) (- arg)
4061 (- (funcall outline-level) arg)))
4062 (org-show-subtree)))
4064 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4065 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4066 ;; At a heading: rotate between three different views
4067 (org-back-to-heading)
4068 (let ((goal-column 0) eoh eol eos)
4069 ;; First, some boundaries
4070 (save-excursion
4071 (org-back-to-heading)
4072 (save-excursion
4073 (beginning-of-line 2)
4074 (while (and (not (eobp)) ;; this is like `next-line'
4075 (get-char-property (1- (point)) 'invisible))
4076 (beginning-of-line 2)) (setq eol (point)))
4077 (outline-end-of-heading) (setq eoh (point))
4078 (org-end-of-subtree t)
4079 (unless (eobp)
4080 (skip-chars-forward " \t\n")
4081 (beginning-of-line 1) ; in case this is an item
4083 (setq eos (1- (point))))
4084 ;; Find out what to do next and set `this-command'
4085 (cond
4086 ((= eos eoh)
4087 ;; Nothing is hidden behind this heading
4088 (message "EMPTY ENTRY")
4089 (setq org-cycle-subtree-status nil)
4090 (save-excursion
4091 (goto-char eos)
4092 (outline-next-heading)
4093 (if (org-invisible-p) (org-flag-heading nil))))
4094 ((or (>= eol eos)
4095 (not (string-match "\\S-" (buffer-substring eol eos))))
4096 ;; Entire subtree is hidden in one line: open it
4097 (org-show-entry)
4098 (show-children)
4099 (message "CHILDREN")
4100 (save-excursion
4101 (goto-char eos)
4102 (outline-next-heading)
4103 (if (org-invisible-p) (org-flag-heading nil)))
4104 (setq org-cycle-subtree-status 'children)
4105 (run-hook-with-args 'org-cycle-hook 'children))
4106 ((and (eq last-command this-command)
4107 (eq org-cycle-subtree-status 'children))
4108 ;; We just showed the children, now show everything.
4109 (org-show-subtree)
4110 (message "SUBTREE")
4111 (setq org-cycle-subtree-status 'subtree)
4112 (run-hook-with-args 'org-cycle-hook 'subtree))
4114 ;; Default action: hide the subtree.
4115 (hide-subtree)
4116 (message "FOLDED")
4117 (setq org-cycle-subtree-status 'folded)
4118 (run-hook-with-args 'org-cycle-hook 'folded)))))
4120 ;; TAB emulation and template completion
4121 (buffer-read-only (org-back-to-heading))
4123 ((org-try-structure-completion))
4125 ((org-try-cdlatex-tab))
4127 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4128 (or (not (bolp))
4129 (not (looking-at outline-regexp))))
4130 (call-interactively (global-key-binding "\t")))
4132 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4133 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4134 (or (and (eq org-cycle-emulate-tab 'white)
4135 (= (match-end 0) (point-at-eol)))
4136 (and (eq org-cycle-emulate-tab 'whitestart)
4137 (>= (match-end 0) pos))))
4139 (eq org-cycle-emulate-tab t))
4140 (call-interactively (global-key-binding "\t")))
4142 (t (save-excursion
4143 (org-back-to-heading)
4144 (org-cycle))))))
4146 ;;;###autoload
4147 (defun org-global-cycle (&optional arg)
4148 "Cycle the global visibility. For details see `org-cycle'.
4149 With C-u prefix arg, switch to startup visibility.
4150 With a numeric prefix, show all headlines up to that level."
4151 (interactive "P")
4152 (let ((org-cycle-include-plain-lists
4153 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4154 (cond
4155 ((integerp arg)
4156 (show-all)
4157 (hide-sublevels arg)
4158 (setq org-cycle-global-status 'contents))
4159 ((equal arg '(4))
4160 (org-set-startup-visibility)
4161 (message "Startup visibility, plus VISIBILITY properties."))
4163 (org-cycle '(4))))))
4165 (defun org-set-startup-visibility ()
4166 "Set the visibility required by startup options and properties."
4167 (cond
4168 ((eq org-startup-folded t)
4169 (org-cycle '(4)))
4170 ((eq org-startup-folded 'content)
4171 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4172 (org-cycle '(4)) (org-cycle '(4)))))
4173 (org-set-visibility-according-to-property 'no-cleanup)
4174 (org-cycle-hide-archived-subtrees 'all)
4175 (org-cycle-hide-drawers 'all)
4176 (org-cycle-show-empty-lines 'all))
4178 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4179 "Switch subtree visibilities according to :VISIBILITY: property."
4180 (interactive)
4181 (let (state)
4182 (save-excursion
4183 (goto-char (point-min))
4184 (while (re-search-forward
4185 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4186 nil t)
4187 (setq state (match-string 1))
4188 (save-excursion
4189 (org-back-to-heading t)
4190 (hide-subtree)
4191 (org-reveal)
4192 (cond
4193 ((equal state '("fold" "folded"))
4194 (hide-subtree))
4195 ((equal state "children")
4196 (org-show-hidden-entry)
4197 (show-children))
4198 ((equal state "content")
4199 (save-excursion
4200 (save-restriction
4201 (org-narrow-to-subtree)
4202 (org-content))))
4203 ((member state '("all" "showall"))
4204 (show-subtree)))))
4205 (unless no-cleanup
4206 (org-cycle-hide-archived-subtrees 'all)
4207 (org-cycle-hide-drawers 'all)
4208 (org-cycle-show-empty-lines 'all)))))
4210 (defun org-overview ()
4211 "Switch to overview mode, shoing only top-level headlines.
4212 Really, this shows all headlines with level equal or greater than the level
4213 of the first headline in the buffer. This is important, because if the
4214 first headline is not level one, then (hide-sublevels 1) gives confusing
4215 results."
4216 (interactive)
4217 (let ((level (save-excursion
4218 (goto-char (point-min))
4219 (if (re-search-forward (concat "^" outline-regexp) nil t)
4220 (progn
4221 (goto-char (match-beginning 0))
4222 (funcall outline-level))))))
4223 (and level (hide-sublevels level))))
4225 (defun org-content (&optional arg)
4226 "Show all headlines in the buffer, like a table of contents.
4227 With numerical argument N, show content up to level N."
4228 (interactive "P")
4229 (save-excursion
4230 ;; Visit all headings and show their offspring
4231 (and (integerp arg) (org-overview))
4232 (goto-char (point-max))
4233 (catch 'exit
4234 (while (and (progn (condition-case nil
4235 (outline-previous-visible-heading 1)
4236 (error (goto-char (point-min))))
4238 (looking-at outline-regexp))
4239 (if (integerp arg)
4240 (show-children (1- arg))
4241 (show-branches))
4242 (if (bobp) (throw 'exit nil))))))
4245 (defun org-optimize-window-after-visibility-change (state)
4246 "Adjust the window after a change in outline visibility.
4247 This function is the default value of the hook `org-cycle-hook'."
4248 (when (get-buffer-window (current-buffer))
4249 (cond
4250 ; ((eq state 'overview) (org-first-headline-recenter 1))
4251 ; ((eq state 'overview) (org-beginning-of-line))
4252 ((eq state 'content) nil)
4253 ((eq state 'all) nil)
4254 ((eq state 'folded) nil)
4255 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4256 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4258 (defun org-compact-display-after-subtree-move ()
4259 (let (beg end)
4260 (save-excursion
4261 (if (org-up-heading-safe)
4262 (progn
4263 (hide-subtree)
4264 (show-entry)
4265 (show-children)
4266 (org-cycle-show-empty-lines 'children)
4267 (org-cycle-hide-drawers 'children))
4268 (org-overview)))))
4270 (defun org-cycle-show-empty-lines (state)
4271 "Show empty lines above all visible headlines.
4272 The region to be covered depends on STATE when called through
4273 `org-cycle-hook'. Lisp program can use t for STATE to get the
4274 entire buffer covered. Note that an empty line is only shown if there
4275 are at least `org-cycle-separator-lines' empty lines before the headeline."
4276 (when (> org-cycle-separator-lines 0)
4277 (save-excursion
4278 (let* ((n org-cycle-separator-lines)
4279 (re (cond
4280 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4281 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4282 (t (let ((ns (number-to-string (- n 2))))
4283 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4284 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4285 beg end)
4286 (cond
4287 ((memq state '(overview contents t))
4288 (setq beg (point-min) end (point-max)))
4289 ((memq state '(children folded))
4290 (setq beg (point) end (progn (org-end-of-subtree t t)
4291 (beginning-of-line 2)
4292 (point)))))
4293 (when beg
4294 (goto-char beg)
4295 (while (re-search-forward re end t)
4296 (if (not (get-char-property (match-end 1) 'invisible))
4297 (outline-flag-region
4298 (match-beginning 1) (match-end 1) nil)))))))
4299 ;; Never hide empty lines at the end of the file.
4300 (save-excursion
4301 (goto-char (point-max))
4302 (outline-previous-heading)
4303 (outline-end-of-heading)
4304 (if (and (looking-at "[ \t\n]+")
4305 (= (match-end 0) (point-max)))
4306 (outline-flag-region (point) (match-end 0) nil))))
4308 (defun org-show-empty-lines-in-parent ()
4309 "Move to the parent and re-show empty lines before visible headlines."
4310 (save-excursion
4311 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4312 (org-cycle-show-empty-lines context))))
4314 (defun org-cycle-hide-drawers (state)
4315 "Re-hide all drawers after a visibility state change."
4316 (when (and (org-mode-p)
4317 (not (memq state '(overview folded))))
4318 (save-excursion
4319 (let* ((globalp (memq state '(contents all)))
4320 (beg (if globalp (point-min) (point)))
4321 (end (if globalp (point-max) (org-end-of-subtree t))))
4322 (goto-char beg)
4323 (while (re-search-forward org-drawer-regexp end t)
4324 (org-flag-drawer t))))))
4326 (defun org-flag-drawer (flag)
4327 (save-excursion
4328 (beginning-of-line 1)
4329 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4330 (let ((b (match-end 0))
4331 (outline-regexp org-outline-regexp))
4332 (if (re-search-forward
4333 "^[ \t]*:END:"
4334 (save-excursion (outline-next-heading) (point)) t)
4335 (outline-flag-region b (point-at-eol) flag)
4336 (error ":END: line missing"))))))
4338 (defun org-subtree-end-visible-p ()
4339 "Is the end of the current subtree visible?"
4340 (pos-visible-in-window-p
4341 (save-excursion (org-end-of-subtree t) (point))))
4343 (defun org-first-headline-recenter (&optional N)
4344 "Move cursor to the first headline and recenter the headline.
4345 Optional argument N means, put the headline into the Nth line of the window."
4346 (goto-char (point-min))
4347 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4348 (beginning-of-line)
4349 (recenter (prefix-numeric-value N))))
4351 ;;; Org-goto
4353 (defvar org-goto-window-configuration nil)
4354 (defvar org-goto-marker nil)
4355 (defvar org-goto-map
4356 (let ((map (make-sparse-keymap)))
4357 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4358 (while (setq cmd (pop cmds))
4359 (substitute-key-definition cmd cmd map global-map)))
4360 (suppress-keymap map)
4361 (org-defkey map "\C-m" 'org-goto-ret)
4362 (org-defkey map [(return)] 'org-goto-ret)
4363 (org-defkey map [(left)] 'org-goto-left)
4364 (org-defkey map [(right)] 'org-goto-right)
4365 (org-defkey map [(control ?g)] 'org-goto-quit)
4366 (org-defkey map "\C-i" 'org-cycle)
4367 (org-defkey map [(tab)] 'org-cycle)
4368 (org-defkey map [(down)] 'outline-next-visible-heading)
4369 (org-defkey map [(up)] 'outline-previous-visible-heading)
4370 (if org-goto-auto-isearch
4371 (if (fboundp 'define-key-after)
4372 (define-key-after map [t] 'org-goto-local-auto-isearch)
4373 nil)
4374 (org-defkey map "q" 'org-goto-quit)
4375 (org-defkey map "n" 'outline-next-visible-heading)
4376 (org-defkey map "p" 'outline-previous-visible-heading)
4377 (org-defkey map "f" 'outline-forward-same-level)
4378 (org-defkey map "b" 'outline-backward-same-level)
4379 (org-defkey map "u" 'outline-up-heading))
4380 (org-defkey map "/" 'org-occur)
4381 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4382 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4383 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4384 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4385 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4386 map))
4388 (defconst org-goto-help
4389 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4390 RET=jump to location [Q]uit and return to previous location
4391 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4393 (defvar org-goto-start-pos) ; dynamically scoped parameter
4395 ;; FIXME: Docstring doe not mention both interfaces
4396 (defun org-goto (&optional alternative-interface)
4397 "Look up a different location in the current file, keeping current visibility.
4399 When you want look-up or go to a different location in a document, the
4400 fastest way is often to fold the entire buffer and then dive into the tree.
4401 This method has the disadvantage, that the previous location will be folded,
4402 which may not be what you want.
4404 This command works around this by showing a copy of the current buffer
4405 in an indirect buffer, in overview mode. You can dive into the tree in
4406 that copy, use org-occur and incremental search to find a location.
4407 When pressing RET or `Q', the command returns to the original buffer in
4408 which the visibility is still unchanged. After RET is will also jump to
4409 the location selected in the indirect buffer and expose the
4410 the headline hierarchy above."
4411 (interactive "P")
4412 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4413 (org-refile-use-outline-path t)
4414 (interface
4415 (if (not alternative-interface)
4416 org-goto-interface
4417 (if (eq org-goto-interface 'outline)
4418 'outline-path-completion
4419 'outline)))
4420 (org-goto-start-pos (point))
4421 (selected-point
4422 (if (eq interface 'outline)
4423 (car (org-get-location (current-buffer) org-goto-help))
4424 (nth 3 (org-refile-get-location "Goto: ")))))
4425 (if selected-point
4426 (progn
4427 (org-mark-ring-push org-goto-start-pos)
4428 (goto-char selected-point)
4429 (if (or (org-invisible-p) (org-invisible-p2))
4430 (org-show-context 'org-goto)))
4431 (message "Quit"))))
4433 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4434 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4435 (defvar org-goto-local-auto-isearch-map) ; defined below
4437 (defun org-get-location (buf help)
4438 "Let the user select a location in the Org-mode buffer BUF.
4439 This function uses a recursive edit. It returns the selected position
4440 or nil."
4441 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4442 (isearch-hide-immediately nil)
4443 (isearch-search-fun-function
4444 (lambda () 'org-goto-local-search-headings))
4445 (org-goto-selected-point org-goto-exit-command))
4446 (save-excursion
4447 (save-window-excursion
4448 (delete-other-windows)
4449 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4450 (switch-to-buffer
4451 (condition-case nil
4452 (make-indirect-buffer (current-buffer) "*org-goto*")
4453 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4454 (with-output-to-temp-buffer "*Help*"
4455 (princ help))
4456 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4457 (setq buffer-read-only nil)
4458 (let ((org-startup-truncated t)
4459 (org-startup-folded nil)
4460 (org-startup-align-all-tables nil))
4461 (org-mode)
4462 (org-overview))
4463 (setq buffer-read-only t)
4464 (if (and (boundp 'org-goto-start-pos)
4465 (integer-or-marker-p org-goto-start-pos))
4466 (let ((org-show-hierarchy-above t)
4467 (org-show-siblings t)
4468 (org-show-following-heading t))
4469 (goto-char org-goto-start-pos)
4470 (and (org-invisible-p) (org-show-context)))
4471 (goto-char (point-min)))
4472 (org-beginning-of-line)
4473 (message "Select location and press RET")
4474 (use-local-map org-goto-map)
4475 (recursive-edit)
4477 (kill-buffer "*org-goto*")
4478 (cons org-goto-selected-point org-goto-exit-command)))
4480 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4481 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4482 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4483 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4485 (defun org-goto-local-search-headings (string bound noerror)
4486 "Search and make sure that any matches are in headlines."
4487 (catch 'return
4488 (while (if isearch-forward
4489 (search-forward string bound noerror)
4490 (search-backward string bound noerror))
4491 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4492 (and (member :headline context)
4493 (not (member :tags context))))
4494 (throw 'return (point))))))
4496 (defun org-goto-local-auto-isearch ()
4497 "Start isearch."
4498 (interactive)
4499 (goto-char (point-min))
4500 (let ((keys (this-command-keys)))
4501 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4502 (isearch-mode t)
4503 (isearch-process-search-char (string-to-char keys)))))
4505 (defun org-goto-ret (&optional arg)
4506 "Finish `org-goto' by going to the new location."
4507 (interactive "P")
4508 (setq org-goto-selected-point (point)
4509 org-goto-exit-command 'return)
4510 (throw 'exit nil))
4512 (defun org-goto-left ()
4513 "Finish `org-goto' by going to the new location."
4514 (interactive)
4515 (if (org-on-heading-p)
4516 (progn
4517 (beginning-of-line 1)
4518 (setq org-goto-selected-point (point)
4519 org-goto-exit-command 'left)
4520 (throw 'exit nil))
4521 (error "Not on a heading")))
4523 (defun org-goto-right ()
4524 "Finish `org-goto' by going to the new location."
4525 (interactive)
4526 (if (org-on-heading-p)
4527 (progn
4528 (setq org-goto-selected-point (point)
4529 org-goto-exit-command 'right)
4530 (throw 'exit nil))
4531 (error "Not on a heading")))
4533 (defun org-goto-quit ()
4534 "Finish `org-goto' without cursor motion."
4535 (interactive)
4536 (setq org-goto-selected-point nil)
4537 (setq org-goto-exit-command 'quit)
4538 (throw 'exit nil))
4540 ;;; Indirect buffer display of subtrees
4542 (defvar org-indirect-dedicated-frame nil
4543 "This is the frame being used for indirect tree display.")
4544 (defvar org-last-indirect-buffer nil)
4546 (defun org-tree-to-indirect-buffer (&optional arg)
4547 "Create indirect buffer and narrow it to current subtree.
4548 With numerical prefix ARG, go up to this level and then take that tree.
4549 If ARG is negative, go up that many levels.
4550 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4551 indirect buffer previously made with this command, to avoid proliferation of
4552 indirect buffers. However, when you call the command with a `C-u' prefix, or
4553 when `org-indirect-buffer-display' is `new-frame', the last buffer
4554 is kept so that you can work with several indirect buffers at the same time.
4555 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4556 requests that a new frame be made for the new buffer, so that the dedicated
4557 frame is not changed."
4558 (interactive "P")
4559 (let ((cbuf (current-buffer))
4560 (cwin (selected-window))
4561 (pos (point))
4562 beg end level heading ibuf)
4563 (save-excursion
4564 (org-back-to-heading t)
4565 (when (numberp arg)
4566 (setq level (org-outline-level))
4567 (if (< arg 0) (setq arg (+ level arg)))
4568 (while (> (setq level (org-outline-level)) arg)
4569 (outline-up-heading 1 t)))
4570 (setq beg (point)
4571 heading (org-get-heading))
4572 (org-end-of-subtree t) (setq end (point)))
4573 (if (and (buffer-live-p org-last-indirect-buffer)
4574 (not (eq org-indirect-buffer-display 'new-frame))
4575 (not arg))
4576 (kill-buffer org-last-indirect-buffer))
4577 (setq ibuf (org-get-indirect-buffer cbuf)
4578 org-last-indirect-buffer ibuf)
4579 (cond
4580 ((or (eq org-indirect-buffer-display 'new-frame)
4581 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4582 (select-frame (make-frame))
4583 (delete-other-windows)
4584 (switch-to-buffer ibuf)
4585 (org-set-frame-title heading))
4586 ((eq org-indirect-buffer-display 'dedicated-frame)
4587 (raise-frame
4588 (select-frame (or (and org-indirect-dedicated-frame
4589 (frame-live-p org-indirect-dedicated-frame)
4590 org-indirect-dedicated-frame)
4591 (setq org-indirect-dedicated-frame (make-frame)))))
4592 (delete-other-windows)
4593 (switch-to-buffer ibuf)
4594 (org-set-frame-title (concat "Indirect: " heading)))
4595 ((eq org-indirect-buffer-display 'current-window)
4596 (switch-to-buffer ibuf))
4597 ((eq org-indirect-buffer-display 'other-window)
4598 (pop-to-buffer ibuf))
4599 (t (error "Invalid value.")))
4600 (if (featurep 'xemacs)
4601 (save-excursion (org-mode) (turn-on-font-lock)))
4602 (narrow-to-region beg end)
4603 (show-all)
4604 (goto-char pos)
4605 (and (window-live-p cwin) (select-window cwin))))
4607 (defun org-get-indirect-buffer (&optional buffer)
4608 (setq buffer (or buffer (current-buffer)))
4609 (let ((n 1) (base (buffer-name buffer)) bname)
4610 (while (buffer-live-p
4611 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4612 (setq n (1+ n)))
4613 (condition-case nil
4614 (make-indirect-buffer buffer bname 'clone)
4615 (error (make-indirect-buffer buffer bname)))))
4617 (defun org-set-frame-title (title)
4618 "Set the title of the current frame to the string TITLE."
4619 ;; FIXME: how to name a single frame in XEmacs???
4620 (unless (featurep 'xemacs)
4621 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4623 ;;;; Structure editing
4625 ;;; Inserting headlines
4627 (defun org-insert-heading (&optional force-heading)
4628 "Insert a new heading or item with same depth at point.
4629 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4630 If point is at the beginning of a headline, insert a sibling before the
4631 current headline. If point is not at the beginning, do not split the line,
4632 but create the new headline after the current line."
4633 (interactive "P")
4634 (if (= (buffer-size) 0)
4635 (insert "\n* ")
4636 (when (or force-heading (not (org-insert-item)))
4637 (let* ((head (save-excursion
4638 (condition-case nil
4639 (progn
4640 (org-back-to-heading)
4641 (match-string 0))
4642 (error "*"))))
4643 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4644 pos hide-previous previous-pos)
4645 (cond
4646 ((and (org-on-heading-p) (bolp)
4647 (or (bobp)
4648 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4649 ;; insert before the current line
4650 (open-line (if blank 2 1)))
4651 ((and (bolp)
4652 (or (bobp)
4653 (save-excursion
4654 (backward-char 1) (not (org-invisible-p)))))
4655 ;; insert right here
4656 nil)
4658 ;; somewhere in the line
4659 (save-excursion
4660 (setq previous-pos (point-at-bol))
4661 (end-of-line)
4662 (setq hide-previous (org-invisible-p)))
4663 (and org-insert-heading-respect-content (org-show-subtree))
4664 (let ((split
4665 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4666 (save-excursion
4667 (let ((p (point)))
4668 (goto-char (point-at-bol))
4669 (and (looking-at org-complex-heading-regexp)
4670 (> p (match-beginning 4)))))))
4671 tags pos)
4672 (cond
4673 (org-insert-heading-respect-content
4674 (org-end-of-subtree nil t)
4675 (or (bolp) (newline))
4676 (open-line 1))
4677 ((org-on-heading-p)
4678 (when hide-previous
4679 (show-children)
4680 (org-show-entry))
4681 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4682 (setq tags (and (match-end 2) (match-string 2)))
4683 (and (match-end 1)
4684 (delete-region (match-beginning 1) (match-end 1)))
4685 (setq pos (point-at-bol))
4686 (or split (end-of-line 1))
4687 (delete-horizontal-space)
4688 (newline (if blank 2 1))
4689 (when tags
4690 (save-excursion
4691 (goto-char pos)
4692 (end-of-line 1)
4693 (insert " " tags)
4694 (org-set-tags nil 'align))))
4696 (or split (end-of-line 1))
4697 (newline (if blank 2 1)))))))
4698 (insert head) (just-one-space)
4699 (setq pos (point))
4700 (end-of-line 1)
4701 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4702 (when (and org-insert-heading-respect-content hide-previous)
4703 (save-excursion
4704 (goto-char previous-pos)
4705 (hide-subtree)))
4706 (run-hooks 'org-insert-heading-hook)))))
4708 (defun org-get-heading (&optional no-tags)
4709 "Return the heading of the current entry, without the stars."
4710 (save-excursion
4711 (org-back-to-heading t)
4712 (if (looking-at
4713 (if no-tags
4714 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4715 "\\*+[ \t]+\\([^\r\n]*\\)"))
4716 (match-string 1) "")))
4718 (defun org-insert-heading-after-current ()
4719 "Insert a new heading with same level as current, after current subtree."
4720 (interactive)
4721 (org-back-to-heading)
4722 (org-insert-heading)
4723 (org-move-subtree-down)
4724 (end-of-line 1))
4726 (defun org-insert-heading-respect-content ()
4727 (interactive)
4728 (let ((org-insert-heading-respect-content t))
4729 (org-insert-heading t)))
4731 (defun org-insert-todo-heading-respect-content (&optional force-state)
4732 (interactive "P")
4733 (let ((org-insert-heading-respect-content t))
4734 (org-insert-todo-heading force-state t)))
4736 (defun org-insert-todo-heading (arg &optional force-heading)
4737 "Insert a new heading with the same level and TODO state as current heading.
4738 If the heading has no TODO state, or if the state is DONE, use the first
4739 state (TODO by default). Also with prefix arg, force first state."
4740 (interactive "P")
4741 (when (or force-heading (not (org-insert-item 'checkbox)))
4742 (org-insert-heading force-heading)
4743 (save-excursion
4744 (org-back-to-heading)
4745 (outline-previous-heading)
4746 (looking-at org-todo-line-regexp))
4747 (if (or arg
4748 (not (match-beginning 2))
4749 (member (match-string 2) org-done-keywords))
4750 (insert (car org-todo-keywords-1) " ")
4751 (insert (match-string 2) " "))
4752 (when org-provide-todo-statistics
4753 (org-update-parent-todo-statistics))))
4755 (defun org-insert-subheading (arg)
4756 "Insert a new subheading and demote it.
4757 Works for outline headings and for plain lists alike."
4758 (interactive "P")
4759 (org-insert-heading arg)
4760 (cond
4761 ((org-on-heading-p) (org-do-demote))
4762 ((org-at-item-p) (org-indent-item 1))))
4764 (defun org-insert-todo-subheading (arg)
4765 "Insert a new subheading with TODO keyword or checkbox and demote it.
4766 Works for outline headings and for plain lists alike."
4767 (interactive "P")
4768 (org-insert-todo-heading arg)
4769 (cond
4770 ((org-on-heading-p) (org-do-demote))
4771 ((org-at-item-p) (org-indent-item 1))))
4773 ;;; Promotion and Demotion
4775 (defun org-promote-subtree ()
4776 "Promote the entire subtree.
4777 See also `org-promote'."
4778 (interactive)
4779 (save-excursion
4780 (org-map-tree 'org-promote))
4781 (org-fix-position-after-promote))
4783 (defun org-demote-subtree ()
4784 "Demote the entire subtree. See `org-demote'.
4785 See also `org-promote'."
4786 (interactive)
4787 (save-excursion
4788 (org-map-tree 'org-demote))
4789 (org-fix-position-after-promote))
4792 (defun org-do-promote ()
4793 "Promote the current heading higher up the tree.
4794 If the region is active in `transient-mark-mode', promote all headings
4795 in the region."
4796 (interactive)
4797 (save-excursion
4798 (if (org-region-active-p)
4799 (org-map-region 'org-promote (region-beginning) (region-end))
4800 (org-promote)))
4801 (org-fix-position-after-promote))
4803 (defun org-do-demote ()
4804 "Demote the current heading lower down the tree.
4805 If the region is active in `transient-mark-mode', demote all headings
4806 in the region."
4807 (interactive)
4808 (save-excursion
4809 (if (org-region-active-p)
4810 (org-map-region 'org-demote (region-beginning) (region-end))
4811 (org-demote)))
4812 (org-fix-position-after-promote))
4814 (defun org-fix-position-after-promote ()
4815 "Make sure that after pro/demotion cursor position is right."
4816 (let ((pos (point)))
4817 (when (save-excursion
4818 (beginning-of-line 1)
4819 (looking-at org-todo-line-regexp)
4820 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4821 (cond ((eobp) (insert " "))
4822 ((eolp) (insert " "))
4823 ((equal (char-after) ?\ ) (forward-char 1))))))
4825 (defun org-reduced-level (l)
4826 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4828 (defun org-get-valid-level (level &optional change)
4829 "Rectify a level change under the influence of `org-odd-levels-only'
4830 LEVEL is a current level, CHANGE is by how much the level should be
4831 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4832 even level numbers will become the next higher odd number."
4833 (if org-odd-levels-only
4834 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4835 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4836 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4837 (max 1 (+ level change))))
4839 (if (boundp 'define-obsolete-function-alias)
4840 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4841 (define-obsolete-function-alias 'org-get-legal-level
4842 'org-get-valid-level)
4843 (define-obsolete-function-alias 'org-get-legal-level
4844 'org-get-valid-level "23.1")))
4846 (defun org-promote ()
4847 "Promote the current heading higher up the tree.
4848 If the region is active in `transient-mark-mode', promote all headings
4849 in the region."
4850 (org-back-to-heading t)
4851 (let* ((level (save-match-data (funcall outline-level)))
4852 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4853 (diff (abs (- level (length up-head) -1))))
4854 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4855 (replace-match up-head nil t)
4856 ;; Fixup tag positioning
4857 (and org-auto-align-tags (org-set-tags nil t))
4858 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4860 (defun org-demote ()
4861 "Demote the current heading lower down the tree.
4862 If the region is active in `transient-mark-mode', demote all headings
4863 in the region."
4864 (org-back-to-heading t)
4865 (let* ((level (save-match-data (funcall outline-level)))
4866 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4867 (diff (abs (- level (length down-head) -1))))
4868 (replace-match down-head nil t)
4869 ;; Fixup tag positioning
4870 (and org-auto-align-tags (org-set-tags nil t))
4871 (if org-adapt-indentation (org-fixup-indentation diff))))
4873 (defun org-map-tree (fun)
4874 "Call FUN for every heading underneath the current one."
4875 (org-back-to-heading)
4876 (let ((level (funcall outline-level)))
4877 (save-excursion
4878 (funcall fun)
4879 (while (and (progn
4880 (outline-next-heading)
4881 (> (funcall outline-level) level))
4882 (not (eobp)))
4883 (funcall fun)))))
4885 (defun org-map-region (fun beg end)
4886 "Call FUN for every heading between BEG and END."
4887 (let ((org-ignore-region t))
4888 (save-excursion
4889 (setq end (copy-marker end))
4890 (goto-char beg)
4891 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4892 (< (point) end))
4893 (funcall fun))
4894 (while (and (progn
4895 (outline-next-heading)
4896 (< (point) end))
4897 (not (eobp)))
4898 (funcall fun)))))
4900 (defun org-fixup-indentation (diff)
4901 "Change the indentation in the current entry by DIFF
4902 However, if any line in the current entry has no indentation, or if it
4903 would end up with no indentation after the change, nothing at all is done."
4904 (save-excursion
4905 (let ((end (save-excursion (outline-next-heading)
4906 (point-marker)))
4907 (prohibit (if (> diff 0)
4908 "^\\S-"
4909 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4910 col)
4911 (unless (save-excursion (end-of-line 1)
4912 (re-search-forward prohibit end t))
4913 (while (and (< (point) end)
4914 (re-search-forward "^[ \t]+" end t))
4915 (goto-char (match-end 0))
4916 (setq col (current-column))
4917 (if (< diff 0) (replace-match ""))
4918 (indent-to (+ diff col))))
4919 (move-marker end nil))))
4921 (defun org-convert-to-odd-levels ()
4922 "Convert an org-mode file with all levels allowed to one with odd levels.
4923 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4924 level 5 etc."
4925 (interactive)
4926 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4927 (let ((org-odd-levels-only nil) n)
4928 (save-excursion
4929 (goto-char (point-min))
4930 (while (re-search-forward "^\\*\\*+ " nil t)
4931 (setq n (- (length (match-string 0)) 2))
4932 (while (>= (setq n (1- n)) 0)
4933 (org-demote))
4934 (end-of-line 1))))))
4937 (defun org-convert-to-oddeven-levels ()
4938 "Convert an org-mode file with only odd levels to one with odd and even levels.
4939 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4940 section with an even level, conversion would destroy the structure of the file. An error
4941 is signaled in this case."
4942 (interactive)
4943 (goto-char (point-min))
4944 ;; First check if there are no even levels
4945 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4946 (org-show-context t)
4947 (error "Not all levels are odd in this file. Conversion not possible."))
4948 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4949 (let ((org-odd-levels-only nil) n)
4950 (save-excursion
4951 (goto-char (point-min))
4952 (while (re-search-forward "^\\*\\*+ " nil t)
4953 (setq n (/ (1- (length (match-string 0))) 2))
4954 (while (>= (setq n (1- n)) 0)
4955 (org-promote))
4956 (end-of-line 1))))))
4958 (defun org-tr-level (n)
4959 "Make N odd if required."
4960 (if org-odd-levels-only (1+ (/ n 2)) n))
4962 ;;; Vertical tree motion, cutting and pasting of subtrees
4964 (defun org-move-subtree-up (&optional arg)
4965 "Move the current subtree up past ARG headlines of the same level."
4966 (interactive "p")
4967 (org-move-subtree-down (- (prefix-numeric-value arg))))
4969 (defun org-move-subtree-down (&optional arg)
4970 "Move the current subtree down past ARG headlines of the same level."
4971 (interactive "p")
4972 (setq arg (prefix-numeric-value arg))
4973 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4974 'outline-get-last-sibling))
4975 (ins-point (make-marker))
4976 (cnt (abs arg))
4977 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4978 ;; Select the tree
4979 (org-back-to-heading)
4980 (setq beg0 (point))
4981 (save-excursion
4982 (setq ne-beg (org-back-over-empty-lines))
4983 (setq beg (point)))
4984 (save-match-data
4985 (save-excursion (outline-end-of-heading)
4986 (setq folded (org-invisible-p)))
4987 (outline-end-of-subtree))
4988 (outline-next-heading)
4989 (setq ne-end (org-back-over-empty-lines))
4990 (setq end (point))
4991 (goto-char beg0)
4992 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4993 ;; include less whitespace
4994 (save-excursion
4995 (goto-char beg)
4996 (forward-line (- ne-beg ne-end))
4997 (setq beg (point))))
4998 ;; Find insertion point, with error handling
4999 (while (> cnt 0)
5000 (or (and (funcall movfunc) (looking-at outline-regexp))
5001 (progn (goto-char beg0)
5002 (error "Cannot move past superior level or buffer limit")))
5003 (setq cnt (1- cnt)))
5004 (if (> arg 0)
5005 ;; Moving forward - still need to move over subtree
5006 (progn (org-end-of-subtree t t)
5007 (save-excursion
5008 (org-back-over-empty-lines)
5009 (or (bolp) (newline)))))
5010 (setq ne-ins (org-back-over-empty-lines))
5011 (move-marker ins-point (point))
5012 (setq txt (buffer-substring beg end))
5013 (org-save-markers-in-region beg end)
5014 (delete-region beg end)
5015 (outline-flag-region (1- beg) beg nil)
5016 (outline-flag-region (1- (point)) (point) nil)
5017 (let ((bbb (point)))
5018 (insert-before-markers txt)
5019 (org-reinstall-markers-in-region bbb)
5020 (move-marker ins-point bbb))
5021 (or (bolp) (insert "\n"))
5022 (setq ins-end (point))
5023 (goto-char ins-point)
5024 (org-skip-whitespace)
5025 (when (and (< arg 0)
5026 (org-first-sibling-p)
5027 (> ne-ins ne-beg))
5028 ;; Move whitespace back to beginning
5029 (save-excursion
5030 (goto-char ins-end)
5031 (let ((kill-whole-line t))
5032 (kill-line (- ne-ins ne-beg)) (point)))
5033 (insert (make-string (- ne-ins ne-beg) ?\n)))
5034 (move-marker ins-point nil)
5035 (org-compact-display-after-subtree-move)
5036 (org-show-empty-lines-in-parent)
5037 (unless folded
5038 (org-show-entry)
5039 (show-children)
5040 (org-cycle-hide-drawers 'children))))
5042 (defvar org-subtree-clip ""
5043 "Clipboard for cut and paste of subtrees.
5044 This is actually only a copy of the kill, because we use the normal kill
5045 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5047 (defvar org-subtree-clip-folded nil
5048 "Was the last copied subtree folded?
5049 This is used to fold the tree back after pasting.")
5051 (defun org-cut-subtree (&optional n)
5052 "Cut the current subtree into the clipboard.
5053 With prefix arg N, cut this many sequential subtrees.
5054 This is a short-hand for marking the subtree and then cutting it."
5055 (interactive "p")
5056 (org-copy-subtree n 'cut))
5058 (defun org-copy-subtree (&optional n cut force-store-markers)
5059 "Cut the current subtree into the clipboard.
5060 With prefix arg N, cut this many sequential subtrees.
5061 This is a short-hand for marking the subtree and then copying it.
5062 If CUT is non-nil, actually cut the subtree.
5063 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5064 of some markers in the region, even if CUT is non-nil. This is
5065 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5066 (interactive "p")
5067 (let (beg end folded (beg0 (point)))
5068 (if (interactive-p)
5069 (org-back-to-heading nil) ; take what looks like a subtree
5070 (org-back-to-heading t)) ; take what is really there
5071 (org-back-over-empty-lines)
5072 (setq beg (point))
5073 (skip-chars-forward " \t\r\n")
5074 (save-match-data
5075 (save-excursion (outline-end-of-heading)
5076 (setq folded (org-invisible-p)))
5077 (condition-case nil
5078 (outline-forward-same-level (1- n))
5079 (error nil))
5080 (org-end-of-subtree t t))
5081 (org-back-over-empty-lines)
5082 (setq end (point))
5083 (goto-char beg0)
5084 (when (> end beg)
5085 (setq org-subtree-clip-folded folded)
5086 (when (or cut force-store-markers)
5087 (org-save-markers-in-region beg end))
5088 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5089 (setq org-subtree-clip (current-kill 0))
5090 (message "%s: Subtree(s) with %d characters"
5091 (if cut "Cut" "Copied")
5092 (length org-subtree-clip)))))
5094 (defun org-paste-subtree (&optional level tree for-yank)
5095 "Paste the clipboard as a subtree, with modification of headline level.
5096 The entire subtree is promoted or demoted in order to match a new headline
5097 level.
5099 If the cursor is at the beginning of a headline, the same level as
5100 that headline is used to paste the tree
5102 If not, the new level is derived from the *visible* headings
5103 before and after the insertion point, and taken to be the inferior headline
5104 level of the two. So if the previous visible heading is level 3 and the
5105 next is level 4 (or vice versa), level 4 will be used for insertion.
5106 This makes sure that the subtree remains an independent subtree and does
5107 not swallow low level entries.
5109 You can also force a different level, either by using a numeric prefix
5110 argument, or by inserting the heading marker by hand. For example, if the
5111 cursor is after \"*****\", then the tree will be shifted to level 5.
5113 If optional TREE is given, use this text instead of the kill ring.
5115 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5116 move back over whitespace before inserting, and move point to the end of
5117 the inserted text when done."
5118 (interactive "P")
5119 (unless (org-kill-is-subtree-p tree)
5120 (error "%s"
5121 (substitute-command-keys
5122 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5123 (let* ((visp (not (org-invisible-p)))
5124 (txt (or tree (and kill-ring (current-kill 0))))
5125 (^re (concat "^\\(" outline-regexp "\\)"))
5126 (re (concat "\\(" outline-regexp "\\)"))
5127 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5129 (old-level (if (string-match ^re txt)
5130 (- (match-end 0) (match-beginning 0) 1)
5131 -1))
5132 (force-level (cond (level (prefix-numeric-value level))
5133 ((and (looking-at "[ \t]*$")
5134 (string-match
5135 ^re_ (buffer-substring
5136 (point-at-bol) (point))))
5137 (- (match-end 1) (match-beginning 1)))
5138 ((and (bolp)
5139 (looking-at org-outline-regexp))
5140 (- (match-end 0) (point) 1))
5141 (t nil)))
5142 (previous-level (save-excursion
5143 (condition-case nil
5144 (progn
5145 (outline-previous-visible-heading 1)
5146 (if (looking-at re)
5147 (- (match-end 0) (match-beginning 0) 1)
5149 (error 1))))
5150 (next-level (save-excursion
5151 (condition-case nil
5152 (progn
5153 (or (looking-at outline-regexp)
5154 (outline-next-visible-heading 1))
5155 (if (looking-at re)
5156 (- (match-end 0) (match-beginning 0) 1)
5158 (error 1))))
5159 (new-level (or force-level (max previous-level next-level)))
5160 (shift (if (or (= old-level -1)
5161 (= new-level -1)
5162 (= old-level new-level))
5164 (- new-level old-level)))
5165 (delta (if (> shift 0) -1 1))
5166 (func (if (> shift 0) 'org-demote 'org-promote))
5167 (org-odd-levels-only nil)
5168 beg end newend)
5169 ;; Remove the forced level indicator
5170 (if force-level
5171 (delete-region (point-at-bol) (point)))
5172 ;; Paste
5173 (beginning-of-line 1)
5174 (unless for-yank (org-back-over-empty-lines))
5175 (setq beg (point))
5176 (insert-before-markers txt)
5177 (unless (string-match "\n\\'" txt) (insert "\n"))
5178 (setq newend (point))
5179 (org-reinstall-markers-in-region beg)
5180 (setq end (point))
5181 (goto-char beg)
5182 (skip-chars-forward " \t\n\r")
5183 (setq beg (point))
5184 (if (and (org-invisible-p) visp)
5185 (save-excursion (outline-show-heading)))
5186 ;; Shift if necessary
5187 (unless (= shift 0)
5188 (save-restriction
5189 (narrow-to-region beg end)
5190 (while (not (= shift 0))
5191 (org-map-region func (point-min) (point-max))
5192 (setq shift (+ delta shift)))
5193 (goto-char (point-min))
5194 (setq newend (point-max))))
5195 (when (or (interactive-p) for-yank)
5196 (message "Clipboard pasted as level %d subtree" new-level))
5197 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5198 kill-ring
5199 (eq org-subtree-clip (current-kill 0))
5200 org-subtree-clip-folded)
5201 ;; The tree was folded before it was killed/copied
5202 (hide-subtree))
5203 (and for-yank (goto-char newend))))
5205 (defun org-kill-is-subtree-p (&optional txt)
5206 "Check if the current kill is an outline subtree, or a set of trees.
5207 Returns nil if kill does not start with a headline, or if the first
5208 headline level is not the largest headline level in the tree.
5209 So this will actually accept several entries of equal levels as well,
5210 which is OK for `org-paste-subtree'.
5211 If optional TXT is given, check this string instead of the current kill."
5212 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5213 (start-level (and kill
5214 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5215 org-outline-regexp "\\)")
5216 kill)
5217 (- (match-end 2) (match-beginning 2) 1)))
5218 (re (concat "^" org-outline-regexp))
5219 (start (1+ (or (match-beginning 2) -1))))
5220 (if (not start-level)
5221 (progn
5222 nil) ;; does not even start with a heading
5223 (catch 'exit
5224 (while (setq start (string-match re kill (1+ start)))
5225 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5226 (throw 'exit nil)))
5227 t))))
5229 (defvar org-markers-to-move nil
5230 "Markers that should be moved with a cut-and-paste operation.
5231 Those markers are stored together with their positions relative to
5232 the start of the region.")
5234 (defun org-save-markers-in-region (beg end)
5235 "Check markers in region.
5236 If these markers are between BEG and END, record their position relative
5237 to BEG, so that after moving the block of text, we can put the markers back
5238 into place.
5239 This function gets called just before an entry or tree gets cut from the
5240 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5241 called immediately, to move the markers with the entries."
5242 (setq org-markers-to-move nil)
5243 (when (featurep 'org-clock)
5244 (org-clock-save-markers-for-cut-and-paste beg end))
5245 (when (featurep 'org-agenda)
5246 (org-agenda-save-markers-for-cut-and-paste beg end)))
5248 (defun org-check-and-save-marker (marker beg end)
5249 "Check if MARKER is between BEG and END.
5250 If yes, remember the marker and the distance to BEG."
5251 (when (and (marker-buffer marker)
5252 (equal (marker-buffer marker) (current-buffer)))
5253 (if (and (>= marker beg) (< marker end))
5254 (push (cons marker (- marker beg)) org-markers-to-move))))
5256 (defun org-reinstall-markers-in-region (beg)
5257 "Move all remembered markers to their position relative to BEG."
5258 (mapc (lambda (x)
5259 (move-marker (car x) (+ beg (cdr x))))
5260 org-markers-to-move)
5261 (setq org-markers-to-move nil))
5263 (defun org-narrow-to-subtree ()
5264 "Narrow buffer to the current subtree."
5265 (interactive)
5266 (save-excursion
5267 (save-match-data
5268 (narrow-to-region
5269 (progn (org-back-to-heading) (point))
5270 (progn (org-end-of-subtree t) (point))))))
5273 ;;; Outline Sorting
5275 (defun org-sort (with-case)
5276 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5277 Optional argument WITH-CASE means sort case-sensitively."
5278 (interactive "P")
5279 (if (org-at-table-p)
5280 (org-call-with-arg 'org-table-sort-lines with-case)
5281 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5283 (defun org-sort-remove-invisible (s)
5284 (remove-text-properties 0 (length s) org-rm-props s)
5285 (while (string-match org-bracket-link-regexp s)
5286 (setq s (replace-match (if (match-end 2)
5287 (match-string 3 s)
5288 (match-string 1 s)) t t s)))
5291 (defvar org-priority-regexp) ; defined later in the file
5293 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5294 "Sort entries on a certain level of an outline tree.
5295 If there is an active region, the entries in the region are sorted.
5296 Else, if the cursor is before the first entry, sort the top-level items.
5297 Else, the children of the entry at point are sorted.
5299 Sorting can be alphabetically, numerically, and by date/time as given by
5300 the first time stamp in the entry. The command prompts for the sorting
5301 type unless it has been given to the function through the SORTING-TYPE
5302 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5303 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5304 called with point at the beginning of the record. It must return either
5305 a string or a number that should serve as the sorting key for that record.
5307 Comparing entries ignores case by default. However, with an optional argument
5308 WITH-CASE, the sorting considers case as well."
5309 (interactive "P")
5310 (let ((case-func (if with-case 'identity 'downcase))
5311 start beg end stars re re2
5312 txt what tmp plain-list-p)
5313 ;; Find beginning and end of region to sort
5314 (cond
5315 ((org-region-active-p)
5316 ;; we will sort the region
5317 (setq end (region-end)
5318 what "region")
5319 (goto-char (region-beginning))
5320 (if (not (org-on-heading-p)) (outline-next-heading))
5321 (setq start (point)))
5322 ((org-at-item-p)
5323 ;; we will sort this plain list
5324 (org-beginning-of-item-list) (setq start (point))
5325 (org-end-of-item-list) (setq end (point))
5326 (goto-char start)
5327 (setq plain-list-p t
5328 what "plain list"))
5329 ((or (org-on-heading-p)
5330 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5331 ;; we will sort the children of the current headline
5332 (org-back-to-heading)
5333 (setq start (point)
5334 end (progn (org-end-of-subtree t t)
5335 (org-back-over-empty-lines)
5336 (point))
5337 what "children")
5338 (goto-char start)
5339 (show-subtree)
5340 (outline-next-heading))
5342 ;; we will sort the top-level entries in this file
5343 (goto-char (point-min))
5344 (or (org-on-heading-p) (outline-next-heading))
5345 (setq start (point) end (point-max) what "top-level")
5346 (goto-char start)
5347 (show-all)))
5349 (setq beg (point))
5350 (if (>= beg end) (error "Nothing to sort"))
5352 (unless plain-list-p
5353 (looking-at "\\(\\*+\\)")
5354 (setq stars (match-string 1)
5355 re (concat "^" (regexp-quote stars) " +")
5356 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5357 txt (buffer-substring beg end))
5358 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5359 (if (and (not (equal stars "*")) (string-match re2 txt))
5360 (error "Region to sort contains a level above the first entry")))
5362 (unless sorting-type
5363 (message
5364 (if plain-list-p
5365 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5366 "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:")
5367 what)
5368 (setq sorting-type (read-char-exclusive))
5370 (and (= (downcase sorting-type) ?f)
5371 (setq getkey-func
5372 (completing-read "Sort using function: "
5373 obarray 'fboundp t nil nil))
5374 (setq getkey-func (intern getkey-func)))
5376 (and (= (downcase sorting-type) ?r)
5377 (setq property
5378 (completing-read "Property: "
5379 (mapcar 'list (org-buffer-property-keys t))
5380 nil t))))
5382 (message "Sorting entries...")
5384 (save-restriction
5385 (narrow-to-region start end)
5387 (let ((dcst (downcase sorting-type))
5388 (now (current-time)))
5389 (sort-subr
5390 (/= dcst sorting-type)
5391 ;; This function moves to the beginning character of the "record" to
5392 ;; be sorted.
5393 (if plain-list-p
5394 (lambda nil
5395 (if (org-at-item-p) t (goto-char (point-max))))
5396 (lambda nil
5397 (if (re-search-forward re nil t)
5398 (goto-char (match-beginning 0))
5399 (goto-char (point-max)))))
5400 ;; This function moves to the last character of the "record" being
5401 ;; sorted.
5402 (if plain-list-p
5403 'org-end-of-item
5404 (lambda nil
5405 (save-match-data
5406 (condition-case nil
5407 (outline-forward-same-level 1)
5408 (error
5409 (goto-char (point-max)))))))
5411 ;; This function returns the value that gets sorted against.
5412 (if plain-list-p
5413 (lambda nil
5414 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5415 (cond
5416 ((= dcst ?n)
5417 (string-to-number (buffer-substring (match-end 0)
5418 (point-at-eol))))
5419 ((= dcst ?a)
5420 (buffer-substring (match-end 0) (point-at-eol)))
5421 ((= dcst ?t)
5422 (if (re-search-forward org-ts-regexp
5423 (point-at-eol) t)
5424 (org-time-string-to-time (match-string 0))
5425 now))
5426 ((= dcst ?f)
5427 (if getkey-func
5428 (progn
5429 (setq tmp (funcall getkey-func))
5430 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5431 tmp)
5432 (error "Invalid key function `%s'" getkey-func)))
5433 (t (error "Invalid sorting type `%c'" sorting-type)))))
5434 (lambda nil
5435 (cond
5436 ((= dcst ?n)
5437 (if (looking-at org-complex-heading-regexp)
5438 (string-to-number (match-string 4))
5439 nil))
5440 ((= dcst ?a)
5441 (if (looking-at org-complex-heading-regexp)
5442 (funcall case-func (match-string 4))
5443 nil))
5444 ((= dcst ?t)
5445 (if (re-search-forward org-ts-regexp
5446 (save-excursion
5447 (forward-line 2)
5448 (point)) t)
5449 (org-time-string-to-time (match-string 0))
5450 now))
5451 ((= dcst ?p)
5452 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5453 (string-to-char (match-string 2))
5454 org-default-priority))
5455 ((= dcst ?r)
5456 (or (org-entry-get nil property) ""))
5457 ((= dcst ?o)
5458 (if (looking-at org-complex-heading-regexp)
5459 (- 9999 (length (member (match-string 2)
5460 org-todo-keywords-1)))))
5461 ((= dcst ?f)
5462 (if getkey-func
5463 (progn
5464 (setq tmp (funcall getkey-func))
5465 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5466 tmp)
5467 (error "Invalid key function `%s'" getkey-func)))
5468 (t (error "Invalid sorting type `%c'" sorting-type)))))
5470 (cond
5471 ((= dcst ?a) 'string<)
5472 ((= dcst ?t) 'time-less-p)
5473 (t nil)))))
5474 (message "Sorting entries...done")))
5476 (defun org-do-sort (table what &optional with-case sorting-type)
5477 "Sort TABLE of WHAT according to SORTING-TYPE.
5478 The user will be prompted for the SORTING-TYPE if the call to this
5479 function does not specify it. WHAT is only for the prompt, to indicate
5480 what is being sorted. The sorting key will be extracted from
5481 the car of the elements of the table.
5482 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5483 (unless sorting-type
5484 (message
5485 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5486 what)
5487 (setq sorting-type (read-char-exclusive)))
5488 (let ((dcst (downcase sorting-type))
5489 extractfun comparefun)
5490 ;; Define the appropriate functions
5491 (cond
5492 ((= dcst ?n)
5493 (setq extractfun 'string-to-number
5494 comparefun (if (= dcst sorting-type) '< '>)))
5495 ((= dcst ?a)
5496 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5497 (lambda(x) (downcase (org-sort-remove-invisible x))))
5498 comparefun (if (= dcst sorting-type)
5499 'string<
5500 (lambda (a b) (and (not (string< a b))
5501 (not (string= a b)))))))
5502 ((= dcst ?t)
5503 (setq extractfun
5504 (lambda (x)
5505 (if (string-match org-ts-regexp x)
5506 (time-to-seconds
5507 (org-time-string-to-time (match-string 0 x)))
5509 comparefun (if (= dcst sorting-type) '< '>)))
5510 (t (error "Invalid sorting type `%c'" sorting-type)))
5512 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5513 table)
5514 (lambda (a b) (funcall comparefun (car a) (car b))))))
5516 ;;; Editing source examples
5518 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5519 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5520 (defvar org-edit-src-force-single-line nil)
5521 (defvar org-edit-src-from-org-mode nil)
5522 (defvar org-edit-src-picture nil)
5524 (define-minor-mode org-exit-edit-mode
5525 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5527 (defun org-edit-src-code ()
5528 "Edit the source code example at point.
5529 An indirect buffer is created, and that buffer is then narrowed to the
5530 example at point and switched to the correct language mode. When done,
5531 exit by killing the buffer with \\[org-edit-src-exit]."
5532 (interactive)
5533 (let ((line (org-current-line))
5534 (case-fold-search t)
5535 (msg (substitute-command-keys
5536 "Edit, then exit with C-c ' (C-c and single quote)"))
5537 (info (org-edit-src-find-region-and-lang))
5538 (org-mode-p (eq major-mode 'org-mode))
5539 beg end lang lang-f single)
5540 (if (not info)
5542 (setq beg (nth 0 info)
5543 end (nth 1 info)
5544 lang (nth 2 info)
5545 single (nth 3 info)
5546 lang-f (intern (concat lang "-mode")))
5547 (unless (functionp lang-f)
5548 (error "No such language mode: %s" lang-f))
5549 (goto-line line)
5550 (if (get-buffer "*Org Edit Src Example*")
5551 (kill-buffer "*Org Edit Src Example*"))
5552 (switch-to-buffer (make-indirect-buffer (current-buffer)
5553 "*Org Edit Src Example*"))
5554 (narrow-to-region beg end)
5555 (remove-text-properties beg end '(display nil invisible nil
5556 intangible nil))
5557 (let ((org-inhibit-startup t))
5558 (funcall lang-f))
5559 (set (make-local-variable 'org-edit-src-force-single-line) single)
5560 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5561 (when org-mode-p
5562 (goto-char (point-min))
5563 (while (re-search-forward "^," nil t)
5564 (replace-match "")))
5565 (goto-line line)
5566 (org-exit-edit-mode)
5567 (org-set-local 'header-line-format msg)
5568 (message "%s" msg)
5569 t)))
5571 (defun org-edit-fixed-width-region ()
5572 "Edit the fixed-width ascii drawing at point.
5573 This must be a region where each line starts with ca colon followed by
5574 a space character.
5575 An indirect buffer is created, and that buffer is then narrowed to the
5576 example at point and switched to artist-mode. When done,
5577 exit by killing the buffer with \\[org-edit-src-exit]."
5578 (interactive)
5579 (let ((line (org-current-line))
5580 (case-fold-search t)
5581 (msg (substitute-command-keys
5582 "Edit, then exit with C-c ' (C-c and single quote)"))
5583 (org-mode-p (eq major-mode 'org-mode))
5584 beg end lang lang-f)
5585 (beginning-of-line 1)
5586 (if (looking-at "[ \t]*[^:\n \t]")
5588 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5589 (setq beg (point) end (match-end 0))
5590 (save-excursion
5591 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5592 (setq beg (point-at-bol 2))
5593 (setq beg (point))))
5594 (save-excursion
5595 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5596 (setq end (1- (match-beginning 0)))
5597 (setq end (point))))
5598 (goto-line line)
5599 (if (get-buffer "*Org Edit Picture*")
5600 (kill-buffer "*Org Edit Picture*"))
5601 (switch-to-buffer (make-indirect-buffer (current-buffer)
5602 "*Org Edit Picture*"))
5603 (narrow-to-region beg end)
5604 (remove-text-properties beg end '(display nil invisible nil
5605 intangible nil))
5606 (when (fboundp 'font-lock-unfontify-region)
5607 (font-lock-unfontify-region (point-min) (point-max)))
5608 (cond
5609 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5610 (fundamental-mode)
5611 (artist-mode 1))
5612 (t (funcall org-edit-fixed-width-region-mode)))
5613 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5614 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5615 (set (make-local-variable 'org-edit-src-picture) t)
5616 (goto-char (point-min))
5617 (while (re-search-forward "^[ \t]*: " nil t)
5618 (replace-match ""))
5619 (goto-line line)
5620 (org-exit-edit-mode)
5621 (org-set-local 'header-line-format msg)
5622 (message "%s" msg)
5623 t))))
5626 (defun org-edit-src-find-region-and-lang ()
5627 "Find the region and language for a local edit.
5628 Return a list with beginning and end of the region, a string representing
5629 the language, a switch telling of the content should be in a single line."
5630 (let ((re-list
5631 (append
5632 org-edit-src-region-extra
5634 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5635 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5636 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5637 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5638 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5639 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5640 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5641 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5642 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5643 ("^#\\+html:" "\n" "html" single-line)
5644 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5645 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5646 ("^#\\+latex:" "\n" "latex" single-line)
5647 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5648 ("^#\\+ascii:" "\n" "ascii" single-line)
5650 (pos (point))
5651 re re1 re2 single beg end lang)
5652 (catch 'exit
5653 (while (setq entry (pop re-list))
5654 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5655 single (nth 3 entry))
5656 (save-excursion
5657 (if (or (looking-at re1)
5658 (re-search-backward re1 nil t))
5659 (progn
5660 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5661 (if (and (re-search-forward re2 nil t)
5662 (>= (match-end 0) pos))
5663 (throw 'exit (list beg (match-beginning 0) lang single))))
5664 (if (or (looking-at re2)
5665 (re-search-forward re2 nil t))
5666 (progn
5667 (setq end (match-beginning 0))
5668 (if (and (re-search-backward re1 nil t)
5669 (<= (match-beginning 0) pos))
5670 (throw 'exit
5671 (list (match-end 0) end
5672 (org-edit-src-get-lang lang) single)))))))))))
5674 (defun org-edit-src-get-lang (lang)
5675 "Extract the src language."
5676 (let ((m (match-string 0)))
5677 (cond
5678 ((stringp lang) lang)
5679 ((integerp lang) (match-string lang))
5680 ((and (eq lang 'lang)
5681 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5682 (match-string 1 m))
5683 ((and (eq lang 'style)
5684 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5685 (match-string 1 m))
5686 (t "fundamental"))))
5688 (defun org-edit-src-exit ()
5689 "Exit special edit and protect problematic lines."
5690 (interactive)
5691 (unless (buffer-base-buffer (current-buffer))
5692 (error "This is not an indirect buffer, something is wrong..."))
5693 (unless (> (point-min) 1)
5694 (error "This buffer is not narrowed, something is wrong..."))
5695 (goto-char (point-min))
5696 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5697 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5698 (when (org-bound-and-true-p org-edit-src-force-single-line)
5699 (goto-char (point-min))
5700 (while (re-search-forward "\n" nil t)
5701 (replace-match " "))
5702 (goto-char (point-min))
5703 (if (looking-at "\\s-*") (replace-match " "))
5704 (if (re-search-forward "\\s-+\\'" nil t)
5705 (replace-match "")))
5706 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5707 (goto-char (point-min))
5708 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5709 (replace-match ",\\1"))
5710 (when font-lock-mode
5711 (font-lock-unfontify-region (point-min) (point-max)))
5712 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5713 (when (org-bound-and-true-p org-edit-src-picture)
5714 (untabify (point-min) (point-max))
5715 (goto-char (point-min))
5716 (while (re-search-forward "^" nil t)
5717 (replace-match ": "))
5718 (when font-lock-mode
5719 (font-lock-unfontify-region (point-min) (point-max)))
5720 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5721 (kill-buffer (current-buffer))
5722 (and (org-mode-p) (org-restart-font-lock)))
5725 ;;; The orgstruct minor mode
5727 ;; Define a minor mode which can be used in other modes in order to
5728 ;; integrate the org-mode structure editing commands.
5730 ;; This is really a hack, because the org-mode structure commands use
5731 ;; keys which normally belong to the major mode. Here is how it
5732 ;; works: The minor mode defines all the keys necessary to operate the
5733 ;; structure commands, but wraps the commands into a function which
5734 ;; tests if the cursor is currently at a headline or a plain list
5735 ;; item. If that is the case, the structure command is used,
5736 ;; temporarily setting many Org-mode variables like regular
5737 ;; expressions for filling etc. However, when any of those keys is
5738 ;; used at a different location, function uses `key-binding' to look
5739 ;; up if the key has an associated command in another currently active
5740 ;; keymap (minor modes, major mode, global), and executes that
5741 ;; command. There might be problems if any of the keys is otherwise
5742 ;; used as a prefix key.
5744 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5745 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5746 ;; addresses this by checking explicitly for both bindings.
5748 (defvar orgstruct-mode-map (make-sparse-keymap)
5749 "Keymap for the minor `orgstruct-mode'.")
5751 (defvar org-local-vars nil
5752 "List of local variables, for use by `orgstruct-mode'")
5754 ;;;###autoload
5755 (define-minor-mode orgstruct-mode
5756 "Toggle the minor more `orgstruct-mode'.
5757 This mode is for using Org-mode structure commands in other modes.
5758 The following key behave as if Org-mode was active, if the cursor
5759 is on a headline, or on a plain list item (both in the definition
5760 of Org-mode).
5762 M-up Move entry/item up
5763 M-down Move entry/item down
5764 M-left Promote
5765 M-right Demote
5766 M-S-up Move entry/item up
5767 M-S-down Move entry/item down
5768 M-S-left Promote subtree
5769 M-S-right Demote subtree
5770 M-q Fill paragraph and items like in Org-mode
5771 C-c ^ Sort entries
5772 C-c - Cycle list bullet
5773 TAB Cycle item visibility
5774 M-RET Insert new heading/item
5775 S-M-RET Insert new TODO heading / Chekbox item
5776 C-c C-c Set tags / toggle checkbox"
5777 nil " OrgStruct" nil
5778 (org-load-modules-maybe)
5779 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5781 ;;;###autoload
5782 (defun turn-on-orgstruct ()
5783 "Unconditionally turn on `orgstruct-mode'."
5784 (orgstruct-mode 1))
5786 ;;;###autoload
5787 (defun turn-on-orgstruct++ ()
5788 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5789 In addition to setting orgstruct-mode, this also exports all indentation and
5790 autofilling variables from org-mode into the buffer. Note that turning
5791 off orgstruct-mode will *not* remove these additional settings."
5792 (orgstruct-mode 1)
5793 (let (var val)
5794 (mapc
5795 (lambda (x)
5796 (when (string-match
5797 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5798 (symbol-name (car x)))
5799 (setq var (car x) val (nth 1 x))
5800 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5801 org-local-vars)))
5803 (defun orgstruct-error ()
5804 "Error when there is no default binding for a structure key."
5805 (interactive)
5806 (error "This key has no function outside structure elements"))
5808 (defun orgstruct-setup ()
5809 "Setup orgstruct keymaps."
5810 (let ((nfunc 0)
5811 (bindings
5812 (list
5813 '([(meta up)] org-metaup)
5814 '([(meta down)] org-metadown)
5815 '([(meta left)] org-metaleft)
5816 '([(meta right)] org-metaright)
5817 '([(meta shift up)] org-shiftmetaup)
5818 '([(meta shift down)] org-shiftmetadown)
5819 '([(meta shift left)] org-shiftmetaleft)
5820 '([(meta shift right)] org-shiftmetaright)
5821 '([(shift up)] org-shiftup)
5822 '([(shift down)] org-shiftdown)
5823 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5824 '("\M-q" fill-paragraph)
5825 '("\C-c^" org-sort)
5826 '("\C-c-" org-cycle-list-bullet)))
5827 elt key fun cmd)
5828 (while (setq elt (pop bindings))
5829 (setq nfunc (1+ nfunc))
5830 (setq key (org-key (car elt))
5831 fun (nth 1 elt)
5832 cmd (orgstruct-make-binding fun nfunc key))
5833 (org-defkey orgstruct-mode-map key cmd))
5835 ;; Special treatment needed for TAB and RET
5836 (org-defkey orgstruct-mode-map [(tab)]
5837 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5838 (org-defkey orgstruct-mode-map "\C-i"
5839 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5841 (org-defkey orgstruct-mode-map "\M-\C-m"
5842 (orgstruct-make-binding 'org-insert-heading 105
5843 "\M-\C-m" [(meta return)]))
5844 (org-defkey orgstruct-mode-map [(meta return)]
5845 (orgstruct-make-binding 'org-insert-heading 106
5846 [(meta return)] "\M-\C-m"))
5848 (org-defkey orgstruct-mode-map [(shift meta return)]
5849 (orgstruct-make-binding 'org-insert-todo-heading 107
5850 [(meta return)] "\M-\C-m"))
5852 (unless org-local-vars
5853 (setq org-local-vars (org-get-local-variables)))
5857 (defun orgstruct-make-binding (fun n &rest keys)
5858 "Create a function for binding in the structure minor mode.
5859 FUN is the command to call inside a table. N is used to create a unique
5860 command name. KEYS are keys that should be checked in for a command
5861 to execute outside of tables."
5862 (eval
5863 (list 'defun
5864 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5865 '(arg)
5866 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5867 "Outside of structure, run the binding of `"
5868 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5869 "'.")
5870 '(interactive "p")
5871 (list 'if
5872 '(org-context-p 'headline 'item)
5873 (list 'org-run-like-in-org-mode (list 'quote fun))
5874 (list 'let '(orgstruct-mode)
5875 (list 'call-interactively
5876 (append '(or)
5877 (mapcar (lambda (k)
5878 (list 'key-binding k))
5879 keys)
5880 '('orgstruct-error))))))))
5882 (defun org-context-p (&rest contexts)
5883 "Check if local context is any of CONTEXTS.
5884 Possible values in the list of contexts are `table', `headline', and `item'."
5885 (let ((pos (point)))
5886 (goto-char (point-at-bol))
5887 (prog1 (or (and (memq 'table contexts)
5888 (looking-at "[ \t]*|"))
5889 (and (memq 'headline contexts)
5890 ;;????????? (looking-at "\\*+"))
5891 (looking-at outline-regexp))
5892 (and (memq 'item contexts)
5893 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5894 (goto-char pos))))
5896 (defun org-get-local-variables ()
5897 "Return a list of all local variables in an org-mode buffer."
5898 (let (varlist)
5899 (with-current-buffer (get-buffer-create "*Org tmp*")
5900 (erase-buffer)
5901 (org-mode)
5902 (setq varlist (buffer-local-variables)))
5903 (kill-buffer "*Org tmp*")
5904 (delq nil
5905 (mapcar
5906 (lambda (x)
5907 (setq x
5908 (if (symbolp x)
5909 (list x)
5910 (list (car x) (list 'quote (cdr x)))))
5911 (if (string-match
5912 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5913 (symbol-name (car x)))
5914 x nil))
5915 varlist))))
5917 ;;;###autoload
5918 (defun org-run-like-in-org-mode (cmd)
5919 (org-load-modules-maybe)
5920 (unless org-local-vars
5921 (setq org-local-vars (org-get-local-variables)))
5922 (eval (list 'let org-local-vars
5923 (list 'call-interactively (list 'quote cmd)))))
5925 ;;;; Archiving
5927 (defun org-get-category (&optional pos)
5928 "Get the category applying to position POS."
5929 (get-text-property (or pos (point)) 'org-category))
5931 (defun org-refresh-category-properties ()
5932 "Refresh category text properties in the buffer."
5933 (let ((def-cat (cond
5934 ((null org-category)
5935 (if buffer-file-name
5936 (file-name-sans-extension
5937 (file-name-nondirectory buffer-file-name))
5938 "???"))
5939 ((symbolp org-category) (symbol-name org-category))
5940 (t org-category)))
5941 beg end cat pos optionp)
5942 (org-unmodified
5943 (save-excursion
5944 (save-restriction
5945 (widen)
5946 (goto-char (point-min))
5947 (put-text-property (point) (point-max) 'org-category def-cat)
5948 (while (re-search-forward
5949 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5950 (setq pos (match-end 0)
5951 optionp (equal (char-after (match-beginning 0)) ?#)
5952 cat (org-trim (match-string 2)))
5953 (if optionp
5954 (setq beg (point-at-bol) end (point-max))
5955 (org-back-to-heading t)
5956 (setq beg (point) end (org-end-of-subtree t t)))
5957 (put-text-property beg end 'org-category cat)
5958 (goto-char pos)))))))
5961 ;;;; Link Stuff
5963 ;;; Link abbreviations
5965 (defun org-link-expand-abbrev (link)
5966 "Apply replacements as defined in `org-link-abbrev-alist."
5967 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5968 (let* ((key (match-string 1 link))
5969 (as (or (assoc key org-link-abbrev-alist-local)
5970 (assoc key org-link-abbrev-alist)))
5971 (tag (and (match-end 2) (match-string 3 link)))
5972 rpl)
5973 (if (not as)
5974 link
5975 (setq rpl (cdr as))
5976 (cond
5977 ((symbolp rpl) (funcall rpl tag))
5978 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5979 (t (concat rpl tag)))))
5980 link))
5982 ;;; Storing and inserting links
5984 (defvar org-insert-link-history nil
5985 "Minibuffer history for links inserted with `org-insert-link'.")
5987 (defvar org-stored-links nil
5988 "Contains the links stored with `org-store-link'.")
5990 (defvar org-store-link-plist nil
5991 "Plist with info about the most recently link created with `org-store-link'.")
5993 (defvar org-link-protocols nil
5994 "Link protocols added to Org-mode using `org-add-link-type'.")
5996 (defvar org-store-link-functions nil
5997 "List of functions that are called to create and store a link.
5998 Each function will be called in turn until one returns a non-nil
5999 value. Each function should check if it is responsible for creating
6000 this link (for example by looking at the major mode).
6001 If not, it must exit and return nil.
6002 If yes, it should return a non-nil value after a calling
6003 `org-store-link-props' with a list of properties and values.
6004 Special properties are:
6006 :type The link prefix. like \"http\". This must be given.
6007 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6008 This is obligatory as well.
6009 :description Optional default description for the second pair
6010 of brackets in an Org-mode link. The user can still change
6011 this when inserting this link into an Org-mode buffer.
6013 In addition to these, any additional properties can be specified
6014 and then used in remember templates.")
6016 (defun org-add-link-type (type &optional follow export)
6017 "Add TYPE to the list of `org-link-types'.
6018 Re-compute all regular expressions depending on `org-link-types'
6020 FOLLOW and EXPORT are two functions.
6022 FOLLOW should take the link path as the single argument and do whatever
6023 is necessary to follow the link, for example find a file or display
6024 a mail message.
6026 EXPORT should format the link path for export to one of the export formats.
6027 It should be a function accepting three arguments:
6029 path the path of the link, the text after the prefix (like \"http:\")
6030 desc the description of the link, if any, nil if there was no descripton
6031 format the export format, a symbol like `html' or `latex'.
6033 The function may use the FORMAT information to return different values
6034 depending on the format. The return value will be put literally into
6035 the exported file.
6036 Org-mode has a built-in default for exporting links. If you are happy with
6037 this default, there is no need to define an export function for the link
6038 type. For a simple example of an export function, see `org-bbdb.el'."
6039 (add-to-list 'org-link-types type t)
6040 (org-make-link-regexps)
6041 (if (assoc type org-link-protocols)
6042 (setcdr (assoc type org-link-protocols) (list follow export))
6043 (push (list type follow export) org-link-protocols)))
6046 ;;;###autoload
6047 (defun org-store-link (arg)
6048 "\\<org-mode-map>Store an org-link to the current location.
6049 This link is added to `org-stored-links' and can later be inserted
6050 into an org-buffer with \\[org-insert-link].
6052 For some link types, a prefix arg is interpreted:
6053 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6054 For file links, arg negates `org-context-in-file-links'."
6055 (interactive "P")
6056 (org-load-modules-maybe)
6057 (setq org-store-link-plist nil) ; reset
6058 (let (link cpltxt desc description search txt)
6059 (cond
6061 ((run-hook-with-args-until-success 'org-store-link-functions)
6062 (setq link (plist-get org-store-link-plist :link)
6063 desc (or (plist-get org-store-link-plist :description) link)))
6065 ((eq major-mode 'calendar-mode)
6066 (let ((cd (calendar-cursor-to-date)))
6067 (setq link
6068 (format-time-string
6069 (car org-time-stamp-formats)
6070 (apply 'encode-time
6071 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6072 nil nil nil))))
6073 (org-store-link-props :type "calendar" :date cd)))
6075 ((eq major-mode 'w3-mode)
6076 (setq cpltxt (url-view-url t)
6077 link (org-make-link cpltxt))
6078 (org-store-link-props :type "w3" :url (url-view-url t)))
6080 ((eq major-mode 'w3m-mode)
6081 (setq cpltxt (or w3m-current-title w3m-current-url)
6082 link (org-make-link w3m-current-url))
6083 (org-store-link-props :type "w3m" :url (url-view-url t)))
6085 ((setq search (run-hook-with-args-until-success
6086 'org-create-file-search-functions))
6087 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6088 "::" search))
6089 (setq cpltxt (or description link)))
6091 ((eq major-mode 'image-mode)
6092 (setq cpltxt (concat "file:"
6093 (abbreviate-file-name buffer-file-name))
6094 link (org-make-link cpltxt))
6095 (org-store-link-props :type "image" :file buffer-file-name))
6097 ((eq major-mode 'dired-mode)
6098 ;; link to the file in the current line
6099 (setq cpltxt (concat "file:"
6100 (abbreviate-file-name
6101 (expand-file-name
6102 (dired-get-filename nil t))))
6103 link (org-make-link cpltxt)))
6105 ((and buffer-file-name (org-mode-p))
6106 ;; Just link to current headline
6107 (setq cpltxt (concat "file:"
6108 (abbreviate-file-name buffer-file-name)))
6109 ;; Add a context search string
6110 (when (org-xor org-context-in-file-links arg)
6111 ;; Check if we are on a target
6112 (if (org-in-regexp "<<\\(.*?\\)>>")
6113 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6114 (setq txt (cond
6115 ((org-on-heading-p) nil)
6116 ((org-region-active-p)
6117 (buffer-substring (region-beginning) (region-end)))
6118 (t nil)))
6119 (when (or (null txt) (string-match "\\S-" txt))
6120 (setq cpltxt
6121 (concat cpltxt "::"
6122 (condition-case nil
6123 (org-make-org-heading-search-string txt)
6124 (error "")))
6125 desc "NONE"))))
6126 (if (string-match "::\\'" cpltxt)
6127 (setq cpltxt (substring cpltxt 0 -2)))
6128 (setq link (org-make-link cpltxt)))
6130 ((buffer-file-name (buffer-base-buffer))
6131 ;; Just link to this file here.
6132 (setq cpltxt (concat "file:"
6133 (abbreviate-file-name
6134 (buffer-file-name (buffer-base-buffer)))))
6135 ;; Add a context string
6136 (when (org-xor org-context-in-file-links arg)
6137 (setq txt (if (org-region-active-p)
6138 (buffer-substring (region-beginning) (region-end))
6139 (buffer-substring (point-at-bol) (point-at-eol))))
6140 ;; Only use search option if there is some text.
6141 (when (string-match "\\S-" txt)
6142 (setq cpltxt
6143 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6144 desc "NONE")))
6145 (setq link (org-make-link cpltxt)))
6147 ((interactive-p)
6148 (error "Cannot link to a buffer which is not visiting a file"))
6150 (t (setq link nil)))
6152 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6153 (setq link (or link cpltxt)
6154 desc (or desc cpltxt))
6155 (if (equal desc "NONE") (setq desc nil))
6157 (if (and (interactive-p) link)
6158 (progn
6159 (setq org-stored-links
6160 (cons (list link desc) org-stored-links))
6161 (message "Stored: %s" (or desc link)))
6162 (and link (org-make-link-string link desc)))))
6164 (defun org-store-link-props (&rest plist)
6165 "Store link properties, extract names and addresses."
6166 (let (x adr)
6167 (when (setq x (plist-get plist :from))
6168 (setq adr (mail-extract-address-components x))
6169 (setq plist (plist-put plist :fromname (car adr)))
6170 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6171 (when (setq x (plist-get plist :to))
6172 (setq adr (mail-extract-address-components x))
6173 (setq plist (plist-put plist :toname (car adr)))
6174 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6175 (let ((from (plist-get plist :from))
6176 (to (plist-get plist :to)))
6177 (when (and from to org-from-is-user-regexp)
6178 (setq plist
6179 (plist-put plist :fromto
6180 (if (string-match org-from-is-user-regexp from)
6181 (concat "to %t")
6182 (concat "from %f"))))))
6183 (setq org-store-link-plist plist))
6185 (defun org-add-link-props (&rest plist)
6186 "Add these properties to the link property list."
6187 (let (key value)
6188 (while plist
6189 (setq key (pop plist) value (pop plist))
6190 (setq org-store-link-plist
6191 (plist-put org-store-link-plist key value)))))
6193 (defun org-email-link-description (&optional fmt)
6194 "Return the description part of an email link.
6195 This takes information from `org-store-link-plist' and formats it
6196 according to FMT (default from `org-email-link-description-format')."
6197 (setq fmt (or fmt org-email-link-description-format))
6198 (let* ((p org-store-link-plist)
6199 (to (plist-get p :toaddress))
6200 (from (plist-get p :fromaddress))
6201 (table
6202 (list
6203 (cons "%c" (plist-get p :fromto))
6204 (cons "%F" (plist-get p :from))
6205 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6206 (cons "%T" (plist-get p :to))
6207 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6208 (cons "%s" (plist-get p :subject))
6209 (cons "%m" (plist-get p :message-id)))))
6210 (when (string-match "%c" fmt)
6211 ;; Check if the user wrote this message
6212 (if (and org-from-is-user-regexp from to
6213 (save-match-data (string-match org-from-is-user-regexp from)))
6214 (setq fmt (replace-match "to %t" t t fmt))
6215 (setq fmt (replace-match "from %f" t t fmt))))
6216 (org-replace-escapes fmt table)))
6218 (defun org-make-org-heading-search-string (&optional string heading)
6219 "Make search string for STRING or current headline."
6220 (interactive)
6221 (let ((s (or string (org-get-heading))))
6222 (unless (and string (not heading))
6223 ;; We are using a headline, clean up garbage in there.
6224 (if (string-match org-todo-regexp s)
6225 (setq s (replace-match "" t t s)))
6226 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6227 (setq s (replace-match "" t t s)))
6228 (setq s (org-trim s))
6229 (if (string-match (concat "^\\(" org-quote-string "\\|"
6230 org-comment-string "\\)") s)
6231 (setq s (replace-match "" t t s)))
6232 (while (string-match org-ts-regexp s)
6233 (setq s (replace-match "" t t s))))
6234 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6235 (setq s (replace-match " " t t s)))
6236 (or string (setq s (concat "*" s))) ; Add * for headlines
6237 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6239 (defun org-make-link (&rest strings)
6240 "Concatenate STRINGS."
6241 (apply 'concat strings))
6243 (defun org-make-link-string (link &optional description)
6244 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6245 (unless (string-match "\\S-" link)
6246 (error "Empty link"))
6247 (when (stringp description)
6248 ;; Remove brackets from the description, they are fatal.
6249 (while (string-match "\\[" description)
6250 (setq description (replace-match "{" t t description)))
6251 (while (string-match "\\]" description)
6252 (setq description (replace-match "}" t t description))))
6253 (when (equal (org-link-escape link) description)
6254 ;; No description needed, it is identical
6255 (setq description nil))
6256 (when (and (not description)
6257 (not (equal link (org-link-escape link))))
6258 (setq description (org-extract-attributes link)))
6259 (concat "[[" (org-link-escape link) "]"
6260 (if description (concat "[" description "]") "")
6261 "]"))
6263 (defconst org-link-escape-chars
6264 '((?\ . "%20")
6265 (?\[ . "%5B")
6266 (?\] . "%5D")
6267 (?\340 . "%E0") ; `a
6268 (?\342 . "%E2") ; ^a
6269 (?\347 . "%E7") ; ,c
6270 (?\350 . "%E8") ; `e
6271 (?\351 . "%E9") ; 'e
6272 (?\352 . "%EA") ; ^e
6273 (?\356 . "%EE") ; ^i
6274 (?\364 . "%F4") ; ^o
6275 (?\371 . "%F9") ; `u
6276 (?\373 . "%FB") ; ^u
6277 (?\; . "%3B")
6278 (?? . "%3F")
6279 (?= . "%3D")
6280 (?+ . "%2B")
6282 "Association list of escapes for some characters problematic in links.
6283 This is the list that is used for internal purposes.")
6285 (defconst org-link-escape-chars-browser
6286 '((?\ . "%20")) ; 32 for the SPC char
6287 "Association list of escapes for some characters problematic in links.
6288 This is the list that is used before handing over to the browser.")
6290 (defun org-link-escape (text &optional table)
6291 "Escape charaters in TEXT that are problematic for links."
6292 (setq table (or table org-link-escape-chars))
6293 (when text
6294 (let ((re (mapconcat (lambda (x) (regexp-quote
6295 (char-to-string (car x))))
6296 table "\\|")))
6297 (while (string-match re text)
6298 (setq text
6299 (replace-match
6300 (cdr (assoc (string-to-char (match-string 0 text))
6301 table))
6302 t t text)))
6303 text)))
6305 (defun org-link-unescape (text &optional table)
6306 "Reverse the action of `org-link-escape'."
6307 (setq table (or table org-link-escape-chars))
6308 (when text
6309 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6310 table "\\|")))
6311 (while (string-match re text)
6312 (setq text
6313 (replace-match
6314 (char-to-string (car (rassoc (match-string 0 text) table)))
6315 t t text)))
6316 text)))
6318 (defun org-xor (a b)
6319 "Exclusive or."
6320 (if a (not b) b))
6322 (defun org-get-header (header)
6323 "Find a header field in the current buffer."
6324 (save-excursion
6325 (goto-char (point-min))
6326 (let ((case-fold-search t) s)
6327 (cond
6328 ((eq header 'from)
6329 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6330 (setq s (match-string 1)))
6331 (while (string-match "\"" s)
6332 (setq s (replace-match "" t t s)))
6333 (if (string-match "[<(].*" s)
6334 (setq s (replace-match "" t t s))))
6335 ((eq header 'message-id)
6336 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6337 (setq s (match-string 1))))
6338 ((eq header 'subject)
6339 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6340 (setq s (match-string 1)))))
6341 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6342 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6343 s)))
6346 (defun org-fixup-message-id-for-http (s)
6347 "Replace special characters in a message id, so it can be used in an http query."
6348 (while (string-match "<" s)
6349 (setq s (replace-match "%3C" t t s)))
6350 (while (string-match ">" s)
6351 (setq s (replace-match "%3E" t t s)))
6352 (while (string-match "@" s)
6353 (setq s (replace-match "%40" t t s)))
6356 ;;;###autoload
6357 (defun org-insert-link-global ()
6358 "Insert a link like Org-mode does.
6359 This command can be called in any mode to insert a link in Org-mode syntax."
6360 (interactive)
6361 (org-load-modules-maybe)
6362 (org-run-like-in-org-mode 'org-insert-link))
6364 (defun org-insert-link (&optional complete-file link-location)
6365 "Insert a link. At the prompt, enter the link.
6367 Completion can be used to insert any of the link protocol prefixes like
6368 http or ftp in use.
6370 The history can be used to select a link previously stored with
6371 `org-store-link'. When the empty string is entered (i.e. if you just
6372 press RET at the prompt), the link defaults to the most recently
6373 stored link. As SPC triggers completion in the minibuffer, you need to
6374 use M-SPC or C-q SPC to force the insertion of a space character.
6376 You will also be prompted for a description, and if one is given, it will
6377 be displayed in the buffer instead of the link.
6379 If there is already a link at point, this command will allow you to edit link
6380 and description parts.
6382 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6383 be selected using completion. The path to the file will be relative to the
6384 current directory if the file is in the current directory or a subdirectory.
6385 Otherwise, the link will be the absolute path as completed in the minibuffer
6386 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6387 option `org-link-file-path-type'.
6389 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6390 the current directory or below.
6392 With three \\[universal-argument] prefixes, negate the meaning of
6393 `org-keep-stored-link-after-insertion'.
6395 If `org-make-link-description-function' is non-nil, this function will be
6396 called with the link target, and the result will be the default
6397 link description.
6399 If the LINK-LOCATION parameter is non-nil, this value will be
6400 used as the link location instead of reading one interactively."
6401 (interactive "P")
6402 (let* ((wcf (current-window-configuration))
6403 (region (if (org-region-active-p)
6404 (buffer-substring (region-beginning) (region-end))))
6405 (remove (and region (list (region-beginning) (region-end))))
6406 (desc region)
6407 tmphist ; byte-compile incorrectly complains about this
6408 (link link-location)
6409 entry file)
6410 (cond
6411 (link-location) ; specified by arg, just use it.
6412 ((org-in-regexp org-bracket-link-regexp 1)
6413 ;; We do have a link at point, and we are going to edit it.
6414 (setq remove (list (match-beginning 0) (match-end 0)))
6415 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6416 (setq link (read-string "Link: "
6417 (org-link-unescape
6418 (org-match-string-no-properties 1)))))
6419 ((or (org-in-regexp org-angle-link-re)
6420 (org-in-regexp org-plain-link-re))
6421 ;; Convert to bracket link
6422 (setq remove (list (match-beginning 0) (match-end 0))
6423 link (read-string "Link: "
6424 (org-remove-angle-brackets (match-string 0)))))
6425 ((member complete-file '((4) (16)))
6426 ;; Completing read for file names.
6427 (setq file (read-file-name "File: "))
6428 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6429 (pwd1 (file-name-as-directory (abbreviate-file-name
6430 (expand-file-name ".")))))
6431 (cond
6432 ((equal complete-file '(16))
6433 (setq link (org-make-link
6434 "file:"
6435 (abbreviate-file-name (expand-file-name file)))))
6436 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6437 (setq link (org-make-link "file:" (match-string 1 file))))
6438 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6439 (expand-file-name file))
6440 (setq link (org-make-link
6441 "file:" (match-string 1 (expand-file-name file)))))
6442 (t (setq link (org-make-link "file:" file))))))
6444 ;; Read link, with completion for stored links.
6445 (with-output-to-temp-buffer "*Org Links*"
6446 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6447 (when org-stored-links
6448 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6449 (princ (mapconcat
6450 (lambda (x)
6451 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6452 (reverse org-stored-links) "\n"))))
6453 (let ((cw (selected-window)))
6454 (select-window (get-buffer-window "*Org Links*"))
6455 (org-fit-window-to-buffer)
6456 (setq truncate-lines t)
6457 (select-window cw))
6458 ;; Fake a link history, containing the stored links.
6459 (setq tmphist (append (mapcar 'car org-stored-links)
6460 org-insert-link-history))
6461 (unwind-protect
6462 (setq link (org-completing-read
6463 "Link: "
6464 (append
6465 (mapcar (lambda (x) (list (concat (car x) ":")))
6466 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6467 (mapcar (lambda (x) (list (concat x ":")))
6468 org-link-types))
6469 nil nil nil
6470 'tmphist
6471 (or (car (car org-stored-links)))))
6472 (set-window-configuration wcf)
6473 (kill-buffer "*Org Links*"))
6474 (setq entry (assoc link org-stored-links))
6475 (or entry (push link org-insert-link-history))
6476 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6477 (not org-keep-stored-link-after-insertion))
6478 (setq org-stored-links (delq (assoc link org-stored-links)
6479 org-stored-links)))
6480 (setq desc (or desc (nth 1 entry)))))
6482 (if (string-match org-plain-link-re link)
6483 ;; URL-like link, normalize the use of angular brackets.
6484 (setq link (org-make-link (org-remove-angle-brackets link))))
6486 ;; Check if we are linking to the current file with a search option
6487 ;; If yes, simplify the link by using only the search option.
6488 (when (and buffer-file-name
6489 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6490 (let* ((path (match-string 1 link))
6491 (case-fold-search nil)
6492 (search (match-string 2 link)))
6493 (save-match-data
6494 (if (equal (file-truename buffer-file-name) (file-truename path))
6495 ;; We are linking to this same file, with a search option
6496 (setq link search)))))
6498 ;; Check if we can/should use a relative path. If yes, simplify the link
6499 (when (string-match "\\<file:\\(.*\\)" link)
6500 (let* ((path (match-string 1 link))
6501 (origpath path)
6502 (case-fold-search nil))
6503 (cond
6504 ((or (eq org-link-file-path-type 'absolute)
6505 (equal complete-file '(16)))
6506 (setq path (abbreviate-file-name (expand-file-name path))))
6507 ((eq org-link-file-path-type 'noabbrev)
6508 (setq path (expand-file-name path)))
6509 ((eq org-link-file-path-type 'relative)
6510 (setq path (file-relative-name path)))
6512 (save-match-data
6513 (if (string-match (concat "^" (regexp-quote
6514 (file-name-as-directory
6515 (expand-file-name "."))))
6516 (expand-file-name path))
6517 ;; We are linking a file with relative path name.
6518 (setq path (substring (expand-file-name path)
6519 (match-end 0)))
6520 (setq path (abbreviate-file-name (expand-file-name path)))))))
6521 (setq link (concat "file:" path))
6522 (if (equal desc origpath)
6523 (setq desc path))))
6525 (if org-make-link-description-function
6526 (setq desc (funcall org-make-link-description-function link desc)))
6528 (setq desc (read-string "Description: " desc))
6529 (unless (string-match "\\S-" desc) (setq desc nil))
6530 (if remove (apply 'delete-region remove))
6531 (insert (org-make-link-string link desc))))
6533 (defun org-completing-read (&rest args)
6534 "Completing-read with SPACE being a normal character."
6535 (let ((minibuffer-local-completion-map
6536 (copy-keymap minibuffer-local-completion-map)))
6537 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6538 (apply 'completing-read args)))
6540 (defun org-extract-attributes (s)
6541 "Extract the attributes cookie from a string and set as text property."
6542 (let (a attr (start 0) key value)
6543 (save-match-data
6544 (when (string-match "{{\\([^}]+\\)}}$" s)
6545 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6546 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6547 (setq key (match-string 1 a) value (match-string 2 a)
6548 start (match-end 0)
6549 attr (plist-put attr (intern key) value))))
6550 (org-add-props s nil 'org-attributes attr))
6553 (defun org-attributes-to-string (plist)
6554 "Format a property list into an HTML attribute list."
6555 (let ((s "") key value)
6556 (while plist
6557 (setq key (pop plist) value (pop plist))
6558 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6561 ;;; Opening/following a link
6563 (defvar org-link-search-failed nil)
6565 (defun org-next-link ()
6566 "Move forward to the next link.
6567 If the link is in hidden text, expose it."
6568 (interactive)
6569 (when (and org-link-search-failed (eq this-command last-command))
6570 (goto-char (point-min))
6571 (message "Link search wrapped back to beginning of buffer"))
6572 (setq org-link-search-failed nil)
6573 (let* ((pos (point))
6574 (ct (org-context))
6575 (a (assoc :link ct)))
6576 (if a (goto-char (nth 2 a)))
6577 (if (re-search-forward org-any-link-re nil t)
6578 (progn
6579 (goto-char (match-beginning 0))
6580 (if (org-invisible-p) (org-show-context)))
6581 (goto-char pos)
6582 (setq org-link-search-failed t)
6583 (error "No further link found"))))
6585 (defun org-previous-link ()
6586 "Move backward to the previous link.
6587 If the link is in hidden text, expose it."
6588 (interactive)
6589 (when (and org-link-search-failed (eq this-command last-command))
6590 (goto-char (point-max))
6591 (message "Link search wrapped back to end of buffer"))
6592 (setq org-link-search-failed nil)
6593 (let* ((pos (point))
6594 (ct (org-context))
6595 (a (assoc :link ct)))
6596 (if a (goto-char (nth 1 a)))
6597 (if (re-search-backward org-any-link-re nil t)
6598 (progn
6599 (goto-char (match-beginning 0))
6600 (if (org-invisible-p) (org-show-context)))
6601 (goto-char pos)
6602 (setq org-link-search-failed t)
6603 (error "No further link found"))))
6605 (defun org-find-file-at-mouse (ev)
6606 "Open file link or URL at mouse."
6607 (interactive "e")
6608 (mouse-set-point ev)
6609 (org-open-at-point 'in-emacs))
6611 (defun org-open-at-mouse (ev)
6612 "Open file link or URL at mouse."
6613 (interactive "e")
6614 (mouse-set-point ev)
6615 (org-open-at-point))
6617 (defvar org-window-config-before-follow-link nil
6618 "The window configuration before following a link.
6619 This is saved in case the need arises to restore it.")
6621 (defvar org-open-link-marker (make-marker)
6622 "Marker pointing to the location where `org-open-at-point; was called.")
6624 ;;;###autoload
6625 (defun org-open-at-point-global ()
6626 "Follow a link like Org-mode does.
6627 This command can be called in any mode to follow a link that has
6628 Org-mode syntax."
6629 (interactive)
6630 (org-run-like-in-org-mode 'org-open-at-point))
6632 ;;;###autoload
6633 (defun org-open-link-from-string (s &optional arg)
6634 "Open a link in the string S, as if it was in Org-mode."
6635 (interactive "sLink: \nP")
6636 (with-temp-buffer
6637 (let ((org-inhibit-startup t))
6638 (org-mode)
6639 (insert s)
6640 (goto-char (point-min))
6641 (org-open-at-point arg))))
6643 (defun org-open-at-point (&optional in-emacs)
6644 "Open link at or after point.
6645 If there is no link at point, this function will search forward up to
6646 the end of the current subtree.
6647 Normally, files will be opened by an appropriate application. If the
6648 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6649 With a double prefix argument, try to open outside of Emacs, in the
6650 application the system uses for this file type."
6651 (interactive "P")
6652 (org-load-modules-maybe)
6653 (move-marker org-open-link-marker (point))
6654 (setq org-window-config-before-follow-link (current-window-configuration))
6655 (org-remove-occur-highlights nil nil t)
6656 (if (org-at-timestamp-p t)
6657 (org-follow-timestamp-link)
6658 (let (type path link line search (pos (point)))
6659 (catch 'match
6660 (save-excursion
6661 (skip-chars-forward "^]\n\r")
6662 (when (org-in-regexp org-bracket-link-regexp)
6663 (setq link (org-extract-attributes
6664 (org-link-unescape (org-match-string-no-properties 1))))
6665 (while (string-match " *\n *" link)
6666 (setq link (replace-match " " t t link)))
6667 (setq link (org-link-expand-abbrev link))
6668 (cond
6669 ((or (file-name-absolute-p link)
6670 (string-match "^\\.\\.?/" link))
6671 (setq type "file" path link))
6672 ((string-match org-link-re-with-space2 link)
6673 (setq type (match-string 1 link) path (match-string 2 link)))
6674 (t (setq type "thisfile" path link)))
6675 (throw 'match t)))
6677 (when (get-text-property (point) 'org-linked-text)
6678 (setq type "thisfile"
6679 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6680 (1+ (point)) (point))
6681 path (buffer-substring
6682 (previous-single-property-change pos 'org-linked-text)
6683 (next-single-property-change pos 'org-linked-text)))
6684 (throw 'match t))
6686 (save-excursion
6687 (when (or (org-in-regexp org-angle-link-re)
6688 (org-in-regexp org-plain-link-re))
6689 (setq type (match-string 1) path (match-string 2))
6690 (throw 'match t)))
6691 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6692 (setq type "tree-match"
6693 path (match-string 1))
6694 (throw 'match t))
6695 (save-excursion
6696 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6697 (setq type "tags"
6698 path (match-string 1))
6699 (while (string-match ":" path)
6700 (setq path (replace-match "+" t t path)))
6701 (throw 'match t))))
6702 (unless path
6703 (error "No link found"))
6704 ;; Remove any trailing spaces in path
6705 (if (string-match " +\\'" path)
6706 (setq path (replace-match "" t t path)))
6708 (cond
6710 ((assoc type org-link-protocols)
6711 (funcall (nth 1 (assoc type org-link-protocols)) path))
6713 ((equal type "mailto")
6714 (let ((cmd (car org-link-mailto-program))
6715 (args (cdr org-link-mailto-program)) args1
6716 (address path) (subject "") a)
6717 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6718 (setq address (match-string 1 path)
6719 subject (org-link-escape (match-string 2 path))))
6720 (while args
6721 (cond
6722 ((not (stringp (car args))) (push (pop args) args1))
6723 (t (setq a (pop args))
6724 (if (string-match "%a" a)
6725 (setq a (replace-match address t t a)))
6726 (if (string-match "%s" a)
6727 (setq a (replace-match subject t t a)))
6728 (push a args1))))
6729 (apply cmd (nreverse args1))))
6731 ((member type '("http" "https" "ftp" "news"))
6732 (browse-url (concat type ":" (org-link-escape
6733 path org-link-escape-chars-browser))))
6735 ((member type '("message"))
6736 (browse-url (concat type ":" path)))
6738 ((string= type "tags")
6739 (org-tags-view in-emacs path))
6740 ((string= type "thisfile")
6741 (if in-emacs
6742 (switch-to-buffer-other-window
6743 (org-get-buffer-for-internal-link (current-buffer)))
6744 (org-mark-ring-push))
6745 (let ((cmd `(org-link-search
6746 ,path
6747 ,(cond ((equal in-emacs '(4)) 'occur)
6748 ((equal in-emacs '(16)) 'org-occur)
6749 (t nil))
6750 ,pos)))
6751 (condition-case nil (eval cmd)
6752 (error (progn (widen) (eval cmd))))))
6754 ((string= type "tree-match")
6755 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6757 ((string= type "file")
6758 (if (string-match "::\\([0-9]+\\)\\'" path)
6759 (setq line (string-to-number (match-string 1 path))
6760 path (substring path 0 (match-beginning 0)))
6761 (if (string-match "::\\(.+\\)\\'" path)
6762 (setq search (match-string 1 path)
6763 path (substring path 0 (match-beginning 0)))))
6764 (if (string-match "[*?{]" (file-name-nondirectory path))
6765 (dired path)
6766 (org-open-file path in-emacs line search)))
6768 ((string= type "news")
6769 (require 'org-gnus)
6770 (org-gnus-follow-link path))
6772 ((string= type "shell")
6773 (let ((cmd path))
6774 (if (or (not org-confirm-shell-link-function)
6775 (funcall org-confirm-shell-link-function
6776 (format "Execute \"%s\" in shell? "
6777 (org-add-props cmd nil
6778 'face 'org-warning))))
6779 (progn
6780 (message "Executing %s" cmd)
6781 (shell-command cmd))
6782 (error "Abort"))))
6784 ((string= type "elisp")
6785 (let ((cmd path))
6786 (if (or (not org-confirm-elisp-link-function)
6787 (funcall org-confirm-elisp-link-function
6788 (format "Execute \"%s\" as elisp? "
6789 (org-add-props cmd nil
6790 'face 'org-warning))))
6791 (message "%s => %s" cmd (eval (read cmd)))
6792 (error "Abort"))))
6795 (browse-url-at-point)))))
6796 (move-marker org-open-link-marker nil)
6797 (run-hook-with-args 'org-follow-link-hook))
6799 ;;;; Time estimates
6801 (defun org-get-effort (&optional pom)
6802 "Get the effort estimate for the current entry."
6803 (org-entry-get pom org-effort-property))
6805 ;;; File search
6807 (defvar org-create-file-search-functions nil
6808 "List of functions to construct the right search string for a file link.
6809 These functions are called in turn with point at the location to
6810 which the link should point.
6812 A function in the hook should first test if it would like to
6813 handle this file type, for example by checking the major-mode or
6814 the file extension. If it decides not to handle this file, it
6815 should just return nil to give other functions a chance. If it
6816 does handle the file, it must return the search string to be used
6817 when following the link. The search string will be part of the
6818 file link, given after a double colon, and `org-open-at-point'
6819 will automatically search for it. If special measures must be
6820 taken to make the search successful, another function should be
6821 added to the companion hook `org-execute-file-search-functions',
6822 which see.
6824 A function in this hook may also use `setq' to set the variable
6825 `description' to provide a suggestion for the descriptive text to
6826 be used for this link when it gets inserted into an Org-mode
6827 buffer with \\[org-insert-link].")
6829 (defvar org-execute-file-search-functions nil
6830 "List of functions to execute a file search triggered by a link.
6832 Functions added to this hook must accept a single argument, the
6833 search string that was part of the file link, the part after the
6834 double colon. The function must first check if it would like to
6835 handle this search, for example by checking the major-mode or the
6836 file extension. If it decides not to handle this search, it
6837 should just return nil to give other functions a chance. If it
6838 does handle the search, it must return a non-nil value to keep
6839 other functions from trying.
6841 Each function can access the current prefix argument through the
6842 variable `current-prefix-argument'. Note that a single prefix is
6843 used to force opening a link in Emacs, so it may be good to only
6844 use a numeric or double prefix to guide the search function.
6846 In case this is needed, a function in this hook can also restore
6847 the window configuration before `org-open-at-point' was called using:
6849 (set-window-configuration org-window-config-before-follow-link)")
6851 (defun org-link-search (s &optional type avoid-pos)
6852 "Search for a link search option.
6853 If S is surrounded by forward slashes, it is interpreted as a
6854 regular expression. In org-mode files, this will create an `org-occur'
6855 sparse tree. In ordinary files, `occur' will be used to list matches.
6856 If the current buffer is in `dired-mode', grep will be used to search
6857 in all files. If AVOID-POS is given, ignore matches near that position."
6858 (let ((case-fold-search t)
6859 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6860 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6861 (append '(("") (" ") ("\t") ("\n"))
6862 org-emphasis-alist)
6863 "\\|") "\\)"))
6864 (pos (point))
6865 (pre nil) (post nil)
6866 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6867 (cond
6868 ;; First check if there are any special
6869 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6870 ;; Now try the builtin stuff
6871 ((save-excursion
6872 (goto-char (point-min))
6873 (and
6874 (re-search-forward
6875 (concat "<<" (regexp-quote s0) ">>") nil t)
6876 (setq type 'dedicated
6877 pos (match-beginning 0))))
6878 ;; There is an exact target for this
6879 (goto-char pos))
6880 ((string-match "^/\\(.*\\)/$" s)
6881 ;; A regular expression
6882 (cond
6883 ((org-mode-p)
6884 (org-occur (match-string 1 s)))
6885 ;;((eq major-mode 'dired-mode)
6886 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6887 (t (org-do-occur (match-string 1 s)))))
6889 ;; A normal search strings
6890 (when (equal (string-to-char s) ?*)
6891 ;; Anchor on headlines, post may include tags.
6892 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6893 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6894 s (substring s 1)))
6895 (remove-text-properties
6896 0 (length s)
6897 '(face nil mouse-face nil keymap nil fontified nil) s)
6898 ;; Make a series of regular expressions to find a match
6899 (setq words (org-split-string s "[ \n\r\t]+")
6901 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6902 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6903 "\\)" markers)
6904 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6905 re2a (concat "[ \t\r\n]" re2a_)
6906 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6907 re4 (concat "[^a-zA-Z_]" re4_)
6909 re1 (concat pre re2 post)
6910 re3 (concat pre (if pre re4_ re4) post)
6911 re5 (concat pre ".*" re4)
6912 re2 (concat pre re2)
6913 re2a (concat pre (if pre re2a_ re2a))
6914 re4 (concat pre (if pre re4_ re4))
6915 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6916 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6917 re5 "\\)"
6919 (cond
6920 ((eq type 'org-occur) (org-occur reall))
6921 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6922 (t (goto-char (point-min))
6923 (setq type 'fuzzy)
6924 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6925 (org-search-not-self 1 re1 nil t)
6926 (org-search-not-self 1 re2 nil t)
6927 (org-search-not-self 1 re2a nil t)
6928 (org-search-not-self 1 re3 nil t)
6929 (org-search-not-self 1 re4 nil t)
6930 (org-search-not-self 1 re5 nil t)
6932 (goto-char (match-beginning 1))
6933 (goto-char pos)
6934 (error "No match")))))
6936 ;; Normal string-search
6937 (goto-char (point-min))
6938 (if (search-forward s nil t)
6939 (goto-char (match-beginning 0))
6940 (error "No match"))))
6941 (and (org-mode-p) (org-show-context 'link-search))
6942 type))
6944 (defun org-search-not-self (group &rest args)
6945 "Execute `re-search-forward', but only accept matches that do not
6946 enclose the position of `org-open-link-marker'."
6947 (let ((m org-open-link-marker))
6948 (catch 'exit
6949 (while (apply 're-search-forward args)
6950 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6951 (goto-char (match-end group))
6952 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6953 (> (match-beginning 0) (marker-position m))
6954 (< (match-end 0) (marker-position m)))
6955 (save-match-data
6956 (or (not (org-in-regexp
6957 org-bracket-link-analytic-regexp 1))
6958 (not (match-end 4)) ; no description
6959 (and (<= (match-beginning 4) (point))
6960 (>= (match-end 4) (point))))))
6961 (throw 'exit (point))))))))
6963 (defun org-get-buffer-for-internal-link (buffer)
6964 "Return a buffer to be used for displaying the link target of internal links."
6965 (cond
6966 ((not org-display-internal-link-with-indirect-buffer)
6967 buffer)
6968 ((string-match "(Clone)$" (buffer-name buffer))
6969 (message "Buffer is already a clone, not making another one")
6970 ;; we also do not modify visibility in this case
6971 buffer)
6972 (t ; make a new indirect buffer for displaying the link
6973 (let* ((bn (buffer-name buffer))
6974 (ibn (concat bn "(Clone)"))
6975 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6976 (with-current-buffer ib (org-overview))
6977 ib))))
6979 (defun org-do-occur (regexp &optional cleanup)
6980 "Call the Emacs command `occur'.
6981 If CLEANUP is non-nil, remove the printout of the regular expression
6982 in the *Occur* buffer. This is useful if the regex is long and not useful
6983 to read."
6984 (occur regexp)
6985 (when cleanup
6986 (let ((cwin (selected-window)) win beg end)
6987 (when (setq win (get-buffer-window "*Occur*"))
6988 (select-window win))
6989 (goto-char (point-min))
6990 (when (re-search-forward "match[a-z]+" nil t)
6991 (setq beg (match-end 0))
6992 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6993 (setq end (1- (match-beginning 0)))))
6994 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6995 (goto-char (point-min))
6996 (select-window cwin))))
6998 ;;; The mark ring for links jumps
7000 (defvar org-mark-ring nil
7001 "Mark ring for positions before jumps in Org-mode.")
7002 (defvar org-mark-ring-last-goto nil
7003 "Last position in the mark ring used to go back.")
7004 ;; Fill and close the ring
7005 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7006 (loop for i from 1 to org-mark-ring-length do
7007 (push (make-marker) org-mark-ring))
7008 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7009 org-mark-ring)
7011 (defun org-mark-ring-push (&optional pos buffer)
7012 "Put the current position or POS into the mark ring and rotate it."
7013 (interactive)
7014 (setq pos (or pos (point)))
7015 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7016 (move-marker (car org-mark-ring)
7017 (or pos (point))
7018 (or buffer (current-buffer)))
7019 (message "%s"
7020 (substitute-command-keys
7021 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7023 (defun org-mark-ring-goto (&optional n)
7024 "Jump to the previous position in the mark ring.
7025 With prefix arg N, jump back that many stored positions. When
7026 called several times in succession, walk through the entire ring.
7027 Org-mode commands jumping to a different position in the current file,
7028 or to another Org-mode file, automatically push the old position
7029 onto the ring."
7030 (interactive "p")
7031 (let (p m)
7032 (if (eq last-command this-command)
7033 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7034 (setq p org-mark-ring))
7035 (setq org-mark-ring-last-goto p)
7036 (setq m (car p))
7037 (switch-to-buffer (marker-buffer m))
7038 (goto-char m)
7039 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7041 (defun org-remove-angle-brackets (s)
7042 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7043 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7045 (defun org-add-angle-brackets (s)
7046 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7047 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7049 (defun org-remove-double-quotes (s)
7050 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7051 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7054 ;;; Following specific links
7056 (defun org-follow-timestamp-link ()
7057 (cond
7058 ((org-at-date-range-p t)
7059 (let ((org-agenda-start-on-weekday)
7060 (t1 (match-string 1))
7061 (t2 (match-string 2)))
7062 (setq t1 (time-to-days (org-time-string-to-time t1))
7063 t2 (time-to-days (org-time-string-to-time t2)))
7064 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7065 ((org-at-timestamp-p t)
7066 (org-agenda-list nil (time-to-days (org-time-string-to-time
7067 (substring (match-string 1) 0 10)))
7069 (t (error "This should not happen"))))
7072 ;;; Following file links
7073 (defvar org-wait nil)
7074 (defun org-open-file (path &optional in-emacs line search)
7075 "Open the file at PATH.
7076 First, this expands any special file name abbreviations. Then the
7077 configuration variable `org-file-apps' is checked if it contains an
7078 entry for this file type, and if yes, the corresponding command is launched.
7080 If no application is found, Emacs simply visits the file.
7082 With optional prefix argument IN-EMACS, Emacs will visit the file.
7083 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7084 and o use an external application to visit the file.
7086 Optional LINE specifies a line to go to, optional SEARCH a string to
7087 search for. If LINE or SEARCH is given, the file will always be
7088 opened in Emacs.
7089 If the file does not exist, an error is thrown."
7090 (setq in-emacs (or in-emacs line search))
7091 (let* ((file (if (equal path "")
7092 buffer-file-name
7093 (substitute-in-file-name (expand-file-name path))))
7094 (apps (append org-file-apps (org-default-apps)))
7095 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7096 (dirp (if remp nil (file-directory-p file)))
7097 (file (if (and dirp org-open-directory-means-index-dot-org)
7098 (concat (file-name-as-directory file) "index.org")
7099 file))
7100 (a-m-a-p (assq 'auto-mode apps))
7101 (dfile (downcase file))
7102 (old-buffer (current-buffer))
7103 (old-pos (point))
7104 (old-mode major-mode)
7105 ext cmd)
7106 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7107 (setq ext (match-string 1 dfile))
7108 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7109 (setq ext (match-string 1 dfile))))
7110 (cond
7111 ((equal in-emacs '(16))
7112 (setq cmd (cdr (assoc 'system apps))))
7113 (in-emacs (setq cmd 'emacs))
7115 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7116 (and dirp (cdr (assoc 'directory apps)))
7117 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7118 'string-match)
7119 (cdr (assoc ext apps))
7120 (cdr (assoc t apps))))))
7121 (when (eq cmd 'system)
7122 (setq cmd (cdr (assoc 'system apps))))
7123 (when (eq cmd 'default)
7124 (setq cmd (cdr (assoc t apps))))
7125 (when (eq cmd 'mailcap)
7126 (require 'mailcap)
7127 (mailcap-parse-mailcaps)
7128 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7129 (command (mailcap-mime-info mime-type)))
7130 (if (stringp command)
7131 (setq cmd command)
7132 (setq cmd 'emacs))))
7133 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7134 (not (file-exists-p file))
7135 (not org-open-non-existing-files))
7136 (error "No such file: %s" file))
7137 (cond
7138 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7139 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7140 (while (string-match "['\"]%s['\"]" cmd)
7141 (setq cmd (replace-match "%s" t t cmd)))
7142 (while (string-match "%s" cmd)
7143 (setq cmd (replace-match
7144 (save-match-data
7145 (shell-quote-argument
7146 (convert-standard-filename file)))
7147 t t cmd)))
7148 (save-window-excursion
7149 (start-process-shell-command cmd nil cmd)
7150 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7152 ((or (stringp cmd)
7153 (eq cmd 'emacs))
7154 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7155 (widen)
7156 (if line (goto-line line)
7157 (if search (org-link-search search))))
7158 ((consp cmd)
7159 (let ((file (convert-standard-filename file)))
7160 (eval cmd)))
7161 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7162 (and (org-mode-p) (eq old-mode 'org-mode)
7163 (or (not (equal old-buffer (current-buffer)))
7164 (not (equal old-pos (point))))
7165 (org-mark-ring-push old-pos old-buffer))))
7167 (defun org-default-apps ()
7168 "Return the default applications for this operating system."
7169 (cond
7170 ((eq system-type 'darwin)
7171 org-file-apps-defaults-macosx)
7172 ((eq system-type 'windows-nt)
7173 org-file-apps-defaults-windowsnt)
7174 (t org-file-apps-defaults-gnu)))
7176 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7177 "Convert extensions to regular expressions in the cars of LIST.
7178 Also, weed out any non-string entries, because the return value is used
7179 only for regexp matching.
7180 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7181 point to the symbol `emacs', indicating that the file should
7182 be opened in Emacs."
7183 (append
7184 (delq nil
7185 (mapcar (lambda (x)
7186 (if (not (stringp (car x)))
7188 (if (string-match "\\W" (car x))
7190 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7191 list))
7192 (if add-auto-mode
7193 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7195 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7196 (defun org-file-remote-p (file)
7197 "Test whether FILE specifies a location on a remote system.
7198 Return non-nil if the location is indeed remote.
7200 For example, the filename \"/user@host:/foo\" specifies a location
7201 on the system \"/user@host:\"."
7202 (cond ((fboundp 'file-remote-p)
7203 (file-remote-p file))
7204 ((fboundp 'tramp-handle-file-remote-p)
7205 (tramp-handle-file-remote-p file))
7206 ((and (boundp 'ange-ftp-name-format)
7207 (string-match (car ange-ftp-name-format) file))
7209 (t nil)))
7212 ;;;; Refiling
7214 (defun org-get-org-file ()
7215 "Read a filename, with default directory `org-directory'."
7216 (let ((default (or org-default-notes-file remember-data-file)))
7217 (read-file-name (format "File name [%s]: " default)
7218 (file-name-as-directory org-directory)
7219 default)))
7221 (defun org-notes-order-reversed-p ()
7222 "Check if the current file should receive notes in reversed order."
7223 (cond
7224 ((not org-reverse-note-order) nil)
7225 ((eq t org-reverse-note-order) t)
7226 ((not (listp org-reverse-note-order)) nil)
7227 (t (catch 'exit
7228 (let ((all org-reverse-note-order)
7229 entry)
7230 (while (setq entry (pop all))
7231 (if (string-match (car entry) buffer-file-name)
7232 (throw 'exit (cdr entry))))
7233 nil)))))
7235 (defvar org-refile-target-table nil
7236 "The list of refile targets, created by `org-refile'.")
7238 (defvar org-agenda-new-buffers nil
7239 "Buffers created to visit agenda files.")
7241 (defun org-get-refile-targets (&optional default-buffer)
7242 "Produce a table with refile targets."
7243 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7244 targets txt re files f desc descre)
7245 (with-current-buffer (or default-buffer (current-buffer))
7246 (while (setq entry (pop entries))
7247 (setq files (car entry) desc (cdr entry))
7248 (cond
7249 ((null files) (setq files (list (current-buffer))))
7250 ((eq files 'org-agenda-files)
7251 (setq files (org-agenda-files 'unrestricted)))
7252 ((and (symbolp files) (fboundp files))
7253 (setq files (funcall files)))
7254 ((and (symbolp files) (boundp files))
7255 (setq files (symbol-value files))))
7256 (if (stringp files) (setq files (list files)))
7257 (cond
7258 ((eq (car desc) :tag)
7259 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7260 ((eq (car desc) :todo)
7261 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7262 ((eq (car desc) :regexp)
7263 (setq descre (cdr desc)))
7264 ((eq (car desc) :level)
7265 (setq descre (concat "^\\*\\{" (number-to-string
7266 (if org-odd-levels-only
7267 (1- (* 2 (cdr desc)))
7268 (cdr desc)))
7269 "\\}[ \t]")))
7270 ((eq (car desc) :maxlevel)
7271 (setq descre (concat "^\\*\\{1," (number-to-string
7272 (if org-odd-levels-only
7273 (1- (* 2 (cdr desc)))
7274 (cdr desc)))
7275 "\\}[ \t]")))
7276 (t (error "Bad refiling target description %s" desc)))
7277 (while (setq f (pop files))
7278 (save-excursion
7279 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7280 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7281 (save-excursion
7282 (save-restriction
7283 (widen)
7284 (goto-char (point-min))
7285 (while (re-search-forward descre nil t)
7286 (goto-char (point-at-bol))
7287 (when (looking-at org-complex-heading-regexp)
7288 (setq txt (org-link-display-format (match-string 4))
7289 re (concat "^" (regexp-quote
7290 (buffer-substring (match-beginning 1)
7291 (match-end 4)))))
7292 (if (match-end 5) (setq re (concat re "[ \t]+"
7293 (regexp-quote
7294 (match-string 5)))))
7295 (setq re (concat re "[ \t]*$"))
7296 (when org-refile-use-outline-path
7297 (setq txt (mapconcat 'org-protect-slash
7298 (append
7299 (if (eq org-refile-use-outline-path 'file)
7300 (list (file-name-nondirectory
7301 (buffer-file-name (buffer-base-buffer))))
7302 (if (eq org-refile-use-outline-path 'full-file-path)
7303 (list (buffer-file-name (buffer-base-buffer)))))
7304 (org-get-outline-path)
7305 (list txt))
7306 "/")))
7307 (push (list txt f re (point)) targets))
7308 (goto-char (point-at-eol))))))))
7309 (nreverse targets))))
7311 (defun org-protect-slash (s)
7312 (while (string-match "/" s)
7313 (setq s (replace-match "\\" t t s)))
7316 (defun org-get-outline-path ()
7317 "Return the outline path to the current entry, as a list."
7318 (let (rtn)
7319 (save-excursion
7320 (while (org-up-heading-safe)
7321 (when (looking-at org-complex-heading-regexp)
7322 (push (org-match-string-no-properties 4) rtn)))
7323 rtn)))
7325 (defvar org-refile-history nil
7326 "History for refiling operations.")
7328 (defun org-refile (&optional goto default-buffer)
7329 "Move the entry at point to another heading.
7330 The list of target headings is compiled using the information in
7331 `org-refile-targets', which see. This list is created before each use
7332 and will therefore always be up-to-date.
7334 At the target location, the entry is filed as a subitem of the target heading.
7335 Depending on `org-reverse-note-order', the new subitem will either be the
7336 first or the last subitem.
7338 If there is an active region, all entries in that region will be moved.
7339 However, the region must fulfil the requirement that the first heading
7340 is the first one sets the top-level of the moved text - at most siblings
7341 below it are allowed.
7343 With prefix arg GOTO, the command will only visit the target location,
7344 not actually move anything.
7345 With a double prefix `C-u C-u', go to the location where the last refiling
7346 operation has put the subtree."
7347 (interactive "P")
7348 (let* ((cbuf (current-buffer))
7349 (regionp (org-region-active-p))
7350 (region-start (and regionp (region-beginning)))
7351 (region-end (and regionp (region-end)))
7352 (region-length (and regionp (- region-end region-start)))
7353 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7354 pos it nbuf file re level reversed)
7355 (when regionp (goto-char region-start)
7356 (unless (org-kill-is-subtree-p
7357 (buffer-substring region-start region-end))
7358 (error "The region is not a (sequence of) subtree(s)")))
7359 (if (equal goto '(16))
7360 (org-refile-goto-last-stored)
7361 (when (setq it (org-refile-get-location
7362 (if goto "Goto: " "Refile to: ") default-buffer))
7363 (setq file (nth 1 it)
7364 re (nth 2 it)
7365 pos (nth 3 it))
7366 (setq nbuf (or (find-buffer-visiting file)
7367 (find-file-noselect file)))
7368 (if goto
7369 (progn
7370 (switch-to-buffer nbuf)
7371 (goto-char pos)
7372 (org-show-context 'org-goto))
7373 (if regionp
7374 (progn
7375 (kill-new (buffer-substring region-start region-end))
7376 (org-save-markers-in-region region-start region-end))
7377 (org-copy-subtree 1 nil t))
7378 (save-excursion
7379 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7380 (find-file-noselect file))))
7381 (setq reversed (org-notes-order-reversed-p))
7382 (save-excursion
7383 (save-restriction
7384 (widen)
7385 (goto-char pos)
7386 (looking-at outline-regexp)
7387 (setq level (org-get-valid-level (funcall outline-level) 1))
7388 (goto-char
7389 (if reversed
7390 (or (outline-next-heading) (point-max))
7391 (or (save-excursion (outline-get-next-sibling))
7392 (org-end-of-subtree t t)
7393 (point-max))))
7394 (if (not (bolp)) (newline))
7395 (bookmark-set "org-refile-last-stored")
7396 (org-paste-subtree level))))
7397 (if regionp
7398 (delete-region (point) (+ (point) region-length))
7399 (org-cut-subtree))
7400 (setq org-markers-to-move nil)
7401 (message "Refiled to \"%s\"" (car it)))))))
7403 (defun org-refile-goto-last-stored ()
7404 "Go to the location where the last refile was stored."
7405 (interactive)
7406 (bookmark-jump "org-refile-last-stored")
7407 (message "This is the location of the last refile"))
7409 (defun org-refile-get-location (&optional prompt default-buffer)
7410 "Prompt the user for a refile location, using PROMPT."
7411 (let ((org-refile-targets org-refile-targets)
7412 (org-refile-use-outline-path org-refile-use-outline-path))
7413 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7414 (unless org-refile-target-table
7415 (error "No refile targets"))
7416 (let* ((cbuf (current-buffer))
7417 (cfunc (if org-refile-use-outline-path
7418 'org-olpath-completing-read
7419 'completing-read))
7420 (extra (if org-refile-use-outline-path "/" ""))
7421 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7422 (fname (and filename (file-truename filename)))
7423 (tbl (mapcar
7424 (lambda (x)
7425 (if (not (equal fname (file-truename (nth 1 x))))
7426 (cons (concat (car x) extra " ("
7427 (file-name-nondirectory (nth 1 x)) ")")
7428 (cdr x))
7429 (cons (concat (car x) extra) (cdr x))))
7430 org-refile-target-table))
7431 (completion-ignore-case t))
7432 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7433 tbl)))
7435 (defun org-olpath-completing-read (prompt collection &rest args)
7436 "Read an outline path like a file name."
7437 (let ((thetable collection))
7438 (apply
7439 'completing-read prompt
7440 (lambda (string predicate &optional flag)
7441 (let (rtn r s f (l (length string)))
7442 (cond
7443 ((eq flag nil)
7444 ;; try completion
7445 (try-completion string thetable))
7446 ((eq flag t)
7447 ;; all-completions
7448 (setq rtn (all-completions string thetable predicate))
7449 (mapcar
7450 (lambda (x)
7451 (setq r (substring x l))
7452 (if (string-match " ([^)]*)$" x)
7453 (setq f (match-string 0 x))
7454 (setq f ""))
7455 (if (string-match "/" r)
7456 (concat string (substring r 0 (match-end 0)) f)
7458 rtn))
7459 ((eq flag 'lambda)
7460 ;; exact match?
7461 (assoc string thetable)))
7463 args)))
7465 ;;;; Dynamic blocks
7467 (defun org-find-dblock (name)
7468 "Find the first dynamic block with name NAME in the buffer.
7469 If not found, stay at current position and return nil."
7470 (let (pos)
7471 (save-excursion
7472 (goto-char (point-min))
7473 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7474 nil t)
7475 (match-beginning 0))))
7476 (if pos (goto-char pos))
7477 pos))
7479 (defconst org-dblock-start-re
7480 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7481 "Matches the startline of a dynamic block, with parameters.")
7483 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7484 "Matches the end of a dyhamic block.")
7486 (defun org-create-dblock (plist)
7487 "Create a dynamic block section, with parameters taken from PLIST.
7488 PLIST must containe a :name entry which is used as name of the block."
7489 (unless (bolp) (newline))
7490 (let ((name (plist-get plist :name)))
7491 (insert "#+BEGIN: " name)
7492 (while plist
7493 (if (eq (car plist) :name)
7494 (setq plist (cddr plist))
7495 (insert " " (prin1-to-string (pop plist)))))
7496 (insert "\n\n#+END:\n")
7497 (beginning-of-line -2)))
7499 (defun org-prepare-dblock ()
7500 "Prepare dynamic block for refresh.
7501 This empties the block, puts the cursor at the insert position and returns
7502 the property list including an extra property :name with the block name."
7503 (unless (looking-at org-dblock-start-re)
7504 (error "Not at a dynamic block"))
7505 (let* ((begdel (1+ (match-end 0)))
7506 (name (org-no-properties (match-string 1)))
7507 (params (append (list :name name)
7508 (read (concat "(" (match-string 3) ")")))))
7509 (unless (re-search-forward org-dblock-end-re nil t)
7510 (error "Dynamic block not terminated"))
7511 (setq params
7512 (append params
7513 (list :content (buffer-substring
7514 begdel (match-beginning 0)))))
7515 (delete-region begdel (match-beginning 0))
7516 (goto-char begdel)
7517 (open-line 1)
7518 params))
7520 (defun org-map-dblocks (&optional command)
7521 "Apply COMMAND to all dynamic blocks in the current buffer.
7522 If COMMAND is not given, use `org-update-dblock'."
7523 (let ((cmd (or command 'org-update-dblock))
7524 pos)
7525 (save-excursion
7526 (goto-char (point-min))
7527 (while (re-search-forward org-dblock-start-re nil t)
7528 (goto-char (setq pos (match-beginning 0)))
7529 (condition-case nil
7530 (funcall cmd)
7531 (error (message "Error during update of dynamic block")))
7532 (goto-char pos)
7533 (unless (re-search-forward org-dblock-end-re nil t)
7534 (error "Dynamic block not terminated"))))))
7536 (defun org-dblock-update (&optional arg)
7537 "User command for updating dynamic blocks.
7538 Update the dynamic block at point. With prefix ARG, update all dynamic
7539 blocks in the buffer."
7540 (interactive "P")
7541 (if arg
7542 (org-update-all-dblocks)
7543 (or (looking-at org-dblock-start-re)
7544 (org-beginning-of-dblock))
7545 (org-update-dblock)))
7547 (defun org-update-dblock ()
7548 "Update the dynamic block at point
7549 This means to empty the block, parse for parameters and then call
7550 the correct writing function."
7551 (save-window-excursion
7552 (let* ((pos (point))
7553 (line (org-current-line))
7554 (params (org-prepare-dblock))
7555 (name (plist-get params :name))
7556 (cmd (intern (concat "org-dblock-write:" name))))
7557 (message "Updating dynamic block `%s' at line %d..." name line)
7558 (funcall cmd params)
7559 (message "Updating dynamic block `%s' at line %d...done" name line)
7560 (goto-char pos))))
7562 (defun org-beginning-of-dblock ()
7563 "Find the beginning of the dynamic block at point.
7564 Error if there is no scuh block at point."
7565 (let ((pos (point))
7566 beg)
7567 (end-of-line 1)
7568 (if (and (re-search-backward org-dblock-start-re nil t)
7569 (setq beg (match-beginning 0))
7570 (re-search-forward org-dblock-end-re nil t)
7571 (> (match-end 0) pos))
7572 (goto-char beg)
7573 (goto-char pos)
7574 (error "Not in a dynamic block"))))
7576 (defun org-update-all-dblocks ()
7577 "Update all dynamic blocks in the buffer.
7578 This function can be used in a hook."
7579 (when (org-mode-p)
7580 (org-map-dblocks 'org-update-dblock)))
7583 ;;;; Completion
7585 (defconst org-additional-option-like-keywords
7586 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7587 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7588 "BEGIN_EXAMPLE" "END_EXAMPLE"
7589 "BEGIN_QUOTE" "END_QUOTE"
7590 "BEGIN_VERSE" "END_VERSE"
7591 "BEGIN_SRC" "END_SRC"))
7593 (defcustom org-structure-template-alist
7595 ("s" "#+begin_src ?\n\n#+end_src"
7596 "<src lang=\"?\">\n\n</src>")
7597 ("e" "#+begin_example\n?\n#+end_example"
7598 "<example>\n?\n</example>")
7599 ("q" "#+begin_quote\n?\n#+end_quote"
7600 "<quote>\n?\n</quote>")
7601 ("v" "#+begin_verse\n?\n#+end_verse"
7602 "<verse>\n?\n/verse>")
7603 ("l" "#+begin_latex\n?\n#+end_latex"
7604 "<literal style=\"latex\">\n?\n</literal>")
7605 ("L" "#+latex: "
7606 "<literal style=\"latex\">?</literal>")
7607 ("h" "#+begin_html\n?\n#+end_html"
7608 "<literal style=\"html\">\n?\n</literal>")
7609 ("H" "#+html: "
7610 "<literal style=\"html\">?</literal>")
7611 ("a" "#+begin_ascii\n?\n#+end_ascii")
7612 ("A" "#+ascii: ")
7613 ("i" "#+include %file ?"
7614 "<include file=%file markup=\"?\">")
7616 "Structure completion elements.
7617 This is a list of abbreviation keys and values. The value gets inserted
7618 it you type @samp{.} followed by the key and then the completion key,
7619 usually `M-TAB'. %file will be replaced by a file name after prompting
7620 for the file uning completion.
7621 There are two templates for each key, the first uses the original Org syntax,
7622 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7623 the default when the /org-mtags.el/ module has been loaded. See also the
7624 variable `org-mtags-prefere-muse-templates'.
7625 This is an experimental feature, it is undecided if it is going to stay in."
7626 :group 'org-completion
7627 :type '(repeat
7628 (string :tag "Key")
7629 (string :tag "Template")
7630 (string :tag "Muse Template")))
7632 (defun org-try-structure-completion ()
7633 "Try to complete a structure template before point.
7634 This looks for strings like \"<e\" on an otherwise empty line and
7635 expands them."
7636 (let ((l (buffer-substring (point-at-bol) (point)))
7638 (when (and (looking-at "[ \t]*$")
7639 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7640 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7641 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7642 (match-beginning 1)) a)
7643 t)))
7645 (defun org-complete-expand-structure-template (start cell)
7646 "Expand a structure template."
7647 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7648 (rpl (nth (if musep 2 1) cell)))
7649 (delete-region start (point))
7650 (when (string-match "\\`#\\+" rpl)
7651 (cond
7652 ((bolp))
7653 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7654 (delete-region (point-at-bol) (point)))
7655 (t (newline))))
7656 (setq start (point))
7657 (if (string-match "%file" rpl)
7658 (setq rpl (replace-match
7659 (concat
7660 "\""
7661 (save-match-data
7662 (abbreviate-file-name (read-file-name "Include file: ")))
7663 "\"")
7664 t t rpl)))
7665 (insert rpl)
7666 (if (re-search-backward "\\?" start t) (delete-char 1))))
7669 (defun org-complete (&optional arg)
7670 "Perform completion on word at point.
7671 At the beginning of a headline, this completes TODO keywords as given in
7672 `org-todo-keywords'.
7673 If the current word is preceded by a backslash, completes the TeX symbols
7674 that are supported for HTML support.
7675 If the current word is preceded by \"#+\", completes special words for
7676 setting file options.
7677 In the line after \"#+STARTUP:, complete valid keywords.\"
7678 At all other locations, this simply calls the value of
7679 `org-completion-fallback-command'."
7680 (interactive "P")
7681 (org-without-partial-completion
7682 (catch 'exit
7683 (let* ((a nil)
7684 (end (point))
7685 (beg1 (save-excursion
7686 (skip-chars-backward (org-re "[:alnum:]_@"))
7687 (point)))
7688 (beg (save-excursion
7689 (skip-chars-backward "a-zA-Z0-9_:$")
7690 (point)))
7691 (confirm (lambda (x) (stringp (car x))))
7692 (searchhead (equal (char-before beg) ?*))
7693 (struct
7694 (when (and (member (char-before beg1) '(?. ?<))
7695 (setq a (assoc (buffer-substring beg1 (point))
7696 org-structure-template-alist)))
7697 (org-complete-expand-structure-template (1- beg1) a)
7698 (throw 'exit t)))
7699 (tag (and (equal (char-before beg1) ?:)
7700 (equal (char-after (point-at-bol)) ?*)))
7701 (prop (and (equal (char-before beg1) ?:)
7702 (not (equal (char-after (point-at-bol)) ?*))))
7703 (texp (equal (char-before beg) ?\\))
7704 (link (equal (char-before beg) ?\[))
7705 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7706 beg)
7707 "#+"))
7708 (startup (string-match "^#\\+STARTUP:.*"
7709 (buffer-substring (point-at-bol) (point))))
7710 (completion-ignore-case opt)
7711 (type nil)
7712 (tbl nil)
7713 (table (cond
7714 (opt
7715 (setq type :opt)
7716 (require 'org-exp)
7717 (append
7718 (mapcar
7719 (lambda (x)
7720 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7721 (cons (match-string 2 x) (match-string 1 x)))
7722 (org-split-string (org-get-current-options) "\n"))
7723 (mapcar 'list org-additional-option-like-keywords)))
7724 (startup
7725 (setq type :startup)
7726 org-startup-options)
7727 (link (append org-link-abbrev-alist-local
7728 org-link-abbrev-alist))
7729 (texp
7730 (setq type :tex)
7731 org-html-entities)
7732 ((string-match "\\`\\*+[ \t]+\\'"
7733 (buffer-substring (point-at-bol) beg))
7734 (setq type :todo)
7735 (mapcar 'list org-todo-keywords-1))
7736 (searchhead
7737 (setq type :searchhead)
7738 (save-excursion
7739 (goto-char (point-min))
7740 (while (re-search-forward org-todo-line-regexp nil t)
7741 (push (list
7742 (org-make-org-heading-search-string
7743 (match-string 3) t))
7744 tbl)))
7745 tbl)
7746 (tag (setq type :tag beg beg1)
7747 (or org-tag-alist (org-get-buffer-tags)))
7748 (prop (setq type :prop beg beg1)
7749 (mapcar 'list (org-buffer-property-keys nil t t)))
7750 (t (progn
7751 (call-interactively org-completion-fallback-command)
7752 (throw 'exit nil)))))
7753 (pattern (buffer-substring-no-properties beg end))
7754 (completion (try-completion pattern table confirm)))
7755 (cond ((eq completion t)
7756 (if (not (assoc (upcase pattern) table))
7757 (message "Already complete")
7758 (if (and (equal type :opt)
7759 (not (member (car (assoc (upcase pattern) table))
7760 org-additional-option-like-keywords)))
7761 (insert (substring (cdr (assoc (upcase pattern) table))
7762 (length pattern)))
7763 (if (memq type '(:tag :prop)) (insert ":")))))
7764 ((null completion)
7765 (message "Can't find completion for \"%s\"" pattern)
7766 (ding))
7767 ((not (string= pattern completion))
7768 (delete-region beg end)
7769 (if (string-match " +$" completion)
7770 (setq completion (replace-match "" t t completion)))
7771 (insert completion)
7772 (if (get-buffer-window "*Completions*")
7773 (delete-window (get-buffer-window "*Completions*")))
7774 (if (assoc completion table)
7775 (if (eq type :todo) (insert " ")
7776 (if (memq type '(:tag :prop)) (insert ":"))))
7777 (if (and (equal type :opt) (assoc completion table))
7778 (message "%s" (substitute-command-keys
7779 "Press \\[org-complete] again to insert example settings"))))
7781 (message "Making completion list...")
7782 (let ((list (sort (all-completions pattern table confirm)
7783 'string<)))
7784 (with-output-to-temp-buffer "*Completions*"
7785 (condition-case nil
7786 ;; Protection needed for XEmacs and emacs 21
7787 (display-completion-list list pattern)
7788 (error (display-completion-list list)))))
7789 (message "Making completion list...%s" "done")))))))
7791 ;;;; TODO, DEADLINE, Comments
7793 (defun org-toggle-comment ()
7794 "Change the COMMENT state of an entry."
7795 (interactive)
7796 (save-excursion
7797 (org-back-to-heading)
7798 (let (case-fold-search)
7799 (if (looking-at (concat outline-regexp
7800 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7801 (replace-match "" t t nil 1)
7802 (if (looking-at outline-regexp)
7803 (progn
7804 (goto-char (match-end 0))
7805 (insert org-comment-string " ")))))))
7807 (defvar org-last-todo-state-is-todo nil
7808 "This is non-nil when the last TODO state change led to a TODO state.
7809 If the last change removed the TODO tag or switched to DONE, then
7810 this is nil.")
7812 (defvar org-setting-tags nil) ; dynamically skiped
7814 (defun org-parse-local-options (string var)
7815 "Parse STRING for startup setting relevant for variable VAR."
7816 (let ((rtn (symbol-value var))
7817 e opts)
7818 (save-match-data
7819 (if (or (not string) (not (string-match "\\S-" string)))
7821 (setq opts (delq nil (mapcar (lambda (x)
7822 (setq e (assoc x org-startup-options))
7823 (if (eq (nth 1 e) var) e nil))
7824 (org-split-string string "[ \t]+"))))
7825 (if (not opts)
7827 (setq rtn nil)
7828 (while (setq e (pop opts))
7829 (if (not (nth 3 e))
7830 (setq rtn (nth 2 e))
7831 (if (not (listp rtn)) (setq rtn nil))
7832 (push (nth 2 e) rtn)))
7833 rtn)))))
7835 (defvar org-blocker-hook nil
7836 "Hook for functions that are allowed to block a state change.
7838 Each function gets as its single argument a property list, see
7839 `org-trigger-hook' for more information about this list.
7841 If any of the functions in this hook returns nil, the state change
7842 is blocked.")
7844 (defvar org-trigger-hook nil
7845 "Hook for functions that are triggered by a state change.
7847 Each function gets as its single argument a property list with at least
7848 the following elements:
7850 (:type type-of-change :position pos-at-entry-start
7851 :from old-state :to new-state)
7853 Depending on the type, more properties may be present.
7855 This mechanism is currently implemented for:
7857 TODO state changes
7858 ------------------
7859 :type todo-state-change
7860 :from previous state (keyword as a string), or nil
7861 :to new state (keyword as a string), or nil")
7863 (defvar org-agenda-headline-snapshot-before-repeat)
7864 (defun org-todo (&optional arg)
7865 "Change the TODO state of an item.
7866 The state of an item is given by a keyword at the start of the heading,
7867 like
7868 *** TODO Write paper
7869 *** DONE Call mom
7871 The different keywords are specified in the variable `org-todo-keywords'.
7872 By default the available states are \"TODO\" and \"DONE\".
7873 So for this example: when the item starts with TODO, it is changed to DONE.
7874 When it starts with DONE, the DONE is removed. And when neither TODO nor
7875 DONE are present, add TODO at the beginning of the heading.
7877 With C-u prefix arg, use completion to determine the new state.
7878 With numeric prefix arg, switch to that state.
7880 For calling through lisp, arg is also interpreted in the following way:
7881 'none -> empty state
7882 \"\"(empty string) -> switch to empty state
7883 'done -> switch to DONE
7884 'nextset -> switch to the next set of keywords
7885 'previousset -> switch to the previous set of keywords
7886 \"WAITING\" -> switch to the specified keyword, but only if it
7887 really is a member of `org-todo-keywords'."
7888 (interactive "P")
7889 (save-excursion
7890 (catch 'exit
7891 (org-back-to-heading)
7892 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7893 (or (looking-at (concat " +" org-todo-regexp " *"))
7894 (looking-at " *"))
7895 (let* ((match-data (match-data))
7896 (startpos (point-at-bol))
7897 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7898 (org-log-done org-log-done)
7899 (org-log-repeat org-log-repeat)
7900 (org-todo-log-states org-todo-log-states)
7901 (this (match-string 1))
7902 (hl-pos (match-beginning 0))
7903 (head (org-get-todo-sequence-head this))
7904 (ass (assoc head org-todo-kwd-alist))
7905 (interpret (nth 1 ass))
7906 (done-word (nth 3 ass))
7907 (final-done-word (nth 4 ass))
7908 (last-state (or this ""))
7909 (completion-ignore-case t)
7910 (member (member this org-todo-keywords-1))
7911 (tail (cdr member))
7912 (state (cond
7913 ((and org-todo-key-trigger
7914 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7915 (and (not arg) org-use-fast-todo-selection
7916 (not (eq org-use-fast-todo-selection 'prefix)))))
7917 ;; Use fast selection
7918 (org-fast-todo-selection))
7919 ((and (equal arg '(4))
7920 (or (not org-use-fast-todo-selection)
7921 (not org-todo-key-trigger)))
7922 ;; Read a state with completion
7923 (completing-read "State: " (mapcar (lambda(x) (list x))
7924 org-todo-keywords-1)
7925 nil t))
7926 ((eq arg 'right)
7927 (if this
7928 (if tail (car tail) nil)
7929 (car org-todo-keywords-1)))
7930 ((eq arg 'left)
7931 (if (equal member org-todo-keywords-1)
7933 (if this
7934 (nth (- (length org-todo-keywords-1) (length tail) 2)
7935 org-todo-keywords-1)
7936 (org-last org-todo-keywords-1))))
7937 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7938 (setq arg nil))) ; hack to fall back to cycling
7939 (arg
7940 ;; user or caller requests a specific state
7941 (cond
7942 ((equal arg "") nil)
7943 ((eq arg 'none) nil)
7944 ((eq arg 'done) (or done-word (car org-done-keywords)))
7945 ((eq arg 'nextset)
7946 (or (car (cdr (member head org-todo-heads)))
7947 (car org-todo-heads)))
7948 ((eq arg 'previousset)
7949 (let ((org-todo-heads (reverse org-todo-heads)))
7950 (or (car (cdr (member head org-todo-heads)))
7951 (car org-todo-heads))))
7952 ((car (member arg org-todo-keywords-1)))
7953 ((nth (1- (prefix-numeric-value arg))
7954 org-todo-keywords-1))))
7955 ((null member) (or head (car org-todo-keywords-1)))
7956 ((equal this final-done-word) nil) ;; -> make empty
7957 ((null tail) nil) ;; -> first entry
7958 ((eq interpret 'sequence)
7959 (car tail))
7960 ((memq interpret '(type priority))
7961 (if (eq this-command last-command)
7962 (car tail)
7963 (if (> (length tail) 0)
7964 (or done-word (car org-done-keywords))
7965 nil)))
7966 (t nil)))
7967 (next (if state (concat " " state " ") " "))
7968 (change-plist (list :type 'todo-state-change :from this :to state
7969 :position startpos))
7970 dolog now-done-p)
7971 (when org-blocker-hook
7972 (unless (save-excursion
7973 (save-match-data
7974 (run-hook-with-args-until-failure
7975 'org-blocker-hook change-plist)))
7976 (if (interactive-p)
7977 (error "TODO state change from %s to %s blocked" this state)
7978 ;; fail silently
7979 (message "TODO state change from %s to %s blocked" this state)
7980 (throw 'exit nil))))
7981 (store-match-data match-data)
7982 (replace-match next t t)
7983 (unless (pos-visible-in-window-p hl-pos)
7984 (message "TODO state changed to %s" (org-trim next)))
7985 (unless head
7986 (setq head (org-get-todo-sequence-head state)
7987 ass (assoc head org-todo-kwd-alist)
7988 interpret (nth 1 ass)
7989 done-word (nth 3 ass)
7990 final-done-word (nth 4 ass)))
7991 (when (memq arg '(nextset previousset))
7992 (message "Keyword-Set %d/%d: %s"
7993 (- (length org-todo-sets) -1
7994 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7995 (length org-todo-sets)
7996 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7997 (setq org-last-todo-state-is-todo
7998 (not (member state org-done-keywords)))
7999 (setq now-done-p (and (member state org-done-keywords)
8000 (not (member this org-done-keywords))))
8001 (and logging (org-local-logging logging))
8002 (when (and (or org-todo-log-states org-log-done)
8003 (not (memq arg '(nextset previousset))))
8004 ;; we need to look at recording a time and note
8005 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8006 (nth 2 (assoc this org-todo-log-states))))
8007 (when (and state
8008 (member state org-not-done-keywords)
8009 (not (member this org-not-done-keywords)))
8010 ;; This is now a todo state and was not one before
8011 ;; If there was a CLOSED time stamp, get rid of it.
8012 (org-add-planning-info nil nil 'closed))
8013 (when (and now-done-p org-log-done)
8014 ;; It is now done, and it was not done before
8015 (org-add-planning-info 'closed (org-current-time))
8016 (if (and (not dolog) (eq 'note org-log-done))
8017 (org-add-log-setup 'done state 'findpos 'note)))
8018 (when (and state dolog)
8019 ;; This is a non-nil state, and we need to log it
8020 (org-add-log-setup 'state state 'findpos dolog)))
8021 ;; Fixup tag positioning
8022 (org-todo-trigger-tag-changes state)
8023 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8024 (when org-provide-todo-statistics
8025 (org-update-parent-todo-statistics))
8026 (run-hooks 'org-after-todo-state-change-hook)
8027 (if (and arg (not (member state org-done-keywords)))
8028 (setq head (org-get-todo-sequence-head state)))
8029 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8030 ;; Do we need to trigger a repeat?
8031 (when now-done-p
8032 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8033 ;; This is for the agenda, take a snapshot of the headline.
8034 (save-match-data
8035 (setq org-agenda-headline-snapshot-before-repeat
8036 (org-get-heading))))
8037 (org-auto-repeat-maybe state))
8038 ;; Fixup cursor location if close to the keyword
8039 (if (and (outline-on-heading-p)
8040 (not (bolp))
8041 (save-excursion (beginning-of-line 1)
8042 (looking-at org-todo-line-regexp))
8043 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8044 (progn
8045 (goto-char (or (match-end 2) (match-end 1)))
8046 (just-one-space)))
8047 (when org-trigger-hook
8048 (save-excursion
8049 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8051 (defun org-update-parent-todo-statistics ()
8052 "Update any statistics cookie in the parent of the current headline."
8053 (interactive)
8054 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8055 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8056 (catch 'exit
8057 (save-excursion
8058 (setq level (org-up-heading-safe))
8059 (unless (and level
8060 (re-search-forward box-re (point-at-eol) t))
8061 (throw 'exit nil))
8062 (setq is-percent (match-end 2))
8063 (save-match-data
8064 (unless (outline-next-heading) (throw 'exit nil))
8065 (while (looking-at org-todo-line-regexp)
8066 (setq kwd (match-string 2))
8067 (and kwd (setq cnt-all (1+ cnt-all)))
8068 (and (member kwd org-done-keywords)
8069 (setq cnt-done (1+ cnt-done)))
8070 (condition-case nil
8071 (org-forward-same-level 1)
8072 (error (end-of-line 1)))))
8073 (replace-match
8074 (if is-percent
8075 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8076 (format "[%d/%d]" cnt-done cnt-all)))
8077 (run-hook-with-args 'org-after-todo-statistics-hook
8078 cnt-done (- cnt-all cnt-done))))))
8080 (defvar org-after-todo-statistics-hook nil
8081 "Hook that is called after a TODO statistics cookie has been updated.
8082 Each function is called with two arguments: the number of not-done entries
8083 and the number of done entries.
8085 For example, the following function, when added to this hook, will switch
8086 an entry to DONE when all children are done, and back to TODO when new
8087 entries are set to a TODO status. Note that this hook is only called
8088 when there is a statistics cookie in the headline!
8090 (defun org-summary-todo (n-done n-not-done)
8091 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8092 (let (org-log-done org-log-states) ; turn off logging
8093 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8096 (defun org-todo-trigger-tag-changes (state)
8097 "Apply the changes defined in `org-todo-state-tags-triggers'."
8098 (let ((l org-todo-state-tags-triggers)
8099 changes)
8100 (when (or (not state) (equal state ""))
8101 (setq changes (append changes (cdr (assoc "" l)))))
8102 (when (and (stringp state) (> (length state) 0))
8103 (setq changes (append changes (cdr (assoc state l)))))
8104 (when (member state org-not-done-keywords)
8105 (setq changes (append changes (cdr (assoc 'todo l)))))
8106 (when (member state org-done-keywords)
8107 (setq changes (append changes (cdr (assoc 'done l)))))
8108 (dolist (c changes)
8109 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8111 (defun org-local-logging (value)
8112 "Get logging settings from a property VALUE."
8113 (let* (words w a)
8114 ;; directly set the variables, they are already local.
8115 (setq org-log-done nil
8116 org-log-repeat nil
8117 org-todo-log-states nil)
8118 (setq words (org-split-string value))
8119 (while (setq w (pop words))
8120 (cond
8121 ((setq a (assoc w org-startup-options))
8122 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8123 (set (nth 1 a) (nth 2 a))))
8124 ((setq a (org-extract-log-state-settings w))
8125 (and (member (car a) org-todo-keywords-1)
8126 (push a org-todo-log-states)))))))
8128 (defun org-get-todo-sequence-head (kwd)
8129 "Return the head of the TODO sequence to which KWD belongs.
8130 If KWD is not set, check if there is a text property remembering the
8131 right sequence."
8132 (let (p)
8133 (cond
8134 ((not kwd)
8135 (or (get-text-property (point-at-bol) 'org-todo-head)
8136 (progn
8137 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8138 nil (point-at-eol)))
8139 (get-text-property p 'org-todo-head))))
8140 ((not (member kwd org-todo-keywords-1))
8141 (car org-todo-keywords-1))
8142 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8144 (defun org-fast-todo-selection ()
8145 "Fast TODO keyword selection with single keys.
8146 Returns the new TODO keyword, or nil if no state change should occur."
8147 (let* ((fulltable org-todo-key-alist)
8148 (done-keywords org-done-keywords) ;; needed for the faces.
8149 (maxlen (apply 'max (mapcar
8150 (lambda (x)
8151 (if (stringp (car x)) (string-width (car x)) 0))
8152 fulltable)))
8153 (expert nil)
8154 (fwidth (+ maxlen 3 1 3))
8155 (ncol (/ (- (window-width) 4) fwidth))
8156 tg cnt e c tbl
8157 groups ingroup)
8158 (save-window-excursion
8159 (if expert
8160 (set-buffer (get-buffer-create " *Org todo*"))
8161 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8162 (erase-buffer)
8163 (org-set-local 'org-done-keywords done-keywords)
8164 (setq tbl fulltable cnt 0)
8165 (while (setq e (pop tbl))
8166 (cond
8167 ((equal e '(:startgroup))
8168 (push '() groups) (setq ingroup t)
8169 (when (not (= cnt 0))
8170 (setq cnt 0)
8171 (insert "\n"))
8172 (insert "{ "))
8173 ((equal e '(:endgroup))
8174 (setq ingroup nil cnt 0)
8175 (insert "}\n"))
8177 (setq tg (car e) c (cdr e))
8178 (if ingroup (push tg (car groups)))
8179 (setq tg (org-add-props tg nil 'face
8180 (org-get-todo-face tg)))
8181 (if (and (= cnt 0) (not ingroup)) (insert " "))
8182 (insert "[" c "] " tg (make-string
8183 (- fwidth 4 (length tg)) ?\ ))
8184 (when (= (setq cnt (1+ cnt)) ncol)
8185 (insert "\n")
8186 (if ingroup (insert " "))
8187 (setq cnt 0)))))
8188 (insert "\n")
8189 (goto-char (point-min))
8190 (if (not expert) (org-fit-window-to-buffer))
8191 (message "[a-z..]:Set [SPC]:clear")
8192 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8193 (cond
8194 ((or (= c ?\C-g)
8195 (and (= c ?q) (not (rassoc c fulltable))))
8196 (setq quit-flag t))
8197 ((= c ?\ ) nil)
8198 ((setq e (rassoc c fulltable) tg (car e))
8200 (t (setq quit-flag t))))))
8202 (defun org-entry-is-todo-p ()
8203 (member (org-get-todo-state) org-not-done-keywords))
8205 (defun org-entry-is-done-p ()
8206 (member (org-get-todo-state) org-done-keywords))
8208 (defun org-get-todo-state ()
8209 (save-excursion
8210 (org-back-to-heading t)
8211 (and (looking-at org-todo-line-regexp)
8212 (match-end 2)
8213 (match-string 2))))
8215 (defun org-at-date-range-p (&optional inactive-ok)
8216 "Is the cursor inside a date range?"
8217 (interactive)
8218 (save-excursion
8219 (catch 'exit
8220 (let ((pos (point)))
8221 (skip-chars-backward "^[<\r\n")
8222 (skip-chars-backward "<[")
8223 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8224 (>= (match-end 0) pos)
8225 (throw 'exit t))
8226 (skip-chars-backward "^<[\r\n")
8227 (skip-chars-backward "<[")
8228 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8229 (>= (match-end 0) pos)
8230 (throw 'exit t)))
8231 nil)))
8233 (defun org-get-repeat ()
8234 "Check if there is a deadline/schedule with repeater in this entry."
8235 (save-match-data
8236 (save-excursion
8237 (org-back-to-heading t)
8238 (if (re-search-forward
8239 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8240 (match-string 1)))))
8242 (defvar org-last-changed-timestamp)
8243 (defvar org-last-inserted-timestamp)
8244 (defvar org-log-post-message)
8245 (defvar org-log-note-purpose)
8246 (defvar org-log-note-how)
8247 (defvar org-log-note-extra)
8248 (defun org-auto-repeat-maybe (done-word)
8249 "Check if the current headline contains a repeated deadline/schedule.
8250 If yes, set TODO state back to what it was and change the base date
8251 of repeating deadline/scheduled time stamps to new date.
8252 This function is run automatically after each state change to a DONE state."
8253 ;; last-state is dynamically scoped into this function
8254 (let* ((repeat (org-get-repeat))
8255 (aa (assoc last-state org-todo-kwd-alist))
8256 (interpret (nth 1 aa))
8257 (head (nth 2 aa))
8258 (whata '(("d" . day) ("m" . month) ("y" . year)))
8259 (msg "Entry repeats: ")
8260 (org-log-done nil)
8261 (org-todo-log-states nil)
8262 (nshiftmax 10) (nshift 0)
8263 re type n what ts mb0 time)
8264 (when repeat
8265 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8266 (org-todo (if (eq interpret 'type) last-state head))
8267 (when org-log-repeat
8268 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8269 (memq 'org-add-log-note post-command-hook))
8270 ;; OK, we are already setup for some record
8271 (if (eq org-log-repeat 'note)
8272 ;; make sure we take a note, not only a time stamp
8273 (setq org-log-note-how 'note))
8274 ;; Set up for taking a record
8275 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8276 'findpos org-log-repeat)))
8277 (org-back-to-heading t)
8278 (org-add-planning-info nil nil 'closed)
8279 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8280 org-deadline-time-regexp "\\)\\|\\("
8281 org-ts-regexp "\\)"))
8282 (while (re-search-forward
8283 re (save-excursion (outline-next-heading) (point)) t)
8284 (setq type (if (match-end 1) org-scheduled-string
8285 (if (match-end 3) org-deadline-string "Plain:"))
8286 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8287 mb0 (match-beginning 0))
8288 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8289 (setq n (string-to-number (match-string 2 ts))
8290 what (match-string 3 ts))
8291 (if (equal what "w") (setq n (* n 7) what "d"))
8292 ;; Preparation, see if we need to modify the start date for the change
8293 (when (match-end 1)
8294 (setq time (save-match-data (org-time-string-to-time ts)))
8295 (cond
8296 ((equal (match-string 1 ts) ".")
8297 ;; Shift starting date to today
8298 (org-timestamp-change
8299 (- (time-to-days (current-time)) (time-to-days time))
8300 'day))
8301 ((equal (match-string 1 ts) "+")
8302 (while (or (= nshift 0)
8303 (<= (time-to-days time) (time-to-days (current-time))))
8304 (when (= (incf nshift) nshiftmax)
8305 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8306 (error "Abort")))
8307 (org-timestamp-change n (cdr (assoc what whata)))
8308 (org-at-timestamp-p t)
8309 (setq ts (match-string 1))
8310 (setq time (save-match-data (org-time-string-to-time ts))))
8311 (org-timestamp-change (- n) (cdr (assoc what whata)))
8312 ;; rematch, so that we have everything in place for the real shift
8313 (org-at-timestamp-p t)
8314 (setq ts (match-string 1))
8315 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8316 (org-timestamp-change n (cdr (assoc what whata)))
8317 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8318 (setq org-log-post-message msg)
8319 (message "%s" msg))))
8321 (defun org-show-todo-tree (arg)
8322 "Make a compact tree which shows all headlines marked with TODO.
8323 The tree will show the lines where the regexp matches, and all higher
8324 headlines above the match.
8325 With a \\[universal-argument] prefix, also show the DONE entries.
8326 With a numeric prefix N, construct a sparse tree for the Nth element
8327 of `org-todo-keywords-1'."
8328 (interactive "P")
8329 (let ((case-fold-search nil)
8330 (kwd-re
8331 (cond ((null arg) org-not-done-regexp)
8332 ((equal arg '(4))
8333 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8334 (mapcar 'list org-todo-keywords-1))))
8335 (concat "\\("
8336 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8337 "\\)\\>")))
8338 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8339 (regexp-quote (nth (1- (prefix-numeric-value arg))
8340 org-todo-keywords-1)))
8341 (t (error "Invalid prefix argument: %s" arg)))))
8342 (message "%d TODO entries found"
8343 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8345 (defun org-deadline (&optional remove time)
8346 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8347 With argument REMOVE, remove any deadline from the item.
8348 When TIME is set, it should be an internal time specification, and the
8349 scheduling will use the corresponding date."
8350 (interactive "P")
8351 (if remove
8352 (progn
8353 (org-remove-timestamp-with-keyword org-deadline-string)
8354 (message "Item no longer has a deadline."))
8355 (if (org-get-repeat)
8356 (error "Cannot change deadline on task with repeater, please do that by hand")
8357 (org-add-planning-info 'deadline time 'closed)
8358 (message "Deadline on %s" org-last-inserted-timestamp))))
8360 (defun org-schedule (&optional remove time)
8361 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8362 With argument REMOVE, remove any scheduling date from the item.
8363 When TIME is set, it should be an internal time specification, and the
8364 scheduling will use the corresponding date."
8365 (interactive "P")
8366 (if remove
8367 (progn
8368 (org-remove-timestamp-with-keyword org-scheduled-string)
8369 (message "Item is no longer scheduled."))
8370 (if (org-get-repeat)
8371 (error "Cannot reschedule task with repeater, please do that by hand")
8372 (org-add-planning-info 'scheduled time 'closed)
8373 (message "Scheduled to %s" org-last-inserted-timestamp))))
8375 (defun org-remove-timestamp-with-keyword (keyword)
8376 "Remove all time stamps with KEYWORD in the current entry."
8377 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8378 beg)
8379 (save-excursion
8380 (org-back-to-heading t)
8381 (setq beg (point))
8382 (org-end-of-subtree t t)
8383 (while (re-search-backward re beg t)
8384 (replace-match "")
8385 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8386 (equal (char-before) ?\ ))
8387 (backward-delete-char 1)
8388 (if (string-match "^[ \t]*$" (buffer-substring
8389 (point-at-bol) (point-at-eol)))
8390 (delete-region (point-at-bol)
8391 (min (point-max) (1+ (point-at-eol))))))))))
8393 (defun org-add-planning-info (what &optional time &rest remove)
8394 "Insert new timestamp with keyword in the line directly after the headline.
8395 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8396 If non is given, the user is prompted for a date.
8397 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8398 be removed."
8399 (interactive)
8400 (let (org-time-was-given org-end-time-was-given ts
8401 end default-time default-input)
8403 (when (and (not time) (memq what '(scheduled deadline)))
8404 ;; Try to get a default date/time from existing timestamp
8405 (save-excursion
8406 (org-back-to-heading t)
8407 (setq end (save-excursion (outline-next-heading) (point)))
8408 (when (re-search-forward (if (eq what 'scheduled)
8409 org-scheduled-time-regexp
8410 org-deadline-time-regexp)
8411 end t)
8412 (setq ts (match-string 1)
8413 default-time
8414 (apply 'encode-time (org-parse-time-string ts))
8415 default-input (and ts (org-get-compact-tod ts))))))
8416 (when what
8417 ;; If necessary, get the time from the user
8418 (setq time (or time (org-read-date nil 'to-time nil nil
8419 default-time default-input))))
8421 (when (and org-insert-labeled-timestamps-at-point
8422 (member what '(scheduled deadline)))
8423 (insert
8424 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8425 (org-insert-time-stamp time org-time-was-given
8426 nil nil nil (list org-end-time-was-given))
8427 (setq what nil))
8428 (save-excursion
8429 (save-restriction
8430 (let (col list elt ts buffer-invisibility-spec)
8431 (org-back-to-heading t)
8432 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8433 (goto-char (match-end 1))
8434 (setq col (current-column))
8435 (goto-char (match-end 0))
8436 (if (eobp) (insert "\n") (forward-char 1))
8437 (if (and (not (looking-at outline-regexp))
8438 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8439 "[^\r\n]*"))
8440 (not (equal (match-string 1) org-clock-string)))
8441 (narrow-to-region (match-beginning 0) (match-end 0))
8442 (insert-before-markers "\n")
8443 (backward-char 1)
8444 (narrow-to-region (point) (point))
8445 (and org-adapt-indentation (org-indent-to-column col)))
8446 ;; Check if we have to remove something.
8447 (setq list (cons what remove))
8448 (while list
8449 (setq elt (pop list))
8450 (goto-char (point-min))
8451 (when (or (and (eq elt 'scheduled)
8452 (re-search-forward org-scheduled-time-regexp nil t))
8453 (and (eq elt 'deadline)
8454 (re-search-forward org-deadline-time-regexp nil t))
8455 (and (eq elt 'closed)
8456 (re-search-forward org-closed-time-regexp nil t)))
8457 (replace-match "")
8458 (if (looking-at "--+<[^>]+>") (replace-match ""))
8459 (if (looking-at " +") (replace-match ""))))
8460 (goto-char (point-max))
8461 (when what
8462 (insert
8463 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8464 (cond ((eq what 'scheduled) org-scheduled-string)
8465 ((eq what 'deadline) org-deadline-string)
8466 ((eq what 'closed) org-closed-string))
8467 " ")
8468 (setq ts (org-insert-time-stamp
8469 time
8470 (or org-time-was-given
8471 (and (eq what 'closed) org-log-done-with-time))
8472 (eq what 'closed)
8473 nil nil (list org-end-time-was-given)))
8474 (end-of-line 1))
8475 (goto-char (point-min))
8476 (widen)
8477 (if (and (looking-at "[ \t]+\n")
8478 (equal (char-before) ?\n))
8479 (delete-region (1- (point)) (point-at-eol)))
8480 ts)))))
8482 (defvar org-log-note-marker (make-marker))
8483 (defvar org-log-note-purpose nil)
8484 (defvar org-log-note-state nil)
8485 (defvar org-log-note-how nil)
8486 (defvar org-log-note-extra nil)
8487 (defvar org-log-note-window-configuration nil)
8488 (defvar org-log-note-return-to (make-marker))
8489 (defvar org-log-post-message nil
8490 "Message to be displayed after a log note has been stored.
8491 The auto-repeater uses this.")
8493 (defun org-add-note ()
8494 "Add a note to the current entry.
8495 This is done in the same way as adding a state change note."
8496 (interactive)
8497 (org-add-log-setup 'note nil 'findpos nil))
8499 (defvar org-property-end-re)
8500 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8501 "Set up the post command hook to take a note.
8502 If this is about to TODO state change, the new state is expected in STATE.
8503 When FINDPOS is non-nil, find the correct position for the note in
8504 the current entry. If not, assume that it can be inserted at point.
8505 HOW is an indicator what kind of note should be created.
8506 EXTRA is additional text that will be inserted into the notes buffer."
8507 (save-restriction
8508 (save-excursion
8509 (when findpos
8510 (org-back-to-heading t)
8511 (narrow-to-region (point) (save-excursion
8512 (outline-next-heading) (point)))
8513 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8514 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8515 "[^\r\n]*\\)?"))
8516 (goto-char (match-end 0))
8517 (when (and org-log-state-notes-insert-after-drawers
8518 (save-excursion
8519 (forward-line) (looking-at org-drawer-regexp)))
8520 (progn (forward-line)
8521 (while (looking-at org-drawer-regexp)
8522 (goto-char (match-end 0))
8523 (re-search-forward org-property-end-re (point-max) t)
8524 (forward-line))
8525 (forward-line -1)))
8526 (unless org-log-states-order-reversed
8527 (and (= (char-after) ?\n) (forward-char 1))
8528 (org-skip-over-state-notes)
8529 (skip-chars-backward " \t\n\r")))
8530 (move-marker org-log-note-marker (point))
8531 (setq org-log-note-purpose purpose
8532 org-log-note-state state
8533 org-log-note-how how
8534 org-log-note-extra extra)
8535 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8537 (defun org-skip-over-state-notes ()
8538 "Skip past the list of State notes in an entry."
8539 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8540 (while (looking-at "[ \t]*- State")
8541 (condition-case nil
8542 (org-next-item)
8543 (error (org-end-of-item)))))
8545 (defun org-add-log-note (&optional purpose)
8546 "Pop up a window for taking a note, and add this note later at point."
8547 (remove-hook 'post-command-hook 'org-add-log-note)
8548 (setq org-log-note-window-configuration (current-window-configuration))
8549 (delete-other-windows)
8550 (move-marker org-log-note-return-to (point))
8551 (switch-to-buffer (marker-buffer org-log-note-marker))
8552 (goto-char org-log-note-marker)
8553 (org-switch-to-buffer-other-window "*Org Note*")
8554 (erase-buffer)
8555 (if (memq org-log-note-how '(time state))
8556 (let (current-prefix-arg) (org-store-log-note))
8557 (let ((org-inhibit-startup t)) (org-mode))
8558 (insert (format "# Insert note for %s.
8559 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8560 (cond
8561 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8562 ((eq org-log-note-purpose 'done) "closed todo item")
8563 ((eq org-log-note-purpose 'state)
8564 (format "state change to \"%s\"" org-log-note-state))
8565 ((eq org-log-note-purpose 'note)
8566 "this entry")
8567 (t (error "This should not happen")))))
8568 (if org-log-note-extra (insert org-log-note-extra))
8569 (org-set-local 'org-finish-function 'org-store-log-note)))
8571 (defvar org-note-abort nil) ; dynamically scoped
8572 (defun org-store-log-note ()
8573 "Finish taking a log note, and insert it to where it belongs."
8574 (let ((txt (buffer-string))
8575 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8576 lines ind)
8577 (kill-buffer (current-buffer))
8578 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8579 (setq txt (replace-match "" t t txt)))
8580 (if (string-match "\\s-+\\'" txt)
8581 (setq txt (replace-match "" t t txt)))
8582 (setq lines (org-split-string txt "\n"))
8583 (when (and note (string-match "\\S-" note))
8584 (setq note
8585 (org-replace-escapes
8586 note
8587 (list (cons "%u" (user-login-name))
8588 (cons "%U" user-full-name)
8589 (cons "%t" (format-time-string
8590 (org-time-stamp-format 'long 'inactive)
8591 (current-time)))
8592 (cons "%s" (if org-log-note-state
8593 (concat "\"" org-log-note-state "\"")
8594 "")))))
8595 (if lines (setq note (concat note " \\\\")))
8596 (push note lines))
8597 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8598 (when lines
8599 (save-excursion
8600 (set-buffer (marker-buffer org-log-note-marker))
8601 (save-excursion
8602 (goto-char org-log-note-marker)
8603 (move-marker org-log-note-marker nil)
8604 (end-of-line 1)
8605 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8606 (indent-relative nil)
8607 (insert "- " (pop lines))
8608 (org-indent-line-function)
8609 (beginning-of-line 1)
8610 (looking-at "[ \t]*")
8611 (setq ind (concat (match-string 0) " "))
8612 (end-of-line 1)
8613 (while lines (insert "\n" ind (pop lines)))))))
8614 (set-window-configuration org-log-note-window-configuration)
8615 (with-current-buffer (marker-buffer org-log-note-return-to)
8616 (goto-char org-log-note-return-to))
8617 (move-marker org-log-note-return-to nil)
8618 (and org-log-post-message (message "%s" org-log-post-message)))
8620 (defun org-sparse-tree (&optional arg)
8621 "Create a sparse tree, prompt for the details.
8622 This command can create sparse trees. You first need to select the type
8623 of match used to create the tree:
8625 t Show entries with a specific TODO keyword.
8626 T Show entries selected by a tags match.
8627 p Enter a property name and its value (both with completion on existing
8628 names/values) and show entries with that property.
8629 r Show entries matching a regular expression
8630 d Show deadlines due within `org-deadline-warning-days'."
8631 (interactive "P")
8632 (let (ans kwd value)
8633 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8634 (setq ans (read-char-exclusive))
8635 (cond
8636 ((equal ans ?d)
8637 (call-interactively 'org-check-deadlines))
8638 ((equal ans ?b)
8639 (call-interactively 'org-check-before-date))
8640 ((equal ans ?t)
8641 (org-show-todo-tree '(4)))
8642 ((equal ans ?T)
8643 (call-interactively 'org-tags-sparse-tree))
8644 ((member ans '(?p ?P))
8645 (setq kwd (completing-read "Property: "
8646 (mapcar 'list (org-buffer-property-keys))))
8647 (setq value (completing-read "Value: "
8648 (mapcar 'list (org-property-values kwd))))
8649 (unless (string-match "\\`{.*}\\'" value)
8650 (setq value (concat "\"" value "\"")))
8651 (org-tags-sparse-tree arg (concat kwd "=" value)))
8652 ((member ans '(?r ?R ?/))
8653 (call-interactively 'org-occur))
8654 (t (error "No such sparse tree command \"%c\"" ans)))))
8656 (defvar org-occur-highlights nil
8657 "List of overlays used for occur matches.")
8658 (make-variable-buffer-local 'org-occur-highlights)
8659 (defvar org-occur-parameters nil
8660 "Parameters of the active org-occur calls.
8661 This is a list, each call to org-occur pushes as cons cell,
8662 containing the regular expression and the callback, onto the list.
8663 The list can contain several entries if `org-occur' has been called
8664 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8665 will only contain one set of parameters. When the highlights are
8666 removed (for example with `C-c C-c', or with the next edit (depending
8667 on `org-remove-highlights-with-change'), this variable is emptied
8668 as well.")
8669 (make-variable-buffer-local 'org-occur-parameters)
8671 (defun org-occur (regexp &optional keep-previous callback)
8672 "Make a compact tree which shows all matches of REGEXP.
8673 The tree will show the lines where the regexp matches, and all higher
8674 headlines above the match. It will also show the heading after the match,
8675 to make sure editing the matching entry is easy.
8676 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8677 call to `org-occur' will be kept, to allow stacking of calls to this
8678 command.
8679 If CALLBACK is non-nil, it is a function which is called to confirm
8680 that the match should indeed be shown."
8681 (interactive "sRegexp: \nP")
8682 (unless keep-previous
8683 (org-remove-occur-highlights nil nil t))
8684 (push (cons regexp callback) org-occur-parameters)
8685 (let ((cnt 0))
8686 (save-excursion
8687 (goto-char (point-min))
8688 (if (or (not keep-previous) ; do not want to keep
8689 (not org-occur-highlights)) ; no previous matches
8690 ;; hide everything
8691 (org-overview))
8692 (while (re-search-forward regexp nil t)
8693 (when (or (not callback)
8694 (save-match-data (funcall callback)))
8695 (setq cnt (1+ cnt))
8696 (when org-highlight-sparse-tree-matches
8697 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8698 (org-show-context 'occur-tree))))
8699 (when org-remove-highlights-with-change
8700 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8701 nil 'local))
8702 (unless org-sparse-tree-open-archived-trees
8703 (org-hide-archived-subtrees (point-min) (point-max)))
8704 (run-hooks 'org-occur-hook)
8705 (if (interactive-p)
8706 (message "%d match(es) for regexp %s" cnt regexp))
8707 cnt))
8709 (defun org-show-context (&optional key)
8710 "Make sure point and context and visible.
8711 How much context is shown depends upon the variables
8712 `org-show-hierarchy-above', `org-show-following-heading'. and
8713 `org-show-siblings'."
8714 (let ((heading-p (org-on-heading-p t))
8715 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8716 (following-p (org-get-alist-option org-show-following-heading key))
8717 (entry-p (org-get-alist-option org-show-entry-below key))
8718 (siblings-p (org-get-alist-option org-show-siblings key)))
8719 (catch 'exit
8720 ;; Show heading or entry text
8721 (if (and heading-p (not entry-p))
8722 (org-flag-heading nil) ; only show the heading
8723 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8724 (org-show-hidden-entry))) ; show entire entry
8725 (when following-p
8726 ;; Show next sibling, or heading below text
8727 (save-excursion
8728 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8729 (org-flag-heading nil))))
8730 (when siblings-p (org-show-siblings))
8731 (when hierarchy-p
8732 ;; show all higher headings, possibly with siblings
8733 (save-excursion
8734 (while (and (condition-case nil
8735 (progn (org-up-heading-all 1) t)
8736 (error nil))
8737 (not (bobp)))
8738 (org-flag-heading nil)
8739 (when siblings-p (org-show-siblings))))))))
8741 (defun org-reveal (&optional siblings)
8742 "Show current entry, hierarchy above it, and the following headline.
8743 This can be used to show a consistent set of context around locations
8744 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8745 not t for the search context.
8747 With optional argument SIBLINGS, on each level of the hierarchy all
8748 siblings are shown. This repairs the tree structure to what it would
8749 look like when opened with hierarchical calls to `org-cycle'."
8750 (interactive "P")
8751 (let ((org-show-hierarchy-above t)
8752 (org-show-following-heading t)
8753 (org-show-siblings (if siblings t org-show-siblings)))
8754 (org-show-context nil)))
8756 (defun org-highlight-new-match (beg end)
8757 "Highlight from BEG to END and mark the highlight is an occur headline."
8758 (let ((ov (org-make-overlay beg end)))
8759 (org-overlay-put ov 'face 'secondary-selection)
8760 (push ov org-occur-highlights)))
8762 (defun org-remove-occur-highlights (&optional beg end noremove)
8763 "Remove the occur highlights from the buffer.
8764 BEG and END are ignored. If NOREMOVE is nil, remove this function
8765 from the `before-change-functions' in the current buffer."
8766 (interactive)
8767 (unless org-inhibit-highlight-removal
8768 (mapc 'org-delete-overlay org-occur-highlights)
8769 (setq org-occur-highlights nil)
8770 (setq org-occur-parameters nil)
8771 (unless noremove
8772 (remove-hook 'before-change-functions
8773 'org-remove-occur-highlights 'local))))
8775 ;;;; Priorities
8777 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8778 "Regular expression matching the priority indicator.")
8780 (defvar org-remove-priority-next-time nil)
8782 (defun org-priority-up ()
8783 "Increase the priority of the current item."
8784 (interactive)
8785 (org-priority 'up))
8787 (defun org-priority-down ()
8788 "Decrease the priority of the current item."
8789 (interactive)
8790 (org-priority 'down))
8792 (defun org-priority (&optional action)
8793 "Change the priority of an item by ARG.
8794 ACTION can be `set', `up', `down', or a character."
8795 (interactive)
8796 (setq action (or action 'set))
8797 (let (current new news have remove)
8798 (save-excursion
8799 (org-back-to-heading)
8800 (if (looking-at org-priority-regexp)
8801 (setq current (string-to-char (match-string 2))
8802 have t)
8803 (setq current org-default-priority))
8804 (cond
8805 ((or (eq action 'set)
8806 (if (featurep 'xemacs) (characterp action) (integerp action)))
8807 (if (not (eq action 'set))
8808 (setq new action)
8809 (message "Priority %c-%c, SPC to remove: "
8810 org-highest-priority org-lowest-priority)
8811 (setq new (read-char-exclusive)))
8812 (if (and (= (upcase org-highest-priority) org-highest-priority)
8813 (= (upcase org-lowest-priority) org-lowest-priority))
8814 (setq new (upcase new)))
8815 (cond ((equal new ?\ ) (setq remove t))
8816 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8817 (error "Priority must be between `%c' and `%c'"
8818 org-highest-priority org-lowest-priority))))
8819 ((eq action 'up)
8820 (if (and (not have) (eq last-command this-command))
8821 (setq new org-lowest-priority)
8822 (setq new (if (and org-priority-start-cycle-with-default (not have))
8823 org-default-priority (1- current)))))
8824 ((eq action 'down)
8825 (if (and (not have) (eq last-command this-command))
8826 (setq new org-highest-priority)
8827 (setq new (if (and org-priority-start-cycle-with-default (not have))
8828 org-default-priority (1+ current)))))
8829 (t (error "Invalid action")))
8830 (if (or (< (upcase new) org-highest-priority)
8831 (> (upcase new) org-lowest-priority))
8832 (setq remove t))
8833 (setq news (format "%c" new))
8834 (if have
8835 (if remove
8836 (replace-match "" t t nil 1)
8837 (replace-match news t t nil 2))
8838 (if remove
8839 (error "No priority cookie found in line")
8840 (looking-at org-todo-line-regexp)
8841 (if (match-end 2)
8842 (progn
8843 (goto-char (match-end 2))
8844 (insert " [#" news "]"))
8845 (goto-char (match-beginning 3))
8846 (insert "[#" news "] ")))))
8847 (org-preserve-lc (org-set-tags nil 'align))
8848 (if remove
8849 (message "Priority removed")
8850 (message "Priority of current item set to %s" news))))
8853 (defun org-get-priority (s)
8854 "Find priority cookie and return priority."
8855 (save-match-data
8856 (if (not (string-match org-priority-regexp s))
8857 (* 1000 (- org-lowest-priority org-default-priority))
8858 (* 1000 (- org-lowest-priority
8859 (string-to-char (match-string 2 s)))))))
8861 ;;;; Tags
8863 (defvar org-agenda-archives-mode)
8864 (defun org-scan-tags (action matcher &optional todo-only)
8865 "Scan headline tags with inheritance and produce output ACTION.
8867 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8868 or `agenda' to produce an entry list for an agenda view. It can also be
8869 a Lisp form or a function that should be called at each matched headline, in
8870 this case the return value is a list of all return values from these calls.
8872 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8873 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8874 only lines with a TODO keyword are included in the output."
8875 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8876 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8877 (org-re
8878 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8879 (props (list 'face 'default
8880 'done-face 'org-done
8881 'undone-face 'default
8882 'mouse-face 'highlight
8883 'org-not-done-regexp org-not-done-regexp
8884 'org-todo-regexp org-todo-regexp
8885 'keymap org-agenda-keymap
8886 'help-echo
8887 (format "mouse-2 or RET jump to org file %s"
8888 (abbreviate-file-name
8889 (or (buffer-file-name (buffer-base-buffer))
8890 (buffer-name (buffer-base-buffer)))))))
8891 (case-fold-search nil)
8892 lspos tags tags-list
8893 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8894 (llast 0) rtn rtn1 level category i txt
8895 todo marker entry priority)
8896 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8897 (setq action (list 'lambda nil action)))
8898 (save-excursion
8899 (goto-char (point-min))
8900 (when (eq action 'sparse-tree)
8901 (org-overview)
8902 (org-remove-occur-highlights))
8903 (while (re-search-forward re nil t)
8904 (catch :skip
8905 (setq todo (if (match-end 1) (match-string 2))
8906 tags (if (match-end 4) (match-string 4)))
8907 (goto-char (setq lspos (1+ (match-beginning 0))))
8908 (setq level (org-reduced-level (funcall outline-level))
8909 category (org-get-category))
8910 (setq i llast llast level)
8911 ;; remove tag lists from same and sublevels
8912 (while (>= i level)
8913 (when (setq entry (assoc i tags-alist))
8914 (setq tags-alist (delete entry tags-alist)))
8915 (setq i (1- i)))
8916 ;; add the next tags
8917 (when tags
8918 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8919 tags-alist
8920 (cons (cons level tags) tags-alist)))
8921 ;; compile tags for current headline
8922 (setq tags-list
8923 (if org-use-tag-inheritance
8924 (apply 'append (mapcar 'cdr tags-alist))
8925 tags))
8926 (when (and tags org-use-tag-inheritance
8927 (not (eq t org-use-tag-inheritance)))
8928 ;; selective inheritance, remove uninherited ones
8929 (setcdr (car tags-alist)
8930 (org-remove-uniherited-tags (cdar tags-alist))))
8931 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8932 (let ((case-fold-search t)) (eval matcher))
8934 (not (member org-archive-tag tags-list))
8935 ;; we have an archive tag, should we use this anyway?
8936 (or (not org-agenda-skip-archived-trees)
8937 (and (eq action 'agenda) org-agenda-archives-mode))))
8938 (unless (eq action 'sparse-tree) (org-agenda-skip))
8940 ;; select this headline
8942 (cond
8943 ((eq action 'sparse-tree)
8944 (and org-highlight-sparse-tree-matches
8945 (org-get-heading) (match-end 0)
8946 (org-highlight-new-match
8947 (match-beginning 0) (match-beginning 1)))
8948 (org-show-context 'tags-tree))
8949 ((eq action 'agenda)
8950 (setq txt (org-format-agenda-item
8952 (concat
8953 (if org-tags-match-list-sublevels
8954 (make-string (1- level) ?.) "")
8955 (org-get-heading))
8956 category tags-list)
8957 priority (org-get-priority txt))
8958 (goto-char lspos)
8959 (setq marker (org-agenda-new-marker))
8960 (org-add-props txt props
8961 'org-marker marker 'org-hd-marker marker 'org-category category
8962 'priority priority 'type "tagsmatch")
8963 (push txt rtn))
8964 ((functionp action)
8965 (save-excursion
8966 (setq rtn1 (funcall action))
8967 (push rtn1 rtn))
8968 (goto-char (point-at-eol)))
8969 (t (error "Invalid action")))
8971 ;; if we are to skip sublevels, jump to end of subtree
8972 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8973 (when (and (eq action 'sparse-tree)
8974 (not org-sparse-tree-open-archived-trees))
8975 (org-hide-archived-subtrees (point-min) (point-max)))
8976 (nreverse rtn)))
8978 (defun org-remove-uniherited-tags (tags)
8979 "Remove all tags that are not inherited from the list TAGS."
8980 (cond
8981 ((eq org-use-tag-inheritance t) tags)
8982 ((not org-use-tag-inheritance) nil)
8983 ((stringp org-use-tag-inheritance)
8984 (delq nil (mapcar
8985 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8986 tags)))
8987 ((listp org-use-tag-inheritance)
8988 (delq nil (mapcar
8989 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8990 tags)))))
8992 (defvar todo-only) ;; dynamically scoped
8994 (defun org-tags-sparse-tree (&optional todo-only match)
8995 "Create a sparse tree according to tags string MATCH.
8996 MATCH can contain positive and negative selection of tags, like
8997 \"+WORK+URGENT-WITHBOSS\".
8998 If optional argument TODO_ONLY is non-nil, only select lines that are
8999 also TODO lines."
9000 (interactive "P")
9001 (org-prepare-agenda-buffers (list (current-buffer)))
9002 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9004 (defvar org-cached-props nil)
9005 (defun org-cached-entry-get (pom property)
9006 (if (or (eq t org-use-property-inheritance)
9007 (and (stringp org-use-property-inheritance)
9008 (string-match org-use-property-inheritance property))
9009 (and (listp org-use-property-inheritance)
9010 (member property org-use-property-inheritance)))
9011 ;; Caching is not possible, check it directly
9012 (org-entry-get pom property 'inherit)
9013 ;; Get all properties, so that we can do complicated checks easily
9014 (cdr (assoc property (or org-cached-props
9015 (setq org-cached-props
9016 (org-entry-properties pom)))))))
9018 (defun org-global-tags-completion-table (&optional files)
9019 "Return the list of all tags in all agenda buffer/files."
9020 (save-excursion
9021 (org-uniquify
9022 (delq nil
9023 (apply 'append
9024 (mapcar
9025 (lambda (file)
9026 (set-buffer (find-file-noselect file))
9027 (append (org-get-buffer-tags)
9028 (mapcar (lambda (x) (if (stringp (car-safe x))
9029 (list (car-safe x)) nil))
9030 org-tag-alist)))
9031 (if (and files (car files))
9032 files
9033 (org-agenda-files))))))))
9035 (defun org-make-tags-matcher (match)
9036 "Create the TAGS//TODO matcher form for the selection string MATCH."
9037 ;; todo-only is scoped dynamically into this function, and the function
9038 ;; may change it it the matcher asksk for it.
9039 (unless match
9040 ;; Get a new match request, with completion
9041 (let ((org-last-tags-completion-table
9042 (org-global-tags-completion-table)))
9043 (setq match (completing-read
9044 "Match: " 'org-tags-completion-function nil nil nil
9045 'org-tags-history))))
9047 ;; Parse the string and create a lisp form
9048 (let ((match0 match)
9049 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9050 minus tag mm
9051 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9052 orterms term orlist re-p str-p level-p level-op time-p
9053 prop-p pn pv po cat-p gv rest)
9054 (if (string-match "/+" match)
9055 ;; match contains also a todo-matching request
9056 (progn
9057 (setq tagsmatch (substring match 0 (match-beginning 0))
9058 todomatch (substring match (match-end 0)))
9059 (if (string-match "^!" todomatch)
9060 (setq todo-only t todomatch (substring todomatch 1)))
9061 (if (string-match "^\\s-*$" todomatch)
9062 (setq todomatch nil)))
9063 ;; only matching tags
9064 (setq tagsmatch match todomatch nil))
9066 ;; Make the tags matcher
9067 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9068 (setq tagsmatcher t)
9069 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9070 (while (setq term (pop orterms))
9071 (while (and (equal (substring term -1) "\\") orterms)
9072 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9073 (while (string-match re term)
9074 (setq rest (substring term (match-end 0))
9075 minus (and (match-end 1)
9076 (equal (match-string 1 term) "-"))
9077 tag (match-string 2 term)
9078 re-p (equal (string-to-char tag) ?{)
9079 level-p (match-end 4)
9080 prop-p (match-end 5)
9081 mm (cond
9082 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9083 (level-p
9084 (setq level-op (org-op-to-function (match-string 3 term)))
9085 `(,level-op level ,(string-to-number
9086 (match-string 4 term))))
9087 (prop-p
9088 (setq pn (match-string 5 term)
9089 po (match-string 6 term)
9090 pv (match-string 7 term)
9091 cat-p (equal pn "CATEGORY")
9092 re-p (equal (string-to-char pv) ?{)
9093 str-p (equal (string-to-char pv) ?\")
9094 time-p (save-match-data
9095 (string-match "^\"[[<].*[]>]\"$" pv))
9096 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9097 (if time-p (setq pv (org-matcher-time pv)))
9098 (setq po (org-op-to-function po (if time-p 'time str-p)))
9099 (cond
9100 ((equal pn "CATEGORY")
9101 (setq gv '(get-text-property (point) 'org-category)))
9102 ((equal pn "TODO")
9103 (setq gv 'todo))
9105 (setq gv `(org-cached-entry-get nil ,pn))))
9106 (if re-p
9107 (if (eq po 'org<>)
9108 `(not (string-match ,pv (or ,gv "")))
9109 `(string-match ,pv (or ,gv "")))
9110 (if str-p
9111 `(,po (or ,gv "") ,pv)
9112 `(,po (string-to-number (or ,gv ""))
9113 ,(string-to-number pv) ))))
9114 (t `(member ,(downcase tag) tags-list)))
9115 mm (if minus (list 'not mm) mm)
9116 term rest)
9117 (push mm tagsmatcher))
9118 (push (if (> (length tagsmatcher) 1)
9119 (cons 'and tagsmatcher)
9120 (car tagsmatcher))
9121 orlist)
9122 (setq tagsmatcher nil))
9123 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9124 (setq tagsmatcher
9125 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9126 ;; Make the todo matcher
9127 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9128 (setq todomatcher t)
9129 (setq orterms (org-split-string todomatch "|") orlist nil)
9130 (while (setq term (pop orterms))
9131 (while (string-match re term)
9132 (setq minus (and (match-end 1)
9133 (equal (match-string 1 term) "-"))
9134 kwd (match-string 2 term)
9135 re-p (equal (string-to-char kwd) ?{)
9136 term (substring term (match-end 0))
9137 mm (if re-p
9138 `(string-match ,(substring kwd 1 -1) todo)
9139 (list 'equal 'todo kwd))
9140 mm (if minus (list 'not mm) mm))
9141 (push mm todomatcher))
9142 (push (if (> (length todomatcher) 1)
9143 (cons 'and todomatcher)
9144 (car todomatcher))
9145 orlist)
9146 (setq todomatcher nil))
9147 (setq todomatcher (if (> (length orlist) 1)
9148 (cons 'or orlist) (car orlist))))
9150 ;; Return the string and lisp forms of the matcher
9151 (setq matcher (if todomatcher
9152 (list 'and tagsmatcher todomatcher)
9153 tagsmatcher))
9154 (cons match0 matcher)))
9156 (defun org-op-to-function (op &optional stringp)
9157 "Turn an operator into the appropriate function."
9158 (setq op
9159 (cond
9160 ((equal op "<" ) '(< string< org-time<))
9161 ((equal op ">" ) '(> org-string> org-time>))
9162 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9163 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9164 ((member op '("=" "==")) '(= string= org-time=))
9165 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9166 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9168 (defun org<> (a b) (not (= a b)))
9169 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9170 (defun org-string>= (a b) (not (string< a b)))
9171 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9172 (defun org-string<> (a b) (not (string= a b)))
9173 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9174 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9175 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9176 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9177 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9178 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9179 (defun org-2ft (s)
9180 "Convert S to a floating point time.
9181 If S is already a number, just return it. If it is a string, parse
9182 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9183 (cond
9184 ((numberp s) s)
9185 ((stringp s)
9186 (condition-case nil
9187 (float-time (apply 'encode-time (org-parse-time-string s)))
9188 (error 0.)))
9189 (t 0.)))
9191 (defun org-matcher-time (s)
9192 (cond
9193 ((equal s "<now>") (float-time))
9194 ((equal s "<today>")
9195 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9196 (t (org-2ft s))))
9198 (defun org-match-any-p (re list)
9199 "Does re match any element of list?"
9200 (setq list (mapcar (lambda (x) (string-match re x)) list))
9201 (delq nil list))
9203 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9204 (defvar org-tags-overlay (org-make-overlay 1 1))
9205 (org-detach-overlay org-tags-overlay)
9207 (defun org-get-local-tags-at (&optional pos)
9208 "Get a list of tags defined in the current headline."
9209 (org-get-tags-at pos 'local))
9211 (defun org-get-local-tags ()
9212 "Get a list of tags defined in the current headline."
9213 (org-get-tags-at nil 'local))
9215 (defun org-get-tags-at (&optional pos local)
9216 "Get a list of all headline tags applicable at POS.
9217 POS defaults to point. If tags are inherited, the list contains
9218 the targets in the same sequence as the headlines appear, i.e.
9219 the tags of the current headline come last.
9220 When LOCAL is non-nil, only return tags from the current headline,
9221 ignore inherited ones."
9222 (interactive)
9223 (let (tags ltags lastpos parent)
9224 (save-excursion
9225 (save-restriction
9226 (widen)
9227 (goto-char (or pos (point)))
9228 (save-match-data
9229 (catch 'done
9230 (condition-case nil
9231 (progn
9232 (org-back-to-heading t)
9233 (while (not (equal lastpos (point)))
9234 (setq lastpos (point))
9235 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9236 (setq ltags (org-split-string
9237 (org-match-string-no-properties 1) ":"))
9238 (setq tags (append
9239 (if parent
9240 (org-remove-uniherited-tags ltags)
9241 ltags)
9242 tags)))
9243 (or org-use-tag-inheritance (throw 'done t))
9244 (if local (throw 'done t))
9245 (org-up-heading-all 1)
9246 (setq parent t)))
9247 (error nil)))))
9248 (append (org-remove-uniherited-tags org-file-tags) tags))))
9250 (defun org-toggle-tag (tag &optional onoff)
9251 "Toggle the tag TAG for the current line.
9252 If ONOFF is `on' or `off', don't toggle but set to this state."
9253 (unless (org-on-heading-p t) (error "Not on headling"))
9254 (let (res current)
9255 (save-excursion
9256 (beginning-of-line)
9257 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9258 (point-at-eol) t)
9259 (progn
9260 (setq current (match-string 1))
9261 (replace-match ""))
9262 (setq current ""))
9263 (setq current (nreverse (org-split-string current ":")))
9264 (cond
9265 ((eq onoff 'on)
9266 (setq res t)
9267 (or (member tag current) (push tag current)))
9268 ((eq onoff 'off)
9269 (or (not (member tag current)) (setq current (delete tag current))))
9270 (t (if (member tag current)
9271 (setq current (delete tag current))
9272 (setq res t)
9273 (push tag current))))
9274 (end-of-line 1)
9275 (if current
9276 (progn
9277 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9278 (org-set-tags nil t))
9279 (delete-horizontal-space))
9280 (run-hooks 'org-after-tags-change-hook))
9281 res))
9283 (defun org-align-tags-here (to-col)
9284 ;; Assumes that this is a headline
9285 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9286 (beginning-of-line 1)
9287 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9288 (< pos (match-beginning 2)))
9289 (progn
9290 (setq tags-l (- (match-end 2) (match-beginning 2)))
9291 (goto-char (match-beginning 1))
9292 (insert " ")
9293 (delete-region (point) (1+ (match-beginning 2)))
9294 (setq ncol (max (1+ (current-column))
9295 (1+ col)
9296 (if (> to-col 0)
9297 to-col
9298 (- (abs to-col) tags-l))))
9299 (setq p (point))
9300 (insert (make-string (- ncol (current-column)) ?\ ))
9301 (setq ncol (current-column))
9302 (when indent-tabs-mode (tabify p (point-at-eol)))
9303 (org-move-to-column (min ncol col) t))
9304 (goto-char pos))))
9306 (defun org-set-tags-command (&optional arg just-align)
9307 "Call the set-tags command for the current entry."
9308 (interactive "P")
9309 (if (org-on-heading-p)
9310 (org-set-tags arg just-align)
9311 (save-excursion
9312 (org-back-to-heading t)
9313 (org-set-tags arg just-align))))
9315 (defun org-set-tags (&optional arg just-align)
9316 "Set the tags for the current headline.
9317 With prefix ARG, realign all tags in headings in the current buffer."
9318 (interactive "P")
9319 (let* ((re (concat "^" outline-regexp))
9320 (current (org-get-tags-string))
9321 (col (current-column))
9322 (org-setting-tags t)
9323 table current-tags inherited-tags ; computed below when needed
9324 tags p0 c0 c1 rpl)
9325 (if arg
9326 (save-excursion
9327 (goto-char (point-min))
9328 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9329 (while (re-search-forward re nil t)
9330 (org-set-tags nil t)
9331 (end-of-line 1)))
9332 (message "All tags realigned to column %d" org-tags-column))
9333 (if just-align
9334 (setq tags current)
9335 ;; Get a new set of tags from the user
9336 (save-excursion
9337 (setq table (or org-tag-alist (org-get-buffer-tags))
9338 org-last-tags-completion-table table
9339 current-tags (org-split-string current ":")
9340 inherited-tags (nreverse
9341 (nthcdr (length current-tags)
9342 (nreverse (org-get-tags-at))))
9343 tags
9344 (if (or (eq t org-use-fast-tag-selection)
9345 (and org-use-fast-tag-selection
9346 (delq nil (mapcar 'cdr table))))
9347 (org-fast-tag-selection
9348 current-tags inherited-tags table
9349 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9350 (let ((org-add-colon-after-tag-completion t))
9351 (org-trim
9352 (org-without-partial-completion
9353 (completing-read "Tags: " 'org-tags-completion-function
9354 nil nil current 'org-tags-history)))))))
9355 (while (string-match "[-+&]+" tags)
9356 ;; No boolean logic, just a list
9357 (setq tags (replace-match ":" t t tags))))
9359 (if (string-match "\\`[\t ]*\\'" tags)
9360 (setq tags "")
9361 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9362 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9364 ;; Insert new tags at the correct column
9365 (beginning-of-line 1)
9366 (cond
9367 ((and (equal current "") (equal tags "")))
9368 ((re-search-forward
9369 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9370 (point-at-eol) t)
9371 (if (equal tags "")
9372 (setq rpl "")
9373 (goto-char (match-beginning 0))
9374 (setq c0 (current-column) p0 (point)
9375 c1 (max (1+ c0) (if (> org-tags-column 0)
9376 org-tags-column
9377 (- (- org-tags-column) (length tags))))
9378 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9379 (replace-match rpl t t)
9380 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9381 tags)
9382 (t (error "Tags alignment failed")))
9383 (org-move-to-column col)
9384 (unless just-align
9385 (run-hooks 'org-after-tags-change-hook)))))
9387 (defun org-change-tag-in-region (beg end tag off)
9388 "Add or remove TAG for each entry in the region.
9389 This works in the agenda, and also in an org-mode buffer."
9390 (interactive
9391 (list (region-beginning) (region-end)
9392 (let ((org-last-tags-completion-table
9393 (if (org-mode-p)
9394 (org-get-buffer-tags)
9395 (org-global-tags-completion-table))))
9396 (completing-read
9397 "Tag: " 'org-tags-completion-function nil nil nil
9398 'org-tags-history))
9399 (progn
9400 (message "[s]et or [r]emove? ")
9401 (equal (read-char-exclusive) ?r))))
9402 (if (fboundp 'deactivate-mark) (deactivate-mark))
9403 (let ((agendap (equal major-mode 'org-agenda-mode))
9404 l1 l2 m buf pos newhead (cnt 0))
9405 (goto-char end)
9406 (setq l2 (1- (org-current-line)))
9407 (goto-char beg)
9408 (setq l1 (org-current-line))
9409 (loop for l from l1 to l2 do
9410 (goto-line l)
9411 (setq m (get-text-property (point) 'org-hd-marker))
9412 (when (or (and (org-mode-p) (org-on-heading-p))
9413 (and agendap m))
9414 (setq buf (if agendap (marker-buffer m) (current-buffer))
9415 pos (if agendap m (point)))
9416 (with-current-buffer buf
9417 (save-excursion
9418 (save-restriction
9419 (goto-char pos)
9420 (setq cnt (1+ cnt))
9421 (org-toggle-tag tag (if off 'off 'on))
9422 (setq newhead (org-get-heading)))))
9423 (and agendap (org-agenda-change-all-lines newhead m))))
9424 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9426 (defun org-tags-completion-function (string predicate &optional flag)
9427 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9428 (confirm (lambda (x) (stringp (car x)))))
9429 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9430 (setq s1 (match-string 1 string)
9431 s2 (match-string 2 string))
9432 (setq s1 "" s2 string))
9433 (cond
9434 ((eq flag nil)
9435 ;; try completion
9436 (setq rtn (try-completion s2 ctable confirm))
9437 (if (stringp rtn)
9438 (setq rtn
9439 (concat s1 s2 (substring rtn (length s2))
9440 (if (and org-add-colon-after-tag-completion
9441 (assoc rtn ctable))
9442 ":" ""))))
9443 rtn)
9444 ((eq flag t)
9445 ;; all-completions
9446 (all-completions s2 ctable confirm)
9448 ((eq flag 'lambda)
9449 ;; exact match?
9450 (assoc s2 ctable)))
9453 (defun org-fast-tag-insert (kwd tags face &optional end)
9454 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9455 (insert (format "%-12s" (concat kwd ":"))
9456 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9457 (or end "")))
9459 (defun org-fast-tag-show-exit (flag)
9460 (save-excursion
9461 (goto-line 3)
9462 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9463 (replace-match ""))
9464 (when flag
9465 (end-of-line 1)
9466 (org-move-to-column (- (window-width) 19) t)
9467 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9469 (defun org-set-current-tags-overlay (current prefix)
9470 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9471 (if (featurep 'xemacs)
9472 (org-overlay-display org-tags-overlay (concat prefix s)
9473 'secondary-selection)
9474 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9475 (org-overlay-display org-tags-overlay (concat prefix s)))))
9477 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9478 "Fast tag selection with single keys.
9479 CURRENT is the current list of tags in the headline, INHERITED is the
9480 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9481 possibly with grouping information. TODO-TABLE is a similar table with
9482 TODO keywords, should these have keys assigned to them.
9483 If the keys are nil, a-z are automatically assigned.
9484 Returns the new tags string, or nil to not change the current settings."
9485 (let* ((fulltable (append table todo-table))
9486 (maxlen (apply 'max (mapcar
9487 (lambda (x)
9488 (if (stringp (car x)) (string-width (car x)) 0))
9489 fulltable)))
9490 (buf (current-buffer))
9491 (expert (eq org-fast-tag-selection-single-key 'expert))
9492 (buffer-tags nil)
9493 (fwidth (+ maxlen 3 1 3))
9494 (ncol (/ (- (window-width) 4) fwidth))
9495 (i-face 'org-done)
9496 (c-face 'org-todo)
9497 tg cnt e c char c1 c2 ntable tbl rtn
9498 ov-start ov-end ov-prefix
9499 (exit-after-next org-fast-tag-selection-single-key)
9500 (done-keywords org-done-keywords)
9501 groups ingroup)
9502 (save-excursion
9503 (beginning-of-line 1)
9504 (if (looking-at
9505 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9506 (setq ov-start (match-beginning 1)
9507 ov-end (match-end 1)
9508 ov-prefix "")
9509 (setq ov-start (1- (point-at-eol))
9510 ov-end (1+ ov-start))
9511 (skip-chars-forward "^\n\r")
9512 (setq ov-prefix
9513 (concat
9514 (buffer-substring (1- (point)) (point))
9515 (if (> (current-column) org-tags-column)
9517 (make-string (- org-tags-column (current-column)) ?\ ))))))
9518 (org-move-overlay org-tags-overlay ov-start ov-end)
9519 (save-window-excursion
9520 (if expert
9521 (set-buffer (get-buffer-create " *Org tags*"))
9522 (delete-other-windows)
9523 (split-window-vertically)
9524 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9525 (erase-buffer)
9526 (org-set-local 'org-done-keywords done-keywords)
9527 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9528 (org-fast-tag-insert "Current" current c-face "\n\n")
9529 (org-fast-tag-show-exit exit-after-next)
9530 (org-set-current-tags-overlay current ov-prefix)
9531 (setq tbl fulltable char ?a cnt 0)
9532 (while (setq e (pop tbl))
9533 (cond
9534 ((equal e '(:startgroup))
9535 (push '() groups) (setq ingroup t)
9536 (when (not (= cnt 0))
9537 (setq cnt 0)
9538 (insert "\n"))
9539 (insert "{ "))
9540 ((equal e '(:endgroup))
9541 (setq ingroup nil cnt 0)
9542 (insert "}\n"))
9544 (setq tg (car e) c2 nil)
9545 (if (cdr e)
9546 (setq c (cdr e))
9547 ;; automatically assign a character.
9548 (setq c1 (string-to-char
9549 (downcase (substring
9550 tg (if (= (string-to-char tg) ?@) 1 0)))))
9551 (if (or (rassoc c1 ntable) (rassoc c1 table))
9552 (while (or (rassoc char ntable) (rassoc char table))
9553 (setq char (1+ char)))
9554 (setq c2 c1))
9555 (setq c (or c2 char)))
9556 (if ingroup (push tg (car groups)))
9557 (setq tg (org-add-props tg nil 'face
9558 (cond
9559 ((not (assoc tg table))
9560 (org-get-todo-face tg))
9561 ((member tg current) c-face)
9562 ((member tg inherited) i-face)
9563 (t nil))))
9564 (if (and (= cnt 0) (not ingroup)) (insert " "))
9565 (insert "[" c "] " tg (make-string
9566 (- fwidth 4 (length tg)) ?\ ))
9567 (push (cons tg c) ntable)
9568 (when (= (setq cnt (1+ cnt)) ncol)
9569 (insert "\n")
9570 (if ingroup (insert " "))
9571 (setq cnt 0)))))
9572 (setq ntable (nreverse ntable))
9573 (insert "\n")
9574 (goto-char (point-min))
9575 (if (not expert) (org-fit-window-to-buffer))
9576 (setq rtn
9577 (catch 'exit
9578 (while t
9579 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9580 (if groups " [!] no groups" " [!]groups")
9581 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9582 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9583 (cond
9584 ((= c ?\r) (throw 'exit t))
9585 ((= c ?!)
9586 (setq groups (not groups))
9587 (goto-char (point-min))
9588 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9589 ((= c ?\C-c)
9590 (if (not expert)
9591 (org-fast-tag-show-exit
9592 (setq exit-after-next (not exit-after-next)))
9593 (setq expert nil)
9594 (delete-other-windows)
9595 (split-window-vertically)
9596 (org-switch-to-buffer-other-window " *Org tags*")
9597 (org-fit-window-to-buffer)))
9598 ((or (= c ?\C-g)
9599 (and (= c ?q) (not (rassoc c ntable))))
9600 (org-detach-overlay org-tags-overlay)
9601 (setq quit-flag t))
9602 ((= c ?\ )
9603 (setq current nil)
9604 (if exit-after-next (setq exit-after-next 'now)))
9605 ((= c ?\t)
9606 (condition-case nil
9607 (setq tg (completing-read
9608 "Tag: "
9609 (or buffer-tags
9610 (with-current-buffer buf
9611 (org-get-buffer-tags)))))
9612 (quit (setq tg "")))
9613 (when (string-match "\\S-" tg)
9614 (add-to-list 'buffer-tags (list tg))
9615 (if (member tg current)
9616 (setq current (delete tg current))
9617 (push tg current)))
9618 (if exit-after-next (setq exit-after-next 'now)))
9619 ((setq e (rassoc c todo-table) tg (car e))
9620 (with-current-buffer buf
9621 (save-excursion (org-todo tg)))
9622 (if exit-after-next (setq exit-after-next 'now)))
9623 ((setq e (rassoc c ntable) tg (car e))
9624 (if (member tg current)
9625 (setq current (delete tg current))
9626 (loop for g in groups do
9627 (if (member tg g)
9628 (mapc (lambda (x)
9629 (setq current (delete x current)))
9630 g)))
9631 (push tg current))
9632 (if exit-after-next (setq exit-after-next 'now))))
9634 ;; Create a sorted list
9635 (setq current
9636 (sort current
9637 (lambda (a b)
9638 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9639 (if (eq exit-after-next 'now) (throw 'exit t))
9640 (goto-char (point-min))
9641 (beginning-of-line 2)
9642 (delete-region (point) (point-at-eol))
9643 (org-fast-tag-insert "Current" current c-face)
9644 (org-set-current-tags-overlay current ov-prefix)
9645 (while (re-search-forward
9646 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9647 (setq tg (match-string 1))
9648 (add-text-properties
9649 (match-beginning 1) (match-end 1)
9650 (list 'face
9651 (cond
9652 ((member tg current) c-face)
9653 ((member tg inherited) i-face)
9654 (t (get-text-property (match-beginning 1) 'face))))))
9655 (goto-char (point-min)))))
9656 (org-detach-overlay org-tags-overlay)
9657 (if rtn
9658 (mapconcat 'identity current ":")
9659 nil))))
9661 (defun org-get-tags-string ()
9662 "Get the TAGS string in the current headline."
9663 (unless (org-on-heading-p t)
9664 (error "Not on a heading"))
9665 (save-excursion
9666 (beginning-of-line 1)
9667 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9668 (org-match-string-no-properties 1)
9669 "")))
9671 (defun org-get-tags ()
9672 "Get the list of tags specified in the current headline."
9673 (org-split-string (org-get-tags-string) ":"))
9675 (defun org-get-buffer-tags ()
9676 "Get a table of all tags used in the buffer, for completion."
9677 (let (tags)
9678 (save-excursion
9679 (goto-char (point-min))
9680 (while (re-search-forward
9681 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9682 (when (equal (char-after (point-at-bol 0)) ?*)
9683 (mapc (lambda (x) (add-to-list 'tags x))
9684 (org-split-string (org-match-string-no-properties 1) ":")))))
9685 (mapcar 'list tags)))
9687 ;;;; The mapping API
9689 ;;;###autoload
9690 (defun org-map-entries (func &optional match scope &rest skip)
9691 "Call FUNC at each headline selected by MATCH in SCOPE.
9693 FUNC is a function or a lisp form. The function will be called without
9694 arguments, with the cursor positioned at the beginning of the headline.
9695 The return values of all calls to the function will be collected and
9696 returned as a list.
9698 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9699 Only headlines that are matched by this query will be considered during
9700 the iteration. When MATCH is nil or t, all headlines will be
9701 visited by the iteration.
9703 SCOPE determines the scope of this command. It can be any of:
9705 nil The current buffer, respecting the restriction if any
9706 tree The subtree started with the entry at point
9707 file The current buffer, without restriction
9708 file-with-archives
9709 The current buffer, and any archives associated with it
9710 agenda All agenda files
9711 agenda-with-archives
9712 All agenda files with any archive files associated with them
9713 \(file1 file2 ...)
9714 If this is a list, all files in the list will be scanned
9716 The remaining args are treated as settings for the skipping facilities of
9717 the scanner. The following items can be given here:
9719 archive skip trees with the archive tag.
9720 comment skip trees with the COMMENT keyword
9721 function or Emacs Lisp form:
9722 will be used as value for `org-agenda-skip-function', so whenever
9723 the the function returns t, FUNC will not be called for that
9724 entry and search will continue from the point where the
9725 function leaves it."
9726 (let* ((org-agenda-archives-mode nil) ; just to make sure
9727 (org-agenda-skip-archived-trees (memq 'archive skip))
9728 (org-agenda-skip-comment-trees (memq 'comment skip))
9729 (org-agenda-skip-function
9730 (car (org-delete-all '(comment archive) skip)))
9731 (org-tags-match-list-sublevels t)
9732 matcher pos file
9733 org-todo-keywords-for-agenda
9734 org-done-keywords-for-agenda
9735 org-todo-keyword-alist-for-agenda
9736 org-tag-alist-for-agenda)
9738 (cond
9739 ((eq match t) (setq matcher t))
9740 ((eq match nil) (setq matcher t))
9741 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9743 (when (eq scope 'tree)
9744 (org-back-to-heading t)
9745 (org-narrow-to-subtree)
9746 (setq scope nil))
9748 (if (not scope)
9749 (progn
9750 (org-prepare-agenda-buffers
9751 (list (buffer-file-name (current-buffer))))
9752 (org-scan-tags func matcher))
9753 ;; Get the right scope
9754 (setq pos (point))
9755 (cond
9756 ((and scope (listp scope) (symbolp (car scope)))
9757 (setq scope (eval scope)))
9758 ((eq scope 'agenda)
9759 (setq scope (org-agenda-files t)))
9760 ((eq scope 'agenda-with-archives)
9761 (setq scope (org-agenda-files t))
9762 (setq scope (org-add-archive-files scope)))
9763 ((eq scope 'file)
9764 (setq scope (list (buffer-file-name))))
9765 ((eq scope 'file-with-archives)
9766 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9767 (org-prepare-agenda-buffers scope)
9768 (while (setq file (pop scope))
9769 (with-current-buffer (org-find-base-buffer-visiting file)
9770 (save-excursion
9771 (save-restriction
9772 (widen)
9773 (goto-char (point-min))
9774 (org-scan-tags func matcher))))))))
9776 ;;;; Properties
9778 ;;; Setting and retrieving properties
9780 (defconst org-special-properties
9781 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9782 "TIMESTAMP" "TIMESTAMP_IA")
9783 "The special properties valid in Org-mode.
9785 These are properties that are not defined in the property drawer,
9786 but in some other way.")
9788 (defconst org-default-properties
9789 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9790 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9791 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9792 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9793 "Some properties that are used by Org-mode for various purposes.
9794 Being in this list makes sure that they are offered for completion.")
9796 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9797 "Regular expression matching the first line of a property drawer.")
9799 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9800 "Regular expression matching the first line of a property drawer.")
9802 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9803 "Regular expression matching the first line of a property drawer.")
9805 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9806 "Regular expression matching the first line of a property drawer.")
9808 (defconst org-property-drawer-re
9809 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9810 org-property-end-re "\\)\n?")
9811 "Matches an entire property drawer.")
9813 (defconst org-clock-drawer-re
9814 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9815 org-property-end-re "\\)\n?")
9816 "Matches an entire clock drawer.")
9818 (defun org-property-action ()
9819 "Do an action on properties."
9820 (interactive)
9821 (let (c)
9822 (org-at-property-p)
9823 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9824 (setq c (read-char-exclusive))
9825 (cond
9826 ((equal c ?s)
9827 (call-interactively 'org-set-property))
9828 ((equal c ?d)
9829 (call-interactively 'org-delete-property))
9830 ((equal c ?D)
9831 (call-interactively 'org-delete-property-globally))
9832 ((equal c ?c)
9833 (call-interactively 'org-compute-property-at-point))
9834 (t (error "No such property action %c" c)))))
9836 (defun org-at-property-p ()
9837 "Is the cursor in a property line?"
9838 ;; FIXME: Does not check if we are actually in the drawer.
9839 ;; FIXME: also returns true on any drawers.....
9840 ;; This is used by C-c C-c for property action.
9841 (save-excursion
9842 (beginning-of-line 1)
9843 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9845 (defun org-get-property-block (&optional beg end force)
9846 "Return the (beg . end) range of the body of the property drawer.
9847 BEG and END can be beginning and end of subtree, if not given
9848 they will be found.
9849 If the drawer does not exist and FORCE is non-nil, create the drawer."
9850 (catch 'exit
9851 (save-excursion
9852 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9853 (end (or end (progn (outline-next-heading) (point)))))
9854 (goto-char beg)
9855 (if (re-search-forward org-property-start-re end t)
9856 (setq beg (1+ (match-end 0)))
9857 (if force
9858 (save-excursion
9859 (org-insert-property-drawer)
9860 (setq end (progn (outline-next-heading) (point))))
9861 (throw 'exit nil))
9862 (goto-char beg)
9863 (if (re-search-forward org-property-start-re end t)
9864 (setq beg (1+ (match-end 0)))))
9865 (if (re-search-forward org-property-end-re end t)
9866 (setq end (match-beginning 0))
9867 (or force (throw 'exit nil))
9868 (goto-char beg)
9869 (setq end beg)
9870 (org-indent-line-function)
9871 (insert ":END:\n"))
9872 (cons beg end)))))
9874 (defun org-entry-properties (&optional pom which)
9875 "Get all properties of the entry at point-or-marker POM.
9876 This includes the TODO keyword, the tags, time strings for deadline,
9877 scheduled, and clocking, and any additional properties defined in the
9878 entry. The return value is an alist, keys may occur multiple times
9879 if the property key was used several times.
9880 POM may also be nil, in which case the current entry is used.
9881 If WHICH is nil or `all', get all properties. If WHICH is
9882 `special' or `standard', only get that subclass."
9883 (setq which (or which 'all))
9884 (org-with-point-at pom
9885 (let ((clockstr (substring org-clock-string 0 -1))
9886 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9887 beg end range props sum-props key value string clocksum)
9888 (save-excursion
9889 (when (condition-case nil (org-back-to-heading t) (error nil))
9890 (setq beg (point))
9891 (setq sum-props (get-text-property (point) 'org-summaries))
9892 (setq clocksum (get-text-property (point) :org-clock-minutes))
9893 (outline-next-heading)
9894 (setq end (point))
9895 (when (memq which '(all special))
9896 ;; Get the special properties, like TODO and tags
9897 (goto-char beg)
9898 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9899 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9900 (when (looking-at org-priority-regexp)
9901 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9902 (when (and (setq value (org-get-tags-string))
9903 (string-match "\\S-" value))
9904 (push (cons "TAGS" value) props))
9905 (when (setq value (org-get-tags-at))
9906 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9907 props))
9908 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9909 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9910 string (if (equal key clockstr)
9911 (org-no-properties
9912 (org-trim
9913 (buffer-substring
9914 (match-beginning 3) (goto-char (point-at-eol)))))
9915 (substring (org-match-string-no-properties 3) 1 -1)))
9916 (unless key
9917 (if (= (char-after (match-beginning 3)) ?\[)
9918 (setq key "TIMESTAMP_IA")
9919 (setq key "TIMESTAMP")))
9920 (when (or (equal key clockstr) (not (assoc key props)))
9921 (push (cons key string) props)))
9925 (when (memq which '(all standard))
9926 ;; Get the standard properties, like :PORP: ...
9927 (setq range (org-get-property-block beg end))
9928 (when range
9929 (goto-char (car range))
9930 (while (re-search-forward
9931 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9932 (cdr range) t)
9933 (setq key (org-match-string-no-properties 1)
9934 value (org-trim (or (org-match-string-no-properties 2) "")))
9935 (unless (member key excluded)
9936 (push (cons key (or value "")) props)))))
9937 (if clocksum
9938 (push (cons "CLOCKSUM"
9939 (org-columns-number-to-string (/ (float clocksum) 60.)
9940 'add_times))
9941 props))
9942 (unless (assoc "CATEGORY" props)
9943 (setq value (or (org-get-category)
9944 (progn (org-refresh-category-properties)
9945 (org-get-category))))
9946 (push (cons "CATEGORY" value) props))
9947 (append sum-props (nreverse props)))))))
9949 (defun org-entry-get (pom property &optional inherit)
9950 "Get value of PROPERTY for entry at point-or-marker POM.
9951 If INHERIT is non-nil and the entry does not have the property,
9952 then also check higher levels of the hierarchy.
9953 If INHERIT is the symbol `selective', use inheritance only if the setting
9954 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9955 If the property is present but empty, the return value is the empty string.
9956 If the property is not present at all, nil is returned."
9957 (org-with-point-at pom
9958 (if (and inherit (if (eq inherit 'selective)
9959 (org-property-inherit-p property)
9961 (org-entry-get-with-inheritance property)
9962 (if (member property org-special-properties)
9963 ;; We need a special property. Use brute force, get all properties.
9964 (cdr (assoc property (org-entry-properties nil 'special)))
9965 (let ((range (org-get-property-block)))
9966 (if (and range
9967 (goto-char (car range))
9968 (re-search-forward
9969 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
9970 (cdr range) t))
9971 ;; Found the property, return it.
9972 (if (match-end 1)
9973 (org-match-string-no-properties 1)
9974 "")))))))
9976 (defun org-property-or-variable-value (var &optional inherit)
9977 "Check if there is a property fixing the value of VAR.
9978 If yes, return this value. If not, return the current value of the variable."
9979 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9980 (if (and prop (stringp prop) (string-match "\\S-" prop))
9981 (read prop)
9982 (symbol-value var))))
9984 (defun org-entry-delete (pom property)
9985 "Delete the property PROPERTY from entry at point-or-marker POM."
9986 (org-with-point-at pom
9987 (if (member property org-special-properties)
9988 nil ; cannot delete these properties.
9989 (let ((range (org-get-property-block)))
9990 (if (and range
9991 (goto-char (car range))
9992 (re-search-forward
9993 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
9994 (cdr range) t))
9995 (progn
9996 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9998 nil)))))
10000 ;; Multi-values properties are properties that contain multiple values
10001 ;; These values are assumed to be single words, separated by whitespace.
10002 (defun org-entry-add-to-multivalued-property (pom property value)
10003 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10004 (let* ((old (org-entry-get pom property))
10005 (values (and old (org-split-string old "[ \t]"))))
10006 (setq value (org-entry-protect-space value))
10007 (unless (member value values)
10008 (setq values (cons value values))
10009 (org-entry-put pom property
10010 (mapconcat 'identity values " ")))))
10012 (defun org-entry-remove-from-multivalued-property (pom property value)
10013 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10014 (let* ((old (org-entry-get pom property))
10015 (values (and old (org-split-string old "[ \t]"))))
10016 (setq value (org-entry-protect-space value))
10017 (when (member value values)
10018 (setq values (delete value values))
10019 (org-entry-put pom property
10020 (mapconcat 'identity values " ")))))
10022 (defun org-entry-member-in-multivalued-property (pom property value)
10023 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10024 (let* ((old (org-entry-get pom property))
10025 (values (and old (org-split-string old "[ \t]"))))
10026 (setq value (org-entry-protect-space value))
10027 (member value values)))
10029 (defun org-entry-get-multivalued-property (pom property)
10030 "Return a list of values in a multivalued property."
10031 (let* ((value (org-entry-get pom property))
10032 (values (and value (org-split-string value "[ \t]"))))
10033 (mapcar 'org-entry-restore-space values)))
10035 (defun org-entry-put-multivalued-property (pom property &rest values)
10036 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10037 VALUES should be a list of strings. Spaces will be protected."
10038 (org-entry-put pom property
10039 (mapconcat 'org-entry-protect-space values " "))
10040 (let* ((value (org-entry-get pom property))
10041 (values (and value (org-split-string value "[ \t]"))))
10042 (mapcar 'org-entry-restore-space values)))
10044 (defun org-entry-protect-space (s)
10045 "Protect spaces and newline in string S."
10046 (while (string-match " " s)
10047 (setq s (replace-match "%20" t t s)))
10048 (while (string-match "\n" s)
10049 (setq s (replace-match "%0A" t t s)))
10052 (defun org-entry-restore-space (s)
10053 "Restore spaces and newline in string S."
10054 (while (string-match "%20" s)
10055 (setq s (replace-match " " t t s)))
10056 (while (string-match "%0A" s)
10057 (setq s (replace-match "\n" t t s)))
10060 (defvar org-entry-property-inherited-from (make-marker)
10061 "Marker pointing to the entry from where a proerty was inherited.
10062 Each call to `org-entry-get-with-inheritance' will set this marker to the
10063 location of the entry where the inheriance search matched. If there was
10064 no match, the marker will point nowhere.
10065 Note that also `org-entry-get' calls this function, if the INHERIT flag
10066 is set.")
10068 (defun org-entry-get-with-inheritance (property)
10069 "Get entry property, and search higher levels if not present."
10070 (move-marker org-entry-property-inherited-from nil)
10071 (let (tmp)
10072 (save-excursion
10073 (save-restriction
10074 (widen)
10075 (catch 'ex
10076 (while t
10077 (when (setq tmp (org-entry-get nil property))
10078 (org-back-to-heading t)
10079 (move-marker org-entry-property-inherited-from (point))
10080 (throw 'ex tmp))
10081 (or (org-up-heading-safe) (throw 'ex nil)))))
10082 (or tmp
10083 (cdr (assoc property org-file-properties))
10084 (cdr (assoc property org-global-properties))
10085 (cdr (assoc property org-global-properties-fixed))))))
10087 (defun org-entry-put (pom property value)
10088 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10089 (org-with-point-at pom
10090 (org-back-to-heading t)
10091 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10092 range)
10093 (cond
10094 ((equal property "TODO")
10095 (when (and (stringp value) (string-match "\\S-" value)
10096 (not (member value org-todo-keywords-1)))
10097 (error "\"%s\" is not a valid TODO state" value))
10098 (if (or (not value)
10099 (not (string-match "\\S-" value)))
10100 (setq value 'none))
10101 (org-todo value)
10102 (org-set-tags nil 'align))
10103 ((equal property "PRIORITY")
10104 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10105 (string-to-char value) ?\ ))
10106 (org-set-tags nil 'align))
10107 ((equal property "SCHEDULED")
10108 (if (re-search-forward org-scheduled-time-regexp end t)
10109 (cond
10110 ((eq value 'earlier) (org-timestamp-change -1 'day))
10111 ((eq value 'later) (org-timestamp-change 1 'day))
10112 (t (call-interactively 'org-schedule)))
10113 (call-interactively 'org-schedule)))
10114 ((equal property "DEADLINE")
10115 (if (re-search-forward org-deadline-time-regexp end t)
10116 (cond
10117 ((eq value 'earlier) (org-timestamp-change -1 'day))
10118 ((eq value 'later) (org-timestamp-change 1 'day))
10119 (t (call-interactively 'org-deadline)))
10120 (call-interactively 'org-deadline)))
10121 ((member property org-special-properties)
10122 (error "The %s property can not yet be set with `org-entry-put'"
10123 property))
10124 (t ; a non-special property
10125 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10126 (setq range (org-get-property-block beg end 'force))
10127 (goto-char (car range))
10128 (if (re-search-forward
10129 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10130 (progn
10131 (delete-region (match-beginning 1) (match-end 1))
10132 (goto-char (match-beginning 1)))
10133 (goto-char (cdr range))
10134 (insert "\n")
10135 (backward-char 1)
10136 (org-indent-line-function)
10137 (insert ":" property ":"))
10138 (and value (insert " " value))
10139 (org-indent-line-function)))))))
10141 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10142 "Get all property keys in the current buffer.
10143 With INCLUDE-SPECIALS, also list the special properties that relect things
10144 like tags and TODO state.
10145 With INCLUDE-DEFAULTS, also include properties that has special meaning
10146 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10147 With INCLUDE-COLUMNS, also include property names given in COLUMN
10148 formats in the current buffer."
10149 (let (rtn range cfmt cols s p)
10150 (save-excursion
10151 (save-restriction
10152 (widen)
10153 (goto-char (point-min))
10154 (while (re-search-forward org-property-start-re nil t)
10155 (setq range (org-get-property-block))
10156 (goto-char (car range))
10157 (while (re-search-forward
10158 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10159 (cdr range) t)
10160 (add-to-list 'rtn (org-match-string-no-properties 1)))
10161 (outline-next-heading))))
10163 (when include-specials
10164 (setq rtn (append org-special-properties rtn)))
10166 (when include-defaults
10167 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10169 (when include-columns
10170 (save-excursion
10171 (save-restriction
10172 (widen)
10173 (goto-char (point-min))
10174 (while (re-search-forward
10175 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10176 nil t)
10177 (setq cfmt (match-string 2) s 0)
10178 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10179 cfmt s)
10180 (setq s (match-end 0)
10181 p (match-string 1 cfmt))
10182 (unless (or (equal p "ITEM")
10183 (member p org-special-properties))
10184 (add-to-list 'rtn (match-string 1 cfmt))))))))
10186 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10188 (defun org-property-values (key)
10189 "Return a list of all values of property KEY."
10190 (save-excursion
10191 (save-restriction
10192 (widen)
10193 (goto-char (point-min))
10194 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10195 values)
10196 (while (re-search-forward re nil t)
10197 (add-to-list 'values (org-trim (match-string 1))))
10198 (delete "" values)))))
10200 (defun org-insert-property-drawer ()
10201 "Insert a property drawer into the current entry."
10202 (interactive)
10203 (org-back-to-heading t)
10204 (looking-at outline-regexp)
10205 (let ((indent (- (match-end 0)(match-beginning 0)))
10206 (beg (point))
10207 (re (concat "^[ \t]*" org-keyword-time-regexp))
10208 end hiddenp)
10209 (outline-next-heading)
10210 (setq end (point))
10211 (goto-char beg)
10212 (while (re-search-forward re end t))
10213 (setq hiddenp (org-invisible-p))
10214 (end-of-line 1)
10215 (and (equal (char-after) ?\n) (forward-char 1))
10216 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10217 (beginning-of-line 2))
10218 (org-skip-over-state-notes)
10219 (skip-chars-backward " \t\n\r")
10220 (if (eq (char-before) ?*) (forward-char 1))
10221 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10222 (beginning-of-line 0)
10223 (org-indent-to-column indent)
10224 (beginning-of-line 2)
10225 (org-indent-to-column indent)
10226 (beginning-of-line 0)
10227 (if hiddenp
10228 (save-excursion
10229 (org-back-to-heading t)
10230 (hide-entry))
10231 (org-flag-drawer t))))
10233 (defun org-set-property (property value)
10234 "In the current entry, set PROPERTY to VALUE.
10235 When called interactively, this will prompt for a property name, offering
10236 completion on existing and default properties. And then it will prompt
10237 for a value, offering competion either on allowed values (via an inherited
10238 xxx_ALL property) or on existing values in other instances of this property
10239 in the current file."
10240 (interactive
10241 (let* ((completion-ignore-case t)
10242 (keys (org-buffer-property-keys nil t t))
10243 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10244 (prop (if (member prop0 keys)
10245 prop0
10246 (or (cdr (assoc (downcase prop0)
10247 (mapcar (lambda (x) (cons (downcase x) x))
10248 keys)))
10249 prop0)))
10250 (cur (org-entry-get nil prop))
10251 (allowed (org-property-get-allowed-values nil prop 'table))
10252 (existing (mapcar 'list (org-property-values prop)))
10253 (val (if allowed
10254 (org-completing-read "Value: " allowed nil 'req-match)
10255 (org-completing-read
10256 (concat "Value" (if (and cur (string-match "\\S-" cur))
10257 (concat "[" cur "]") "")
10258 ": ")
10259 existing nil nil "" nil cur))))
10260 (list prop (if (equal val "") cur val))))
10261 (unless (equal (org-entry-get nil property) value)
10262 (org-entry-put nil property value)))
10264 (defun org-delete-property (property)
10265 "In the current entry, delete PROPERTY."
10266 (interactive
10267 (let* ((completion-ignore-case t)
10268 (prop (completing-read
10269 "Property: " (org-entry-properties nil 'standard))))
10270 (list prop)))
10271 (message "Property %s %s" property
10272 (if (org-entry-delete nil property)
10273 "deleted"
10274 "was not present in the entry")))
10276 (defun org-delete-property-globally (property)
10277 "Remove PROPERTY globally, from all entries."
10278 (interactive
10279 (let* ((completion-ignore-case t)
10280 (prop (completing-read
10281 "Globally remove property: "
10282 (mapcar 'list (org-buffer-property-keys)))))
10283 (list prop)))
10284 (save-excursion
10285 (save-restriction
10286 (widen)
10287 (goto-char (point-min))
10288 (let ((cnt 0))
10289 (while (re-search-forward
10290 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10291 nil t)
10292 (setq cnt (1+ cnt))
10293 (replace-match ""))
10294 (message "Property \"%s\" removed from %d entries" property cnt)))))
10296 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10298 (defun org-compute-property-at-point ()
10299 "Compute the property at point.
10300 This looks for an enclosing column format, extracts the operator and
10301 then applies it to the proerty in the column format's scope."
10302 (interactive)
10303 (unless (org-at-property-p)
10304 (error "Not at a property"))
10305 (let ((prop (org-match-string-no-properties 2)))
10306 (org-columns-get-format-and-top-level)
10307 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10308 (error "No operator defined for property %s" prop))
10309 (org-columns-compute prop)))
10311 (defun org-property-get-allowed-values (pom property &optional table)
10312 "Get allowed values for the property PROPERTY.
10313 When TABLE is non-nil, return an alist that can directly be used for
10314 completion."
10315 (let (vals)
10316 (cond
10317 ((equal property "TODO")
10318 (setq vals (org-with-point-at pom
10319 (append org-todo-keywords-1 '("")))))
10320 ((equal property "PRIORITY")
10321 (let ((n org-lowest-priority))
10322 (while (>= n org-highest-priority)
10323 (push (char-to-string n) vals)
10324 (setq n (1- n)))))
10325 ((member property org-special-properties))
10327 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10329 (when (and vals (string-match "\\S-" vals))
10330 (setq vals (car (read-from-string (concat "(" vals ")"))))
10331 (setq vals (mapcar (lambda (x)
10332 (cond ((stringp x) x)
10333 ((numberp x) (number-to-string x))
10334 ((symbolp x) (symbol-name x))
10335 (t "???")))
10336 vals)))))
10337 (if table (mapcar 'list vals) vals)))
10339 (defun org-property-previous-allowed-value (&optional previous)
10340 "Switch to the next allowed value for this property."
10341 (interactive)
10342 (org-property-next-allowed-value t))
10344 (defun org-property-next-allowed-value (&optional previous)
10345 "Switch to the next allowed value for this property."
10346 (interactive)
10347 (unless (org-at-property-p)
10348 (error "Not at a property"))
10349 (let* ((key (match-string 2))
10350 (value (match-string 3))
10351 (allowed (or (org-property-get-allowed-values (point) key)
10352 (and (member value '("[ ]" "[-]" "[X]"))
10353 '("[ ]" "[X]"))))
10354 nval)
10355 (unless allowed
10356 (error "Allowed values for this property have not been defined"))
10357 (if previous (setq allowed (reverse allowed)))
10358 (if (member value allowed)
10359 (setq nval (car (cdr (member value allowed)))))
10360 (setq nval (or nval (car allowed)))
10361 (if (equal nval value)
10362 (error "Only one allowed value for this property"))
10363 (org-at-property-p)
10364 (replace-match (concat " :" key ": " nval) t t)
10365 (org-indent-line-function)
10366 (beginning-of-line 1)
10367 (skip-chars-forward " \t")))
10369 (defun org-find-entry-with-id (ident)
10370 "Locate the entry that contains the ID property with exact value IDENT.
10371 IDENT can be a string, a symbol or a number, this function will search for
10372 the string representation of it.
10373 Return the position where this entry starts, or nil if there is no such entry."
10374 (let ((id (cond
10375 ((stringp ident) ident)
10376 ((symbol-name ident) (symbol-name ident))
10377 ((numberp ident) (number-to-string ident))
10378 (t (error "IDENT %s must be a string, symbol or number" ident))))
10379 (case-fold-search nil))
10380 (save-excursion
10381 (save-restriction
10382 (widen)
10383 (goto-char (point-min))
10384 (when (re-search-forward
10385 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10386 nil t)
10387 (org-back-to-heading)
10388 (point))))))
10390 ;;;; Timestamps
10392 (defvar org-last-changed-timestamp nil)
10393 (defvar org-last-inserted-timestamp nil
10394 "The last time stamp inserted with `org-insert-time-stamp'.")
10395 (defvar org-time-was-given) ; dynamically scoped parameter
10396 (defvar org-end-time-was-given) ; dynamically scoped parameter
10397 (defvar org-ts-what) ; dynamically scoped parameter
10399 (defun org-time-stamp (arg &optional inactive)
10400 "Prompt for a date/time and insert a time stamp.
10401 If the user specifies a time like HH:MM, or if this command is called
10402 with a prefix argument, the time stamp will contain date and time.
10403 Otherwise, only the date will be included. All parts of a date not
10404 specified by the user will be filled in from the current date/time.
10405 So if you press just return without typing anything, the time stamp
10406 will represent the current date/time. If there is already a timestamp
10407 at the cursor, it will be modified."
10408 (interactive "P")
10409 (let* ((ts nil)
10410 (default-time
10411 ;; Default time is either today, or, when entering a range,
10412 ;; the range start.
10413 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10414 (save-excursion
10415 (re-search-backward
10416 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10417 (- (point) 20) t)))
10418 (apply 'encode-time (org-parse-time-string (match-string 1)))
10419 (current-time)))
10420 (default-input (and ts (org-get-compact-tod ts)))
10421 org-time-was-given org-end-time-was-given time)
10422 (cond
10423 ((and (org-at-timestamp-p t)
10424 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10425 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10426 (insert "--")
10427 (setq time (let ((this-command this-command))
10428 (org-read-date arg 'totime nil nil
10429 default-time default-input)))
10430 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10431 ((org-at-timestamp-p t)
10432 (setq time (let ((this-command this-command))
10433 (org-read-date arg 'totime nil nil default-time default-input)))
10434 (when (org-at-timestamp-p t) ; just to get the match data
10435 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10436 (replace-match "")
10437 (setq org-last-changed-timestamp
10438 (org-insert-time-stamp
10439 time (or org-time-was-given arg)
10440 inactive nil nil (list org-end-time-was-given))))
10441 (message "Timestamp updated"))
10443 (setq time (let ((this-command this-command))
10444 (org-read-date arg 'totime nil nil default-time default-input)))
10445 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10446 nil nil (list org-end-time-was-given))))))
10448 ;; FIXME: can we use this for something else, like computing time differences?
10449 (defun org-get-compact-tod (s)
10450 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10451 (let* ((t1 (match-string 1 s))
10452 (h1 (string-to-number (match-string 2 s)))
10453 (m1 (string-to-number (match-string 3 s)))
10454 (t2 (and (match-end 4) (match-string 5 s)))
10455 (h2 (and t2 (string-to-number (match-string 6 s))))
10456 (m2 (and t2 (string-to-number (match-string 7 s))))
10457 dh dm)
10458 (if (not t2)
10460 (setq dh (- h2 h1) dm (- m2 m1))
10461 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10462 (concat t1 "+" (number-to-string dh)
10463 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10465 (defun org-time-stamp-inactive (&optional arg)
10466 "Insert an inactive time stamp.
10467 An inactive time stamp is enclosed in square brackets instead of angle
10468 brackets. It is inactive in the sense that it does not trigger agenda entries,
10469 does not link to the calendar and cannot be changed with the S-cursor keys.
10470 So these are more for recording a certain time/date."
10471 (interactive "P")
10472 (org-time-stamp arg 'inactive))
10474 (defvar org-date-ovl (org-make-overlay 1 1))
10475 (org-overlay-put org-date-ovl 'face 'org-warning)
10476 (org-detach-overlay org-date-ovl)
10478 (defvar org-ans1) ; dynamically scoped parameter
10479 (defvar org-ans2) ; dynamically scoped parameter
10481 (defvar org-plain-time-of-day-regexp) ; defined below
10483 (defvar org-overriding-default-time nil) ; dynamically scoped
10484 (defvar org-read-date-overlay nil)
10485 (defvar org-dcst nil) ; dynamically scoped
10487 (defun org-read-date (&optional with-time to-time from-string prompt
10488 default-time default-input)
10489 "Read a date, possibly a time, and make things smooth for the user.
10490 The prompt will suggest to enter an ISO date, but you can also enter anything
10491 which will at least partially be understood by `parse-time-string'.
10492 Unrecognized parts of the date will default to the current day, month, year,
10493 hour and minute. If this command is called to replace a timestamp at point,
10494 of to enter the second timestamp of a range, the default time is taken from the
10495 existing stamp. For example,
10496 3-2-5 --> 2003-02-05
10497 feb 15 --> currentyear-02-15
10498 sep 12 9 --> 2009-09-12
10499 12:45 --> today 12:45
10500 22 sept 0:34 --> currentyear-09-22 0:34
10501 12 --> currentyear-currentmonth-12
10502 Fri --> nearest Friday (today or later)
10503 etc.
10505 Furthermore you can specify a relative date by giving, as the *first* thing
10506 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10507 change in days weeks, months, years.
10508 With a single plus or minus, the date is relative to today. With a double
10509 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10510 +4d --> four days from today
10511 +4 --> same as above
10512 +2w --> two weeks from today
10513 ++5 --> five days from default date
10515 The function understands only English month and weekday abbreviations,
10516 but this can be configured with the variables `parse-time-months' and
10517 `parse-time-weekdays'.
10519 While prompting, a calendar is popped up - you can also select the
10520 date with the mouse (button 1). The calendar shows a period of three
10521 months. To scroll it to other months, use the keys `>' and `<'.
10522 If you don't like the calendar, turn it off with
10523 \(setq org-read-date-popup-calendar nil)
10525 With optional argument TO-TIME, the date will immediately be converted
10526 to an internal time.
10527 With an optional argument WITH-TIME, the prompt will suggest to also
10528 insert a time. Note that when WITH-TIME is not set, you can still
10529 enter a time, and this function will inform the calling routine about
10530 this change. The calling routine may then choose to change the format
10531 used to insert the time stamp into the buffer to include the time.
10532 With optional argument FROM-STRING, read from this string instead from
10533 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10534 the time/date that is used for everything that is not specified by the
10535 user."
10536 (require 'parse-time)
10537 (let* ((org-time-stamp-rounding-minutes
10538 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10539 (org-dcst org-display-custom-times)
10540 (ct (org-current-time))
10541 (def (or org-overriding-default-time default-time ct))
10542 (defdecode (decode-time def))
10543 (dummy (progn
10544 (when (< (nth 2 defdecode) org-extend-today-until)
10545 (setcar (nthcdr 2 defdecode) -1)
10546 (setcar (nthcdr 1 defdecode) 59)
10547 (setq def (apply 'encode-time defdecode)
10548 defdecode (decode-time def)))))
10549 (calendar-move-hook nil)
10550 (calendar-view-diary-initially-flag nil)
10551 (view-diary-entries-initially nil)
10552 (calendar-view-holidays-initially-flag nil)
10553 (view-calendar-holidays-initially nil)
10554 (timestr (format-time-string
10555 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10556 (prompt (concat (if prompt (concat prompt " ") "")
10557 (format "Date+time [%s]: " timestr)))
10558 ans (org-ans0 "") org-ans1 org-ans2 final)
10560 (cond
10561 (from-string (setq ans from-string))
10562 (org-read-date-popup-calendar
10563 (save-excursion
10564 (save-window-excursion
10565 (calendar)
10566 (calendar-forward-day (- (time-to-days def)
10567 (calendar-absolute-from-gregorian
10568 (calendar-current-date))))
10569 (org-eval-in-calendar nil t)
10570 (let* ((old-map (current-local-map))
10571 (map (copy-keymap calendar-mode-map))
10572 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10573 (org-defkey map (kbd "RET") 'org-calendar-select)
10574 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10575 'org-calendar-select-mouse)
10576 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10577 'org-calendar-select-mouse)
10578 (org-defkey minibuffer-local-map [(meta shift left)]
10579 (lambda () (interactive)
10580 (org-eval-in-calendar '(calendar-backward-month 1))))
10581 (org-defkey minibuffer-local-map [(meta shift right)]
10582 (lambda () (interactive)
10583 (org-eval-in-calendar '(calendar-forward-month 1))))
10584 (org-defkey minibuffer-local-map [(meta shift up)]
10585 (lambda () (interactive)
10586 (org-eval-in-calendar '(calendar-backward-year 1))))
10587 (org-defkey minibuffer-local-map [(meta shift down)]
10588 (lambda () (interactive)
10589 (org-eval-in-calendar '(calendar-forward-year 1))))
10590 (org-defkey minibuffer-local-map [(shift up)]
10591 (lambda () (interactive)
10592 (org-eval-in-calendar '(calendar-backward-week 1))))
10593 (org-defkey minibuffer-local-map [(shift down)]
10594 (lambda () (interactive)
10595 (org-eval-in-calendar '(calendar-forward-week 1))))
10596 (org-defkey minibuffer-local-map [(shift left)]
10597 (lambda () (interactive)
10598 (org-eval-in-calendar '(calendar-backward-day 1))))
10599 (org-defkey minibuffer-local-map [(shift right)]
10600 (lambda () (interactive)
10601 (org-eval-in-calendar '(calendar-forward-day 1))))
10602 (org-defkey minibuffer-local-map ">"
10603 (lambda () (interactive)
10604 (org-eval-in-calendar '(scroll-calendar-left 1))))
10605 (org-defkey minibuffer-local-map "<"
10606 (lambda () (interactive)
10607 (org-eval-in-calendar '(scroll-calendar-right 1))))
10608 (unwind-protect
10609 (progn
10610 (use-local-map map)
10611 (add-hook 'post-command-hook 'org-read-date-display)
10612 (setq org-ans0 (read-string prompt default-input nil nil))
10613 ;; org-ans0: from prompt
10614 ;; org-ans1: from mouse click
10615 ;; org-ans2: from calendar motion
10616 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10617 (remove-hook 'post-command-hook 'org-read-date-display)
10618 (use-local-map old-map)
10619 (when org-read-date-overlay
10620 (org-delete-overlay org-read-date-overlay)
10621 (setq org-read-date-overlay nil)))))))
10623 (t ; Naked prompt only
10624 (unwind-protect
10625 (setq ans (read-string prompt default-input nil timestr))
10626 (when org-read-date-overlay
10627 (org-delete-overlay org-read-date-overlay)
10628 (setq org-read-date-overlay nil)))))
10630 (setq final (org-read-date-analyze ans def defdecode))
10632 (if to-time
10633 (apply 'encode-time final)
10634 (if (and (boundp 'org-time-was-given) org-time-was-given)
10635 (format "%04d-%02d-%02d %02d:%02d"
10636 (nth 5 final) (nth 4 final) (nth 3 final)
10637 (nth 2 final) (nth 1 final))
10638 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10639 (defvar def)
10640 (defvar defdecode)
10641 (defvar with-time)
10642 (defun org-read-date-display ()
10643 "Display the currrent date prompt interpretation in the minibuffer."
10644 (when org-read-date-display-live
10645 (when org-read-date-overlay
10646 (org-delete-overlay org-read-date-overlay))
10647 (let ((p (point)))
10648 (end-of-line 1)
10649 (while (not (equal (buffer-substring
10650 (max (point-min) (- (point) 4)) (point))
10651 " "))
10652 (insert " "))
10653 (goto-char p))
10654 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10655 " " (or org-ans1 org-ans2)))
10656 (org-end-time-was-given nil)
10657 (f (org-read-date-analyze ans def defdecode))
10658 (fmts (if org-dcst
10659 org-time-stamp-custom-formats
10660 org-time-stamp-formats))
10661 (fmt (if (or with-time
10662 (and (boundp 'org-time-was-given) org-time-was-given))
10663 (cdr fmts)
10664 (car fmts)))
10665 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10666 (when (and org-end-time-was-given
10667 (string-match org-plain-time-of-day-regexp txt))
10668 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10669 org-end-time-was-given
10670 (substring txt (match-end 0)))))
10671 (setq org-read-date-overlay
10672 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10673 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10675 (defun org-read-date-analyze (ans def defdecode)
10676 "Analyze the combined answer of the date prompt."
10677 ;; FIXME: cleanup and comment
10678 (let (delta deltan deltaw deltadef year month day
10679 hour minute second wday pm h2 m2 tl wday1
10680 iso-year iso-weekday iso-week iso-year iso-date)
10682 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10683 (setq ans "+0"))
10685 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10686 (setq ans (replace-match "" t t ans)
10687 deltan (car delta)
10688 deltaw (nth 1 delta)
10689 deltadef (nth 2 delta)))
10691 ;; Check if there is an iso week date in there
10692 ;; If yes, sore the info and ostpone interpreting it until the rest
10693 ;; of the parsing is done
10694 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10695 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10696 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10697 iso-week (string-to-number (match-string 2 ans)))
10698 (setq ans (replace-match "" t t ans)))
10700 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10701 (when (string-match
10702 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10703 (setq year (if (match-end 2)
10704 (string-to-number (match-string 2 ans))
10705 (string-to-number (format-time-string "%Y")))
10706 month (string-to-number (match-string 3 ans))
10707 day (string-to-number (match-string 4 ans)))
10708 (if (< year 100) (setq year (+ 2000 year)))
10709 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10710 t nil ans)))
10711 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10712 ;; If there is a time with am/pm, and *no* time without it, we convert
10713 ;; so that matching will be successful.
10714 (loop for i from 1 to 2 do ; twice, for end time as well
10715 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10716 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10717 (setq hour (string-to-number (match-string 1 ans))
10718 minute (if (match-end 3)
10719 (string-to-number (match-string 3 ans))
10721 pm (equal ?p
10722 (string-to-char (downcase (match-string 4 ans)))))
10723 (if (and (= hour 12) (not pm))
10724 (setq hour 0)
10725 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10726 (setq ans (replace-match (format "%02d:%02d" hour minute)
10727 t t ans))))
10729 ;; Check if a time range is given as a duration
10730 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10731 (setq hour (string-to-number (match-string 1 ans))
10732 h2 (+ hour (string-to-number (match-string 3 ans)))
10733 minute (string-to-number (match-string 2 ans))
10734 m2 (+ minute (if (match-end 5) (string-to-number
10735 (match-string 5 ans))0)))
10736 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10737 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10738 t t ans)))
10740 ;; Check if there is a time range
10741 (when (boundp 'org-end-time-was-given)
10742 (setq org-time-was-given nil)
10743 (when (and (string-match org-plain-time-of-day-regexp ans)
10744 (match-end 8))
10745 (setq org-end-time-was-given (match-string 8 ans))
10746 (setq ans (concat (substring ans 0 (match-beginning 7))
10747 (substring ans (match-end 7))))))
10749 (setq tl (parse-time-string ans)
10750 day (or (nth 3 tl) (nth 3 defdecode))
10751 month (or (nth 4 tl)
10752 (if (and org-read-date-prefer-future
10753 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10754 (1+ (nth 4 defdecode))
10755 (nth 4 defdecode)))
10756 year (or (nth 5 tl)
10757 (if (and org-read-date-prefer-future
10758 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10759 (1+ (nth 5 defdecode))
10760 (nth 5 defdecode)))
10761 hour (or (nth 2 tl) (nth 2 defdecode))
10762 minute (or (nth 1 tl) (nth 1 defdecode))
10763 second (or (nth 0 tl) 0)
10764 wday (nth 6 tl))
10766 ;; Special date definitions below
10767 (cond
10768 (iso-week
10769 ;; There was an iso week
10770 (setq year (or iso-year year)
10771 day (or iso-weekday wday 1)
10772 wday nil ; to make sure that the trigger below does not match
10773 iso-date (calendar-gregorian-from-absolute
10774 (calendar-absolute-from-iso
10775 (list iso-week day year))))
10776 ; FIXME: Should we also push ISO weeks into the future?
10777 ; (when (and org-read-date-prefer-future
10778 ; (not iso-year)
10779 ; (< (calendar-absolute-from-gregorian iso-date)
10780 ; (time-to-days (current-time))))
10781 ; (setq year (1+ year)
10782 ; iso-date (calendar-gregorian-from-absolute
10783 ; (calendar-absolute-from-iso
10784 ; (list iso-week day year)))))
10785 (setq month (car iso-date)
10786 year (nth 2 iso-date)
10787 day (nth 1 iso-date)))
10788 (deltan
10789 (unless deltadef
10790 (let ((now (decode-time (current-time))))
10791 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10792 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10793 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10794 ((equal deltaw "m") (setq month (+ month deltan)))
10795 ((equal deltaw "y") (setq year (+ year deltan)))))
10796 ((and wday (not (nth 3 tl)))
10797 ;; Weekday was given, but no day, so pick that day in the week
10798 ;; on or after the derived date.
10799 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10800 (unless (equal wday wday1)
10801 (setq day (+ day (% (- wday wday1 -7) 7))))))
10802 (if (and (boundp 'org-time-was-given)
10803 (nth 2 tl))
10804 (setq org-time-was-given t))
10805 (if (< year 100) (setq year (+ 2000 year)))
10806 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10807 (list second minute hour day month year)))
10809 (defvar parse-time-weekdays)
10811 (defun org-read-date-get-relative (s today default)
10812 "Check string S for special relative date string.
10813 TODAY and DEFAULT are internal times, for today and for a default.
10814 Return shift list (N what def-flag)
10815 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10816 N is the number of WHATs to shift.
10817 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10818 the DEFAULT date rather than TODAY."
10819 (when (and
10820 (string-match
10821 (concat
10822 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10823 "\\([0-9]+\\)?"
10824 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10825 "\\([ \t]\\|$\\)") s)
10826 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10827 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10828 (string-to-char (substring (match-string 1 s) -1))
10829 ?+))
10830 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10831 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10832 (what (if (match-end 3) (match-string 3 s) "d"))
10833 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10834 (date (if rel default today))
10835 (wday (nth 6 (decode-time date)))
10836 delta)
10837 (if wday1
10838 (progn
10839 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10840 (if (= dir ?-) (setq delta (- delta 7)))
10841 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10842 (list delta "d" rel))
10843 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10845 (defun org-eval-in-calendar (form &optional keepdate)
10846 "Eval FORM in the calendar window and return to current window.
10847 Also, store the cursor date in variable org-ans2."
10848 (let ((sw (selected-window)))
10849 (select-window (get-buffer-window "*Calendar*"))
10850 (eval form)
10851 (when (and (not keepdate) (calendar-cursor-to-date))
10852 (let* ((date (calendar-cursor-to-date))
10853 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10854 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10855 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10856 (select-window sw)))
10858 (defun org-calendar-select ()
10859 "Return to `org-read-date' with the date currently selected.
10860 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10861 (interactive)
10862 (when (calendar-cursor-to-date)
10863 (let* ((date (calendar-cursor-to-date))
10864 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10865 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10866 (if (active-minibuffer-window) (exit-minibuffer))))
10868 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10869 "Insert a date stamp for the date given by the internal TIME.
10870 WITH-HM means, use the stamp format that includes the time of the day.
10871 INACTIVE means use square brackets instead of angular ones, so that the
10872 stamp will not contribute to the agenda.
10873 PRE and POST are optional strings to be inserted before and after the
10874 stamp.
10875 The command returns the inserted time stamp."
10876 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10877 stamp)
10878 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10879 (insert-before-markers (or pre ""))
10880 (insert-before-markers (setq stamp (format-time-string fmt time)))
10881 (when (listp extra)
10882 (setq extra (car extra))
10883 (if (and (stringp extra)
10884 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10885 (setq extra (format "-%02d:%02d"
10886 (string-to-number (match-string 1 extra))
10887 (string-to-number (match-string 2 extra))))
10888 (setq extra nil)))
10889 (when extra
10890 (backward-char 1)
10891 (insert-before-markers extra)
10892 (forward-char 1))
10893 (insert-before-markers (or post ""))
10894 (setq org-last-inserted-timestamp stamp)))
10896 (defun org-toggle-time-stamp-overlays ()
10897 "Toggle the use of custom time stamp formats."
10898 (interactive)
10899 (setq org-display-custom-times (not org-display-custom-times))
10900 (unless org-display-custom-times
10901 (let ((p (point-min)) (bmp (buffer-modified-p)))
10902 (while (setq p (next-single-property-change p 'display))
10903 (if (and (get-text-property p 'display)
10904 (eq (get-text-property p 'face) 'org-date))
10905 (remove-text-properties
10906 p (setq p (next-single-property-change p 'display))
10907 '(display t))))
10908 (set-buffer-modified-p bmp)))
10909 (if (featurep 'xemacs)
10910 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10911 (org-restart-font-lock)
10912 (setq org-table-may-need-update t)
10913 (if org-display-custom-times
10914 (message "Time stamps are overlayed with custom format")
10915 (message "Time stamp overlays removed")))
10917 (defun org-display-custom-time (beg end)
10918 "Overlay modified time stamp format over timestamp between BEG and END."
10919 (let* ((ts (buffer-substring beg end))
10920 t1 w1 with-hm tf time str w2 (off 0))
10921 (save-match-data
10922 (setq t1 (org-parse-time-string ts t))
10923 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10924 (setq off (- (match-end 0) (match-beginning 0)))))
10925 (setq end (- end off))
10926 (setq w1 (- end beg)
10927 with-hm (and (nth 1 t1) (nth 2 t1))
10928 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10929 time (org-fix-decoded-time t1)
10930 str (org-add-props
10931 (format-time-string
10932 (substring tf 1 -1) (apply 'encode-time time))
10933 nil 'mouse-face 'highlight)
10934 w2 (length str))
10935 (if (not (= w2 w1))
10936 (add-text-properties (1+ beg) (+ 2 beg)
10937 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10938 (if (featurep 'xemacs)
10939 (progn
10940 (put-text-property beg end 'invisible t)
10941 (put-text-property beg end 'end-glyph (make-glyph str)))
10942 (put-text-property beg end 'display str))))
10944 (defun org-translate-time (string)
10945 "Translate all timestamps in STRING to custom format.
10946 But do this only if the variable `org-display-custom-times' is set."
10947 (when org-display-custom-times
10948 (save-match-data
10949 (let* ((start 0)
10950 (re org-ts-regexp-both)
10951 t1 with-hm inactive tf time str beg end)
10952 (while (setq start (string-match re string start))
10953 (setq beg (match-beginning 0)
10954 end (match-end 0)
10955 t1 (save-match-data
10956 (org-parse-time-string (substring string beg end) t))
10957 with-hm (and (nth 1 t1) (nth 2 t1))
10958 inactive (equal (substring string beg (1+ beg)) "[")
10959 tf (funcall (if with-hm 'cdr 'car)
10960 org-time-stamp-custom-formats)
10961 time (org-fix-decoded-time t1)
10962 str (format-time-string
10963 (concat
10964 (if inactive "[" "<") (substring tf 1 -1)
10965 (if inactive "]" ">"))
10966 (apply 'encode-time time))
10967 string (replace-match str t t string)
10968 start (+ start (length str)))))))
10969 string)
10971 (defun org-fix-decoded-time (time)
10972 "Set 0 instead of nil for the first 6 elements of time.
10973 Don't touch the rest."
10974 (let ((n 0))
10975 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10977 (defun org-days-to-time (timestamp-string)
10978 "Difference between TIMESTAMP-STRING and now in days."
10979 (- (time-to-days (org-time-string-to-time timestamp-string))
10980 (time-to-days (current-time))))
10982 (defun org-deadline-close (timestamp-string &optional ndays)
10983 "Is the time in TIMESTAMP-STRING close to the current date?"
10984 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10985 (and (< (org-days-to-time timestamp-string) ndays)
10986 (not (org-entry-is-done-p))))
10988 (defun org-get-wdays (ts)
10989 "Get the deadline lead time appropriate for timestring TS."
10990 (cond
10991 ((<= org-deadline-warning-days 0)
10992 ;; 0 or negative, enforce this value no matter what
10993 (- org-deadline-warning-days))
10994 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10995 ;; lead time is specified.
10996 (floor (* (string-to-number (match-string 1 ts))
10997 (cdr (assoc (match-string 2 ts)
10998 '(("d" . 1) ("w" . 7)
10999 ("m" . 30.4) ("y" . 365.25)))))))
11000 ;; go for the default.
11001 (t org-deadline-warning-days)))
11003 (defun org-calendar-select-mouse (ev)
11004 "Return to `org-read-date' with the date currently selected.
11005 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11006 (interactive "e")
11007 (mouse-set-point ev)
11008 (when (calendar-cursor-to-date)
11009 (let* ((date (calendar-cursor-to-date))
11010 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11011 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11012 (if (active-minibuffer-window) (exit-minibuffer))))
11014 (defun org-check-deadlines (ndays)
11015 "Check if there are any deadlines due or past due.
11016 A deadline is considered due if it happens within `org-deadline-warning-days'
11017 days from today's date. If the deadline appears in an entry marked DONE,
11018 it is not shown. The prefix arg NDAYS can be used to test that many
11019 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11020 (interactive "P")
11021 (let* ((org-warn-days
11022 (cond
11023 ((equal ndays '(4)) 100000)
11024 (ndays (prefix-numeric-value ndays))
11025 (t (abs org-deadline-warning-days))))
11026 (case-fold-search nil)
11027 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11028 (callback
11029 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11031 (message "%d deadlines past-due or due within %d days"
11032 (org-occur regexp nil callback)
11033 org-warn-days)))
11035 (defun org-check-before-date (date)
11036 "Check if there are deadlines or scheduled entries before DATE."
11037 (interactive (list (org-read-date)))
11038 (let ((case-fold-search nil)
11039 (regexp (concat "\\<\\(" org-deadline-string
11040 "\\|" org-scheduled-string
11041 "\\) *<\\([^>]+\\)>"))
11042 (callback
11043 (lambda () (time-less-p
11044 (org-time-string-to-time (match-string 2))
11045 (org-time-string-to-time date)))))
11046 (message "%d entries before %s"
11047 (org-occur regexp nil callback) date)))
11049 (defun org-evaluate-time-range (&optional to-buffer)
11050 "Evaluate a time range by computing the difference between start and end.
11051 Normally the result is just printed in the echo area, but with prefix arg
11052 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11053 If the time range is actually in a table, the result is inserted into the
11054 next column.
11055 For time difference computation, a year is assumed to be exactly 365
11056 days in order to avoid rounding problems."
11057 (interactive "P")
11059 (org-clock-update-time-maybe)
11060 (save-excursion
11061 (unless (org-at-date-range-p t)
11062 (goto-char (point-at-bol))
11063 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11064 (if (not (org-at-date-range-p t))
11065 (error "Not at a time-stamp range, and none found in current line")))
11066 (let* ((ts1 (match-string 1))
11067 (ts2 (match-string 2))
11068 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11069 (match-end (match-end 0))
11070 (time1 (org-time-string-to-time ts1))
11071 (time2 (org-time-string-to-time ts2))
11072 (t1 (time-to-seconds time1))
11073 (t2 (time-to-seconds time2))
11074 (diff (abs (- t2 t1)))
11075 (negative (< (- t2 t1) 0))
11076 ;; (ys (floor (* 365 24 60 60)))
11077 (ds (* 24 60 60))
11078 (hs (* 60 60))
11079 (fy "%dy %dd %02d:%02d")
11080 (fy1 "%dy %dd")
11081 (fd "%dd %02d:%02d")
11082 (fd1 "%dd")
11083 (fh "%02d:%02d")
11084 y d h m align)
11085 (if havetime
11086 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11088 d (floor (/ diff ds)) diff (mod diff ds)
11089 h (floor (/ diff hs)) diff (mod diff hs)
11090 m (floor (/ diff 60)))
11091 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11093 d (floor (+ (/ diff ds) 0.5))
11094 h 0 m 0))
11095 (if (not to-buffer)
11096 (message "%s" (org-make-tdiff-string y d h m))
11097 (if (org-at-table-p)
11098 (progn
11099 (goto-char match-end)
11100 (setq align t)
11101 (and (looking-at " *|") (goto-char (match-end 0))))
11102 (goto-char match-end))
11103 (if (looking-at
11104 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11105 (replace-match ""))
11106 (if negative (insert " -"))
11107 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11108 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11109 (insert " " (format fh h m))))
11110 (if align (org-table-align))
11111 (message "Time difference inserted")))))
11113 (defun org-make-tdiff-string (y d h m)
11114 (let ((fmt "")
11115 (l nil))
11116 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11117 l (push y l)))
11118 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11119 l (push d l)))
11120 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11121 l (push h l)))
11122 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11123 l (push m l)))
11124 (apply 'format fmt (nreverse l))))
11126 (defun org-time-string-to-time (s)
11127 (apply 'encode-time (org-parse-time-string s)))
11129 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11130 "Convert a time stamp to an absolute day number.
11131 If there is a specifyer for a cyclic time stamp, get the closest date to
11132 DAYNR.
11133 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11134 (cond
11135 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11136 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11137 daynr
11138 (+ daynr 1000)))
11139 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11140 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11141 (time-to-days (current-time))) (match-string 0 s)
11142 prefer show-all))
11143 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11145 (defun org-days-to-iso-week (days)
11146 "Return the iso week number."
11147 (require 'cal-iso)
11148 (car (calendar-iso-from-absolute days)))
11150 (defun org-small-year-to-year (year)
11151 "Convert 2-digit years into 4-digit years.
11152 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11153 The year 2000 cannot be abbreviated. Any year lager than 99
11154 is retrned unchanged."
11155 (if (< year 38)
11156 (setq year (+ 2000 year))
11157 (if (< year 100)
11158 (setq year (+ 1900 year))))
11159 year)
11161 (defun org-time-from-absolute (d)
11162 "Return the time corresponding to date D.
11163 D may be an absolute day number, or a calendar-type list (month day year)."
11164 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11165 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11167 (defun org-calendar-holiday ()
11168 "List of holidays, for Diary display in Org-mode."
11169 (require 'holidays)
11170 (let ((hl (funcall
11171 (if (fboundp 'calendar-check-holidays)
11172 'calendar-check-holidays 'check-calendar-holidays) date)))
11173 (if hl (mapconcat 'identity hl "; "))))
11175 (defun org-diary-sexp-entry (sexp entry date)
11176 "Process a SEXP diary ENTRY for DATE."
11177 (require 'diary-lib)
11178 (let ((result (if calendar-debug-sexp
11179 (let ((stack-trace-on-error t))
11180 (eval (car (read-from-string sexp))))
11181 (condition-case nil
11182 (eval (car (read-from-string sexp)))
11183 (error
11184 (beep)
11185 (message "Bad sexp at line %d in %s: %s"
11186 (org-current-line)
11187 (buffer-file-name) sexp)
11188 (sleep-for 2))))))
11189 (cond ((stringp result) result)
11190 ((and (consp result)
11191 (stringp (cdr result))) (cdr result))
11192 (result entry)
11193 (t nil))))
11195 (defun org-diary-to-ical-string (frombuf)
11196 "Get iCalendar entries from diary entries in buffer FROMBUF.
11197 This uses the icalendar.el library."
11198 (let* ((tmpdir (if (featurep 'xemacs)
11199 (temp-directory)
11200 temporary-file-directory))
11201 (tmpfile (make-temp-name
11202 (expand-file-name "orgics" tmpdir)))
11203 buf rtn b e)
11204 (save-excursion
11205 (set-buffer frombuf)
11206 (icalendar-export-region (point-min) (point-max) tmpfile)
11207 (setq buf (find-buffer-visiting tmpfile))
11208 (set-buffer buf)
11209 (goto-char (point-min))
11210 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11211 (setq b (match-beginning 0)))
11212 (goto-char (point-max))
11213 (if (re-search-backward "^END:VEVENT" nil t)
11214 (setq e (match-end 0)))
11215 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11216 (kill-buffer buf)
11217 (delete-file tmpfile)
11218 rtn))
11220 (defun org-closest-date (start current change prefer show-all)
11221 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11222 When PREFER is `past' return a date that is either CURRENT or past.
11223 When PREFER is `future', return a date that is either CURRENT or future.
11224 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11225 ;; Make the proper lists from the dates
11226 (catch 'exit
11227 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11228 dn dw sday cday n1 n2
11229 d m y y1 y2 date1 date2 nmonths nm ny m2)
11231 (setq start (org-date-to-gregorian start)
11232 current (org-date-to-gregorian
11233 (if show-all
11234 current
11235 (time-to-days (current-time))))
11236 sday (calendar-absolute-from-gregorian start)
11237 cday (calendar-absolute-from-gregorian current))
11239 (if (<= cday sday) (throw 'exit sday))
11241 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11242 (setq dn (string-to-number (match-string 1 change))
11243 dw (cdr (assoc (match-string 2 change) a1)))
11244 (error "Invalid change specifyer: %s" change))
11245 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11246 (cond
11247 ((eq dw 'day)
11248 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11249 n2 (+ n1 dn)))
11250 ((eq dw 'year)
11251 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11252 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11253 (setq date1 (list m d y1)
11254 n1 (calendar-absolute-from-gregorian date1)
11255 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11256 n2 (calendar-absolute-from-gregorian date2)))
11257 ((eq dw 'month)
11258 ;; approx number of month between the two dates
11259 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11260 ;; How often does dn fit in there?
11261 (setq d (nth 1 start) m (car start) y (nth 2 start)
11262 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11263 m (+ m nm)
11264 ny (floor (/ m 12))
11265 y (+ y ny)
11266 m (- m (* ny 12)))
11267 (while (> m 12) (setq m (- m 12) y (1+ y)))
11268 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11269 (setq m2 (+ m dn) y2 y)
11270 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11271 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11272 (while (<= n2 cday)
11273 (setq n1 n2 m m2 y y2)
11274 (setq m2 (+ m dn) y2 y)
11275 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11276 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11277 (if show-all
11278 (cond
11279 ((eq prefer 'past) n1)
11280 ((eq prefer 'future) (if (= cday n1) n1 n2))
11281 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11282 (cond
11283 ((eq prefer 'past) n1)
11284 ((eq prefer 'future) (if (= cday n1) n1 n2))
11285 (t (if (= cday n1) n1 n2)))))))
11287 (defun org-date-to-gregorian (date)
11288 "Turn any specification of DATE into a gregorian date for the calendar."
11289 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11290 ((and (listp date) (= (length date) 3)) date)
11291 ((stringp date)
11292 (setq date (org-parse-time-string date))
11293 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11294 ((listp date)
11295 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11297 (defun org-parse-time-string (s &optional nodefault)
11298 "Parse the standard Org-mode time string.
11299 This should be a lot faster than the normal `parse-time-string'.
11300 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11301 hour and minute fields will be nil if not given."
11302 (if (string-match org-ts-regexp0 s)
11303 (list 0
11304 (if (or (match-beginning 8) (not nodefault))
11305 (string-to-number (or (match-string 8 s) "0")))
11306 (if (or (match-beginning 7) (not nodefault))
11307 (string-to-number (or (match-string 7 s) "0")))
11308 (string-to-number (match-string 4 s))
11309 (string-to-number (match-string 3 s))
11310 (string-to-number (match-string 2 s))
11311 nil nil nil)
11312 (make-list 9 0)))
11314 (defun org-timestamp-up (&optional arg)
11315 "Increase the date item at the cursor by one.
11316 If the cursor is on the year, change the year. If it is on the month or
11317 the day, change that.
11318 With prefix ARG, change by that many units."
11319 (interactive "p")
11320 (org-timestamp-change (prefix-numeric-value arg)))
11322 (defun org-timestamp-down (&optional arg)
11323 "Decrease the date item at the cursor by one.
11324 If the cursor is on the year, change the year. If it is on the month or
11325 the day, change that.
11326 With prefix ARG, change by that many units."
11327 (interactive "p")
11328 (org-timestamp-change (- (prefix-numeric-value arg))))
11330 (defun org-timestamp-up-day (&optional arg)
11331 "Increase the date in the time stamp by one day.
11332 With prefix ARG, change that many days."
11333 (interactive "p")
11334 (if (and (not (org-at-timestamp-p t))
11335 (org-on-heading-p))
11336 (org-todo 'up)
11337 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11339 (defun org-timestamp-down-day (&optional arg)
11340 "Decrease the date in the time stamp by one day.
11341 With prefix ARG, change that many days."
11342 (interactive "p")
11343 (if (and (not (org-at-timestamp-p t))
11344 (org-on-heading-p))
11345 (org-todo 'down)
11346 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11348 (defun org-at-timestamp-p (&optional inactive-ok)
11349 "Determine if the cursor is in or at a timestamp."
11350 (interactive)
11351 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11352 (pos (point))
11353 (ans (or (looking-at tsr)
11354 (save-excursion
11355 (skip-chars-backward "^[<\n\r\t")
11356 (if (> (point) (point-min)) (backward-char 1))
11357 (and (looking-at tsr)
11358 (> (- (match-end 0) pos) -1))))))
11359 (and ans
11360 (boundp 'org-ts-what)
11361 (setq org-ts-what
11362 (cond
11363 ((= pos (match-beginning 0)) 'bracket)
11364 ((= pos (1- (match-end 0))) 'bracket)
11365 ((org-pos-in-match-range pos 2) 'year)
11366 ((org-pos-in-match-range pos 3) 'month)
11367 ((org-pos-in-match-range pos 7) 'hour)
11368 ((org-pos-in-match-range pos 8) 'minute)
11369 ((or (org-pos-in-match-range pos 4)
11370 (org-pos-in-match-range pos 5)) 'day)
11371 ((and (> pos (or (match-end 8) (match-end 5)))
11372 (< pos (match-end 0)))
11373 (- pos (or (match-end 8) (match-end 5))))
11374 (t 'day))))
11375 ans))
11377 (defun org-toggle-timestamp-type ()
11378 "Toggle the type (<active> or [inactive]) of a time stamp."
11379 (interactive)
11380 (when (org-at-timestamp-p t)
11381 (let ((beg (match-beginning 0)) (end (match-end 0))
11382 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11383 (save-excursion
11384 (goto-char beg)
11385 (while (re-search-forward "[][<>]" end t)
11386 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11387 t t)))
11388 (message "Timestamp is now %sactive"
11389 (if (equal (char-after beg) ?<) "" "in")))))
11391 (defun org-timestamp-change (n &optional what)
11392 "Change the date in the time stamp at point.
11393 The date will be changed by N times WHAT. WHAT can be `day', `month',
11394 `year', `minute', `second'. If WHAT is not given, the cursor position
11395 in the timestamp determines what will be changed."
11396 (let ((pos (point))
11397 with-hm inactive
11398 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11399 org-ts-what
11400 extra rem
11401 ts time time0)
11402 (if (not (org-at-timestamp-p t))
11403 (error "Not at a timestamp"))
11404 (if (and (not what) (eq org-ts-what 'bracket))
11405 (org-toggle-timestamp-type)
11406 (if (and (not what) (not (eq org-ts-what 'day))
11407 org-display-custom-times
11408 (get-text-property (point) 'display)
11409 (not (get-text-property (1- (point)) 'display)))
11410 (setq org-ts-what 'day))
11411 (setq org-ts-what (or what org-ts-what)
11412 inactive (= (char-after (match-beginning 0)) ?\[)
11413 ts (match-string 0))
11414 (replace-match "")
11415 (if (string-match
11416 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11418 (setq extra (match-string 1 ts)))
11419 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11420 (setq with-hm t))
11421 (setq time0 (org-parse-time-string ts))
11422 (when (and (eq org-ts-what 'minute)
11423 (eq current-prefix-arg nil))
11424 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11425 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11426 (setcar (cdr time0) (+ (nth 1 time0)
11427 (if (> n 0) (- rem) (- dm rem))))))
11428 (setq time
11429 (encode-time (or (car time0) 0)
11430 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11431 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11432 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11433 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11434 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11435 (nthcdr 6 time0)))
11436 (when (integerp org-ts-what)
11437 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11438 (if (eq what 'calendar)
11439 (let ((cal-date (org-get-date-from-calendar)))
11440 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11441 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11442 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11443 (setcar time0 (or (car time0) 0))
11444 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11445 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11446 (setq time (apply 'encode-time time0))))
11447 (setq org-last-changed-timestamp
11448 (org-insert-time-stamp time with-hm inactive nil nil extra))
11449 (org-clock-update-time-maybe)
11450 (goto-char pos)
11451 ;; Try to recenter the calendar window, if any
11452 (if (and org-calendar-follow-timestamp-change
11453 (get-buffer-window "*Calendar*" t)
11454 (memq org-ts-what '(day month year)))
11455 (org-recenter-calendar (time-to-days time))))))
11457 (defun org-modify-ts-extra (s pos n dm)
11458 "Change the different parts of the lead-time and repeat fields in timestamp."
11459 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11460 ng h m new rem)
11461 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11462 (cond
11463 ((or (org-pos-in-match-range pos 2)
11464 (org-pos-in-match-range pos 3))
11465 (setq m (string-to-number (match-string 3 s))
11466 h (string-to-number (match-string 2 s)))
11467 (if (org-pos-in-match-range pos 2)
11468 (setq h (+ h n))
11469 (setq n (* dm (org-no-warnings (signum n))))
11470 (when (not (= 0 (setq rem (% m dm))))
11471 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11472 (setq m (+ m n)))
11473 (if (< m 0) (setq m (+ m 60) h (1- h)))
11474 (if (> m 59) (setq m (- m 60) h (1+ h)))
11475 (setq h (min 24 (max 0 h)))
11476 (setq ng 1 new (format "-%02d:%02d" h m)))
11477 ((org-pos-in-match-range pos 6)
11478 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11479 ((org-pos-in-match-range pos 5)
11480 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11482 ((org-pos-in-match-range pos 9)
11483 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11484 ((org-pos-in-match-range pos 8)
11485 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11487 (when ng
11488 (setq s (concat
11489 (substring s 0 (match-beginning ng))
11491 (substring s (match-end ng))))))
11494 (defun org-recenter-calendar (date)
11495 "If the calendar is visible, recenter it to DATE."
11496 (let* ((win (selected-window))
11497 (cwin (get-buffer-window "*Calendar*" t))
11498 (calendar-move-hook nil))
11499 (when cwin
11500 (select-window cwin)
11501 (calendar-goto-date (if (listp date) date
11502 (calendar-gregorian-from-absolute date)))
11503 (select-window win))))
11505 (defun org-goto-calendar (&optional arg)
11506 "Go to the Emacs calendar at the current date.
11507 If there is a time stamp in the current line, go to that date.
11508 A prefix ARG can be used to force the current date."
11509 (interactive "P")
11510 (let ((tsr org-ts-regexp) diff
11511 (calendar-move-hook nil)
11512 (calendar-view-holidays-initially-flag nil)
11513 (view-calendar-holidays-initially nil)
11514 (calendar-view-diary-initially-flag nil)
11515 (view-diary-entries-initially nil))
11516 (if (or (org-at-timestamp-p)
11517 (save-excursion
11518 (beginning-of-line 1)
11519 (looking-at (concat ".*" tsr))))
11520 (let ((d1 (time-to-days (current-time)))
11521 (d2 (time-to-days
11522 (org-time-string-to-time (match-string 1)))))
11523 (setq diff (- d2 d1))))
11524 (calendar)
11525 (calendar-goto-today)
11526 (if (and diff (not arg)) (calendar-forward-day diff))))
11528 (defun org-get-date-from-calendar ()
11529 "Return a list (month day year) of date at point in calendar."
11530 (with-current-buffer "*Calendar*"
11531 (save-match-data
11532 (calendar-cursor-to-date))))
11534 (defun org-date-from-calendar ()
11535 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11536 If there is already a time stamp at the cursor position, update it."
11537 (interactive)
11538 (if (org-at-timestamp-p t)
11539 (org-timestamp-change 0 'calendar)
11540 (let ((cal-date (org-get-date-from-calendar)))
11541 (org-insert-time-stamp
11542 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11544 (defun org-minutes-to-hh:mm-string (m)
11545 "Compute H:MM from a number of minutes."
11546 (let ((h (/ m 60)))
11547 (setq m (- m (* 60 h)))
11548 (format org-time-clocksum-format h m)))
11550 (defun org-hh:mm-string-to-minutes (s)
11551 "Convert a string H:MM to a number of minutes."
11552 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11553 (+ (* (string-to-number (match-string 1 s)) 60)
11554 (string-to-number (match-string 2 s)))
11557 ;;;; Agenda files
11559 ;;;###autoload
11560 (defun org-iswitchb (&optional arg)
11561 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11562 With a prefix argument, restrict available to files.
11563 With two prefix arguments, restrict available buffers to agenda files.
11565 Due to some yet unresolved reason, the global function
11566 `iswitchb-mode' needs to be active for this function to work."
11567 (interactive "P")
11568 (require 'iswitchb)
11569 (let ((enabled iswitchb-mode) blist)
11570 (or enabled (iswitchb-mode 1))
11571 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11572 ((equal arg '(16)) (org-buffer-list 'agenda))
11573 (t (org-buffer-list))))
11574 (unwind-protect
11575 (let ((iswitchb-make-buflist-hook
11576 (lambda ()
11577 (setq iswitchb-temp-buflist
11578 (mapcar 'buffer-name blist)))))
11579 (switch-to-buffer
11580 (iswitchb-read-buffer
11581 "Switch-to: " nil t))
11582 (or enabled (iswitchb-mode -1))))))
11584 (defun org-buffer-list (&optional predicate exclude-tmp)
11585 "Return a list of Org buffers.
11586 PREDICATE can be `export', `files' or `agenda'.
11588 export restrict the list to Export buffers.
11589 files restrict the list to buffers visiting Org files.
11590 agenda restrict the list to buffers visiting agenda files.
11592 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11593 (let* ((bfn nil)
11594 (agenda-files (and (eq predicate 'agenda)
11595 (mapcar 'file-truename (org-agenda-files t))))
11596 (filter
11597 (cond
11598 ((eq predicate 'files)
11599 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11600 ((eq predicate 'export)
11601 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11602 ((eq predicate 'agenda)
11603 (lambda (b)
11604 (with-current-buffer b
11605 (and (eq major-mode 'org-mode)
11606 (setq bfn (buffer-file-name b))
11607 (member (file-truename bfn) agenda-files)))))
11608 (t (lambda (b) (with-current-buffer b
11609 (or (eq major-mode 'org-mode)
11610 (string-match "\*Org .*Export"
11611 (buffer-name b)))))))))
11612 (delq nil
11613 (mapcar
11614 (lambda(b)
11615 (if (and (funcall filter b)
11616 (or (not exclude-tmp)
11617 (not (string-match "tmp" (buffer-name b)))))
11619 nil))
11620 (buffer-list)))))
11622 (defun org-agenda-files (&optional unrestricted archives)
11623 "Get the list of agenda files.
11624 Optional UNRESTRICTED means return the full list even if a restriction
11625 is currently in place.
11626 When ARCHIVES is t, include all archive files hat are really being
11627 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11628 `org-agenda-archives-mode' is t."
11629 (let ((files
11630 (cond
11631 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11632 ((stringp org-agenda-files) (org-read-agenda-file-list))
11633 ((listp org-agenda-files) org-agenda-files)
11634 (t (error "Invalid value of `org-agenda-files'")))))
11635 (setq files (apply 'append
11636 (mapcar (lambda (f)
11637 (if (file-directory-p f)
11638 (directory-files
11639 f t org-agenda-file-regexp)
11640 (list f)))
11641 files)))
11642 (when org-agenda-skip-unavailable-files
11643 (setq files (delq nil
11644 (mapcar (function
11645 (lambda (file)
11646 (and (file-readable-p file) file)))
11647 files))))
11648 (when (or (eq archives t)
11649 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11650 (setq files (org-add-archive-files files)))
11651 files))
11653 (defun org-edit-agenda-file-list ()
11654 "Edit the list of agenda files.
11655 Depending on setup, this either uses customize to edit the variable
11656 `org-agenda-files', or it visits the file that is holding the list. In the
11657 latter case, the buffer is set up in a way that saving it automatically kills
11658 the buffer and restores the previous window configuration."
11659 (interactive)
11660 (if (stringp org-agenda-files)
11661 (let ((cw (current-window-configuration)))
11662 (find-file org-agenda-files)
11663 (org-set-local 'org-window-configuration cw)
11664 (org-add-hook 'after-save-hook
11665 (lambda ()
11666 (set-window-configuration
11667 (prog1 org-window-configuration
11668 (kill-buffer (current-buffer))))
11669 (org-install-agenda-files-menu)
11670 (message "New agenda file list installed"))
11671 nil 'local)
11672 (message "%s" (substitute-command-keys
11673 "Edit list and finish with \\[save-buffer]")))
11674 (customize-variable 'org-agenda-files)))
11676 (defun org-store-new-agenda-file-list (list)
11677 "Set new value for the agenda file list and save it correcly."
11678 (if (stringp org-agenda-files)
11679 (let ((f org-agenda-files) b)
11680 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11681 (with-temp-file f
11682 (insert (mapconcat 'identity list "\n") "\n")))
11683 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11684 (setq org-agenda-files list)
11685 (customize-save-variable 'org-agenda-files org-agenda-files))))
11687 (defun org-read-agenda-file-list ()
11688 "Read the list of agenda files from a file."
11689 (when (file-directory-p org-agenda-files)
11690 (error "`org-agenda-files' cannot be a single directory"))
11691 (when (stringp org-agenda-files)
11692 (with-temp-buffer
11693 (insert-file-contents org-agenda-files)
11694 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11697 ;;;###autoload
11698 (defun org-cycle-agenda-files ()
11699 "Cycle through the files in `org-agenda-files'.
11700 If the current buffer visits an agenda file, find the next one in the list.
11701 If the current buffer does not, find the first agenda file."
11702 (interactive)
11703 (let* ((fs (org-agenda-files t))
11704 (files (append fs (list (car fs))))
11705 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11706 file)
11707 (unless files (error "No agenda files"))
11708 (catch 'exit
11709 (while (setq file (pop files))
11710 (if (equal (file-truename file) tcf)
11711 (when (car files)
11712 (find-file (car files))
11713 (throw 'exit t))))
11714 (find-file (car fs)))
11715 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11717 (defun org-agenda-file-to-front (&optional to-end)
11718 "Move/add the current file to the top of the agenda file list.
11719 If the file is not present in the list, it is added to the front. If it is
11720 present, it is moved there. With optional argument TO-END, add/move to the
11721 end of the list."
11722 (interactive "P")
11723 (let ((org-agenda-skip-unavailable-files nil)
11724 (file-alist (mapcar (lambda (x)
11725 (cons (file-truename x) x))
11726 (org-agenda-files t)))
11727 (ctf (file-truename buffer-file-name))
11728 x had)
11729 (setq x (assoc ctf file-alist) had x)
11731 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11732 (if to-end
11733 (setq file-alist (append (delq x file-alist) (list x)))
11734 (setq file-alist (cons x (delq x file-alist))))
11735 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11736 (org-install-agenda-files-menu)
11737 (message "File %s to %s of agenda file list"
11738 (if had "moved" "added") (if to-end "end" "front"))))
11740 (defun org-remove-file (&optional file)
11741 "Remove current file from the list of files in variable `org-agenda-files'.
11742 These are the files which are being checked for agenda entries.
11743 Optional argument FILE means, use this file instead of the current."
11744 (interactive)
11745 (let* ((org-agenda-skip-unavailable-files nil)
11746 (file (or file buffer-file-name))
11747 (true-file (file-truename file))
11748 (afile (abbreviate-file-name file))
11749 (files (delq nil (mapcar
11750 (lambda (x)
11751 (if (equal true-file
11752 (file-truename x))
11753 nil x))
11754 (org-agenda-files t)))))
11755 (if (not (= (length files) (length (org-agenda-files t))))
11756 (progn
11757 (org-store-new-agenda-file-list files)
11758 (org-install-agenda-files-menu)
11759 (message "Removed file: %s" afile))
11760 (message "File was not in list: %s (not removed)" afile))))
11762 (defun org-file-menu-entry (file)
11763 (vector file (list 'find-file file) t))
11765 (defun org-check-agenda-file (file)
11766 "Make sure FILE exists. If not, ask user what to do."
11767 (when (not (file-exists-p file))
11768 (message "non-existent file %s. [R]emove from list or [A]bort?"
11769 (abbreviate-file-name file))
11770 (let ((r (downcase (read-char-exclusive))))
11771 (cond
11772 ((equal r ?r)
11773 (org-remove-file file)
11774 (throw 'nextfile t))
11775 (t (error "Abort"))))))
11777 (defun org-get-agenda-file-buffer (file)
11778 "Get a buffer visiting FILE. If the buffer needs to be created, add
11779 it to the list of buffers which might be released later."
11780 (let ((buf (org-find-base-buffer-visiting file)))
11781 (if buf
11782 buf ; just return it
11783 ;; Make a new buffer and remember it
11784 (setq buf (find-file-noselect file))
11785 (if buf (push buf org-agenda-new-buffers))
11786 buf)))
11788 (defun org-release-buffers (blist)
11789 "Release all buffers in list, asking the user for confirmation when needed.
11790 When a buffer is unmodified, it is just killed. When modified, it is saved
11791 \(if the user agrees) and then killed."
11792 (let (buf file)
11793 (while (setq buf (pop blist))
11794 (setq file (buffer-file-name buf))
11795 (when (and (buffer-modified-p buf)
11796 file
11797 (y-or-n-p (format "Save file %s? " file)))
11798 (with-current-buffer buf (save-buffer)))
11799 (kill-buffer buf))))
11801 (defun org-prepare-agenda-buffers (files)
11802 "Create buffers for all agenda files, protect archived trees and comments."
11803 (interactive)
11804 (let ((pa '(:org-archived t))
11805 (pc '(:org-comment t))
11806 (pall '(:org-archived t :org-comment t))
11807 (inhibit-read-only t)
11808 (rea (concat ":" org-archive-tag ":"))
11809 bmp file re)
11810 (save-excursion
11811 (save-restriction
11812 (while (setq file (pop files))
11813 (if (bufferp file)
11814 (set-buffer file)
11815 (org-check-agenda-file file)
11816 (set-buffer (org-get-agenda-file-buffer file)))
11817 (widen)
11818 (setq bmp (buffer-modified-p))
11819 (org-refresh-category-properties)
11820 (setq org-todo-keywords-for-agenda
11821 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11822 (setq org-done-keywords-for-agenda
11823 (append org-done-keywords-for-agenda org-done-keywords))
11824 (setq org-todo-keyword-alist-for-agenda
11825 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11826 (setq org-tag-alist-for-agenda
11827 (append org-tag-alist-for-agenda org-tag-alist))
11829 (save-excursion
11830 (remove-text-properties (point-min) (point-max) pall)
11831 (when org-agenda-skip-archived-trees
11832 (goto-char (point-min))
11833 (while (re-search-forward rea nil t)
11834 (if (org-on-heading-p t)
11835 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11836 (goto-char (point-min))
11837 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11838 (while (re-search-forward re nil t)
11839 (add-text-properties
11840 (match-beginning 0) (org-end-of-subtree t) pc)))
11841 (set-buffer-modified-p bmp))))
11842 (setq org-todo-keyword-alist-for-agenda
11843 (org-uniquify org-todo-keyword-alist-for-agenda)
11844 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11846 ;;;; Embedded LaTeX
11848 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11849 "Keymap for the minor `org-cdlatex-mode'.")
11851 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11852 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11853 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11854 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11855 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11857 (defvar org-cdlatex-texmathp-advice-is-done nil
11858 "Flag remembering if we have applied the advice to texmathp already.")
11860 (define-minor-mode org-cdlatex-mode
11861 "Toggle the minor `org-cdlatex-mode'.
11862 This mode supports entering LaTeX environment and math in LaTeX fragments
11863 in Org-mode.
11864 \\{org-cdlatex-mode-map}"
11865 nil " OCDL" nil
11866 (when org-cdlatex-mode (require 'cdlatex))
11867 (unless org-cdlatex-texmathp-advice-is-done
11868 (setq org-cdlatex-texmathp-advice-is-done t)
11869 (defadvice texmathp (around org-math-always-on activate)
11870 "Always return t in org-mode buffers.
11871 This is because we want to insert math symbols without dollars even outside
11872 the LaTeX math segments. If Orgmode thinks that point is actually inside
11873 en embedded LaTeX fragement, let texmathp do its job.
11874 \\[org-cdlatex-mode-map]"
11875 (interactive)
11876 (let (p)
11877 (cond
11878 ((not (org-mode-p)) ad-do-it)
11879 ((eq this-command 'cdlatex-math-symbol)
11880 (setq ad-return-value t
11881 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11883 (let ((p (org-inside-LaTeX-fragment-p)))
11884 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11885 (setq ad-return-value t
11886 texmathp-why '("Org-mode embedded math" . 0))
11887 (if p ad-do-it)))))))))
11889 (defun turn-on-org-cdlatex ()
11890 "Unconditionally turn on `org-cdlatex-mode'."
11891 (org-cdlatex-mode 1))
11893 (defun org-inside-LaTeX-fragment-p ()
11894 "Test if point is inside a LaTeX fragment.
11895 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11896 sequence appearing also before point.
11897 Even though the matchers for math are configurable, this function assumes
11898 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11899 delimiters are skipped when they have been removed by customization.
11900 The return value is nil, or a cons cell with the delimiter and
11901 and the position of this delimiter.
11903 This function does a reasonably good job, but can locally be fooled by
11904 for example currency specifications. For example it will assume being in
11905 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11906 fragments that are properly closed, but during editing, we have to live
11907 with the uncertainty caused by missing closing delimiters. This function
11908 looks only before point, not after."
11909 (catch 'exit
11910 (let ((pos (point))
11911 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11912 (lim (progn
11913 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11914 (point)))
11915 dd-on str (start 0) m re)
11916 (goto-char pos)
11917 (when dodollar
11918 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11919 re (nth 1 (assoc "$" org-latex-regexps)))
11920 (while (string-match re str start)
11921 (cond
11922 ((= (match-end 0) (length str))
11923 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11924 ((= (match-end 0) (- (length str) 5))
11925 (throw 'exit nil))
11926 (t (setq start (match-end 0))))))
11927 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11928 (goto-char pos)
11929 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11930 (and (match-beginning 2) (throw 'exit nil))
11931 ;; count $$
11932 (while (re-search-backward "\\$\\$" lim t)
11933 (setq dd-on (not dd-on)))
11934 (goto-char pos)
11935 (if dd-on (cons "$$" m))))))
11938 (defun org-try-cdlatex-tab ()
11939 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11940 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11941 - inside a LaTeX fragment, or
11942 - after the first word in a line, where an abbreviation expansion could
11943 insert a LaTeX environment."
11944 (when org-cdlatex-mode
11945 (cond
11946 ((save-excursion
11947 (skip-chars-backward "a-zA-Z0-9*")
11948 (skip-chars-backward " \t")
11949 (bolp))
11950 (cdlatex-tab) t)
11951 ((org-inside-LaTeX-fragment-p)
11952 (cdlatex-tab) t)
11953 (t nil))))
11955 (defun org-cdlatex-underscore-caret (&optional arg)
11956 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11957 Revert to the normal definition outside of these fragments."
11958 (interactive "P")
11959 (if (org-inside-LaTeX-fragment-p)
11960 (call-interactively 'cdlatex-sub-superscript)
11961 (let (org-cdlatex-mode)
11962 (call-interactively (key-binding (vector last-input-event))))))
11964 (defun org-cdlatex-math-modify (&optional arg)
11965 "Execute `cdlatex-math-modify' in LaTeX fragments.
11966 Revert to the normal definition outside of these fragments."
11967 (interactive "P")
11968 (if (org-inside-LaTeX-fragment-p)
11969 (call-interactively 'cdlatex-math-modify)
11970 (let (org-cdlatex-mode)
11971 (call-interactively (key-binding (vector last-input-event))))))
11973 (defvar org-latex-fragment-image-overlays nil
11974 "List of overlays carrying the images of latex fragments.")
11975 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11977 (defun org-remove-latex-fragment-image-overlays ()
11978 "Remove all overlays with LaTeX fragment images in current buffer."
11979 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11980 (setq org-latex-fragment-image-overlays nil))
11982 (defun org-preview-latex-fragment (&optional subtree)
11983 "Preview the LaTeX fragment at point, or all locally or globally.
11984 If the cursor is in a LaTeX fragment, create the image and overlay
11985 it over the source code. If there is no fragment at point, display
11986 all fragments in the current text, from one headline to the next. With
11987 prefix SUBTREE, display all fragments in the current subtree. With a
11988 double prefix `C-u C-u', or when the cursor is before the first headline,
11989 display all fragments in the buffer.
11990 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11991 (interactive "P")
11992 (org-remove-latex-fragment-image-overlays)
11993 (save-excursion
11994 (save-restriction
11995 (let (beg end at msg)
11996 (cond
11997 ((or (equal subtree '(16))
11998 (not (save-excursion
11999 (re-search-backward (concat "^" outline-regexp) nil t))))
12000 (setq beg (point-min) end (point-max)
12001 msg "Creating images for buffer...%s"))
12002 ((equal subtree '(4))
12003 (org-back-to-heading)
12004 (setq beg (point) end (org-end-of-subtree t)
12005 msg "Creating images for subtree...%s"))
12007 (if (setq at (org-inside-LaTeX-fragment-p))
12008 (goto-char (max (point-min) (- (cdr at) 2)))
12009 (org-back-to-heading))
12010 (setq beg (point) end (progn (outline-next-heading) (point))
12011 msg (if at "Creating image...%s"
12012 "Creating images for entry...%s"))))
12013 (message msg "")
12014 (narrow-to-region beg end)
12015 (goto-char beg)
12016 (org-format-latex
12017 (concat "ltxpng/" (file-name-sans-extension
12018 (file-name-nondirectory
12019 buffer-file-name)))
12020 default-directory 'overlays msg at 'forbuffer)
12021 (message msg "done. Use `C-c C-c' to remove images.")))))
12023 (defvar org-latex-regexps
12024 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12025 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12026 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12027 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12028 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12029 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12030 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12031 "Regular expressions for matching embedded LaTeX.")
12033 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12034 "Replace LaTeX fragments with links to an image, and produce images."
12035 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12036 (let* ((prefixnodir (file-name-nondirectory prefix))
12037 (absprefix (expand-file-name prefix dir))
12038 (todir (file-name-directory absprefix))
12039 (opt org-format-latex-options)
12040 (matchers (plist-get opt :matchers))
12041 (re-list org-latex-regexps)
12042 (cnt 0) txt link beg end re e checkdir
12043 m n block linkfile movefile ov)
12044 ;; Check if there are old images files with this prefix, and remove them
12045 (when (file-directory-p todir)
12046 (mapc 'delete-file
12047 (directory-files
12048 todir 'full
12049 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12050 ;; Check the different regular expressions
12051 (while (setq e (pop re-list))
12052 (setq m (car e) re (nth 1 e) n (nth 2 e)
12053 block (if (nth 3 e) "\n\n" ""))
12054 (when (member m matchers)
12055 (goto-char (point-min))
12056 (while (re-search-forward re nil t)
12057 (when (or (not at) (equal (cdr at) (match-beginning n)))
12058 (setq txt (match-string n)
12059 beg (match-beginning n) end (match-end n)
12060 cnt (1+ cnt)
12061 linkfile (format "%s_%04d.png" prefix cnt)
12062 movefile (format "%s_%04d.png" absprefix cnt)
12063 link (concat block "[[file:" linkfile "]]" block))
12064 (if msg (message msg cnt))
12065 (goto-char beg)
12066 (unless checkdir ; make sure the directory exists
12067 (setq checkdir t)
12068 (or (file-directory-p todir) (make-directory todir)))
12069 (org-create-formula-image
12070 txt movefile opt forbuffer)
12071 (if overlays
12072 (progn
12073 (setq ov (org-make-overlay beg end))
12074 (if (featurep 'xemacs)
12075 (progn
12076 (org-overlay-put ov 'invisible t)
12077 (org-overlay-put
12078 ov 'end-glyph
12079 (make-glyph (vector 'png :file movefile))))
12080 (org-overlay-put
12081 ov 'display
12082 (list 'image :type 'png :file movefile :ascent 'center)))
12083 (push ov org-latex-fragment-image-overlays)
12084 (goto-char end))
12085 (delete-region beg end)
12086 (insert link))))))))
12088 ;; This function borrows from Ganesh Swami's latex2png.el
12089 (defun org-create-formula-image (string tofile options buffer)
12090 (let* ((tmpdir (if (featurep 'xemacs)
12091 (temp-directory)
12092 temporary-file-directory))
12093 (texfilebase (make-temp-name
12094 (expand-file-name "orgtex" tmpdir)))
12095 (texfile (concat texfilebase ".tex"))
12096 (dvifile (concat texfilebase ".dvi"))
12097 (pngfile (concat texfilebase ".png"))
12098 (fnh (if (featurep 'xemacs)
12099 (font-height (get-face-font 'default))
12100 (face-attribute 'default :height nil)))
12101 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12102 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12103 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12104 "Black"))
12105 (bg (or (plist-get options (if buffer :background :html-background))
12106 "Transparent")))
12107 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12108 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12109 (with-temp-file texfile
12110 (insert org-format-latex-header
12111 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12112 (let ((dir default-directory))
12113 (condition-case nil
12114 (progn
12115 (cd tmpdir)
12116 (call-process "latex" nil nil nil texfile))
12117 (error nil))
12118 (cd dir))
12119 (if (not (file-exists-p dvifile))
12120 (progn (message "Failed to create dvi file from %s" texfile) nil)
12121 (condition-case nil
12122 (call-process "dvipng" nil nil nil
12123 "-E" "-fg" fg "-bg" bg
12124 "-D" dpi
12125 ;;"-x" scale "-y" scale
12126 "-T" "tight"
12127 "-o" pngfile
12128 dvifile)
12129 (error nil))
12130 (if (not (file-exists-p pngfile))
12131 (progn (message "Failed to create png file from %s" texfile) nil)
12132 ;; Use the requested file name and clean up
12133 (copy-file pngfile tofile 'replace)
12134 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12135 (delete-file (concat texfilebase e)))
12136 pngfile))))
12138 (defun org-dvipng-color (attr)
12139 "Return an rgb color specification for dvipng."
12140 (apply 'format "rgb %s %s %s"
12141 (mapcar 'org-normalize-color
12142 (color-values (face-attribute 'default attr nil)))))
12144 (defun org-normalize-color (value)
12145 "Return string to be used as color value for an RGB component."
12146 (format "%g" (/ value 65535.0)))
12149 ;;;; Key bindings
12151 ;; Make `C-c C-x' a prefix key
12152 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12154 ;; TAB key with modifiers
12155 (org-defkey org-mode-map "\C-i" 'org-cycle)
12156 (org-defkey org-mode-map [(tab)] 'org-cycle)
12157 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12158 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12159 (org-defkey org-mode-map "\M-\t" 'org-complete)
12160 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12161 ;; The following line is necessary under Suse GNU/Linux
12162 (unless (featurep 'xemacs)
12163 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12164 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12165 (define-key org-mode-map [backtab] 'org-shifttab)
12167 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12168 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12169 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12171 ;; Cursor keys with modifiers
12172 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12173 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12174 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12175 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12177 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12178 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12179 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12180 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12182 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12183 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12184 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12185 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12187 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12188 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12190 ;;; Extra keys for tty access.
12191 ;; We only set them when really needed because otherwise the
12192 ;; menus don't show the simple keys
12194 (when (or org-use-extra-keys
12195 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12196 (not window-system))
12197 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12198 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12199 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12200 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12201 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12202 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12203 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12204 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12205 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12206 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12207 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12208 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12209 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12210 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12211 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12212 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12213 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12214 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12215 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12216 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12217 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12218 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12220 ;; All the other keys
12222 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12223 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12224 (if (boundp 'narrow-map)
12225 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12226 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12227 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12228 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12229 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12230 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12231 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12232 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12233 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12234 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12235 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12236 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12237 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12238 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12239 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12240 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12241 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12242 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12243 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12244 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12245 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12246 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12247 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12248 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12249 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12250 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12251 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12252 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12253 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12254 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12255 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12256 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12257 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12258 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12259 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12260 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12261 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12262 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12263 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12264 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12265 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12266 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12267 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12268 (org-defkey org-mode-map "\C-c^" 'org-sort)
12269 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12270 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12271 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12272 (org-defkey org-mode-map "\C-m" 'org-return)
12273 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12274 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12275 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12276 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12277 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12278 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12279 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12280 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12281 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12282 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12283 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12284 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12285 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12286 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12287 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12288 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12290 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12291 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12292 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12293 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12295 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12296 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12297 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12298 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12299 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12300 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12301 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12302 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12303 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12304 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12305 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12306 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12308 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12310 (when (featurep 'xemacs)
12311 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12313 (defvar org-table-auto-blank-field) ; defined in org-table.el
12314 (defun org-self-insert-command (N)
12315 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12316 If the cursor is in a table looking at whitespace, the whitespace is
12317 overwritten, and the table is not marked as requiring realignment."
12318 (interactive "p")
12319 (if (and (org-table-p)
12320 (progn
12321 ;; check if we blank the field, and if that triggers align
12322 (and (featurep 'org-table) org-table-auto-blank-field
12323 (member last-command
12324 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12325 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12326 ;; got extra space, this field does not determine column width
12327 (let (org-table-may-need-update) (org-table-blank-field))
12328 ;; no extra space, this field may determine column width
12329 (org-table-blank-field)))
12331 (eq N 1)
12332 (looking-at "[^|\n]* |"))
12333 (let (org-table-may-need-update)
12334 (goto-char (1- (match-end 0)))
12335 (delete-backward-char 1)
12336 (goto-char (match-beginning 0))
12337 (self-insert-command N))
12338 (setq org-table-may-need-update t)
12339 (self-insert-command N)
12340 (org-fix-tags-on-the-fly)))
12342 (defun org-fix-tags-on-the-fly ()
12343 (when (and (equal (char-after (point-at-bol)) ?*)
12344 (org-on-heading-p))
12345 (org-align-tags-here org-tags-column)))
12347 (defun org-delete-backward-char (N)
12348 "Like `delete-backward-char', insert whitespace at field end in tables.
12349 When deleting backwards, in tables this function will insert whitespace in
12350 front of the next \"|\" separator, to keep the table aligned. The table will
12351 still be marked for re-alignment if the field did fill the entire column,
12352 because, in this case the deletion might narrow the column."
12353 (interactive "p")
12354 (if (and (org-table-p)
12355 (eq N 1)
12356 (string-match "|" (buffer-substring (point-at-bol) (point)))
12357 (looking-at ".*?|"))
12358 (let ((pos (point))
12359 (noalign (looking-at "[^|\n\r]* |"))
12360 (c org-table-may-need-update))
12361 (backward-delete-char N)
12362 (skip-chars-forward "^|")
12363 (insert " ")
12364 (goto-char (1- pos))
12365 ;; noalign: if there were two spaces at the end, this field
12366 ;; does not determine the width of the column.
12367 (if noalign (setq org-table-may-need-update c)))
12368 (backward-delete-char N)
12369 (org-fix-tags-on-the-fly)))
12371 (defun org-delete-char (N)
12372 "Like `delete-char', but insert whitespace at field end in tables.
12373 When deleting characters, in tables this function will insert whitespace in
12374 front of the next \"|\" separator, to keep the table aligned. The table will
12375 still be marked for re-alignment if the field did fill the entire column,
12376 because, in this case the deletion might narrow the column."
12377 (interactive "p")
12378 (if (and (org-table-p)
12379 (not (bolp))
12380 (not (= (char-after) ?|))
12381 (eq N 1))
12382 (if (looking-at ".*?|")
12383 (let ((pos (point))
12384 (noalign (looking-at "[^|\n\r]* |"))
12385 (c org-table-may-need-update))
12386 (replace-match (concat
12387 (substring (match-string 0) 1 -1)
12388 " |"))
12389 (goto-char pos)
12390 ;; noalign: if there were two spaces at the end, this field
12391 ;; does not determine the width of the column.
12392 (if noalign (setq org-table-may-need-update c)))
12393 (delete-char N))
12394 (delete-char N)
12395 (org-fix-tags-on-the-fly)))
12397 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12398 (put 'org-self-insert-command 'delete-selection t)
12399 (put 'orgtbl-self-insert-command 'delete-selection t)
12400 (put 'org-delete-char 'delete-selection 'supersede)
12401 (put 'org-delete-backward-char 'delete-selection 'supersede)
12403 ;; Make `flyspell-mode' delay after some commands
12404 (put 'org-self-insert-command 'flyspell-delayed t)
12405 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12406 (put 'org-delete-char 'flyspell-delayed t)
12407 (put 'org-delete-backward-char 'flyspell-delayed t)
12409 ;; Make pabbrev-mode expand after org-mode commands
12410 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12411 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12413 ;; How to do this: Measure non-white length of current string
12414 ;; If equal to column width, we should realign.
12416 (defun org-remap (map &rest commands)
12417 "In MAP, remap the functions given in COMMANDS.
12418 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12419 (let (new old)
12420 (while commands
12421 (setq old (pop commands) new (pop commands))
12422 (if (fboundp 'command-remapping)
12423 (org-defkey map (vector 'remap old) new)
12424 (substitute-key-definition old new map global-map)))))
12426 (when (eq org-enable-table-editor 'optimized)
12427 ;; If the user wants maximum table support, we need to hijack
12428 ;; some standard editing functions
12429 (org-remap org-mode-map
12430 'self-insert-command 'org-self-insert-command
12431 'delete-char 'org-delete-char
12432 'delete-backward-char 'org-delete-backward-char)
12433 (org-defkey org-mode-map "|" 'org-force-self-insert))
12435 (defun org-shiftcursor-error ()
12436 "Throw an error because Shift-Cursor command was applied in wrong context."
12437 (error "This command is active in special context like tables, headlines or timestamps"))
12439 (defun org-shifttab (&optional arg)
12440 "Global visibility cycling or move to previous table field.
12441 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12442 on context.
12443 See the individual commands for more information."
12444 (interactive "P")
12445 (cond
12446 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12447 ((integerp arg)
12448 (message "Content view to level: %d" arg)
12449 (org-content (prefix-numeric-value arg))
12450 (setq org-cycle-global-status 'overview))
12451 (t (call-interactively 'org-global-cycle))))
12453 (defun org-shiftmetaleft ()
12454 "Promote subtree or delete table column.
12455 Calls `org-promote-subtree', `org-outdent-item',
12456 or `org-table-delete-column', depending on context.
12457 See the individual commands for more information."
12458 (interactive)
12459 (cond
12460 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12461 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12462 ((org-at-item-p) (call-interactively 'org-outdent-item))
12463 (t (org-shiftcursor-error))))
12465 (defun org-shiftmetaright ()
12466 "Demote subtree or insert table column.
12467 Calls `org-demote-subtree', `org-indent-item',
12468 or `org-table-insert-column', depending on context.
12469 See the individual commands for more information."
12470 (interactive)
12471 (cond
12472 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12473 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12474 ((org-at-item-p) (call-interactively 'org-indent-item))
12475 (t (org-shiftcursor-error))))
12477 (defun org-shiftmetaup (&optional arg)
12478 "Move subtree up or kill table row.
12479 Calls `org-move-subtree-up' or `org-table-kill-row' or
12480 `org-move-item-up' depending on context. See the individual commands
12481 for more information."
12482 (interactive "P")
12483 (cond
12484 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12485 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12486 ((org-at-item-p) (call-interactively 'org-move-item-up))
12487 (t (org-shiftcursor-error))))
12488 (defun org-shiftmetadown (&optional arg)
12489 "Move subtree down or insert table row.
12490 Calls `org-move-subtree-down' or `org-table-insert-row' or
12491 `org-move-item-down', depending on context. See the individual
12492 commands for more information."
12493 (interactive "P")
12494 (cond
12495 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12496 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12497 ((org-at-item-p) (call-interactively 'org-move-item-down))
12498 (t (org-shiftcursor-error))))
12500 (defun org-metaleft (&optional arg)
12501 "Promote heading or move table column to left.
12502 Calls `org-do-promote' or `org-table-move-column', depending on context.
12503 With no specific context, calls the Emacs default `backward-word'.
12504 See the individual commands for more information."
12505 (interactive "P")
12506 (cond
12507 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12508 ((or (org-on-heading-p) (org-region-active-p))
12509 (call-interactively 'org-do-promote))
12510 ((org-at-item-p) (call-interactively 'org-outdent-item))
12511 (t (call-interactively 'backward-word))))
12513 (defun org-metaright (&optional arg)
12514 "Demote subtree or move table column to right.
12515 Calls `org-do-demote' or `org-table-move-column', depending on context.
12516 With no specific context, calls the Emacs default `forward-word'.
12517 See the individual commands for more information."
12518 (interactive "P")
12519 (cond
12520 ((org-at-table-p) (call-interactively 'org-table-move-column))
12521 ((or (org-on-heading-p) (org-region-active-p))
12522 (call-interactively 'org-do-demote))
12523 ((org-at-item-p) (call-interactively 'org-indent-item))
12524 (t (call-interactively 'forward-word))))
12526 (defun org-metaup (&optional arg)
12527 "Move subtree up or move table row up.
12528 Calls `org-move-subtree-up' or `org-table-move-row' or
12529 `org-move-item-up', depending on context. See the individual commands
12530 for more information."
12531 (interactive "P")
12532 (cond
12533 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12534 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12535 ((org-at-item-p) (call-interactively 'org-move-item-up))
12536 (t (transpose-lines 1) (beginning-of-line -1))))
12538 (defun org-metadown (&optional arg)
12539 "Move subtree down or move table row down.
12540 Calls `org-move-subtree-down' or `org-table-move-row' or
12541 `org-move-item-down', depending on context. See the individual
12542 commands for more information."
12543 (interactive "P")
12544 (cond
12545 ((org-at-table-p) (call-interactively 'org-table-move-row))
12546 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12547 ((org-at-item-p) (call-interactively 'org-move-item-down))
12548 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12550 (defun org-shiftup (&optional arg)
12551 "Increase item in timestamp or increase priority of current headline.
12552 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12553 depending on context. See the individual commands for more information."
12554 (interactive "P")
12555 (cond
12556 ((org-at-timestamp-p t)
12557 (call-interactively (if org-edit-timestamp-down-means-later
12558 'org-timestamp-down 'org-timestamp-up)))
12559 ((org-on-heading-p) (call-interactively 'org-priority-up))
12560 ((org-at-item-p) (call-interactively 'org-previous-item))
12561 ((org-clocktable-try-shift 'up arg))
12562 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12564 (defun org-shiftdown (&optional arg)
12565 "Decrease item in timestamp or decrease priority of current headline.
12566 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12567 depending on context. See the individual commands for more information."
12568 (interactive "P")
12569 (cond
12570 ((org-at-timestamp-p t)
12571 (call-interactively (if org-edit-timestamp-down-means-later
12572 'org-timestamp-up 'org-timestamp-down)))
12573 ((org-on-heading-p) (call-interactively 'org-priority-down))
12574 ((org-clocktable-try-shift 'down arg))
12575 (t (call-interactively 'org-next-item))))
12577 (defun org-shiftright (&optional arg)
12578 "Next TODO keyword or timestamp one day later, depending on context."
12579 (interactive "P")
12580 (cond
12581 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12582 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12583 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12584 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12585 ((org-clocktable-try-shift 'right arg))
12586 (t (org-shiftcursor-error))))
12588 (defun org-shiftleft (&optional arg)
12589 "Previous TODO keyword or timestamp one day earlier, depending on context."
12590 (interactive "P")
12591 (cond
12592 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12593 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12594 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12595 ((org-at-property-p)
12596 (call-interactively 'org-property-previous-allowed-value))
12597 ((org-clocktable-try-shift 'left arg))
12598 (t (org-shiftcursor-error))))
12600 (defun org-shiftcontrolright ()
12601 "Switch to next TODO set."
12602 (interactive)
12603 (cond
12604 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12605 (t (org-shiftcursor-error))))
12607 (defun org-shiftcontrolleft ()
12608 "Switch to previous TODO set."
12609 (interactive)
12610 (cond
12611 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12612 (t (org-shiftcursor-error))))
12614 (defun org-ctrl-c-ret ()
12615 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12616 (interactive)
12617 (cond
12618 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12619 (t (call-interactively 'org-insert-heading))))
12621 (defun org-copy-special ()
12622 "Copy region in table or copy current subtree.
12623 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12624 See the individual commands for more information."
12625 (interactive)
12626 (call-interactively
12627 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12629 (defun org-cut-special ()
12630 "Cut region in table or cut current subtree.
12631 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12632 See the individual commands for more information."
12633 (interactive)
12634 (call-interactively
12635 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12637 (defun org-paste-special (arg)
12638 "Paste rectangular region into table, or past subtree relative to level.
12639 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12640 See the individual commands for more information."
12641 (interactive "P")
12642 (if (org-at-table-p)
12643 (org-table-paste-rectangle)
12644 (org-paste-subtree arg)))
12646 (defun org-edit-special ()
12647 "Call a special editor for the stuff at point.
12648 When at a table, call the formula editor with `org-table-edit-formulas'.
12649 When at the first line of an src example, call `org-edit-src-code'.
12650 When in an #+include line, visit the include file. Otherwise call
12651 `ffap' to visit the file at point."
12652 (interactive)
12653 (cond
12654 ((org-at-table-p)
12655 (call-interactively 'org-table-edit-formulas))
12656 ((save-excursion
12657 (beginning-of-line 1)
12658 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12659 (find-file (org-trim (match-string 1))))
12660 ((org-edit-src-code))
12661 ((org-edit-fixed-width-region))
12662 (t (call-interactively 'ffap))))
12664 (defun org-ctrl-c-ctrl-c (&optional arg)
12665 "Set tags in headline, or update according to changed information at point.
12667 This command does many different things, depending on context:
12669 - If the cursor is in a headline, prompt for tags and insert them
12670 into the current line, aligned to `org-tags-column'. When called
12671 with prefix arg, realign all tags in the current buffer.
12673 - If the cursor is in one of the special #+KEYWORD lines, this
12674 triggers scanning the buffer for these lines and updating the
12675 information.
12677 - If the cursor is inside a table, realign the table. This command
12678 works even if the automatic table editor has been turned off.
12680 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12681 the entire table.
12683 - If the cursor is a the beginning of a dynamic block, update it.
12685 - If the cursor is inside a table created by the table.el package,
12686 activate that table.
12688 - If the current buffer is a remember buffer, close note and file
12689 it. A prefix argument of 1 files to the default location
12690 without further interaction. A prefix argument of 2 files to
12691 the currently clocking task.
12693 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12694 links in this buffer.
12696 - If the cursor is on a numbered item in a plain list, renumber the
12697 ordered list.
12699 - If the cursor is on a checkbox, toggle it."
12700 (interactive "P")
12701 (let ((org-enable-table-editor t))
12702 (cond
12703 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12704 org-occur-highlights
12705 org-latex-fragment-image-overlays)
12706 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12707 (org-remove-occur-highlights)
12708 (org-remove-latex-fragment-image-overlays)
12709 (message "Temporary highlights/overlays removed from current buffer"))
12710 ((and (local-variable-p 'org-finish-function (current-buffer))
12711 (fboundp org-finish-function))
12712 (funcall org-finish-function))
12713 ((org-at-property-p)
12714 (call-interactively 'org-property-action))
12715 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12716 ((org-on-heading-p) (call-interactively 'org-set-tags))
12717 ((org-at-table.el-p)
12718 (require 'table)
12719 (beginning-of-line 1)
12720 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12721 (call-interactively 'table-recognize-table))
12722 ((org-at-table-p)
12723 (org-table-maybe-eval-formula)
12724 (if arg
12725 (call-interactively 'org-table-recalculate)
12726 (org-table-maybe-recalculate-line))
12727 (call-interactively 'org-table-align))
12728 ((org-at-item-checkbox-p)
12729 (call-interactively 'org-toggle-checkbox))
12730 ((org-at-item-p)
12731 (call-interactively 'org-maybe-renumber-ordered-list))
12732 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12733 ;; Dynamic block
12734 (beginning-of-line 1)
12735 (save-excursion (org-update-dblock)))
12736 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12737 (cond
12738 ((equal (match-string 1) "TBLFM")
12739 ;; Recalculate the table before this line
12740 (save-excursion
12741 (beginning-of-line 1)
12742 (skip-chars-backward " \r\n\t")
12743 (if (org-at-table-p)
12744 (org-call-with-arg 'org-table-recalculate t))))
12746 ; (org-set-regexps-and-options)
12747 ; (org-restart-font-lock)
12748 (let ((org-inhibit-startup t)) (org-mode-restart))
12749 (message "Local setup has been refreshed"))))
12750 (t (error "C-c C-c can do nothing useful at this location.")))))
12752 (defun org-mode-restart ()
12753 "Restart Org-mode, to scan again for special lines.
12754 Also updates the keyword regular expressions."
12755 (interactive)
12756 (org-mode)
12757 (message "Org-mode restarted"))
12759 (defun org-kill-note-or-show-branches ()
12760 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12761 (interactive)
12762 (if (not org-finish-function)
12763 (call-interactively 'show-branches)
12764 (let ((org-note-abort t))
12765 (funcall org-finish-function))))
12767 (defun org-return (&optional indent)
12768 "Goto next table row or insert a newline.
12769 Calls `org-table-next-row' or `newline', depending on context.
12770 See the individual commands for more information."
12771 (interactive)
12772 (cond
12773 ((bobp) (if indent (newline-and-indent) (newline)))
12774 ((and (org-at-heading-p)
12775 (looking-at
12776 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12777 (org-show-entry)
12778 (end-of-line 1)
12779 (newline))
12780 ((org-at-table-p)
12781 (org-table-justify-field-maybe)
12782 (call-interactively 'org-table-next-row))
12783 (t (if indent (newline-and-indent) (newline)))))
12785 (defun org-return-indent ()
12786 "Goto next table row or insert a newline and indent.
12787 Calls `org-table-next-row' or `newline-and-indent', depending on
12788 context. See the individual commands for more information."
12789 (interactive)
12790 (org-return t))
12792 (defun org-ctrl-c-star ()
12793 "Compute table, or change heading status of lines.
12794 Calls `org-table-recalculate' or `org-toggle-region-headings',
12795 depending on context. This will also turn a plain list item or a normal
12796 line into a subheading."
12797 (interactive)
12798 (cond
12799 ((org-at-table-p)
12800 (call-interactively 'org-table-recalculate))
12801 ((org-region-active-p)
12802 ;; Convert all lines in region to list items
12803 (call-interactively 'org-toggle-region-headings))
12804 ((org-on-heading-p)
12805 (org-toggle-region-headings (point-at-bol)
12806 (min (1+ (point-at-eol)) (point-max))))
12807 ((org-at-item-p)
12808 ;; Convert to heading
12809 (let ((level (save-match-data
12810 (save-excursion
12811 (condition-case nil
12812 (progn
12813 (org-back-to-heading t)
12814 (funcall outline-level))
12815 (error 0))))))
12816 (replace-match
12817 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12818 (t (org-toggle-region-headings (point-at-bol)
12819 (min (1+ (point-at-eol)) (point-max))))))
12821 (defun org-ctrl-c-minus ()
12822 "Insert separator line in table or modify bullet status of line.
12823 Also turns a plain line or a region of lines into list items.
12824 Calls `org-table-insert-hline', `org-toggle-region-items', or
12825 `org-cycle-list-bullet', depending on context."
12826 (interactive)
12827 (cond
12828 ((org-at-table-p)
12829 (call-interactively 'org-table-insert-hline))
12830 ((org-on-heading-p)
12831 ;; Convert to item
12832 (save-excursion
12833 (beginning-of-line 1)
12834 (if (looking-at "\\*+ ")
12835 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12836 ((org-region-active-p)
12837 ;; Convert all lines in region to list items
12838 (call-interactively 'org-toggle-region-items))
12839 ((org-in-item-p)
12840 (call-interactively 'org-cycle-list-bullet))
12841 (t (org-toggle-region-items (point-at-bol)
12842 (min (1+ (point-at-eol)) (point-max))))))
12844 (defun org-toggle-region-items (beg end)
12845 "Convert all lines in region to list items.
12846 If the first line is already an item, convert all list items in the region
12847 to normal lines."
12848 (interactive "r")
12849 (let (l2 l)
12850 (save-excursion
12851 (goto-char end)
12852 (setq l2 (org-current-line))
12853 (goto-char beg)
12854 (beginning-of-line 1)
12855 (setq l (1- (org-current-line)))
12856 (if (org-at-item-p)
12857 ;; We already have items, de-itemize
12858 (while (< (setq l (1+ l)) l2)
12859 (when (org-at-item-p)
12860 (goto-char (match-beginning 2))
12861 (delete-region (match-beginning 2) (match-end 2))
12862 (and (looking-at "[ \t]+") (replace-match "")))
12863 (beginning-of-line 2))
12864 (while (< (setq l (1+ l)) l2)
12865 (unless (org-at-item-p)
12866 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12867 (replace-match "\\1- \\2")))
12868 (beginning-of-line 2))))))
12870 (defun org-toggle-region-headings (beg end)
12871 "Convert all lines in region to list items.
12872 If the first line is already an item, convert all list items in the region
12873 to normal lines."
12874 (interactive "r")
12875 (let (l2 l)
12876 (save-excursion
12877 (goto-char end)
12878 (setq l2 (org-current-line))
12879 (goto-char beg)
12880 (beginning-of-line 1)
12881 (setq l (1- (org-current-line)))
12882 (if (org-on-heading-p)
12883 ;; We already have headlines, de-star them
12884 (while (< (setq l (1+ l)) l2)
12885 (when (org-on-heading-p t)
12886 (and (looking-at outline-regexp) (replace-match "")))
12887 (beginning-of-line 2))
12888 (let* ((stars (save-excursion
12889 (re-search-backward org-complex-heading-regexp nil t)
12890 (or (match-string 1) "*")))
12891 (add-stars (if org-odd-levels-only "**" "*"))
12892 (rpl (concat stars add-stars " \\2")))
12893 (while (< (setq l (1+ l)) l2)
12894 (unless (org-on-heading-p)
12895 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12896 (replace-match rpl)))
12897 (beginning-of-line 2)))))))
12899 (defun org-meta-return (&optional arg)
12900 "Insert a new heading or wrap a region in a table.
12901 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12902 See the individual commands for more information."
12903 (interactive "P")
12904 (cond
12905 ((org-at-table-p)
12906 (call-interactively 'org-table-wrap-region))
12907 (t (call-interactively 'org-insert-heading))))
12909 ;;; Menu entries
12911 ;; Define the Org-mode menus
12912 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12913 '("Tbl"
12914 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12915 ["Next Field" org-cycle (org-at-table-p)]
12916 ["Previous Field" org-shifttab (org-at-table-p)]
12917 ["Next Row" org-return (org-at-table-p)]
12918 "--"
12919 ["Blank Field" org-table-blank-field (org-at-table-p)]
12920 ["Edit Field" org-table-edit-field (org-at-table-p)]
12921 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12922 "--"
12923 ("Column"
12924 ["Move Column Left" org-metaleft (org-at-table-p)]
12925 ["Move Column Right" org-metaright (org-at-table-p)]
12926 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12927 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12928 ("Row"
12929 ["Move Row Up" org-metaup (org-at-table-p)]
12930 ["Move Row Down" org-metadown (org-at-table-p)]
12931 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12932 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12933 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12934 "--"
12935 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12936 ("Rectangle"
12937 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12938 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12939 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12940 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12941 "--"
12942 ("Calculate"
12943 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12944 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12945 ["Edit Formulas" org-edit-special (org-at-table-p)]
12946 "--"
12947 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12948 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12949 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12950 "--"
12951 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12952 "--"
12953 ["Sum Column/Rectangle" org-table-sum
12954 (or (org-at-table-p) (org-region-active-p))]
12955 ["Which Column?" org-table-current-column (org-at-table-p)])
12956 ["Debug Formulas"
12957 org-table-toggle-formula-debugger
12958 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12959 ["Show Col/Row Numbers"
12960 org-table-toggle-coordinate-overlays
12961 :style toggle
12962 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12963 "--"
12964 ["Create" org-table-create (and (not (org-at-table-p))
12965 org-enable-table-editor)]
12966 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12967 ["Import from File" org-table-import (not (org-at-table-p))]
12968 ["Export to File" org-table-export (org-at-table-p)]
12969 "--"
12970 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12972 (easy-menu-define org-org-menu org-mode-map "Org menu"
12973 '("Org"
12974 ("Show/Hide"
12975 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12976 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12977 ["Sparse Tree..." org-sparse-tree t]
12978 ["Reveal Context" org-reveal t]
12979 ["Show All" show-all t]
12980 "--"
12981 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12982 "--"
12983 ["New Heading" org-insert-heading t]
12984 ("Navigate Headings"
12985 ["Up" outline-up-heading t]
12986 ["Next" outline-next-visible-heading t]
12987 ["Previous" outline-previous-visible-heading t]
12988 ["Next Same Level" outline-forward-same-level t]
12989 ["Previous Same Level" outline-backward-same-level t]
12990 "--"
12991 ["Jump" org-goto t])
12992 ("Edit Structure"
12993 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12994 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12995 "--"
12996 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12997 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12998 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12999 "--"
13000 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13001 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13002 ["Demote Heading" org-metaright (not (org-at-table-p))]
13003 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13004 "--"
13005 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13006 "--"
13007 ["Convert to odd levels" org-convert-to-odd-levels t]
13008 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13009 ("Editing"
13010 ["Emphasis..." org-emphasize t]
13011 ["Edit Source Example" org-edit-special t])
13012 ("Archive"
13013 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13014 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13015 ; :active t :keys "C-u C-c C-x C-a"]
13016 ["Sparse trees open ARCHIVE trees"
13017 (setq org-sparse-tree-open-archived-trees
13018 (not org-sparse-tree-open-archived-trees))
13019 :style toggle :selected org-sparse-tree-open-archived-trees]
13020 ["Cycling opens ARCHIVE trees"
13021 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13022 :style toggle :selected org-cycle-open-archived-trees]
13023 "--"
13024 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13025 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13026 ; ["Check and Move Children" (org-archive-subtree '(4))
13027 ; :active t :keys "C-u C-c C-x C-s"]
13029 "--"
13030 ("TODO Lists"
13031 ["TODO/DONE/-" org-todo t]
13032 ("Select keyword"
13033 ["Next keyword" org-shiftright (org-on-heading-p)]
13034 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13035 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13036 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13037 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13038 ["Show TODO Tree" org-show-todo-tree t]
13039 ["Global TODO list" org-todo-list t]
13040 "--"
13041 ["Set Priority" org-priority t]
13042 ["Priority Up" org-shiftup t]
13043 ["Priority Down" org-shiftdown t])
13044 ("TAGS and Properties"
13045 ["Set Tags" 'org-set-tags-command t]
13046 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13047 "--"
13048 ["Set property" 'org-set-property t]
13049 ["Column view of properties" org-columns t]
13050 ["Insert Column View DBlock" org-insert-columns-dblock t])
13051 ("Dates and Scheduling"
13052 ["Timestamp" org-time-stamp t]
13053 ["Timestamp (inactive)" org-time-stamp-inactive t]
13054 ("Change Date"
13055 ["1 Day Later" org-shiftright t]
13056 ["1 Day Earlier" org-shiftleft t]
13057 ["1 ... Later" org-shiftup t]
13058 ["1 ... Earlier" org-shiftdown t])
13059 ["Compute Time Range" org-evaluate-time-range t]
13060 ["Schedule Item" org-schedule t]
13061 ["Deadline" org-deadline t]
13062 "--"
13063 ["Custom time format" org-toggle-time-stamp-overlays
13064 :style radio :selected org-display-custom-times]
13065 "--"
13066 ["Goto Calendar" org-goto-calendar t]
13067 ["Date from Calendar" org-date-from-calendar t])
13068 ("Logging work"
13069 ["Clock in" org-clock-in t]
13070 ["Clock out" org-clock-out t]
13071 ["Clock cancel" org-clock-cancel t]
13072 ["Goto running clock" org-clock-goto t]
13073 ["Display times" org-clock-display t]
13074 ["Create clock table" org-clock-report t]
13075 "--"
13076 ["Record DONE time"
13077 (progn (setq org-log-done (not org-log-done))
13078 (message "Switching to %s will %s record a timestamp"
13079 (car org-done-keywords)
13080 (if org-log-done "automatically" "not")))
13081 :style toggle :selected org-log-done])
13082 "--"
13083 ["Agenda Command..." org-agenda t]
13084 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13085 ("File List for Agenda")
13086 ("Special views current file"
13087 ["TODO Tree" org-show-todo-tree t]
13088 ["Check Deadlines" org-check-deadlines t]
13089 ["Timeline" org-timeline t]
13090 ["Tags Tree" org-tags-sparse-tree t])
13091 "--"
13092 ("Hyperlinks"
13093 ["Store Link (Global)" org-store-link t]
13094 ["Insert Link" org-insert-link t]
13095 ["Follow Link" org-open-at-point t]
13096 "--"
13097 ["Next link" org-next-link t]
13098 ["Previous link" org-previous-link t]
13099 "--"
13100 ["Descriptive Links"
13101 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13102 :style radio
13103 :selected (member '(org-link) buffer-invisibility-spec)]
13104 ["Literal Links"
13105 (progn
13106 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13107 :style radio
13108 :selected (not (member '(org-link) buffer-invisibility-spec))])
13109 "--"
13110 ["Export/Publish..." org-export t]
13111 ("LaTeX"
13112 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13113 :selected org-cdlatex-mode]
13114 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13115 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13116 ["Modify math symbol" org-cdlatex-math-modify
13117 (org-inside-LaTeX-fragment-p)]
13118 ["Export LaTeX fragments as images"
13119 (if (featurep 'org-exp)
13120 (setq org-export-with-LaTeX-fragments
13121 (not org-export-with-LaTeX-fragments))
13122 (require 'org-exp))
13123 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13124 org-export-with-LaTeX-fragments)])
13125 "--"
13126 ("Documentation"
13127 ["Show Version" org-version t]
13128 ["Info Documentation" org-info t])
13129 ("Customize"
13130 ["Browse Org Group" org-customize t]
13131 "--"
13132 ["Expand This Menu" org-create-customize-menu
13133 (fboundp 'customize-menu-create)])
13134 "--"
13135 ["Refresh setup" org-mode-restart t]
13138 (defun org-info (&optional node)
13139 "Read documentation for Org-mode in the info system.
13140 With optional NODE, go directly to that node."
13141 (interactive)
13142 (info (format "(org)%s" (or node ""))))
13144 (defun org-install-agenda-files-menu ()
13145 (let ((bl (buffer-list)))
13146 (save-excursion
13147 (while bl
13148 (set-buffer (pop bl))
13149 (if (org-mode-p) (setq bl nil)))
13150 (when (org-mode-p)
13151 (easy-menu-change
13152 '("Org") "File List for Agenda"
13153 (append
13154 (list
13155 ["Edit File List" (org-edit-agenda-file-list) t]
13156 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13157 ["Remove Current File from List" org-remove-file t]
13158 ["Cycle through agenda files" org-cycle-agenda-files t]
13159 ["Occur in all agenda files" org-occur-in-agenda-files t]
13160 "--")
13161 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13163 ;;;; Documentation
13165 ;;;###autoload
13166 (defun org-require-autoloaded-modules ()
13167 (interactive)
13168 (mapc 'require
13169 '(org-agenda org-archive org-clock org-colview
13170 org-exp org-id org-export-latex org-publish
13171 org-remember org-table)))
13173 ;;;###autoload
13174 (defun org-customize ()
13175 "Call the customize function with org as argument."
13176 (interactive)
13177 (org-load-modules-maybe)
13178 (org-require-autoloaded-modules)
13179 (customize-browse 'org))
13181 (defun org-create-customize-menu ()
13182 "Create a full customization menu for Org-mode, insert it into the menu."
13183 (interactive)
13184 (org-load-modules-maybe)
13185 (org-require-autoloaded-modules)
13186 (if (fboundp 'customize-menu-create)
13187 (progn
13188 (easy-menu-change
13189 '("Org") "Customize"
13190 `(["Browse Org group" org-customize t]
13191 "--"
13192 ,(customize-menu-create 'org)
13193 ["Set" Custom-set t]
13194 ["Save" Custom-save t]
13195 ["Reset to Current" Custom-reset-current t]
13196 ["Reset to Saved" Custom-reset-saved t]
13197 ["Reset to Standard Settings" Custom-reset-standard t]))
13198 (message "\"Org\"-menu now contains full customization menu"))
13199 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13201 ;;;; Miscellaneous stuff
13203 ;;; Generally useful functions
13205 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13206 "Display the given MESSAGE as a warning."
13207 (if (fboundp 'display-warning)
13208 (display-warning 'org message
13209 (if (featurep 'xemacs)
13210 'warning
13211 :warning))
13212 (let ((buf (get-buffer-create "*Org warnings*")))
13213 (with-current-buffer buf
13214 (goto-char (point-max))
13215 (insert "Warning (Org): " message)
13216 (unless (bolp)
13217 (newline)))
13218 (display-buffer buf)
13219 (sit-for 0))))
13221 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13222 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13223 (if (and marker (marker-buffer marker)
13224 (buffer-live-p (marker-buffer marker)))
13225 (progn
13226 (switch-to-buffer (marker-buffer marker))
13227 (if (or (> marker (point-max)) (< marker (point-min)))
13228 (widen))
13229 (goto-char marker))
13230 (if bookmark
13231 (bookmark-jump bookmark)
13232 (error "Cannot find location"))))
13234 (defun org-quote-csv-field (s)
13235 "Quote field for inclusion in CSV material."
13236 (if (string-match "[\",]" s)
13237 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13240 (defun org-plist-delete (plist property)
13241 "Delete PROPERTY from PLIST.
13242 This is in contrast to merely setting it to 0."
13243 (let (p)
13244 (while plist
13245 (if (not (eq property (car plist)))
13246 (setq p (plist-put p (car plist) (nth 1 plist))))
13247 (setq plist (cddr plist)))
13250 (defun org-force-self-insert (N)
13251 "Needed to enforce self-insert under remapping."
13252 (interactive "p")
13253 (self-insert-command N))
13255 (defun org-string-width (s)
13256 "Compute width of string, ignoring invisible characters.
13257 This ignores character with invisibility property `org-link', and also
13258 characters with property `org-cwidth', because these will become invisible
13259 upon the next fontification round."
13260 (let (b l)
13261 (when (or (eq t buffer-invisibility-spec)
13262 (assq 'org-link buffer-invisibility-spec))
13263 (while (setq b (text-property-any 0 (length s)
13264 'invisible 'org-link s))
13265 (setq s (concat (substring s 0 b)
13266 (substring s (or (next-single-property-change
13267 b 'invisible s) (length s)))))))
13268 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13269 (setq s (concat (substring s 0 b)
13270 (substring s (or (next-single-property-change
13271 b 'org-cwidth s) (length s))))))
13272 (setq l (string-width s) b -1)
13273 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13274 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13277 (defun org-get-indentation (&optional line)
13278 "Get the indentation of the current line, interpreting tabs.
13279 When LINE is given, assume it represents a line and compute its indentation."
13280 (if line
13281 (if (string-match "^ *" (org-remove-tabs line))
13282 (match-end 0))
13283 (save-excursion
13284 (beginning-of-line 1)
13285 (skip-chars-forward " \t")
13286 (current-column))))
13288 (defun org-remove-tabs (s &optional width)
13289 "Replace tabulators in S with spaces.
13290 Assumes that s is a single line, starting in column 0."
13291 (setq width (or width tab-width))
13292 (while (string-match "\t" s)
13293 (setq s (replace-match
13294 (make-string
13295 (- (* width (/ (+ (match-beginning 0) width) width))
13296 (match-beginning 0)) ?\ )
13297 t t s)))
13300 (defun org-fix-indentation (line ind)
13301 "Fix indentation in LINE.
13302 IND is a cons cell with target and minimum indentation.
13303 If the current indenation in LINE is smaller than the minimum,
13304 leave it alone. If it is larger than ind, set it to the target."
13305 (let* ((l (org-remove-tabs line))
13306 (i (org-get-indentation l))
13307 (i1 (car ind)) (i2 (cdr ind)))
13308 (if (>= i i2) (setq l (substring line i2)))
13309 (if (> i1 0)
13310 (concat (make-string i1 ?\ ) l)
13311 l)))
13313 (defun org-base-buffer (buffer)
13314 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13315 (if (not buffer)
13316 buffer
13317 (or (buffer-base-buffer buffer)
13318 buffer)))
13320 (defun org-trim (s)
13321 "Remove whitespace at beginning and end of string."
13322 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13323 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13326 (defun org-wrap (string &optional width lines)
13327 "Wrap string to either a number of lines, or a width in characters.
13328 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13329 that costs. If there is a word longer than WIDTH, the text is actually
13330 wrapped to the length of that word.
13331 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13332 many lines, whatever width that takes.
13333 The return value is a list of lines, without newlines at the end."
13334 (let* ((words (org-split-string string "[ \t\n]+"))
13335 (maxword (apply 'max (mapcar 'org-string-width words)))
13336 w ll)
13337 (cond (width
13338 (org-do-wrap words (max maxword width)))
13339 (lines
13340 (setq w maxword)
13341 (setq ll (org-do-wrap words maxword))
13342 (if (<= (length ll) lines)
13344 (setq ll words)
13345 (while (> (length ll) lines)
13346 (setq w (1+ w))
13347 (setq ll (org-do-wrap words w)))
13348 ll))
13349 (t (error "Cannot wrap this")))))
13351 (defun org-do-wrap (words width)
13352 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13353 (let (lines line)
13354 (while words
13355 (setq line (pop words))
13356 (while (and words (< (+ (length line) (length (car words))) width))
13357 (setq line (concat line " " (pop words))))
13358 (setq lines (push line lines)))
13359 (nreverse lines)))
13361 (defun org-split-string (string &optional separators)
13362 "Splits STRING into substrings at SEPARATORS.
13363 No empty strings are returned if there are matches at the beginning
13364 and end of string."
13365 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13366 (start 0)
13367 notfirst
13368 (list nil))
13369 (while (and (string-match rexp string
13370 (if (and notfirst
13371 (= start (match-beginning 0))
13372 (< start (length string)))
13373 (1+ start) start))
13374 (< (match-beginning 0) (length string)))
13375 (setq notfirst t)
13376 (or (eq (match-beginning 0) 0)
13377 (and (eq (match-beginning 0) (match-end 0))
13378 (eq (match-beginning 0) start))
13379 (setq list
13380 (cons (substring string start (match-beginning 0))
13381 list)))
13382 (setq start (match-end 0)))
13383 (or (eq start (length string))
13384 (setq list
13385 (cons (substring string start)
13386 list)))
13387 (nreverse list)))
13389 (defun org-context ()
13390 "Return a list of contexts of the current cursor position.
13391 If several contexts apply, all are returned.
13392 Each context entry is a list with a symbol naming the context, and
13393 two positions indicating start and end of the context. Possible
13394 contexts are:
13396 :headline anywhere in a headline
13397 :headline-stars on the leading stars in a headline
13398 :todo-keyword on a TODO keyword (including DONE) in a headline
13399 :tags on the TAGS in a headline
13400 :priority on the priority cookie in a headline
13401 :item on the first line of a plain list item
13402 :item-bullet on the bullet/number of a plain list item
13403 :checkbox on the checkbox in a plain list item
13404 :table in an org-mode table
13405 :table-special on a special filed in a table
13406 :table-table in a table.el table
13407 :link on a hyperlink
13408 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13409 :target on a <<target>>
13410 :radio-target on a <<<radio-target>>>
13411 :latex-fragment on a LaTeX fragment
13412 :latex-preview on a LaTeX fragment with overlayed preview image
13414 This function expects the position to be visible because it uses font-lock
13415 faces as a help to recognize the following contexts: :table-special, :link,
13416 and :keyword."
13417 (let* ((f (get-text-property (point) 'face))
13418 (faces (if (listp f) f (list f)))
13419 (p (point)) clist o)
13420 ;; First the large context
13421 (cond
13422 ((org-on-heading-p t)
13423 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13424 (when (progn
13425 (beginning-of-line 1)
13426 (looking-at org-todo-line-tags-regexp))
13427 (push (org-point-in-group p 1 :headline-stars) clist)
13428 (push (org-point-in-group p 2 :todo-keyword) clist)
13429 (push (org-point-in-group p 4 :tags) clist))
13430 (goto-char p)
13431 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13432 (if (looking-at "\\[#[A-Z0-9]\\]")
13433 (push (org-point-in-group p 0 :priority) clist)))
13435 ((org-at-item-p)
13436 (push (org-point-in-group p 2 :item-bullet) clist)
13437 (push (list :item (point-at-bol)
13438 (save-excursion (org-end-of-item) (point)))
13439 clist)
13440 (and (org-at-item-checkbox-p)
13441 (push (org-point-in-group p 0 :checkbox) clist)))
13443 ((org-at-table-p)
13444 (push (list :table (org-table-begin) (org-table-end)) clist)
13445 (if (memq 'org-formula faces)
13446 (push (list :table-special
13447 (previous-single-property-change p 'face)
13448 (next-single-property-change p 'face)) clist)))
13449 ((org-at-table-p 'any)
13450 (push (list :table-table) clist)))
13451 (goto-char p)
13453 ;; Now the small context
13454 (cond
13455 ((org-at-timestamp-p)
13456 (push (org-point-in-group p 0 :timestamp) clist))
13457 ((memq 'org-link faces)
13458 (push (list :link
13459 (previous-single-property-change p 'face)
13460 (next-single-property-change p 'face)) clist))
13461 ((memq 'org-special-keyword faces)
13462 (push (list :keyword
13463 (previous-single-property-change p 'face)
13464 (next-single-property-change p 'face)) clist))
13465 ((org-on-target-p)
13466 (push (org-point-in-group p 0 :target) clist)
13467 (goto-char (1- (match-beginning 0)))
13468 (if (looking-at org-radio-target-regexp)
13469 (push (org-point-in-group p 0 :radio-target) clist))
13470 (goto-char p))
13471 ((setq o (car (delq nil
13472 (mapcar
13473 (lambda (x)
13474 (if (memq x org-latex-fragment-image-overlays) x))
13475 (org-overlays-at (point))))))
13476 (push (list :latex-fragment
13477 (org-overlay-start o) (org-overlay-end o)) clist)
13478 (push (list :latex-preview
13479 (org-overlay-start o) (org-overlay-end o)) clist))
13480 ((org-inside-LaTeX-fragment-p)
13481 ;; FIXME: positions wrong.
13482 (push (list :latex-fragment (point) (point)) clist)))
13484 (setq clist (nreverse (delq nil clist)))
13485 clist))
13487 ;; FIXME: Compare with at-regexp-p Do we need both?
13488 (defun org-in-regexp (re &optional nlines visually)
13489 "Check if point is inside a match of regexp.
13490 Normally only the current line is checked, but you can include NLINES extra
13491 lines both before and after point into the search.
13492 If VISUALLY is set, require that the cursor is not after the match but
13493 really on, so that the block visually is on the match."
13494 (catch 'exit
13495 (let ((pos (point))
13496 (eol (point-at-eol (+ 1 (or nlines 0))))
13497 (inc (if visually 1 0)))
13498 (save-excursion
13499 (beginning-of-line (- 1 (or nlines 0)))
13500 (while (re-search-forward re eol t)
13501 (if (and (<= (match-beginning 0) pos)
13502 (>= (+ inc (match-end 0)) pos))
13503 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13505 (defun org-at-regexp-p (regexp)
13506 "Is point inside a match of REGEXP in the current line?"
13507 (catch 'exit
13508 (save-excursion
13509 (let ((pos (point)) (end (point-at-eol)))
13510 (beginning-of-line 1)
13511 (while (re-search-forward regexp end t)
13512 (if (and (<= (match-beginning 0) pos)
13513 (>= (match-end 0) pos))
13514 (throw 'exit t)))
13515 nil))))
13517 (defun org-occur-in-agenda-files (regexp &optional nlines)
13518 "Call `multi-occur' with buffers for all agenda files."
13519 (interactive "sOrg-files matching: \np")
13520 (let* ((files (org-agenda-files))
13521 (tnames (mapcar 'file-truename files))
13522 (extra org-agenda-text-search-extra-files)
13524 (when (eq (car extra) 'agenda-archives)
13525 (setq extra (cdr extra))
13526 (setq files (org-add-archive-files files)))
13527 (while (setq f (pop extra))
13528 (unless (member (file-truename f) tnames)
13529 (add-to-list 'files f 'append)
13530 (add-to-list 'tnames (file-truename f) 'append)))
13531 (multi-occur
13532 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13533 regexp)))
13535 (if (boundp 'occur-mode-find-occurrence-hook)
13536 ;; Emacs 23
13537 (add-hook 'occur-mode-find-occurrence-hook
13538 (lambda ()
13539 (when (org-mode-p)
13540 (org-reveal))))
13541 ;; Emacs 22
13542 (defadvice occur-mode-goto-occurrence
13543 (after org-occur-reveal activate)
13544 (and (org-mode-p) (org-reveal)))
13545 (defadvice occur-mode-goto-occurrence-other-window
13546 (after org-occur-reveal activate)
13547 (and (org-mode-p) (org-reveal)))
13548 (defadvice occur-mode-display-occurrence
13549 (after org-occur-reveal activate)
13550 (when (org-mode-p)
13551 (let ((pos (occur-mode-find-occurrence)))
13552 (with-current-buffer (marker-buffer pos)
13553 (save-excursion
13554 (goto-char pos)
13555 (org-reveal)))))))
13557 (defun org-uniquify (list)
13558 "Remove duplicate elements from LIST."
13559 (let (res)
13560 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13561 res))
13563 (defun org-delete-all (elts list)
13564 "Remove all elements in ELTS from LIST."
13565 (while elts
13566 (setq list (delete (pop elts) list)))
13567 list)
13569 (defun org-back-over-empty-lines ()
13570 "Move backwards over witespace, to the beginning of the first empty line.
13571 Returns the number of empty lines passed."
13572 (let ((pos (point)))
13573 (skip-chars-backward " \t\n\r")
13574 (beginning-of-line 2)
13575 (goto-char (min (point) pos))
13576 (count-lines (point) pos)))
13578 (defun org-skip-whitespace ()
13579 (skip-chars-forward " \t\n\r"))
13581 (defun org-point-in-group (point group &optional context)
13582 "Check if POINT is in match-group GROUP.
13583 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13584 match. If the match group does ot exist or point is not inside it,
13585 return nil."
13586 (and (match-beginning group)
13587 (>= point (match-beginning group))
13588 (<= point (match-end group))
13589 (if context
13590 (list context (match-beginning group) (match-end group))
13591 t)))
13593 (defun org-switch-to-buffer-other-window (&rest args)
13594 "Switch to buffer in a second window on the current frame.
13595 In particular, do not allow pop-up frames."
13596 (let (pop-up-frames special-display-buffer-names special-display-regexps
13597 special-display-function)
13598 (apply 'switch-to-buffer-other-window args)))
13600 (defun org-combine-plists (&rest plists)
13601 "Create a single property list from all plists in PLISTS.
13602 The process starts by copying the first list, and then setting properties
13603 from the other lists. Settings in the last list are the most significant
13604 ones and overrule settings in the other lists."
13605 (let ((rtn (copy-sequence (pop plists)))
13606 p v ls)
13607 (while plists
13608 (setq ls (pop plists))
13609 (while ls
13610 (setq p (pop ls) v (pop ls))
13611 (setq rtn (plist-put rtn p v))))
13612 rtn))
13614 (defun org-move-line-down (arg)
13615 "Move the current line down. With prefix argument, move it past ARG lines."
13616 (interactive "p")
13617 (let ((col (current-column))
13618 beg end pos)
13619 (beginning-of-line 1) (setq beg (point))
13620 (beginning-of-line 2) (setq end (point))
13621 (beginning-of-line (+ 1 arg))
13622 (setq pos (move-marker (make-marker) (point)))
13623 (insert (delete-and-extract-region beg end))
13624 (goto-char pos)
13625 (org-move-to-column col)))
13627 (defun org-move-line-up (arg)
13628 "Move the current line up. With prefix argument, move it past ARG lines."
13629 (interactive "p")
13630 (let ((col (current-column))
13631 beg end pos)
13632 (beginning-of-line 1) (setq beg (point))
13633 (beginning-of-line 2) (setq end (point))
13634 (beginning-of-line (- arg))
13635 (setq pos (move-marker (make-marker) (point)))
13636 (insert (delete-and-extract-region beg end))
13637 (goto-char pos)
13638 (org-move-to-column col)))
13640 (defun org-replace-escapes (string table)
13641 "Replace %-escapes in STRING with values in TABLE.
13642 TABLE is an association list with keys like \"%a\" and string values.
13643 The sequences in STRING may contain normal field width and padding information,
13644 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13645 so values can contain further %-escapes if they are define later in TABLE."
13646 (let ((case-fold-search nil)
13647 e re rpl)
13648 (while (setq e (pop table))
13649 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13650 (while (string-match re string)
13651 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13652 (cdr e)))
13653 (setq string (replace-match rpl t t string))))
13654 string))
13657 (defun org-sublist (list start end)
13658 "Return a section of LIST, from START to END.
13659 Counting starts at 1."
13660 (let (rtn (c start))
13661 (setq list (nthcdr (1- start) list))
13662 (while (and list (<= c end))
13663 (push (pop list) rtn)
13664 (setq c (1+ c)))
13665 (nreverse rtn)))
13667 (defun org-find-base-buffer-visiting (file)
13668 "Like `find-buffer-visiting' but alway return the base buffer and
13669 not an indirect buffer."
13670 (let ((buf (find-buffer-visiting file)))
13671 (if buf
13672 (or (buffer-base-buffer buf) buf)
13673 nil)))
13675 (defun org-image-file-name-regexp ()
13676 "Return regexp matching the file names of images."
13677 (if (fboundp 'image-file-name-regexp)
13678 (image-file-name-regexp)
13679 (let ((image-file-name-extensions
13680 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13681 "xbm" "xpm" "pbm" "pgm" "ppm")))
13682 (concat "\\."
13683 (regexp-opt (nconc (mapcar 'upcase
13684 image-file-name-extensions)
13685 image-file-name-extensions)
13687 "\\'"))))
13689 (defun org-file-image-p (file)
13690 "Return non-nil if FILE is an image."
13691 (save-match-data
13692 (string-match (org-image-file-name-regexp) file)))
13694 (defun org-get-cursor-date ()
13695 "Return the date at cursor in as a time.
13696 This works in the calendar and in the agenda, anywhere else it just
13697 returns the current time."
13698 (let (date day defd)
13699 (cond
13700 ((eq major-mode 'calendar-mode)
13701 (setq date (calendar-cursor-to-date)
13702 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13703 ((eq major-mode 'org-agenda-mode)
13704 (setq day (get-text-property (point) 'day))
13705 (if day
13706 (setq date (calendar-gregorian-from-absolute day)
13707 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13708 (nth 2 date))))))
13709 (or defd (current-time))))
13711 (defvar org-agenda-action-marker (make-marker)
13712 "Marker pointing to the entry for the next agenda action.")
13714 (defun org-mark-entry-for-agenda-action ()
13715 "Mark the current entry as target of an agenda action.
13716 Agenda actions are actions executed from the agenda with the key `k',
13717 which make use of the date at the cursor."
13718 (interactive)
13719 (move-marker org-agenda-action-marker
13720 (save-excursion (org-back-to-heading t) (point))
13721 (current-buffer))
13722 (message
13723 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13725 ;;; Paragraph filling stuff.
13726 ;; We want this to be just right, so use the full arsenal.
13728 (defun org-indent-line-function ()
13729 "Indent line like previous, but further if previous was headline or item."
13730 (interactive)
13731 (let* ((pos (point))
13732 (itemp (org-at-item-p))
13733 column bpos bcol tpos tcol bullet btype bullet-type)
13734 ;; Find the previous relevant line
13735 (beginning-of-line 1)
13736 (cond
13737 ((looking-at "#") (setq column 0))
13738 ((looking-at "\\*+ ") (setq column 0))
13740 (beginning-of-line 0)
13741 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13742 (beginning-of-line 0))
13743 (cond
13744 ((looking-at "\\*+[ \t]+")
13745 (if (not org-adapt-indentation)
13746 (setq column 0)
13747 (goto-char (match-end 0))
13748 (setq column (current-column))))
13749 ((org-in-item-p)
13750 (org-beginning-of-item)
13751 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13752 (setq bpos (match-beginning 1) tpos (match-end 0)
13753 bcol (progn (goto-char bpos) (current-column))
13754 tcol (progn (goto-char tpos) (current-column))
13755 bullet (match-string 1)
13756 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13757 (if (> tcol (+ bcol org-description-max-indent))
13758 (setq tcol (+ bcol 5)))
13759 (if (not itemp)
13760 (setq column tcol)
13761 (goto-char pos)
13762 (beginning-of-line 1)
13763 (if (looking-at "\\S-")
13764 (progn
13765 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13766 (setq bullet (match-string 1)
13767 btype (if (string-match "[0-9]" bullet) "n" bullet))
13768 (setq column (if (equal btype bullet-type) bcol tcol)))
13769 (setq column (org-get-indentation)))))
13770 (t (setq column (org-get-indentation))))))
13771 (goto-char pos)
13772 (if (<= (current-column) (current-indentation))
13773 (org-indent-line-to column)
13774 (save-excursion (org-indent-line-to column)))
13775 (setq column (current-column))
13776 (beginning-of-line 1)
13777 (if (looking-at
13778 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13779 (replace-match (concat "\\1" (format org-property-format
13780 (match-string 2) (match-string 3)))
13781 t nil))
13782 (org-move-to-column column)))
13784 (defun org-set-autofill-regexps ()
13785 (interactive)
13786 ;; In the paragraph separator we include headlines, because filling
13787 ;; text in a line directly attached to a headline would otherwise
13788 ;; fill the headline as well.
13789 (org-set-local 'comment-start-skip "^#+[ \t]*")
13790 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13791 ;; The paragraph starter includes hand-formatted lists.
13792 (org-set-local 'paragraph-start
13793 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13794 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13795 ;; But only if the user has not turned off tables or fixed-width regions
13796 (org-set-local
13797 'auto-fill-inhibit-regexp
13798 (concat "\\*+ \\|#\\+"
13799 "\\|[ \t]*" org-keyword-time-regexp
13800 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13801 (concat
13802 "\\|[ \t]*["
13803 (if org-enable-table-editor "|" "")
13804 (if org-enable-fixed-width-editor ":" "")
13805 "]"))))
13806 ;; We use our own fill-paragraph function, to make sure that tables
13807 ;; and fixed-width regions are not wrapped. That function will pass
13808 ;; through to `fill-paragraph' when appropriate.
13809 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13810 ; Adaptive filling: To get full control, first make sure that
13811 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13812 (org-set-local 'adaptive-fill-regexp "\000")
13813 (org-set-local 'adaptive-fill-function
13814 'org-adaptive-fill-function)
13815 (org-set-local
13816 'align-mode-rules-list
13817 '((org-in-buffer-settings
13818 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13819 (modes . '(org-mode))))))
13821 (defun org-fill-paragraph (&optional justify)
13822 "Re-align a table, pass through to fill-paragraph if no table."
13823 (let ((table-p (org-at-table-p))
13824 (table.el-p (org-at-table.el-p)))
13825 (cond ((and (equal (char-after (point-at-bol)) ?*)
13826 (save-excursion (goto-char (point-at-bol))
13827 (looking-at outline-regexp)))
13828 t) ; skip headlines
13829 (table.el-p t) ; skip table.el tables
13830 (table-p (org-table-align) t) ; align org-mode tables
13831 (t nil)))) ; call paragraph-fill
13833 ;; For reference, this is the default value of adaptive-fill-regexp
13834 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13836 (defun org-adaptive-fill-function ()
13837 "Return a fill prefix for org-mode files.
13838 In particular, this makes sure hanging paragraphs for hand-formatted lists
13839 work correctly."
13840 (cond ((looking-at "#[ \t]+")
13841 (match-string 0))
13842 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13843 (save-excursion
13844 (if (> (match-end 1) (+ (match-beginning 1)
13845 org-description-max-indent))
13846 (goto-char (+ (match-beginning 1) 5))
13847 (goto-char (match-end 0)))
13848 (make-string (current-column) ?\ )))
13849 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13850 (save-excursion
13851 (goto-char (match-end 0))
13852 (make-string (current-column) ?\ )))
13853 (t nil)))
13855 ;;; Other stuff.
13857 (defun org-toggle-fixed-width-section (arg)
13858 "Toggle the fixed-width export.
13859 If there is no active region, the QUOTE keyword at the current headline is
13860 inserted or removed. When present, it causes the text between this headline
13861 and the next to be exported as fixed-width text, and unmodified.
13862 If there is an active region, this command adds or removes a colon as the
13863 first character of this line. If the first character of a line is a colon,
13864 this line is also exported in fixed-width font."
13865 (interactive "P")
13866 (let* ((cc 0)
13867 (regionp (org-region-active-p))
13868 (beg (if regionp (region-beginning) (point)))
13869 (end (if regionp (region-end)))
13870 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13871 (case-fold-search nil)
13872 (re "[ \t]*\\(:\\)")
13873 off)
13874 (if regionp
13875 (save-excursion
13876 (goto-char beg)
13877 (setq cc (current-column))
13878 (beginning-of-line 1)
13879 (setq off (looking-at re))
13880 (while (> nlines 0)
13881 (setq nlines (1- nlines))
13882 (beginning-of-line 1)
13883 (cond
13884 (arg
13885 (org-move-to-column cc t)
13886 (insert ":\n")
13887 (forward-line -1))
13888 ((and off (looking-at re))
13889 (replace-match "" t t nil 1))
13890 ((not off) (org-move-to-column cc t) (insert ":")))
13891 (forward-line 1)))
13892 (save-excursion
13893 (org-back-to-heading)
13894 (if (looking-at (concat outline-regexp
13895 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13896 (replace-match "" t t nil 1)
13897 (if (looking-at outline-regexp)
13898 (progn
13899 (goto-char (match-end 0))
13900 (insert org-quote-string " "))))))))
13902 ;;;; Functions extending outline functionality
13904 (defun org-beginning-of-line (&optional arg)
13905 "Go to the beginning of the current line. If that is invisible, continue
13906 to a visible line beginning. This makes the function of C-a more intuitive.
13907 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13908 first attempt, and only move to after the tags when the cursor is already
13909 beyond the end of the headline."
13910 (interactive "P")
13911 (let ((pos (point)) refpos)
13912 (beginning-of-line 1)
13913 (if (bobp)
13915 (backward-char 1)
13916 (if (org-invisible-p)
13917 (while (and (not (bobp)) (org-invisible-p))
13918 (backward-char 1)
13919 (beginning-of-line 1))
13920 (forward-char 1)))
13921 (when org-special-ctrl-a/e
13922 (cond
13923 ((and (looking-at org-complex-heading-regexp)
13924 (= (char-after (match-end 1)) ?\ ))
13925 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13926 (point-at-eol)))
13927 (goto-char
13928 (if (eq org-special-ctrl-a/e t)
13929 (cond ((> pos refpos) refpos)
13930 ((= pos (point)) refpos)
13931 (t (point)))
13932 (cond ((> pos (point)) (point))
13933 ((not (eq last-command this-command)) (point))
13934 (t refpos)))))
13935 ((org-at-item-p)
13936 (goto-char
13937 (if (eq org-special-ctrl-a/e t)
13938 (cond ((> pos (match-end 4)) (match-end 4))
13939 ((= pos (point)) (match-end 4))
13940 (t (point)))
13941 (cond ((> pos (point)) (point))
13942 ((not (eq last-command this-command)) (point))
13943 (t (match-end 4))))))))
13944 (org-no-warnings
13945 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13947 (defun org-end-of-line (&optional arg)
13948 "Go to the end of the line.
13949 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13950 first attempt, and only move to after the tags when the cursor is already
13951 beyond the end of the headline."
13952 (interactive "P")
13953 (if (or (not org-special-ctrl-a/e)
13954 (not (org-on-heading-p)))
13955 (end-of-line arg)
13956 (let ((pos (point)))
13957 (beginning-of-line 1)
13958 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13959 (if (eq org-special-ctrl-a/e t)
13960 (if (or (< pos (match-beginning 1))
13961 (= pos (match-end 0)))
13962 (goto-char (match-beginning 1))
13963 (goto-char (match-end 0)))
13964 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13965 (goto-char (match-end 0))
13966 (goto-char (match-beginning 1))))
13967 (end-of-line arg))))
13968 (org-no-warnings
13969 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13972 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13973 (define-key org-mode-map "\C-e" 'org-end-of-line)
13975 (defun org-kill-line (&optional arg)
13976 "Kill line, to tags or end of line."
13977 (interactive "P")
13978 (cond
13979 ((or (not org-special-ctrl-k)
13980 (bolp)
13981 (not (org-on-heading-p)))
13982 (call-interactively 'kill-line))
13983 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13984 (kill-region (point) (match-beginning 1))
13985 (org-set-tags nil t))
13986 (t (kill-region (point) (point-at-eol)))))
13988 (define-key org-mode-map "\C-k" 'org-kill-line)
13990 (defun org-yank (&optional arg)
13991 "Yank. If the kill is a subtree, treat it specially.
13992 This command will look at the current kill and check if is a single
13993 subtree, or a series of subtrees[1]. If it passes the test, and if the
13994 cursor is at the beginning of a line or after the stars of a currently
13995 empty headline, then the yank is handeled specially. How exactly depends
13996 on the value of the following variables, both set by default.
13998 org-yank-folded-subtrees
13999 When set, the subree(s) will be folded after insertion, but only
14000 if doing so would now swallow text after the yanked text.
14002 org-yank-adjusted-subtrees
14003 When set, the subtree will be promoted or demoted in order to
14004 fit into the local outline tree structure, which means that the level
14005 will be adjusted so that it becomes the smaller one of the two
14006 *visible* surrounding headings.
14008 Any prefix to this command will cause `yank' to be called directly with
14009 no special treatment. In particular, a simple `C-u' prefix will just
14010 plainly yank the text as it is.
14012 \[1] Basically, the test checks if the first non-white line is a heading
14013 and if there are no other headings with fewer stars."
14014 (interactive "P")
14015 (if arg
14016 (call-interactively 'yank)
14017 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14018 (and (org-kill-is-subtree-p)
14019 (or (bolp)
14020 (and (looking-at "[ \t]*$")
14021 (string-match
14022 "\\`\\*+\\'"
14023 (buffer-substring (point-at-bol) (point)))))))
14024 swallowp)
14025 (cond
14026 ((and subtreep org-yank-folded-subtrees)
14027 (let ((beg (point))
14028 end)
14029 (if (and subtreep org-yank-adjusted-subtrees)
14030 (org-paste-subtree nil nil 'for-yank)
14031 (call-interactively 'yank))
14032 (setq end (point))
14033 (goto-char beg)
14034 (when (and (bolp) subtreep
14035 (not (setq swallowp
14036 (org-yank-folding-would-swallow-text beg end))))
14037 (or (looking-at outline-regexp)
14038 (re-search-forward (concat "^" outline-regexp) end t))
14039 (while (and (< (point) end) (looking-at outline-regexp))
14040 (hide-subtree)
14041 (org-cycle-show-empty-lines 'folded)
14042 (condition-case nil
14043 (outline-forward-same-level 1)
14044 (error (goto-char end)))))
14045 (when swallowp
14046 (message
14047 "Yanked text not folded because that would swallow text"))
14048 (goto-char end)
14049 (skip-chars-forward " \t\n\r")
14050 (beginning-of-line 1)))
14051 ((and subtreep org-yank-adjusted-subtrees)
14052 (org-paste-subtree nil nil 'for-yank))
14054 (call-interactively 'yank))))))
14056 (defun org-yank-folding-would-swallow-text (beg end)
14057 "Would hide-subtree at BEG swallow any text after END?"
14058 (let (level)
14059 (save-excursion
14060 (goto-char beg)
14061 (when (or (looking-at outline-regexp)
14062 (re-search-forward (concat "^" outline-regexp) end t))
14063 (setq level (org-outline-level)))
14064 (goto-char end)
14065 (skip-chars-forward " \t\r\n\v\f")
14066 (if (or (eobp)
14067 (and (bolp) (looking-at org-outline-regexp)
14068 (<= (org-outline-level) level)))
14069 nil ; Nothing would be swallowed
14070 t)))) ; something would swallow
14072 (define-key org-mode-map "\C-y" 'org-yank)
14074 (defun org-invisible-p ()
14075 "Check if point is at a character currently not visible."
14076 ;; Early versions of noutline don't have `outline-invisible-p'.
14077 (if (fboundp 'outline-invisible-p)
14078 (outline-invisible-p)
14079 (get-char-property (point) 'invisible)))
14081 (defun org-invisible-p2 ()
14082 "Check if point is at a character currently not visible."
14083 (save-excursion
14084 (if (and (eolp) (not (bobp))) (backward-char 1))
14085 ;; Early versions of noutline don't have `outline-invisible-p'.
14086 (if (fboundp 'outline-invisible-p)
14087 (outline-invisible-p)
14088 (get-char-property (point) 'invisible))))
14090 (defun org-back-to-heading (invisible-ok)
14091 "Call `outline-back-to-heading', but provide a better error message."
14092 (condition-case nil
14093 (outline-back-to-heading invisible-ok)
14094 (error (error "Before first headline at position %d in buffer %s"
14095 (point) (current-buffer)))))
14097 (defalias 'org-on-heading-p 'outline-on-heading-p)
14098 (defalias 'org-at-heading-p 'outline-on-heading-p)
14099 (defun org-at-heading-or-item-p ()
14100 (or (org-on-heading-p) (org-at-item-p)))
14102 (defun org-on-target-p ()
14103 (or (org-in-regexp org-radio-target-regexp)
14104 (org-in-regexp org-target-regexp)))
14106 (defun org-up-heading-all (arg)
14107 "Move to the heading line of which the present line is a subheading.
14108 This function considers both visible and invisible heading lines.
14109 With argument, move up ARG levels."
14110 (if (fboundp 'outline-up-heading-all)
14111 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14112 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14114 (defun org-up-heading-safe ()
14115 "Move to the heading line of which the present line is a subheading.
14116 This version will not throw an error. It will return the level of the
14117 headline found, or nil if no higher level is found."
14118 (let ((pos (point)) start-level level
14119 (re (concat "^" outline-regexp)))
14120 (catch 'exit
14121 (org-back-to-heading t)
14122 (setq start-level (funcall outline-level))
14123 (if (equal start-level 1) (throw 'exit nil))
14124 (while (re-search-backward re nil t)
14125 (setq level (funcall outline-level))
14126 (if (< level start-level) (throw 'exit level)))
14127 nil)))
14129 (defun org-first-sibling-p ()
14130 "Is this heading the first child of its parents?"
14131 (interactive)
14132 (let ((re (concat "^" outline-regexp))
14133 level l)
14134 (unless (org-at-heading-p t)
14135 (error "Not at a heading"))
14136 (setq level (funcall outline-level))
14137 (save-excursion
14138 (if (not (re-search-backward re nil t))
14140 (setq l (funcall outline-level))
14141 (< l level)))))
14143 (defun org-goto-sibling (&optional previous)
14144 "Goto the next sibling, even if it is invisible.
14145 When PREVIOUS is set, go to the previous sibling instead. Returns t
14146 when a sibling was found. When none is found, return nil and don't
14147 move point."
14148 (let ((fun (if previous 're-search-backward 're-search-forward))
14149 (pos (point))
14150 (re (concat "^" outline-regexp))
14151 level l)
14152 (when (condition-case nil (org-back-to-heading t) (error nil))
14153 (setq level (funcall outline-level))
14154 (catch 'exit
14155 (or previous (forward-char 1))
14156 (while (funcall fun re nil t)
14157 (setq l (funcall outline-level))
14158 (when (< l level) (goto-char pos) (throw 'exit nil))
14159 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14160 (goto-char pos)
14161 nil))))
14163 (defun org-show-siblings ()
14164 "Show all siblings of the current headline."
14165 (save-excursion
14166 (while (org-goto-sibling) (org-flag-heading nil)))
14167 (save-excursion
14168 (while (org-goto-sibling 'previous)
14169 (org-flag-heading nil))))
14171 (defun org-show-hidden-entry ()
14172 "Show an entry where even the heading is hidden."
14173 (save-excursion
14174 (org-show-entry)))
14176 (defun org-flag-heading (flag &optional entry)
14177 "Flag the current heading. FLAG non-nil means make invisible.
14178 When ENTRY is non-nil, show the entire entry."
14179 (save-excursion
14180 (org-back-to-heading t)
14181 ;; Check if we should show the entire entry
14182 (if entry
14183 (progn
14184 (org-show-entry)
14185 (save-excursion
14186 (and (outline-next-heading)
14187 (org-flag-heading nil))))
14188 (outline-flag-region (max (point-min) (1- (point)))
14189 (save-excursion (outline-end-of-heading) (point))
14190 flag))))
14192 (defun org-forward-same-level (arg)
14193 "Move forward to the ARG'th subheading at same level as this one.
14194 Stop at the first and last subheadings of a superior heading.
14195 This is like outline-forward-same-level, but invisible headings are ok."
14196 (interactive "p")
14197 (org-back-to-heading t)
14198 (while (> arg 0)
14199 (let ((point-to-move-to (save-excursion
14200 (org-get-next-sibling))))
14201 (if point-to-move-to
14202 (progn
14203 (goto-char point-to-move-to)
14204 (setq arg (1- arg)))
14205 (progn
14206 (setq arg 0)
14207 (error "No following same-level heading"))))))
14209 (defun org-get-next-sibling ()
14210 "Move to next heading of the same level, and return point.
14211 If there is no such heading, return nil.
14212 This is like outline-next-sibling, but invisible headings are ok."
14213 (let ((level (funcall outline-level)))
14214 (outline-next-heading)
14215 (while (and (not (eobp)) (> (funcall outline-level) level))
14216 (outline-next-heading))
14217 (if (or (eobp) (< (funcall outline-level) level))
14219 (point))))
14221 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14222 ;; This is an exact copy of the original function, but it uses
14223 ;; `org-back-to-heading', to make it work also in invisible
14224 ;; trees. And is uses an invisible-OK argument.
14225 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14226 (org-back-to-heading invisible-OK)
14227 (let ((first t)
14228 (level (funcall outline-level)))
14229 (while (and (not (eobp))
14230 (or first (> (funcall outline-level) level)))
14231 (setq first nil)
14232 (outline-next-heading))
14233 (unless to-heading
14234 (if (memq (preceding-char) '(?\n ?\^M))
14235 (progn
14236 ;; Go to end of line before heading
14237 (forward-char -1)
14238 (if (memq (preceding-char) '(?\n ?\^M))
14239 ;; leave blank line before heading
14240 (forward-char -1))))))
14241 (point))
14243 (defun org-show-subtree ()
14244 "Show everything after this heading at deeper levels."
14245 (outline-flag-region
14246 (point)
14247 (save-excursion
14248 (outline-end-of-subtree) (outline-next-heading) (point))
14249 nil))
14251 (defun org-show-entry ()
14252 "Show the body directly following this heading.
14253 Show the heading too, if it is currently invisible."
14254 (interactive)
14255 (save-excursion
14256 (condition-case nil
14257 (progn
14258 (org-back-to-heading t)
14259 (outline-flag-region
14260 (max (point-min) (1- (point)))
14261 (save-excursion
14262 (re-search-forward
14263 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14264 (or (match-beginning 1) (point-max)))
14265 nil))
14266 (error nil))))
14268 (defun org-make-options-regexp (kwds)
14269 "Make a regular expression for keyword lines."
14270 (concat
14272 "#?[ \t]*\\+\\("
14273 (mapconcat 'regexp-quote kwds "\\|")
14274 "\\):[ \t]*"
14275 "\\(.+\\)"))
14277 ;; Make isearch reveal the necessary context
14278 (defun org-isearch-end ()
14279 "Reveal context after isearch exits."
14280 (when isearch-success ; only if search was successful
14281 (if (featurep 'xemacs)
14282 ;; Under XEmacs, the hook is run in the correct place,
14283 ;; we directly show the context.
14284 (org-show-context 'isearch)
14285 ;; In Emacs the hook runs *before* restoring the overlays.
14286 ;; So we have to use a one-time post-command-hook to do this.
14287 ;; (Emacs 22 has a special variable, see function `org-mode')
14288 (unless (and (boundp 'isearch-mode-end-hook-quit)
14289 isearch-mode-end-hook-quit)
14290 ;; Only when the isearch was not quitted.
14291 (org-add-hook 'post-command-hook 'org-isearch-post-command
14292 'append 'local)))))
14294 (defun org-isearch-post-command ()
14295 "Remove self from hook, and show context."
14296 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14297 (org-show-context 'isearch))
14300 ;;;; Integration with and fixes for other packages
14302 ;;; Imenu support
14304 (defvar org-imenu-markers nil
14305 "All markers currently used by Imenu.")
14306 (make-variable-buffer-local 'org-imenu-markers)
14308 (defun org-imenu-new-marker (&optional pos)
14309 "Return a new marker for use by Imenu, and remember the marker."
14310 (let ((m (make-marker)))
14311 (move-marker m (or pos (point)))
14312 (push m org-imenu-markers)
14315 (defun org-imenu-get-tree ()
14316 "Produce the index for Imenu."
14317 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14318 (setq org-imenu-markers nil)
14319 (let* ((n org-imenu-depth)
14320 (re (concat "^" outline-regexp))
14321 (subs (make-vector (1+ n) nil))
14322 (last-level 0)
14323 m tree level head)
14324 (save-excursion
14325 (save-restriction
14326 (widen)
14327 (goto-char (point-max))
14328 (while (re-search-backward re nil t)
14329 (setq level (org-reduced-level (funcall outline-level)))
14330 (when (<= level n)
14331 (looking-at org-complex-heading-regexp)
14332 (setq head (org-link-display-format
14333 (org-match-string-no-properties 4))
14334 m (org-imenu-new-marker))
14335 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14336 (if (>= level last-level)
14337 (push (cons head m) (aref subs level))
14338 (push (cons head (aref subs (1+ level))) (aref subs level))
14339 (loop for i from (1+ level) to n do (aset subs i nil)))
14340 (setq last-level level)))))
14341 (aref subs 1)))
14343 (eval-after-load "imenu"
14344 '(progn
14345 (add-hook 'imenu-after-jump-hook
14346 (lambda ()
14347 (if (eq major-mode 'org-mode)
14348 (org-show-context 'org-goto))))))
14350 (defun org-link-display-format (link)
14351 "Replace a link with either the description, or the link target
14352 if no description is present"
14353 (save-match-data
14354 (if (string-match org-bracket-link-analytic-regexp link)
14355 (replace-match (or (match-string 5 link)
14356 (concat (match-string 1 link)
14357 (match-string 3 link)))
14358 nil nil link)
14359 link)))
14361 ;; Speedbar support
14363 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14364 "Overlay marking the agenda restriction line in speedbar.")
14365 (org-overlay-put org-speedbar-restriction-lock-overlay
14366 'face 'org-agenda-restriction-lock)
14367 (org-overlay-put org-speedbar-restriction-lock-overlay
14368 'help-echo "Agendas are currently limited to this item.")
14369 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14371 (defun org-speedbar-set-agenda-restriction ()
14372 "Restrict future agenda commands to the location at point in speedbar.
14373 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14374 (interactive)
14375 (require 'org-agenda)
14376 (let (p m tp np dir txt w)
14377 (cond
14378 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14379 'org-imenu t))
14380 (setq m (get-text-property p 'org-imenu-marker))
14381 (save-excursion
14382 (save-restriction
14383 (set-buffer (marker-buffer m))
14384 (goto-char m)
14385 (org-agenda-set-restriction-lock 'subtree))))
14386 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14387 'speedbar-function 'speedbar-find-file))
14388 (setq tp (previous-single-property-change
14389 (1+ p) 'speedbar-function)
14390 np (next-single-property-change
14391 tp 'speedbar-function)
14392 dir (speedbar-line-directory)
14393 txt (buffer-substring-no-properties (or tp (point-min))
14394 (or np (point-max))))
14395 (save-excursion
14396 (save-restriction
14397 (set-buffer (find-file-noselect
14398 (let ((default-directory dir))
14399 (expand-file-name txt))))
14400 (unless (org-mode-p)
14401 (error "Cannot restrict to non-Org-mode file"))
14402 (org-agenda-set-restriction-lock 'file))))
14403 (t (error "Don't know how to restrict Org-mode's agenda")))
14404 (org-move-overlay org-speedbar-restriction-lock-overlay
14405 (point-at-bol) (point-at-eol))
14406 (setq current-prefix-arg nil)
14407 (org-agenda-maybe-redo)))
14409 (eval-after-load "speedbar"
14410 '(progn
14411 (speedbar-add-supported-extension ".org")
14412 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14413 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14414 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14415 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14416 (add-hook 'speedbar-visiting-tag-hook
14417 (lambda () (org-show-context 'org-goto)))))
14420 ;;; Fixes and Hacks for problems with other packages
14422 ;; Make flyspell not check words in links, to not mess up our keymap
14423 (defun org-mode-flyspell-verify ()
14424 "Don't let flyspell put overlays at active buttons."
14425 (not (get-text-property (point) 'keymap)))
14427 ;; Make `bookmark-jump' show the jump location if it was hidden.
14428 (eval-after-load "bookmark"
14429 '(if (boundp 'bookmark-after-jump-hook)
14430 ;; We can use the hook
14431 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14432 ;; Hook not available, use advice
14433 (defadvice bookmark-jump (after org-make-visible activate)
14434 "Make the position visible."
14435 (org-bookmark-jump-unhide))))
14437 ;; Make sure saveplace show the location if it was hidden
14438 (eval-after-load "saveplace"
14439 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14440 "Make the position visible."
14441 (org-bookmark-jump-unhide)))
14443 (defun org-bookmark-jump-unhide ()
14444 "Unhide the current position, to show the bookmark location."
14445 (and (org-mode-p)
14446 (or (org-invisible-p)
14447 (save-excursion (goto-char (max (point-min) (1- (point))))
14448 (org-invisible-p)))
14449 (org-show-context 'bookmark-jump)))
14451 ;; Make session.el ignore our circular variable
14452 (eval-after-load "session"
14453 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14455 ;;;; Experimental code
14457 (defun org-closed-in-range ()
14458 "Sparse tree of items closed in a certain time range.
14459 Still experimental, may disappear in the future."
14460 (interactive)
14461 ;; Get the time interval from the user.
14462 (let* ((time1 (time-to-seconds
14463 (org-read-date nil 'to-time nil "Starting date: ")))
14464 (time2 (time-to-seconds
14465 (org-read-date nil 'to-time nil "End date:")))
14466 ;; callback function
14467 (callback (lambda ()
14468 (let ((time
14469 (time-to-seconds
14470 (apply 'encode-time
14471 (org-parse-time-string
14472 (match-string 1))))))
14473 ;; check if time in interval
14474 (and (>= time time1) (<= time time2))))))
14475 ;; make tree, check each match with the callback
14476 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14479 ;;;; Finish up
14481 (provide 'org)
14483 (run-hooks 'org-load-hook)
14485 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14487 ;;; org.el ends here